@jamiexiongr/panda-hub 0.1.30 → 0.1.32
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-MXQGMO73.mjs → chunk-JKHCCCUZ.mjs} +2 -2
- package/dist/{chunk-VOWZ4V3B.mjs → chunk-TYL3A3VC.mjs} +24 -9
- package/dist/cli.mjs +2 -2
- package/dist/index.mjs +2 -2
- package/dist/{src-NI7ZHUVP.mjs → src-FZ5WMACF.mjs} +1 -1
- package/dist/web/assets/{diagnostics-page-BX9ilH-j.js → diagnostics-page-4wwMLeXa.js} +1 -1
- package/dist/web/assets/{index-DPapkx9A.js → index-Buoz6IYL.js} +5 -5
- package/dist/web/assets/{index-CdvROdNu.css → index-qres5phQ.css} +1 -1
- package/dist/web/assets/{session-diff-preview-kDHdPa6S.js → session-diff-preview-5oB0rJ5W.js} +1 -1
- package/dist/web/assets/{session-file-markdown-preview-DKYviOHs.js → session-file-markdown-preview-BoOjcJcb.js} +1 -1
- package/dist/web/assets/{session-file-preview-page-B5cY0GxO.js → session-file-preview-page-DbdsZil_.js} +3 -3
- package/dist/web/assets/{web-BCkw8FnT.js → web-BBYipy_G.js} +1 -1
- package/dist/web/assets/{web-Cg2SPsir.js → web-BiBxkdSf.js} +1 -1
- package/dist/web/assets/{web-CcQ2B2v6.js → web-Cv1t4xrp.js} +1 -1
- package/dist/web/assets/{web-CI5VgZbX.js → web-D9nPg8kF.js} +1 -1
- package/dist/web/assets/{web-CiNw0NeJ.js → web-OEcsiG9z.js} +1 -1
- package/dist/web/assets/{xml-hyN8lXhw.js → xml-BJn4g2Sn.js} +1 -1
- package/dist/web/index.html +2 -2
- 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-5oB0rJ5W.js","assets/xml-BJn4g2Sn.js","assets/session-file-preview-page-DbdsZil_.js","assets/diagnostics-page-4wwMLeXa.js","assets/diagnostics-page-BmzeM8p1.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
var B8=e=>{throw TypeError(e)};var _1=(e,t,i)=>t.has(e)||B8("Cannot "+i);var H=(e,t,i)=>(_1(e,t,"read from private field"),i?i.call(e):t.get(e)),jt=(e,t,i)=>t.has(e)?B8("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),et=(e,t,i,r)=>(_1(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),Yt=(e,t,i)=>(_1(e,t,"access private method"),i);var Am=(e,t,i,r)=>({set _(o){et(e,t,o,i)},get _(){return H(e,t,r)}});(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const u of o)if(u.type==="childList")for(const d of u.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function i(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 r(o){if(o.ep)return;o.ep=!0;const u=i(o);fetch(o.href,u)}})();const W9="modulepreload",K9=function(e){return"/"+e},$8={},cl=function(t,i,r){let o=Promise.resolve();if(i&&i.length>0){let d=function(g){return Promise.all(g.map(b=>Promise.resolve(b).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=d(i.map(g=>{if(g=K9(g),g in $8)return;$8[g]=!0;const b=g.endsWith(".css"),p=b?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${g}"]${p}`))return;const v=document.createElement("link");if(v.rel=b?"stylesheet":W9,b||(v.as="script"),v.crossOrigin="",v.href=g,y&&v.setAttribute("nonce",y),document.head.appendChild(v),b)return new Promise((w,N)=>{v.addEventListener("load",w),v.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${g}`)))})}))}function u(d){const m=new Event("vite:preloadError",{cancelable:!0});if(m.payload=d,window.dispatchEvent(m),!m.defaultPrevented)throw d}return o.then(d=>{for(const m of d||[])m.status==="rejected"&&u(m.reason);return t().catch(u)})};function Q9(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var y1={exports:{}},Tf={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react-jsx-runtime.production.js
|
|
@@ -63,7 +63,7 @@ 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 Tb;function v7(){if(Tb)return R1;Tb=1;var e=jh(),t=y7();function i(g,b){return g===b&&(g!==0||1/g===1/b)||g!==g&&b!==b}var r=typeof Object.is=="function"?Object.is:i,o=t.useSyncExternalStore,u=e.useRef,d=e.useEffect,m=e.useMemo,y=e.useDebugValue;return R1.useSyncExternalStoreWithSelector=function(g,b,p,v,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 M(Q){if(!P){if(P=!0,I=Q,Q=v(Q),w!==void 0&&j.hasValue){var J=j.value;if(w(J,Q))return k=J}return k=Q}if(J=k,r(I,Q))return J;var F=v(Q);return w!==void 0&&w(J,F)?(I=Q,J):(I=Q,k=F)}var P=!1,I,k,O=p===void 0?null:p;return[function(){return M(b())},O===null?void 0:function(){return M(O())}]},[b,p,v,w]);var T=o(g,N[0],N[1]);return d(function(){j.hasValue=!0,j.value=T},[T]),y(T),T},R1}var Mb;function b7(){return Mb||(Mb=1,M1.exports=v7()),M1.exports}var x7=b7();function S7(e,t){return e===t}function j7(e,t,i=S7){const r=_.useCallback(d=>{if(!e)return()=>{};const{unsubscribe:m}=e.subscribe(d);return m},[e]),o=_.useCallback(()=>e==null?void 0:e.get(),[e]);return x7.useSyncExternalStoreWithSelector(r,o,o,t,i)}function ai(e){const t=xi({warn:(e==null?void 0:e.router)===void 0}),i=(e==null?void 0:e.router)||t,r=_.useRef(void 0);return j7(i.__store,o=>{if(e!=null&&e.select){if(e.structuralSharing??i.options.defaultStructuralSharing){const u=oc(r.current,e.select(o));return r.current=u,u}return e.select(o)}return o})}var Gp=_.createContext(void 0),w7=_.createContext(void 0);function _o(e){const t=_.useContext(e.from?w7:Gp);return ai({select:i=>{const r=i.matches.find(o=>e.from?e.from===o.routeId:o.id===t);if(po(!((e.shouldThrow??!0)&&!r),`Could not find ${e.from?`an active match from "${e.from}"`:"a nearest match!"}`),r!==void 0)return e.select?e.select(r):r},structuralSharing:e.structuralSharing})}function M0(e){return _o({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function R0(e){const{select:t,...i}=e;return _o({...i,select:r=>t?t(r.loaderDeps):r.loaderDeps})}function Mc(e){return _o({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const i=e.strict===!1?t.params:t._strictParams;return e.select?e.select(i):i}})}function A0(e){return _o({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function Hi(e){const t=xi();return _.useCallback(i=>t.navigate({...i,from:i.from??(e==null?void 0:e.from)}),[e==null?void 0:e.from,t])}function I0(e){return _o({...e,select:t=>e.select?e.select(t.context):t.context})}var ra=d2();function N7(e,t){const i=xi(),r=YS(t),{activeProps:o,inactiveProps:u,activeOptions:d,to:m,preload:y,preloadDelay:g,hashScrollIntoView:b,replace:p,startTransition:v,resetScroll:w,viewTransition:N,children:j,target:T,disabled:M,style:P,className:I,onClick:k,onBlur:O,onFocus:Q,onMouseEnter:J,onMouseLeave:F,onTouchStart:B,ignoreBlocker:G,params:Z,search:ae,hash:he,state:ne,mask:Ce,reloadDocument:R,unsafeRelative:X,from:le,_fromLocation:ue,...ye}=e,D=z2(),oe=ai({select:lt=>{const Et=lt.matches[lt.matches.length-1];return{search:Et==null?void 0:Et.search,hash:lt.location.hash,path:Et==null?void 0:Et.pathname}},structuralSharing:!0}),je=e.from,z=_.useMemo(()=>({...e,from:je}),[i,oe,je,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),be=_.useMemo(()=>i.buildLocation({...z}),[i,z]),De=be.maskedLocation?be.maskedLocation.publicHref:be.publicHref,se=be.maskedLocation?be.maskedLocation.external:be.external,pe=_.useMemo(()=>R7(De,se,i.history,M),[M,se,De,i.history]),ke=_.useMemo(()=>{if(pe!=null&&pe.external)return hp(pe.href,i.protocolAllowlist)?void 0:pe.href;if(!A7(m)&&!(typeof m!="string"||m.indexOf(":")===-1))try{return new URL(m),hp(m,i.protocolAllowlist)?void 0:m}catch{}},[m,pe,i.protocolAllowlist]),Ze=ai({select:lt=>{if(ke)return!1;if(d!=null&&d.exact){if(!mj(lt.location.pathname,be.pathname,i.basepath))return!1}else{const Et=pp(lt.location.pathname,i.basepath),rt=pp(be.pathname,i.basepath);if(!(Et.startsWith(rt)&&(Et.length===rt.length||Et[rt.length]==="/")))return!1}return((d==null?void 0:d.includeSearch)??!0)&&!bc(lt.location.search,be.search,{partial:!(d!=null&&d.exact),ignoreUndefined:!(d!=null&&d.explicitUndefined)})?!1:d!=null&&d.includeHash?D&<.location.hash===be.hash:!0}}),zt=Ze?oo(o,{})??k7:D1,Fe=Ze?D1:oo(u,{})??D1,kt=[I,zt.className,Fe.className].filter(Boolean).join(" "),Bt=(P||zt.style||Fe.style)&&{...P,...zt.style,...Fe.style},[Gt,Xt]=_.useState(!1),Ft=_.useRef(!1),qe=e.reloadDocument||ke?!1:y??i.options.defaultPreload,dt=g??i.options.defaultPreloadDelay??0,un=_.useCallback(()=>{i.preloadRoute({...z,_builtLocation:be}).catch(lt=>{console.warn(lt),console.warn(f7)})},[i,z,be]);GS(r,_.useCallback(lt=>{lt!=null&<.isIntersecting&&un()},[un]),M7,{disabled:!!M||qe!=="viewport"}),_.useEffect(()=>{Ft.current||!M&&qe==="render"&&(un(),Ft.current=!0)},[M,un,qe]);const $t=lt=>{const Et=lt.currentTarget.getAttribute("target"),rt=T!==void 0?T:Et;if(!M&&!I7(lt)&&!lt.defaultPrevented&&(!rt||rt==="_self")&<.button===0){lt.preventDefault(),ra.flushSync(()=>{Xt(!0)});const st=i.subscribe("onResolved",()=>{st(),Xt(!1)});i.navigate({...z,replace:p,resetScroll:w,hashScrollIntoView:b,startTransition:v,viewTransition:N,ignoreBlocker:G})}};if(ke)return{...ye,ref:r,href:ke,...j&&{children:j},...T&&{target:T},...M&&{disabled:M},...P&&{style:P},...I&&{className:I},...k&&{onClick:k},...O&&{onBlur:O},...Q&&{onFocus:Q},...J&&{onMouseEnter:J},...F&&{onMouseLeave:F},...B&&{onTouchStart:B}};const An=lt=>{if(M||qe!=="intent")return;if(!dt){un();return}const Et=lt.currentTarget;if(Df.has(Et))return;const rt=setTimeout(()=>{Df.delete(Et),un()},dt);Df.set(Et,rt)},Nn=lt=>{M||qe!=="intent"||un()},Tt=lt=>{if(M||!qe||!dt)return;const Et=lt.currentTarget,rt=Df.get(Et);rt&&(clearTimeout(rt),Df.delete(Et))};return{...ye,...zt,...Fe,href:pe==null?void 0:pe.href,ref:r,onClick:Eu([k,$t]),onBlur:Eu([O,Tt]),onFocus:Eu([Q,An]),onMouseEnter:Eu([J,An]),onMouseLeave:Eu([F,Tt]),onTouchStart:Eu([B,Nn]),disabled:!!M,target:T,...Bt&&{style:Bt},...kt&&{className:kt},...M&&E7,...Ze&&C7,...D&&Gt&&T7}}var D1={},k7={className:"active"},E7={role:"link","aria-disabled":!0},C7={"data-status":"active","aria-current":"page"},T7={"data-transitioning":"transitioning"},Df=new WeakMap,M7={rootMargin:"100px"},Eu=e=>t=>{for(const i of e)if(i){if(t.defaultPrevented)return;i(t)}};function R7(e,t,i,r){if(!r)return t?{href:e,external:!0}:{href:i.createHref(e)||"/",external:!1}}function A7(e){if(typeof e!="string")return!1;const t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var bp=_.forwardRef((e,t)=>{const{_asChild:i,...r}=e,{type:o,...u}=N7(r,t),d=typeof r.children=="function"?r.children({isActive:u["data-status"]==="active"}):r.children;if(!i){const{disabled:m,...y}=u;return _.createElement("a",y,d)}return _.createElement(i,u,d)});function I7(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var D7=class extends U2{constructor(e){super(e),this.useMatch=t=>_o({select:t==null?void 0:t.select,from:this.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>I0({...t,from:this.id}),this.useSearch=t=>A0({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useParams=t=>Mc({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useLoaderDeps=t=>R0({...t,from:this.id}),this.useLoaderData=t=>M0({...t,from:this.id}),this.useNavigate=()=>Hi({from:this.fullPath}),this.Link=tl.forwardRef((t,i)=>a.jsx(bp,{ref:i,from:this.fullPath,...t})),this.$$typeof=Symbol.for("react.memo")}};function Rc(e){return new D7(e)}var O7=class extends h7{constructor(e){super(e),this.useMatch=t=>_o({select:t==null?void 0:t.select,from:this.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>I0({...t,from:this.id}),this.useSearch=t=>A0({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useParams=t=>Mc({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useLoaderDeps=t=>R0({...t,from:this.id}),this.useLoaderData=t=>M0({...t,from:this.id}),this.useNavigate=()=>Hi({from:this.fullPath}),this.Link=tl.forwardRef((t,i)=>a.jsx(bp,{ref:i,from:this.fullPath,...t})),this.$$typeof=Symbol.for("react.memo")}};function L7(e){return new O7(e)}function Rb(e){return typeof e=="object"?new Ab(e,{silent:!0}).createRoute(e):new Ab(e,{silent:!0}).createRoute}var Ab=class{constructor(e,t){this.path=e,this.createRoute=i=>{const r=Rc(i);return r.isRoot=!1,r},this.silent=t==null?void 0:t.silent}},Ib=class{constructor(e){this.useMatch=t=>_o({select:t==null?void 0:t.select,from:this.options.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>I0({...t,from:this.options.id}),this.useSearch=t=>A0({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.options.id}),this.useParams=t=>Mc({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.options.id}),this.useLoaderDeps=t=>R0({...t,from:this.options.id}),this.useLoaderData=t=>M0({...t,from:this.options.id}),this.useNavigate=()=>Hi({from:xi().routesById[this.options.id].fullPath}),this.options=e,this.$$typeof=Symbol.for("react.memo")}};function Db(e){return typeof e=="object"?new Ib(e):t=>new Ib({id:e,...t})}function P7(e){const t=ai({select:i=>`not-found-${i.location.pathname}-${i.status}`});return a.jsx(C0,{getResetKey:()=>t,onCatch:(i,r)=>{var o;if(Ca(i))(o=e.onCatch)==null||o.call(e,i,r);else throw i},errorComponent:({error:i})=>{var r;if(Ca(i))return(r=e.fallback)==null?void 0:r.call(e,i);throw i},children:e.children})}function U7(){return a.jsx("p",{children:"Not Found"})}function Lu(e){return a.jsx(a.Fragment,{children:e.children})}function $2(e,t,i){return t.options.notFoundComponent?a.jsx(t.options.notFoundComponent,{...i}):e.options.defaultNotFoundComponent?a.jsx(e.options.defaultNotFoundComponent,{...i}):a.jsx(U7,{})}function z7(){return xi().isScrollRestoring,null}var H2=_.memo(function({matchId:t}){var N,j;const i=xi(),r=ai({select:T=>{var I;const M=T.matches.findIndex(k=>k.id===t),P=T.matches[M];return po(P),{routeId:P.routeId,ssr:P.ssr,_displayPending:P._displayPending,resetKey:T.loadedAt,parentRouteId:(I=T.matches[M-1])==null?void 0:I.routeId}},structuralSharing:!0}),o=i.routesById[r.routeId],u=o.options.pendingComponent??i.options.defaultPendingComponent,d=u?a.jsx(u,{}):null,m=o.options.errorComponent??i.options.defaultErrorComponent,y=o.options.onCatch??i.options.defaultOnCatch,g=o.isRoot?o.options.notFoundComponent??((N=i.options.notFoundRoute)==null?void 0:N.options.component):o.options.notFoundComponent,b=r.ssr===!1||r.ssr==="data-only",p=(!o.isRoot||o.options.wrapInSuspense||b)&&(o.options.wrapInSuspense??u??(((j=o.options.errorComponent)==null?void 0:j.preload)||b))?_.Suspense:Lu,v=m?C0:Lu,w=g?P7:Lu;return a.jsxs(o.isRoot?o.options.shellComponent??Lu:Lu,{children:[a.jsx(Gp.Provider,{value:t,children:a.jsx(p,{fallback:d,children:a.jsx(v,{getResetKey:()=>r.resetKey,errorComponent:m||T0,onCatch:(T,M)=>{if(Ca(T))throw T;y==null||y(T,M)},children:a.jsx(w,{fallback:T=>{if(!g||T.routeId&&T.routeId!==r.routeId||!T.routeId&&!o.isRoot)throw T;return _.createElement(g,T)},children:b||r._displayPending?a.jsx(p7,{fallback:d,children:a.jsx(Ob,{matchId:t})}):a.jsx(Ob,{matchId:t})})})})}),r.parentRouteId===xc&&i.options.scrollRestoration?a.jsxs(a.Fragment,{children:[a.jsx(B7,{}),a.jsx(z7,{})]}):null]})});function B7(){const e=xi(),t=_.useRef(void 0);return a.jsx("script",{suppressHydrationWarning:!0,ref:i=>{i&&(t.current===void 0||t.current.href!==e.latestLocation.href)&&(e.emit({type:"onRendered",...jc(e.state)}),t.current=e.latestLocation)}},e.latestLocation.state.__TSR_key)}var Ob=_.memo(function({matchId:t}){var y,g,b,p;const i=xi(),{match:r,key:o,routeId:u}=ai({select:v=>{var T;const w=v.matches.find(M=>M.id===t),N=w.routeId,j=(T=i.routesById[N].options.remountDeps??i.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}),d=i.routesById[u],m=_.useMemo(()=>{const v=d.options.component??i.options.defaultComponent;return v?a.jsx(v,{},o):a.jsx(F2,{})},[o,d.options.component,i.options.defaultComponent]);if(r._displayPending)throw(y=i.getMatch(r.id))==null?void 0:y._nonReactive.displayPendingPromise;if(r._forcePending)throw(g=i.getMatch(r.id))==null?void 0:g._nonReactive.minPendingPromise;if(r.status==="pending"){const v=d.options.pendingMinMs??i.options.defaultPendingMinMs;if(v){const w=i.getMatch(r.id);if(w&&!w._nonReactive.minPendingPromise){const N=ad();w._nonReactive.minPendingPromise=N,setTimeout(()=>{N.resolve(),w._nonReactive.minPendingPromise=void 0},v)}}throw(b=i.getMatch(r.id))==null?void 0:b._nonReactive.loadPromise}if(r.status==="notFound")return po(Ca(r.error)),$2(i,d,r.error);if(r.status==="redirected")throw po(Wa(r.error)),(p=i.getMatch(r.id))==null?void 0:p._nonReactive.loadPromise;if(r.status==="error")throw r.error;return m}),F2=_.memo(function(){const t=xi(),i=_.useContext(Gp),r=ai({select:g=>{var b;return(b=g.matches.find(p=>p.id===i))==null?void 0:b.routeId}}),o=t.routesById[r],u=ai({select:g=>{const b=g.matches.find(p=>p.id===i);return po(b),b.globalNotFound}}),d=ai({select:g=>{var p;const b=g.matches;return(p=b[b.findIndex(v=>v.id===i)+1])==null?void 0:p.id}}),m=t.options.defaultPendingComponent?a.jsx(t.options.defaultPendingComponent,{}):null;if(u)return $2(t,o,void 0);if(!d)return null;const y=a.jsx(H2,{matchId:d});return r===xc?a.jsx(_.Suspense,{fallback:m,children:y}):y});function $7(){const e=xi(),t=_.useRef({router:e,mounted:!1}),[i,r]=_.useState(!1),{hasPendingMatches:o,isLoading:u}=ai({select:p=>({isLoading:p.isLoading,hasPendingMatches:p.matches.some(v=>v.status==="pending")}),structuralSharing:!0}),d=w1(u),m=u||i||o,y=w1(m),g=u||o,b=w1(g);return e.startTransition=p=>{r(!0),_.startTransition(()=>{p(),r(!1)})},_.useEffect(()=>{const p=e.history.subscribe(e.load),v=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return fo(e.latestLocation.publicHref)!==fo(v.publicHref)&&e.commitLocation({...v,replace:!0}),()=>{p()}},[e,e.history]),Dm(()=>{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(v){console.error(v)}})()},[e]),Dm(()=>{d&&!u&&e.emit({type:"onLoad",...jc(e.state)})},[d,e,u]),Dm(()=>{b&&!g&&e.emit({type:"onBeforeRouteMount",...jc(e.state)})},[g,b,e]),Dm(()=>{if(y&&!m){const p=jc(e.state);e.emit({type:"onResolved",...p}),e.__store.setState(v=>({...v,status:"idle",resolvedLocation:v.location})),p.hrefChanged&&wj(e)}},[m,y,e]),null}function H7(){const e=xi(),t=e.routesById[xc].options.pendingComponent??e.options.defaultPendingComponent,i=t?a.jsx(t,{}):null,r=a.jsxs(typeof document<"u"&&e.ssr?Lu:_.Suspense,{fallback:i,children:[a.jsx($7,{}),a.jsx(F7,{})]});return e.options.InnerWrap?a.jsx(e.options.InnerWrap,{children:r}):r}function F7(){const e=xi(),t=ai({select:o=>{var u;return(u=o.matches[0])==null?void 0:u.id}}),i=ai({select:o=>o.loadedAt}),r=t?a.jsx(H2,{matchId:t}):null;return a.jsx(Gp.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:a.jsx(C0,{getResetKey:()=>i,errorComponent:T0,onCatch:void 0,children:r})})}var q7=e=>new W7(e),W7=class extends i7{constructor(e){super(e)}};typeof globalThis<"u"?(globalThis.createFileRoute=Rb,globalThis.createLazyFileRoute=Db):typeof window<"u"&&(window.createFileRoute=Rb,window.createLazyFileRoute=Db);function K7({router:e,children:t,...i}){Object.keys(i).length>0&&e.update({...e.options,...i,context:{...e.options.context,...i.context}});const r=a.jsx(B2.Provider,{value:e,children:t});return e.options.Wrap?a.jsx(e.options.Wrap,{children:r}):r}function Q7({router:e,...t}){return a.jsx(K7,{router:e,...t,children:a.jsx(H7,{})})}/*! Capacitor: https://capacitorjs.com/ - MIT License */var id;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(id||(id={}));class O1 extends Error{constructor(t,i,r){super(t),this.message=t,this.code=i,this.data=r}}const G7=e=>{var t,i;return e!=null&&e.androidBridge?"android":!((i=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||i===void 0)&&i.bridge?"ios":"web"},Y7=e=>{const t=e.CapacitorCustomPlatform||null,i=e.Capacitor||{},r=i.Plugins=i.Plugins||{},o=()=>t!==null?t.name:G7(e),u=()=>o()!=="web",d=p=>{const v=g.get(p);return!!(v!=null&&v.platforms.has(o())||m(p))},m=p=>{var v;return(v=i.PluginHeaders)===null||v===void 0?void 0:v.find(w=>w.name===p)},y=p=>e.console.error(p),g=new Map,b=(p,v={})=>{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 M=async()=>(!T&&N in v?T=typeof v[N]=="function"?T=await v[N]():T=v[N]:t!==null&&!T&&"web"in v&&(T=typeof v.web=="function"?T=await v.web():T=v.web),T),P=(F,B)=>{var G,Z;if(j){const ae=j==null?void 0:j.methods.find(he=>B===he.name);if(ae)return ae.rtype==="promise"?he=>i.nativePromise(p,B.toString(),he):(he,ne)=>i.nativeCallback(p,B.toString(),he,ne);if(F)return(G=F[B])===null||G===void 0?void 0:G.bind(F)}else{if(F)return(Z=F[B])===null||Z===void 0?void 0:Z.bind(F);throw new O1(`"${p}" plugin is not implemented on ${N}`,id.Unimplemented)}},I=F=>{let B;const G=(...Z)=>{const ae=M().then(he=>{const ne=P(he,F);if(ne){const Ce=ne(...Z);return B=Ce==null?void 0:Ce.remove,Ce}else throw new O1(`"${p}.${F}()" is not implemented on ${N}`,id.Unimplemented)});return F==="addListener"&&(ae.remove=async()=>B()),ae};return G.toString=()=>`${F.toString()}() { [capacitor code] }`,Object.defineProperty(G,"name",{value:F,writable:!1,configurable:!1}),G},k=I("addListener"),O=I("removeListener"),Q=(F,B)=>{const G=k({eventName:F},B),Z=async()=>{const he=await G;O({eventName:F,callbackId:he},B)},ae=new Promise(he=>G.then(()=>he({remove:Z})));return ae.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await Z()},ae},J=new Proxy({},{get(F,B){switch(B){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return j?Q:k;case"removeListener":return O;default:return I(B)}}});return r[p]=J,g.set(p,{name:p,proxy:J,platforms:new Set([...Object.keys(v),...j?[N]:[]])}),J};return i.convertFileSrc||(i.convertFileSrc=p=>p),i.getPlatform=o,i.handleError=y,i.isNativePlatform=u,i.isPluginAvailable=d,i.registerPlugin=b,i.Exception=O1,i.DEBUG=!!i.DEBUG,i.isLoggingEnabled=!!i.isLoggingEnabled,i},V7=e=>e.Capacitor=Y7(e),il=V7(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Ac=il.registerPlugin;class q2{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,i){let r=!1;this.listeners[t]||(this.listeners[t]=[],r=!0),this.listeners[t].push(i);const u=this.windowListeners[t];u&&!u.registered&&this.addWindowListener(u),r&&this.sendRetainedArgumentsForEvent(t);const d=async()=>this.removeListener(t,i);return Promise.resolve({remove:d})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,i,r){const o=this.listeners[t];if(!o){if(r){let u=this.retainedEventArguments[t];u||(u=[]),u.push(i),this.retainedEventArguments[t]=u}return}o.forEach(u=>u(i))}hasListeners(t){var i;return!!(!((i=this.listeners[t])===null||i===void 0)&&i.length)}registerWindowListener(t,i){this.windowListeners[i]={registered:!1,windowEventName:t,pluginEventName:i,handler:r=>{this.notifyListeners(i,r)}}}unimplemented(t="not implemented"){return new il.Exception(t,id.Unimplemented)}unavailable(t="not available"){return new il.Exception(t,id.Unavailable)}async removeListener(t,i){const r=this.listeners[t];if(!r)return;const o=r.indexOf(i);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 i=this.retainedEventArguments[t];i&&(delete this.retainedEventArguments[t],i.forEach(r=>{this.notifyListeners(t,r)}))}}const Lb=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Pb=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class X7 extends q2{async getCookies(){const t=document.cookie,i={};return t.split(";").forEach(r=>{if(r.length<=0)return;let[o,u]=r.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");o=Pb(o).trim(),u=Pb(u).trim(),i[o]=u}),i}async setCookie(t){try{const i=Lb(t.key),r=Lb(t.value),o=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",u=(t.path||"/").replace("path=",""),d=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${i}=${r||""}${o}; path=${u}; ${d};`}catch(i){return Promise.reject(i)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(i){return Promise.reject(i)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const i of t)document.cookie=i.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)}}}Ac("CapacitorCookies",{web:()=>new X7});const Z7=async e=>new Promise((t,i)=>{const r=new FileReader;r.onload=()=>{const o=r.result;t(o.indexOf(",")>=0?o.split(",")[1]:o)},r.onerror=o=>i(o),r.readAsDataURL(e)}),J7=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(o=>o.toLocaleLowerCase()).reduce((o,u,d)=>(o[u]=e[t[d]],o),{})},ew=(e,t=!0)=>e?Object.entries(e).reduce((r,o)=>{const[u,d]=o;let m,y;return Array.isArray(d)?(y="",d.forEach(g=>{m=t?encodeURIComponent(g):g,y+=`${u}=${m}&`}),y.slice(0,-1)):(m=t?encodeURIComponent(d):d,y=`${u}=${m}`),`${r}&${y}`},"").substr(1):null,tw=(e,t={})=>{const i=Object.assign({method:e.method||"GET",headers:e.headers},t),o=J7(e.headers)["content-type"]||"";if(typeof e.data=="string")i.body=e.data;else if(o.includes("application/x-www-form-urlencoded")){const u=new URLSearchParams;for(const[d,m]of Object.entries(e.data||{}))u.set(d,m);i.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]);i.body=u;const d=new Headers(i.headers);d.delete("content-type"),i.headers=d}else(o.includes("application/json")||typeof e.data=="object")&&(i.body=JSON.stringify(e.data));return i};class nw extends q2{async request(t){const i=tw(t,t.webFetchExtra),r=ew(t.params,t.shouldEncodeUrlParams),o=r?`${t.url}?${r}`:t.url,u=await fetch(o,i),d=u.headers.get("content-type")||"";let{responseType:m="text"}=u.ok?t:{};d.includes("application/json")&&(m="json");let y,g;switch(m){case"arraybuffer":case"blob":g=await u.blob(),y=await Z7(g);break;case"json":y=await u.json();break;case"document":case"text":default:y=await u.text()}const b={};return u.headers.forEach((p,v)=>{b[v]=p}),{data:y,headers:b,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"}))}}Ac("CapacitorHttp",{web:()=>new nw});var D_;(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"})(D_||(D_={}));var Ub;(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"})(Ub||(Ub={}));var O_;(function(e){e[e["640x480"]=0]="640x480",e[e["1280x720"]=1]="1280x720",e[e["1920x1080"]=2]="1920x1080",e[e["3840x2160"]=3]="3840x2160"})(O_||(O_={}));var L_;(function(e){e.Front="FRONT",e.Back="BACK"})(L_||(L_={}));var zb;(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"})(zb||(zb={}));var Bb;(function(e){e[e.HOME=0]="HOME",e[e.UNKNOWN=1]="UNKNOWN",e[e.WORK=2]="WORK"})(Bb||(Bb={}));var $b;(function(e){e[e.HOME=0]="HOME",e[e.UNKNOWN=1]="UNKNOWN",e[e.WORK=2]="WORK"})($b||($b={}));var Hb;(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"})(Hb||(Hb={}));var Fb;(function(e){e[e.OPEN=1]="OPEN",e[e.WEP=2]="WEP",e[e.WPA=3]="WPA"})(Fb||(Fb={}));const Jo=Ac("BarcodeScanner",{web:()=>cl(()=>import("./web-BCkw8FnT.js"),[]).then(e=>new e.BarcodeScannerWeb)}),sw=8e3,xp=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";const i=t.replace(/\/+$/,"");try{const r=new URL(i);return r.pathname==="/health"&&(r.pathname="",r.search="",r.hash=""),r.toString().replace(/\/+$/,"")}catch{return i.replace(/\/health$/i,"")}},W2=e=>new Error(`连接探测超时(${e} ms),请确认手机能直接访问该 Hub 地址。`),aw=(e,t)=>{if(!(e instanceof Error))return"连接失败";const i=e.message.trim();return e.name==="AbortError"||e.name==="TimeoutError"||/aborted/i.test(i)?W2(t).message:i||"连接失败"},P_=async(e,t)=>{const i=xp(e),r=new Date().toISOString();if(!i)return{url:"",healthOk:!1,latencyMs:null,checkedAt:r,error:"地址为空"};const o=sw,u=`${i}/health`,d=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),m=new AbortController,y=window.setTimeout(()=>m.abort(W2(o)),o);try{const g=await fetch(u,{cache:"no-store",signal:m.signal}),b=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();return{url:i,healthOk:g.ok,latencyMs:b-d,checkedAt:r,error:g.ok?null:`HTTP ${g.status}`}}catch(g){return{url:i,healthOk:!1,latencyMs:null,checkedAt:r,error:aw(g,o)}}finally{clearTimeout(y)}},iw=()=>{var e;try{const t=(e=il.getPlatform)==null?void 0:e.call(il);if(t==="android"||t==="ios")return t}catch{}return"web"},rd=()=>iw(),K2=()=>{var e;try{return((e=il.isNativePlatform)==null?void 0:e.call(il))===!0}catch{return!1}},Yp=()=>rd()==="android"&&K2(),rw=()=>rd()==="ios"&&K2(),ba=()=>Yp()||rw(),qb=e=>typeof e!="number"||!Number.isFinite(e)?"未测得":`${Math.max(0,Math.round(e))} ms`,lw=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},L1=e=>{var r;const t=e.trim();if(!t)return"";try{const o=new URL(t);if(o.protocol==="http:"||o.protocol==="https:")return xp(o.toString())}catch{}const i=(r=t.match(/https?:\/\/[^\s]+/i))==null?void 0:r[0];return i?xp(i):""},ow=e=>{var i;const t=[e.rawValue,e.displayValue,(i=e.urlBookmark)==null?void 0:i.url];for(const r of t){const o=(r==null?void 0:r.trim())??"";if(o)try{const u=new URL(o);return u.protocol==="panda:"&&u.searchParams.get("url")?L1(u.searchParams.get("url")??""):L1(u.toString())}catch{return L1(o)}}return""},cw=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"M8 9.25h8M8 12h8M8 14.75h5"})]}),uw=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M6 6 18 18M18 6 6 18"})}),Q2=({title:e,description:t,currentHubUrl:i,initialHubUrl:r,hint:o,saveLabel:u,savingLabel:d,saveDescription:m,saveSuccessMessage:y,onSaveSuccess:g})=>{const[b,p]=_.useState(r),[v,w]=_.useState({loading:!1,result:null}),[N,j]=_.useState({saving:!1}),[T,M]=_.useState(null),[P,I]=_.useState({active:!1,starting:!1}),k=_.useRef([]),O=xp(b),Q=ba();_.useEffect(()=>{p(r)},[r]),_.useEffect(()=>{if(!(typeof document>"u"))return document.documentElement.classList.toggle("hub-scanner-active",P.active),document.body.classList.toggle("hub-scanner-active",P.active),()=>{document.documentElement.classList.remove("hub-scanner-active"),document.body.classList.remove("hub-scanner-active")}},[P.active]),_.useEffect(()=>()=>{(async()=>(await Promise.all(k.current.map(he=>he.remove().catch(()=>{}))),k.current=[],await Jo.stopScan().catch(()=>{})))()},[]);const J=async()=>{const he=[...k.current];k.current=[],await Promise.all(he.map(ne=>ne.remove().catch(()=>{})))},F=async()=>{I(he=>({...he,active:!1})),await J(),await Jo.stopScan().catch(()=>{})},B=async()=>{if(!O){M({tone:"danger",text:"请先输入可访问的 Hub 地址。"});return}M(null),w({loading:!0,result:null});const he=await P_(O);w({loading:!1,result:he}),M({tone:he.healthOk?"success":"danger",text:he.healthOk?`连接成功,延迟 ${qb(he.latencyMs)}。`:he.error??"连接测试失败。"})},G=async()=>{var he;if(!O){M({tone:"danger",text:"请先输入可访问的 Hub 地址。"});return}M(null),j({saving:!0});try{const ne=((he=v.result)==null?void 0:he.url)===O?v.result:await P_(O);if(w({loading:!1,result:ne}),!ne.healthOk){M({tone:"danger",text:ne.error??"请先确认 Hub 地址可访问,再继续保存。"});return}await g(ne),M({tone:"success",text:y})}catch(ne){M({tone:"danger",text:ne instanceof Error?ne.message:"保存 Hub 地址失败。"})}finally{j({saving:!1})}},Z=async()=>{if(Q){M(null),I({active:!1,starting:!0});try{if(!(await Jo.isSupported()).supported){M({tone:"danger",text:"当前设备不支持扫码填入,请手动输入地址。"});return}const ne=await Jo.requestPermissions();if(ne.camera!=="granted"&&ne.camera!=="limited"){M({tone:"danger",text:"需要相机权限才能扫码,请在系统设置中允许 Panda 使用相机。"});return}const Ce=await Promise.all([Jo.addListener("barcodesScanned",R=>{const X=R.barcodes.map(ow).find(Boolean);if(!X){M({tone:"danger",text:"二维码已识别,但没有拿到可用的 Hub 地址。"}),F();return}p(X),w({loading:!1,result:null}),M({tone:"success",text:"已通过扫码填入地址,可以直接测试或保存。"}),F()}),Jo.addListener("scanError",R=>{M({tone:"danger",text:R.message||"扫码失败,请稍后重试。"}),F()})]);k.current=Ce,I({active:!0,starting:!1}),await Jo.startScan({formats:[D_.QrCode],lensFacing:L_.Back,resolution:O_["1280x720"]})}catch(he){await F(),M({tone:"danger",text:he instanceof Error?he.message:"无法启动扫码,请稍后重试。"})}finally{I(he=>({...he,starting:!1}))}}},ae=P.active&&typeof document<"u"?ra.createPortal(a.jsx("div",{className:"hub-scanner-sheet",role:"dialog","aria-modal":"true","aria-label":"扫描 Hub 地址二维码",children:a.jsxs("div",{className:"hub-scanner-sheet__content",children:[a.jsxs("div",{className:"hub-scanner-sheet__topbar",children:[a.jsx("span",{className:"hub-scanner-sheet__badge",children:"扫码填入"}),a.jsx("button",{type:"button",className:"hub-scanner-sheet__close",onClick:()=>{F()},"aria-label":"关闭扫码",children:a.jsx(uw,{})})]}),a.jsxs("div",{className:"hub-scanner-sheet__frame","aria-hidden":"true",children:[a.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--tl"}),a.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--tr"}),a.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--bl"}),a.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--br"})]}),a.jsxs("div",{className:"hub-scanner-sheet__footer",children:[a.jsx("p",{children:"把电脑端显示的 Hub 二维码放进取景框,识别后会自动填入地址。"}),a.jsx("button",{type:"button",className:"settings-ghost-button hub-scanner-sheet__cancel",onClick:()=>{F()},children:"取消扫码"})]})]})}),document.body):null;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"hub-connection-form",children:[a.jsxs("div",{className:"hub-connection-form__header",children:[a.jsxs("div",{className:"hub-connection-form__copy",children:[a.jsx("h3",{className:"hub-connection-form__title",children:e}),a.jsx("p",{className:"hub-connection-form__description",children:t})]}),i?a.jsxs("div",{className:"hub-connection-form__current",children:[a.jsx("span",{children:"当前"}),a.jsx("strong",{children:i})]}):null]}),a.jsxs("label",{className:"hub-connection-form__field",children:[a.jsx("span",{className:"hub-connection-form__label",children:"Hub 地址"}),a.jsxs("span",{className:"hub-connection-form__input-shell",children:[a.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:b,onChange:he=>{p(he.target.value),w({loading:!1,result:null}),M(null)}}),Q?a.jsxs("button",{type:"button",className:"hub-connection-form__scan",onClick:()=>{Z()},disabled:P.starting||N.saving||v.loading,"aria-label":"扫码填入 Hub 地址",children:[a.jsx(cw,{}),a.jsx("span",{children:P.starting?"启动中":"扫码"})]}):null]})]}),a.jsx("p",{className:"hub-connection-form__hint",children:o}),a.jsxs("div",{className:"hub-connection-form__actions",children:[a.jsxs("button",{type:"button",className:"settings-action hub-connection-form__save",onClick:()=>{G()},disabled:!O||N.saving||P.starting,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:N.saving?d:u}),a.jsx("span",{children:m})]}),a.jsx("span",{className:"settings-action__state",children:N.saving?"处理中…":"→"})]}),a.jsx("button",{type:"button",className:"settings-ghost-button hub-connection-form__test",onClick:()=>{B()},disabled:!O||v.loading||N.saving||P.starting,children:v.loading?"测试中…":"测试连接"})]}),v.result?a.jsxs("div",{className:"hub-connection-form__probe",children:[a.jsxs("div",{className:"hub-connection-form__probe-item",children:[a.jsx("span",{children:"探测地址"}),a.jsx("strong",{children:v.result.url})]}),a.jsxs("div",{className:"hub-connection-form__probe-item",children:[a.jsx("span",{children:"连通结果"}),a.jsx("strong",{className:v.result.healthOk?"is-ok":"is-danger",children:v.result.healthOk?"Hub 在线":v.result.error??"无法连接"})]}),a.jsxs("div",{className:"hub-connection-form__probe-item",children:[a.jsx("span",{children:"延迟"}),a.jsx("strong",{children:qb(v.result.latencyMs)})]}),a.jsxs("div",{className:"hub-connection-form__probe-item",children:[a.jsx("span",{children:"最近探测"}),a.jsx("strong",{children:lw(v.result.checkedAt)})]})]}):null,T?a.jsx("p",{className:`hub-connection-form__notice is-${T.tone}`,children:T.text}):null]}),ae]})};var Wb;(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"})(Wb||(Wb={}));const wh=Ac("LocalNotifications",{web:()=>cl(()=>import("./web-CI5VgZbX.js"),[]).then(e=>new e.LocalNotificationsWeb)});var Rn;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function i(o){throw new Error}e.assertNever=i,e.arrayToEnum=o=>{const u={};for(const d of o)u[d]=d;return u},e.getValidEnumValues=o=>{const u=e.objectKeys(o).filter(m=>typeof o[o[m]]!="number"),d={};for(const m of u)d[m]=o[m];return e.objectValues(d)},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 d in o)Object.prototype.hasOwnProperty.call(o,d)&&u.push(d);return u},e.find=(o,u)=>{for(const d of o)if(u(d))return d},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,u=" | "){return o.map(d=>typeof d=="string"?`'${d}'`:d).join(u)}e.joinValues=r,e.jsonStringifyReplacer=(o,u)=>typeof u=="bigint"?u.toString():u})(Rn||(Rn={}));var Kb;(function(e){e.mergeShapes=(t,i)=>({...t,...i})})(Kb||(Kb={}));const mt=Rn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xl=e=>{switch(typeof e){case"undefined":return mt.undefined;case"string":return mt.string;case"number":return Number.isNaN(e)?mt.nan:mt.number;case"boolean":return mt.boolean;case"function":return mt.function;case"bigint":return mt.bigint;case"symbol":return mt.symbol;case"object":return Array.isArray(e)?mt.array:e===null?mt.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?mt.promise:typeof Map<"u"&&e instanceof Map?mt.map:typeof Set<"u"&&e instanceof Set?mt.set:typeof Date<"u"&&e instanceof Date?mt.date:mt.object;default:return mt.unknown}},We=Rn.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 ol extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const i=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,i):this.__proto__=i,this.name="ZodError",this.issues=t}format(t){const i=t||function(u){return u.message},r={_errors:[]},o=u=>{for(const d of u.issues)if(d.code==="invalid_union")d.unionErrors.map(o);else if(d.code==="invalid_return_type")o(d.returnTypeError);else if(d.code==="invalid_arguments")o(d.argumentsError);else if(d.path.length===0)r._errors.push(i(d));else{let m=r,y=0;for(;y<d.path.length;){const g=d.path[y];y===d.path.length-1?(m[g]=m[g]||{_errors:[]},m[g]._errors.push(i(d))):m[g]=m[g]||{_errors:[]},m=m[g],y++}}};return o(this),r}static assert(t){if(!(t instanceof ol))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Rn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=i=>i.message){const i={},r=[];for(const o of this.issues)if(o.path.length>0){const u=o.path[0];i[u]=i[u]||[],i[u].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:i}}get formErrors(){return this.flatten()}}ol.create=e=>new ol(e);const U_=(e,t)=>{let i;switch(e.code){case We.invalid_type:e.received===mt.undefined?i="Required":i=`Expected ${e.expected}, received ${e.received}`;break;case We.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(e.expected,Rn.jsonStringifyReplacer)}`;break;case We.unrecognized_keys:i=`Unrecognized key(s) in object: ${Rn.joinValues(e.keys,", ")}`;break;case We.invalid_union:i="Invalid input";break;case We.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${Rn.joinValues(e.options)}`;break;case We.invalid_enum_value:i=`Invalid enum value. Expected ${Rn.joinValues(e.options)}, received '${e.received}'`;break;case We.invalid_arguments:i="Invalid function arguments";break;case We.invalid_return_type:i="Invalid function return type";break;case We.invalid_date:i="Invalid date";break;case We.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(i=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(i=`${i} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?i=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?i=`Invalid input: must end with "${e.validation.endsWith}"`:Rn.assertNever(e.validation):e.validation!=="regex"?i=`Invalid ${e.validation}`:i="Invalid";break;case We.too_small:e.type==="array"?i=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?i=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?i=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?i=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?i=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:i="Invalid input";break;case We.too_big:e.type==="array"?i=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?i=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?i=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?i=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?i=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:i="Invalid input";break;case We.custom:i="Invalid input";break;case We.invalid_intersection_types:i="Intersection results could not be merged";break;case We.not_multiple_of:i=`Number must be a multiple of ${e.multipleOf}`;break;case We.not_finite:i="Number must be finite";break;default:i=t.defaultError,Rn.assertNever(e)}return{message:i}};let dw=U_;function fw(){return dw}const hw=e=>{const{data:t,path:i,errorMaps:r,issueData:o}=e,u=[...i,...o.path||[]],d={...o,path:u};if(o.message!==void 0)return{...o,path:u,message:o.message};let m="";const y=r.filter(g=>!!g).slice().reverse();for(const g of y)m=g(d,{data:t,defaultError:m}).message;return{...o,path:u,message:m}};function it(e,t){const i=fw(),r=hw({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,i,i===U_?void 0:U_].filter(o=>!!o)});e.common.issues.push(r)}class Ta{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,i){const r=[];for(const o of i){if(o.status==="aborted")return Ht;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,i){const r=[];for(const o of i){const u=await o.key,d=await o.value;r.push({key:u,value:d})}return Ta.mergeObjectSync(t,r)}static mergeObjectSync(t,i){const r={};for(const o of i){const{key:u,value:d}=o;if(u.status==="aborted"||d.status==="aborted")return Ht;u.status==="dirty"&&t.dirty(),d.status==="dirty"&&t.dirty(),u.value!=="__proto__"&&(typeof d.value<"u"||o.alwaysSet)&&(r[u.value]=d.value)}return{status:t.value,value:r}}}const Ht=Object.freeze({status:"aborted"}),Bf=e=>({status:"dirty",value:e}),Si=e=>({status:"valid",value:e}),Qb=e=>e.status==="aborted",Gb=e=>e.status==="dirty",ld=e=>e.status==="valid",Sp=e=>typeof Promise<"u"&&e instanceof Promise;var yt;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(yt||(yt={}));class mr{constructor(t,i,r,o){this._cachedPath=[],this.parent=t,this.data=i,this._path=r,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 Yb=(e,t)=>{if(ld(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 i=new ol(e.common.issues);return this._error=i,this._error}}};function Vt(e){if(!e)return{};const{errorMap:t,invalid_type_error:i,required_error:r,description:o}=e;if(t&&(i||r))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:(d,m)=>{const{message:y}=e;return d.code==="invalid_enum_value"?{message:y??m.defaultError}:typeof m.data>"u"?{message:y??r??m.defaultError}:d.code!=="invalid_type"?{message:m.defaultError}:{message:y??i??m.defaultError}},description:o}}class xn{get description(){return this._def.description}_getType(t){return Xl(t.data)}_getOrReturnCtx(t,i){return i||{common:t.parent.common,data:t.data,parsedType:Xl(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:Xl(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const i=this._parse(t);if(Sp(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(t){const i=this._parse(t);return Promise.resolve(i)}parse(t,i){const r=this.safeParse(t,i);if(r.success)return r.data;throw r.error}safeParse(t,i){const r={common:{issues:[],async:(i==null?void 0:i.async)??!1,contextualErrorMap:i==null?void 0:i.errorMap},path:(i==null?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xl(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Yb(r,o)}"~validate"(t){var r,o;const i={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xl(t)};if(!this["~standard"].async)try{const u=this._parseSync({data:t,path:[],parent:i});return ld(u)?{value:u.value}:{issues:i.common.issues}}catch(u){(o=(r=u==null?void 0:u.message)==null?void 0:r.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),i.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:i}).then(u=>ld(u)?{value:u.value}:{issues:i.common.issues})}async parseAsync(t,i){const r=await this.safeParseAsync(t,i);if(r.success)return r.data;throw r.error}async safeParseAsync(t,i){const r={common:{issues:[],contextualErrorMap:i==null?void 0:i.errorMap,async:!0},path:(i==null?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xl(t)},o=this._parse({data:t,path:r.path,parent:r}),u=await(Sp(o)?o:Promise.resolve(o));return Yb(r,u)}refine(t,i){const r=o=>typeof i=="string"||typeof i>"u"?{message:i}:typeof i=="function"?i(o):i;return this._refinement((o,u)=>{const d=t(o),m=()=>u.addIssue({code:We.custom,...r(o)});return typeof Promise<"u"&&d instanceof Promise?d.then(y=>y?!0:(m(),!1)):d?!0:(m(),!1)})}refinement(t,i){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof i=="function"?i(r,o):i),!1))}_refinement(t){return new ud({schema:this,typeName:Ut.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:i=>this["~validate"](i)}}optional(){return mo.create(this,this._def)}nullable(){return dd.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return hr.create(this)}promise(){return Ep.create(this,this._def)}or(t){return wp.create([this,t],this._def)}and(t){return Np.create(this,t,this._def)}transform(t){return new ud({...Vt(this._def),schema:this,typeName:Ut.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const i=typeof t=="function"?t:()=>t;return new F_({...Vt(this._def),innerType:this,defaultValue:i,typeName:Ut.ZodDefault})}brand(){return new Lw({typeName:Ut.ZodBranded,type:this,...Vt(this._def)})}catch(t){const i=typeof t=="function"?t:()=>t;return new q_({...Vt(this._def),innerType:this,catchValue:i,typeName:Ut.ZodCatch})}describe(t){const i=this.constructor;return new i({...this._def,description:t})}pipe(t){return D0.create(this,t)}readonly(){return W_.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const mw=/^c[^\s-]{8,}$/i,pw=/^[0-9a-z]+$/,gw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_w=/^[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,yw=/^[a-z0-9_-]{21}$/i,vw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bw=/^[-+]?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)?)??$/,xw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Sw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let P1;const jw=/^(?:(?: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])$/,ww=/^(?:(?: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])$/,Nw=/^(([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]))$/,kw=/^(([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])$/,Ew=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Cw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,G2="((\\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])))",Tw=new RegExp(`^${G2}$`);function Y2(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const i=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${i}`}function Mw(e){return new RegExp(`^${Y2(e)}$`)}function Rw(e){let t=`${G2}T${Y2(e)}`;const i=[];return i.push(e.local?"Z?":"Z"),e.offset&&i.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${i.join("|")})`,new RegExp(`^${t}$`)}function Aw(e,t){return!!((t==="v4"||!t)&&jw.test(e)||(t==="v6"||!t)&&Nw.test(e))}function Iw(e,t){if(!vw.test(e))return!1;try{const[i]=e.split(".");if(!i)return!1;const r=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),o=JSON.parse(atob(r));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 Dw(e,t){return!!((t==="v4"||!t)&&ww.test(e)||(t==="v6"||!t)&&kw.test(e))}class nl extends xn{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==mt.string){const u=this._getOrReturnCtx(t);return it(u,{code:We.invalid_type,expected:mt.string,received:u.parsedType}),Ht}const r=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),it(o,{code:We.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),r.dirty());else if(u.kind==="max")t.data.length>u.value&&(o=this._getOrReturnCtx(t,o),it(o,{code:We.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),r.dirty());else if(u.kind==="length"){const d=t.data.length>u.value,m=t.data.length<u.value;(d||m)&&(o=this._getOrReturnCtx(t,o),d?it(o,{code:We.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}):m&&it(o,{code:We.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}),r.dirty())}else if(u.kind==="email")xw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"email",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="emoji")P1||(P1=new RegExp(Sw,"u")),P1.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"emoji",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="uuid")_w.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"uuid",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="nanoid")yw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"nanoid",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="cuid")mw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"cuid",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="cuid2")pw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"cuid2",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="ulid")gw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"ulid",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),it(o,{validation:"url",code:We.invalid_string,message:u.message}),r.dirty()}else u.kind==="regex"?(u.regex.lastIndex=0,u.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"regex",code:We.invalid_string,message:u.message}),r.dirty())):u.kind==="trim"?t.data=t.data.trim():u.kind==="includes"?t.data.includes(u.value,u.position)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:{includes:u.value,position:u.position},message:u.message}),r.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),it(o,{code:We.invalid_string,validation:{startsWith:u.value},message:u.message}),r.dirty()):u.kind==="endsWith"?t.data.endsWith(u.value)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:{endsWith:u.value},message:u.message}),r.dirty()):u.kind==="datetime"?Rw(u).test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:"datetime",message:u.message}),r.dirty()):u.kind==="date"?Tw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:"date",message:u.message}),r.dirty()):u.kind==="time"?Mw(u).test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:"time",message:u.message}),r.dirty()):u.kind==="duration"?bw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"duration",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="ip"?Aw(t.data,u.version)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"ip",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="jwt"?Iw(t.data,u.alg)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"jwt",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="cidr"?Dw(t.data,u.version)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"cidr",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="base64"?Ew.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"base64",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="base64url"?Cw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"base64url",code:We.invalid_string,message:u.message}),r.dirty()):Rn.assertNever(u);return{status:r.value,value:t.data}}_regex(t,i,r){return this.refinement(o=>t.test(o),{validation:i,code:We.invalid_string,...yt.errToObj(r)})}_addCheck(t){return new nl({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...yt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...yt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...yt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...yt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...yt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...yt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...yt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...yt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...yt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...yt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...yt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...yt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...yt.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,...yt.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,...yt.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...yt.errToObj(t)})}regex(t,i){return this._addCheck({kind:"regex",regex:t,...yt.errToObj(i)})}includes(t,i){return this._addCheck({kind:"includes",value:t,position:i==null?void 0:i.position,...yt.errToObj(i==null?void 0:i.message)})}startsWith(t,i){return this._addCheck({kind:"startsWith",value:t,...yt.errToObj(i)})}endsWith(t,i){return this._addCheck({kind:"endsWith",value:t,...yt.errToObj(i)})}min(t,i){return this._addCheck({kind:"min",value:t,...yt.errToObj(i)})}max(t,i){return this._addCheck({kind:"max",value:t,...yt.errToObj(i)})}length(t,i){return this._addCheck({kind:"length",value:t,...yt.errToObj(i)})}nonempty(t){return this.min(1,yt.errToObj(t))}trim(){return new nl({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new nl({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new nl({...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 i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t}get maxLength(){let t=null;for(const i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t}}nl.create=e=>new nl({checks:[],typeName:Ut.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Vt(e)});function Ow(e,t){const i=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=i>r?i:r,u=Number.parseInt(e.toFixed(o).replace(".","")),d=Number.parseInt(t.toFixed(o).replace(".",""));return u%d/10**o}class od extends xn{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)!==mt.number){const u=this._getOrReturnCtx(t);return it(u,{code:We.invalid_type,expected:mt.number,received:u.parsedType}),Ht}let r;const o=new Ta;for(const u of this._def.checks)u.kind==="int"?Rn.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),it(r,{code:We.invalid_type,expected:"integer",received:"float",message:u.message}),o.dirty()):u.kind==="min"?(u.inclusive?t.data<u.value:t.data<=u.value)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.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)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.too_big,maximum:u.value,type:"number",inclusive:u.inclusive,exact:!1,message:u.message}),o.dirty()):u.kind==="multipleOf"?Ow(t.data,u.value)!==0&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.not_multiple_of,multipleOf:u.value,message:u.message}),o.dirty()):u.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),it(r,{code:We.not_finite,message:u.message}),o.dirty()):Rn.assertNever(u);return{status:o.value,value:t.data}}gte(t,i){return this.setLimit("min",t,!0,yt.toString(i))}gt(t,i){return this.setLimit("min",t,!1,yt.toString(i))}lte(t,i){return this.setLimit("max",t,!0,yt.toString(i))}lt(t,i){return this.setLimit("max",t,!1,yt.toString(i))}setLimit(t,i,r,o){return new od({...this._def,checks:[...this._def.checks,{kind:t,value:i,inclusive:r,message:yt.toString(o)}]})}_addCheck(t){return new od({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:yt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:yt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:yt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:yt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:yt.toString(t)})}multipleOf(t,i){return this._addCheck({kind:"multipleOf",value:t,message:yt.toString(i)})}finite(t){return this._addCheck({kind:"finite",message:yt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:yt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:yt.toString(t)})}get minValue(){let t=null;for(const i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t}get maxValue(){let t=null;for(const i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Rn.isInteger(t.value))}get isFinite(){let t=null,i=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(i===null||r.value>i)&&(i=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(i)&&Number.isFinite(t)}}od.create=e=>new od({checks:[],typeName:Ut.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Vt(e)});class ah extends xn{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)!==mt.bigint)return this._getInvalidInput(t);let r;const o=new Ta;for(const u of this._def.checks)u.kind==="min"?(u.inclusive?t.data<u.value:t.data<=u.value)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.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)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.too_big,type:"bigint",maximum:u.value,inclusive:u.inclusive,message:u.message}),o.dirty()):u.kind==="multipleOf"?t.data%u.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.not_multiple_of,multipleOf:u.value,message:u.message}),o.dirty()):Rn.assertNever(u);return{status:o.value,value:t.data}}_getInvalidInput(t){const i=this._getOrReturnCtx(t);return it(i,{code:We.invalid_type,expected:mt.bigint,received:i.parsedType}),Ht}gte(t,i){return this.setLimit("min",t,!0,yt.toString(i))}gt(t,i){return this.setLimit("min",t,!1,yt.toString(i))}lte(t,i){return this.setLimit("max",t,!0,yt.toString(i))}lt(t,i){return this.setLimit("max",t,!1,yt.toString(i))}setLimit(t,i,r,o){return new ah({...this._def,checks:[...this._def.checks,{kind:t,value:i,inclusive:r,message:yt.toString(o)}]})}_addCheck(t){return new ah({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:yt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:yt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:yt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:yt.toString(t)})}multipleOf(t,i){return this._addCheck({kind:"multipleOf",value:t,message:yt.toString(i)})}get minValue(){let t=null;for(const i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t}get maxValue(){let t=null;for(const i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t}}ah.create=e=>new ah({checks:[],typeName:Ut.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Vt(e)});class z_ extends xn{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==mt.boolean){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.boolean,received:r.parsedType}),Ht}return Si(t.data)}}z_.create=e=>new z_({typeName:Ut.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Vt(e)});class jp extends xn{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==mt.date){const u=this._getOrReturnCtx(t);return it(u,{code:We.invalid_type,expected:mt.date,received:u.parsedType}),Ht}if(Number.isNaN(t.data.getTime())){const u=this._getOrReturnCtx(t);return it(u,{code:We.invalid_date}),Ht}const r=new Ta;let o;for(const u of this._def.checks)u.kind==="min"?t.data.getTime()<u.value&&(o=this._getOrReturnCtx(t,o),it(o,{code:We.too_small,message:u.message,inclusive:!0,exact:!1,minimum:u.value,type:"date"}),r.dirty()):u.kind==="max"?t.data.getTime()>u.value&&(o=this._getOrReturnCtx(t,o),it(o,{code:We.too_big,message:u.message,inclusive:!0,exact:!1,maximum:u.value,type:"date"}),r.dirty()):Rn.assertNever(u);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new jp({...this._def,checks:[...this._def.checks,t]})}min(t,i){return this._addCheck({kind:"min",value:t.getTime(),message:yt.toString(i)})}max(t,i){return this._addCheck({kind:"max",value:t.getTime(),message:yt.toString(i)})}get minDate(){let t=null;for(const i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t!=null?new Date(t):null}}jp.create=e=>new jp({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Ut.ZodDate,...Vt(e)});class Vb extends xn{_parse(t){if(this._getType(t)!==mt.symbol){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.symbol,received:r.parsedType}),Ht}return Si(t.data)}}Vb.create=e=>new Vb({typeName:Ut.ZodSymbol,...Vt(e)});class Xb extends xn{_parse(t){if(this._getType(t)!==mt.undefined){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.undefined,received:r.parsedType}),Ht}return Si(t.data)}}Xb.create=e=>new Xb({typeName:Ut.ZodUndefined,...Vt(e)});class Zb extends xn{_parse(t){if(this._getType(t)!==mt.null){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.null,received:r.parsedType}),Ht}return Si(t.data)}}Zb.create=e=>new Zb({typeName:Ut.ZodNull,...Vt(e)});class B_ extends xn{constructor(){super(...arguments),this._any=!0}_parse(t){return Si(t.data)}}B_.create=e=>new B_({typeName:Ut.ZodAny,...Vt(e)});class Jb extends xn{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Si(t.data)}}Jb.create=e=>new Jb({typeName:Ut.ZodUnknown,...Vt(e)});class go extends xn{_parse(t){const i=this._getOrReturnCtx(t);return it(i,{code:We.invalid_type,expected:mt.never,received:i.parsedType}),Ht}}go.create=e=>new go({typeName:Ut.ZodNever,...Vt(e)});class e4 extends xn{_parse(t){if(this._getType(t)!==mt.undefined){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.void,received:r.parsedType}),Ht}return Si(t.data)}}e4.create=e=>new e4({typeName:Ut.ZodVoid,...Vt(e)});class hr extends xn{_parse(t){const{ctx:i,status:r}=this._processInputParams(t),o=this._def;if(i.parsedType!==mt.array)return it(i,{code:We.invalid_type,expected:mt.array,received:i.parsedType}),Ht;if(o.exactLength!==null){const d=i.data.length>o.exactLength.value,m=i.data.length<o.exactLength.value;(d||m)&&(it(i,{code:d?We.too_big:We.too_small,minimum:m?o.exactLength.value:void 0,maximum:d?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&i.data.length<o.minLength.value&&(it(i,{code:We.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&i.data.length>o.maxLength.value&&(it(i,{code:We.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),i.common.async)return Promise.all([...i.data].map((d,m)=>o.type._parseAsync(new mr(i,d,i.path,m)))).then(d=>Ta.mergeArray(r,d));const u=[...i.data].map((d,m)=>o.type._parseSync(new mr(i,d,i.path,m)));return Ta.mergeArray(r,u)}get element(){return this._def.type}min(t,i){return new hr({...this._def,minLength:{value:t,message:yt.toString(i)}})}max(t,i){return new hr({...this._def,maxLength:{value:t,message:yt.toString(i)}})}length(t,i){return new hr({...this._def,exactLength:{value:t,message:yt.toString(i)}})}nonempty(t){return this.min(1,t)}}hr.create=(e,t)=>new hr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ut.ZodArray,...Vt(t)});function Pu(e){if(e instanceof Ds){const t={};for(const i in e.shape){const r=e.shape[i];t[i]=mo.create(Pu(r))}return new Ds({...e._def,shape:()=>t})}else return e instanceof hr?new hr({...e._def,type:Pu(e.element)}):e instanceof mo?mo.create(Pu(e.unwrap())):e instanceof dd?dd.create(Pu(e.unwrap())):e instanceof Ec?Ec.create(e.items.map(t=>Pu(t))):e}class Ds extends xn{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(),i=Rn.objectKeys(t);return this._cached={shape:t,keys:i},this._cached}_parse(t){if(this._getType(t)!==mt.object){const g=this._getOrReturnCtx(t);return it(g,{code:We.invalid_type,expected:mt.object,received:g.parsedType}),Ht}const{status:r,ctx:o}=this._processInputParams(t),{shape:u,keys:d}=this._getCached(),m=[];if(!(this._def.catchall instanceof go&&this._def.unknownKeys==="strip"))for(const g in o.data)d.includes(g)||m.push(g);const y=[];for(const g of d){const b=u[g],p=o.data[g];y.push({key:{status:"valid",value:g},value:b._parse(new mr(o,p,o.path,g)),alwaysSet:g in o.data})}if(this._def.catchall instanceof go){const g=this._def.unknownKeys;if(g==="passthrough")for(const b of m)y.push({key:{status:"valid",value:b},value:{status:"valid",value:o.data[b]}});else if(g==="strict")m.length>0&&(it(o,{code:We.unrecognized_keys,keys:m}),r.dirty());else if(g!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const g=this._def.catchall;for(const b of m){const p=o.data[b];y.push({key:{status:"valid",value:b},value:g._parse(new mr(o,p,o.path,b)),alwaysSet:b in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const g=[];for(const b of y){const p=await b.key,v=await b.value;g.push({key:p,value:v,alwaysSet:b.alwaysSet})}return g}).then(g=>Ta.mergeObjectSync(r,g)):Ta.mergeObjectSync(r,y)}get shape(){return this._def.shape()}strict(t){return yt.errToObj,new Ds({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(i,r)=>{var u,d;const o=((d=(u=this._def).errorMap)==null?void 0:d.call(u,i,r).message)??r.defaultError;return i.code==="unrecognized_keys"?{message:yt.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Ds({...this._def,unknownKeys:"strip"})}passthrough(){return new Ds({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ds({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ds({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ut.ZodObject})}setKey(t,i){return this.augment({[t]:i})}catchall(t){return new Ds({...this._def,catchall:t})}pick(t){const i={};for(const r of Rn.objectKeys(t))t[r]&&this.shape[r]&&(i[r]=this.shape[r]);return new Ds({...this._def,shape:()=>i})}omit(t){const i={};for(const r of Rn.objectKeys(this.shape))t[r]||(i[r]=this.shape[r]);return new Ds({...this._def,shape:()=>i})}deepPartial(){return Pu(this)}partial(t){const i={};for(const r of Rn.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?i[r]=o:i[r]=o.optional()}return new Ds({...this._def,shape:()=>i})}required(t){const i={};for(const r of Rn.objectKeys(this.shape))if(t&&!t[r])i[r]=this.shape[r];else{let u=this.shape[r];for(;u instanceof mo;)u=u._def.innerType;i[r]=u}return new Ds({...this._def,shape:()=>i})}keyof(){return V2(Rn.objectKeys(this.shape))}}Ds.create=(e,t)=>new Ds({shape:()=>e,unknownKeys:"strip",catchall:go.create(),typeName:Ut.ZodObject,...Vt(t)});Ds.strictCreate=(e,t)=>new Ds({shape:()=>e,unknownKeys:"strict",catchall:go.create(),typeName:Ut.ZodObject,...Vt(t)});Ds.lazycreate=(e,t)=>new Ds({shape:e,unknownKeys:"strip",catchall:go.create(),typeName:Ut.ZodObject,...Vt(t)});class wp extends xn{_parse(t){const{ctx:i}=this._processInputParams(t),r=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 i.common.issues.push(...m.ctx.common.issues),m.result;const d=u.map(m=>new ol(m.ctx.common.issues));return it(i,{code:We.invalid_union,unionErrors:d}),Ht}if(i.common.async)return Promise.all(r.map(async u=>{const d={...i,common:{...i.common,issues:[]},parent:null};return{result:await u._parseAsync({data:i.data,path:i.path,parent:d}),ctx:d}})).then(o);{let u;const d=[];for(const y of r){const g={...i,common:{...i.common,issues:[]},parent:null},b=y._parseSync({data:i.data,path:i.path,parent:g});if(b.status==="valid")return b;b.status==="dirty"&&!u&&(u={result:b,ctx:g}),g.common.issues.length&&d.push(g.common.issues)}if(u)return i.common.issues.push(...u.ctx.common.issues),u.result;const m=d.map(y=>new ol(y));return it(i,{code:We.invalid_union,unionErrors:m}),Ht}}get options(){return this._def.options}}wp.create=(e,t)=>new wp({options:e,typeName:Ut.ZodUnion,...Vt(t)});function $_(e,t){const i=Xl(e),r=Xl(t);if(e===t)return{valid:!0,data:e};if(i===mt.object&&r===mt.object){const o=Rn.objectKeys(t),u=Rn.objectKeys(e).filter(m=>o.indexOf(m)!==-1),d={...e,...t};for(const m of u){const y=$_(e[m],t[m]);if(!y.valid)return{valid:!1};d[m]=y.data}return{valid:!0,data:d}}else if(i===mt.array&&r===mt.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let u=0;u<e.length;u++){const d=e[u],m=t[u],y=$_(d,m);if(!y.valid)return{valid:!1};o.push(y.data)}return{valid:!0,data:o}}else return i===mt.date&&r===mt.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Np extends xn{_parse(t){const{status:i,ctx:r}=this._processInputParams(t),o=(u,d)=>{if(Qb(u)||Qb(d))return Ht;const m=$_(u.value,d.value);return m.valid?((Gb(u)||Gb(d))&&i.dirty(),{status:i.value,value:m.data}):(it(r,{code:We.invalid_intersection_types}),Ht)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([u,d])=>o(u,d)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Np.create=(e,t,i)=>new Np({left:e,right:t,typeName:Ut.ZodIntersection,...Vt(i)});class Ec extends xn{_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.parsedType!==mt.array)return it(r,{code:We.invalid_type,expected:mt.array,received:r.parsedType}),Ht;if(r.data.length<this._def.items.length)return it(r,{code:We.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ht;!this._def.rest&&r.data.length>this._def.items.length&&(it(r,{code:We.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());const u=[...r.data].map((d,m)=>{const y=this._def.items[m]||this._def.rest;return y?y._parse(new mr(r,d,r.path,m)):null}).filter(d=>!!d);return r.common.async?Promise.all(u).then(d=>Ta.mergeArray(i,d)):Ta.mergeArray(i,u)}get items(){return this._def.items}rest(t){return new Ec({...this._def,rest:t})}}Ec.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ec({items:e,typeName:Ut.ZodTuple,rest:null,...Vt(t)})};class kp extends xn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.parsedType!==mt.object)return it(r,{code:We.invalid_type,expected:mt.object,received:r.parsedType}),Ht;const o=[],u=this._def.keyType,d=this._def.valueType;for(const m in r.data)o.push({key:u._parse(new mr(r,m,r.path,m)),value:d._parse(new mr(r,r.data[m],r.path,m)),alwaysSet:m in r.data});return r.common.async?Ta.mergeObjectAsync(i,o):Ta.mergeObjectSync(i,o)}get element(){return this._def.valueType}static create(t,i,r){return i instanceof xn?new kp({keyType:t,valueType:i,typeName:Ut.ZodRecord,...Vt(r)}):new kp({keyType:nl.create(),valueType:t,typeName:Ut.ZodRecord,...Vt(i)})}}class t4 extends xn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.parsedType!==mt.map)return it(r,{code:We.invalid_type,expected:mt.map,received:r.parsedType}),Ht;const o=this._def.keyType,u=this._def.valueType,d=[...r.data.entries()].map(([m,y],g)=>({key:o._parse(new mr(r,m,r.path,[g,"key"])),value:u._parse(new mr(r,y,r.path,[g,"value"]))}));if(r.common.async){const m=new Map;return Promise.resolve().then(async()=>{for(const y of d){const g=await y.key,b=await y.value;if(g.status==="aborted"||b.status==="aborted")return Ht;(g.status==="dirty"||b.status==="dirty")&&i.dirty(),m.set(g.value,b.value)}return{status:i.value,value:m}})}else{const m=new Map;for(const y of d){const g=y.key,b=y.value;if(g.status==="aborted"||b.status==="aborted")return Ht;(g.status==="dirty"||b.status==="dirty")&&i.dirty(),m.set(g.value,b.value)}return{status:i.value,value:m}}}}t4.create=(e,t,i)=>new t4({valueType:t,keyType:e,typeName:Ut.ZodMap,...Vt(i)});class ih extends xn{_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.parsedType!==mt.set)return it(r,{code:We.invalid_type,expected:mt.set,received:r.parsedType}),Ht;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(it(r,{code:We.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),i.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(it(r,{code:We.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),i.dirty());const u=this._def.valueType;function d(y){const g=new Set;for(const b of y){if(b.status==="aborted")return Ht;b.status==="dirty"&&i.dirty(),g.add(b.value)}return{status:i.value,value:g}}const m=[...r.data.values()].map((y,g)=>u._parse(new mr(r,y,r.path,g)));return r.common.async?Promise.all(m).then(y=>d(y)):d(m)}min(t,i){return new ih({...this._def,minSize:{value:t,message:yt.toString(i)}})}max(t,i){return new ih({...this._def,maxSize:{value:t,message:yt.toString(i)}})}size(t,i){return this.min(t,i).max(t,i)}nonempty(t){return this.min(1,t)}}ih.create=(e,t)=>new ih({valueType:e,minSize:null,maxSize:null,typeName:Ut.ZodSet,...Vt(t)});class n4 extends xn{get schema(){return this._def.getter()}_parse(t){const{ctx:i}=this._processInputParams(t);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}}n4.create=(e,t)=>new n4({getter:e,typeName:Ut.ZodLazy,...Vt(t)});class H_ extends xn{_parse(t){if(t.data!==this._def.value){const i=this._getOrReturnCtx(t);return it(i,{received:i.data,code:We.invalid_literal,expected:this._def.value}),Ht}return{status:"valid",value:t.data}}get value(){return this._def.value}}H_.create=(e,t)=>new H_({value:e,typeName:Ut.ZodLiteral,...Vt(t)});function V2(e,t){return new cd({values:e,typeName:Ut.ZodEnum,...Vt(t)})}class cd extends xn{_parse(t){if(typeof t.data!="string"){const i=this._getOrReturnCtx(t),r=this._def.values;return it(i,{expected:Rn.joinValues(r),received:i.parsedType,code:We.invalid_type}),Ht}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const i=this._getOrReturnCtx(t),r=this._def.values;return it(i,{received:i.data,code:We.invalid_enum_value,options:r}),Ht}return Si(t.data)}get options(){return this._def.values}get enum(){const t={};for(const i of this._def.values)t[i]=i;return t}get Values(){const t={};for(const i of this._def.values)t[i]=i;return t}get Enum(){const t={};for(const i of this._def.values)t[i]=i;return t}extract(t,i=this._def){return cd.create(t,{...this._def,...i})}exclude(t,i=this._def){return cd.create(this.options.filter(r=>!t.includes(r)),{...this._def,...i})}}cd.create=V2;class s4 extends xn{_parse(t){const i=Rn.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==mt.string&&r.parsedType!==mt.number){const o=Rn.objectValues(i);return it(r,{expected:Rn.joinValues(o),received:r.parsedType,code:We.invalid_type}),Ht}if(this._cache||(this._cache=new Set(Rn.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Rn.objectValues(i);return it(r,{received:r.data,code:We.invalid_enum_value,options:o}),Ht}return Si(t.data)}get enum(){return this._def.values}}s4.create=(e,t)=>new s4({values:e,typeName:Ut.ZodNativeEnum,...Vt(t)});class Ep extends xn{unwrap(){return this._def.type}_parse(t){const{ctx:i}=this._processInputParams(t);if(i.parsedType!==mt.promise&&i.common.async===!1)return it(i,{code:We.invalid_type,expected:mt.promise,received:i.parsedType}),Ht;const r=i.parsedType===mt.promise?i.data:Promise.resolve(i.data);return Si(r.then(o=>this._def.type.parseAsync(o,{path:i.path,errorMap:i.common.contextualErrorMap})))}}Ep.create=(e,t)=>new Ep({type:e,typeName:Ut.ZodPromise,...Vt(t)});class ud extends xn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ut.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:i,ctx:r}=this._processInputParams(t),o=this._def.effect||null,u={addIssue:d=>{it(r,d),d.fatal?i.abort():i.dirty()},get path(){return r.path}};if(u.addIssue=u.addIssue.bind(u),o.type==="preprocess"){const d=o.transform(r.data,u);if(r.common.async)return Promise.resolve(d).then(async m=>{if(i.value==="aborted")return Ht;const y=await this._def.schema._parseAsync({data:m,path:r.path,parent:r});return y.status==="aborted"?Ht:y.status==="dirty"||i.value==="dirty"?Bf(y.value):y});{if(i.value==="aborted")return Ht;const m=this._def.schema._parseSync({data:d,path:r.path,parent:r});return m.status==="aborted"?Ht:m.status==="dirty"||i.value==="dirty"?Bf(m.value):m}}if(o.type==="refinement"){const d=m=>{const y=o.refinement(m,u);if(r.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(r.common.async===!1){const m=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return m.status==="aborted"?Ht:(m.status==="dirty"&&i.dirty(),d(m.value),{status:i.value,value:m.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(m=>m.status==="aborted"?Ht:(m.status==="dirty"&&i.dirty(),d(m.value).then(()=>({status:i.value,value:m.value}))))}if(o.type==="transform")if(r.common.async===!1){const d=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ld(d))return Ht;const m=o.transform(d.value,u);if(m instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:m}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(d=>ld(d)?Promise.resolve(o.transform(d.value,u)).then(m=>({status:i.value,value:m})):Ht);Rn.assertNever(o)}}ud.create=(e,t,i)=>new ud({schema:e,typeName:Ut.ZodEffects,effect:t,...Vt(i)});ud.createWithPreprocess=(e,t,i)=>new ud({schema:t,effect:{type:"preprocess",transform:e},typeName:Ut.ZodEffects,...Vt(i)});class mo extends xn{_parse(t){return this._getType(t)===mt.undefined?Si(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mo.create=(e,t)=>new mo({innerType:e,typeName:Ut.ZodOptional,...Vt(t)});class dd extends xn{_parse(t){return this._getType(t)===mt.null?Si(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}dd.create=(e,t)=>new dd({innerType:e,typeName:Ut.ZodNullable,...Vt(t)});class F_ extends xn{_parse(t){const{ctx:i}=this._processInputParams(t);let r=i.data;return i.parsedType===mt.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:i.path,parent:i})}removeDefault(){return this._def.innerType}}F_.create=(e,t)=>new F_({innerType:e,typeName:Ut.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Vt(t)});class q_ extends xn{_parse(t){const{ctx:i}=this._processInputParams(t),r={...i,common:{...i.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Sp(o)?o.then(u=>({status:"valid",value:u.status==="valid"?u.value:this._def.catchValue({get error(){return new ol(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ol(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}q_.create=(e,t)=>new q_({innerType:e,typeName:Ut.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Vt(t)});class a4 extends xn{_parse(t){if(this._getType(t)!==mt.nan){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.nan,received:r.parsedType}),Ht}return{status:"valid",value:t.data}}}a4.create=e=>new a4({typeName:Ut.ZodNaN,...Vt(e)});class Lw extends xn{_parse(t){const{ctx:i}=this._processInputParams(t),r=i.data;return this._def.type._parse({data:r,path:i.path,parent:i})}unwrap(){return this._def.type}}class D0 extends xn{_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const u=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?Ht:u.status==="dirty"?(i.dirty(),Bf(u.value)):this._def.out._parseAsync({data:u.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ht:o.status==="dirty"?(i.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,i){return new D0({in:t,out:i,typeName:Ut.ZodPipeline})}}class W_ extends xn{_parse(t){const i=this._def.innerType._parse(t),r=o=>(ld(o)&&(o.value=Object.freeze(o.value)),o);return Sp(i)?i.then(o=>r(o)):r(i)}unwrap(){return this._def.innerType}}W_.create=(e,t)=>new W_({innerType:e,typeName:Ut.ZodReadonly,...Vt(t)});var Ut;(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"})(Ut||(Ut={}));const E=nl.create,Ve=od.create,It=z_.create,Pw=B_.create;go.create;const nt=hr.create,Te=Ds.create;wp.create;Np.create;Ec.create;const Cp=kp.create,yo=H_.create,ut=cd.create;Ep.create;mo.create;dd.create;const X2=ut(["codex","claude","image"]),Uw=ut(["managed","attached-live","history-only"]),zw=ut(["active","idle","attention","offline"]),Z2=ut(["idle","running","completed"]),J2=ut(["image","file"]),Bw=ut(["user","repo","system","admin"]),$w=ut(["openai","xai","gemini"]),Vp=E().trim().min(1).max(120),e6=ut(["auto","low","medium","high"]),t6=ut(["auto","1024x1024","1536x1024","1024x1536","2048x2048","2048x1152","1152x2048","3840x2160","2160x3840"]),n6=ut(["low","high"]),s6=ut(["png","jpeg","webp"]),a6=ut(["auto","opaque"]),i6=ut(["auto","low"]),r6=ut(["auto","1:1","4:3","3:4","16:9","9:16"]),Hw=ut(["generated","source","mask"]),Fw=ut(["upload","session_asset"]),qw=ut(["pending","completed","failed"]),Ww=ut(["generate","edit"]),l6=Te({id:Vp,vendor:$w.default("openai"),label:E().trim().min(1).max(160),enabled:It().default(!0)}),Kw=Te({can_stream_live:It(),can_send_input:It(),can_interrupt:It(),can_approve:It(),can_reject:It(),can_show_git:It(),can_show_terminal:It()}),o6=Te({used_tokens:Ve(),total_tokens:Ve(),remaining_tokens:Ve(),percent_used:Ve(),cached_input_tokens:Ve(),output_tokens:Ve(),reasoning_output_tokens:Ve(),updated_at:E()}),Qw=ut(["pending","in_progress","completed"]),Gw=Te({id:E(),step:E(),status:Qw}),O0=Te({session_id:E(),turn_id:E().nullable(),source:ut(["rollout","app-server"]),updated_at:E(),explanation:E().nullable().default(null),steps:nt(Gw),completed_count:Ve().int().nonnegative(),total_count:Ve().int().nonnegative(),is_active:It()}),Yw=Te({parent_session_id:E(),root_session_id:E().nullable().default(null),nickname:E().nullable().default(null),role:E().nullable().default(null),depth:Ve().int().nonnegative()}),Vw=ut(["user_input","command_execution_approval","file_change_approval","permissions_approval","mcp_elicitation"]),Xw=ut(["pending","submitting","resolved"]),c6=Te({id:E(),label:E(),description:E().nullable().default(null),emphasis:ut(["default","primary","danger"]).default("default")}),Zw=Te({id:E(),header:E().nullable().default(null),question:E(),options:nt(c6).default([]),allow_other:It().default(!1),is_secret:It().default(!1)}),L0=Te({id:E(),session_id:E(),turn_id:E().nullable().default(null),item_id:E().nullable().default(null),kind:Vw,status:Xw,title:E(),description:E().nullable().default(null),created_at:E(),updated_at:E(),options:nt(c6).default([]),questions:nt(Zw).default([]),allow_freeform:It().default(!1),freeform_placeholder:E().nullable().default(null),submit_label:E().nullable().default(null)}),Jw=Te({id:E(),kind:J2,name:E().nullable().default(null),mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),content_url:E().nullable().default(null)}),U1=Te({id:E(),kind:J2,name:E(),mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),data_url:E()}),i4=Te({id:E(),session_id:E(),turn_id:E().nullable().default(null),kind:Hw,name:E(),mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),width:Ve().int().positive().nullable().default(null),height:Ve().int().positive().nullable().default(null),content_url:E(),created_at:E()}),eN=Te({id:E(),kind:Fw,name:E(),mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),data_url:E().nullable().default(null),asset_id:E().nullable().default(null),mask_data_url:E().nullable().default(null)}),tN=Te({id:E(),session_id:E(),created_at:E(),completed_at:E().nullable().default(null),prompt:E(),prompt_suffix:E().nullable().default(null),operation:Ww,status:qw,error:E().nullable().default(null),model:Vp,quality:e6,size:t6,input_fidelity:n6.nullable().default(null),aspect_ratio:r6,output_format:s6.default("png"),output_compression:Ve().int().min(0).max(100).nullable().default(null),background:a6.default("auto"),moderation:i6.default("auto"),n:Ve().int().min(1).max(10).default(1),sources:nt(i4).default([]),outputs:nt(i4).default([])}),nN=Te({id:E(),remark:E(),base_url:E(),models:nt(l6).default([]),resolved_api_key_source:ut(["stored","env","missing"]).default("missing"),has_stored_api_key:It().default(!1),updated_at:E().nullable().default(null)}),sN=Te({id:E(),remark:E().trim().min(1).max(80),base_url:E(),models:nt(l6).default([]),api_key:E().optional().nullable(),api_key_mode:ut(["keep","set","clear"]).default("keep")}),r4=Te({active_channel_id:E().nullable().default(null),base_url:E(),channels:nt(nN).default([]),model:Vp.default("gpt-image-2"),resolved_api_key_source:ut(["stored","env","missing"]).default("missing"),has_stored_api_key:It().default(!1),updated_at:E().nullable().default(null)}),l4=Te({active_channel_id:E().nullable().default(null),channels:nt(sN).default([])}),aN=Te({ok:It(),message:E(),model_available:It().default(!1),resolved_base_url:E()}),iN=Te({base_url:E(),api_key:E().optional().nullable(),api_key_mode:ut(["keep","set","clear"]).default("keep"),channel_id:E().nullable().default(null)}),rN=Te({models:nt(Te({id:E(),label:E()}))}),lN=Te({title:E().trim().min(1).max(80).optional()}),oN=Te({prompt:E(),append_to_turn_id:E().nullable().default(null),model:Vp.default("gpt-image-2"),quality:e6.default("auto"),size:t6.default("1024x1024"),input_fidelity:n6.nullable().default(null),aspect_ratio:r6.default("auto"),output_format:s6.default("png"),output_compression:Ve().int().min(0).max(100).nullable().default(null),background:a6.default("auto"),moderation:i6.default("auto"),n:Ve().int().min(1).max(10).default(1),sources:nt(eN).default([])}),cN=Te({name:E(),description:E(),path:E(),scope:Bw,enabled:It()}),uN=ut(["supported","unsupported"]),dN=Te({name:E(),description:E(),availability:uN.default("supported")}),o4=Te({cli_version:E().nullable().default(null),loaded_at:E(),cache_ttl_ms:Ve().int().nonnegative(),commands:nt(dN)});Te({id:E(),label:E(),description:E(),isDefault:It(),defaultReasoningEffort:E().nullable().default(null),supportedReasoningEfforts:nt(E()).default([])});const fN=ut(["running","awaiting_input","completed","failed"]),hN=ut(["none","choice","text"]),mN=Te({id:E(),label:E(),description:E().nullable().default(null)}),pN=Te({type:yo("set_session_model"),model:E(),reasoning_effort:E().nullable().default(null)}).nullable().default(null),gN=Te({panel_id:E(),session_id:E(),command_name:E(),command_text:E(),title:E(),description:E().nullable().default(null),status:fN,body:E(),submitted_at:E(),updated_at:E(),input_type:hN,options:nt(mN).default([]),input_placeholder:E().nullable().default(null),submit_label:E().nullable().default(null),effect:pN}),c4=Te({panel:gN}),_N=ut(["online","offline"]),Xp=Te({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:_N,provider_availability:nt(X2),project_count:Ve(),session_count:Ve(),transport:ut(["direct-agent","hub-routed"]),version:E().nullable().default(null),registered_at:E().nullable().default(null),last_seen_at:E().nullable().default(null)}),P0=Te({id:E(),agent_id:E(),name:E(),display_name:E().nullable(),pinned:It(),path:E(),branch:E(),worktree:E(),runtime_profiles:nt(E()),preview_url:E().nullable()}),Nh=Te({id:E(),agent_id:E(),project_id:E(),provider:X2,archived:It(),title:E(),mode:Uw,health:zw,branch:E(),worktree:E(),summary:E(),latest_assistant_message:E().nullable().default(null),last_event_at:E(),pinned:It(),run_state:Z2,run_state_changed_at:E().nullable(),context_usage:o6.nullable().default(null),subagent:Yw.nullable().default(null),capability:Kw}),yN=Te({path:E(),additions:Ve(),deletions:Ve()}),vN=Te({files:nt(yN),additions:Ve(),deletions:Ve()}),rh=Te({id:E(),kind:ut(["user","assistant","thinking","tool","system"]),title:E(),body:E(),body_truncated:It().default(!1),detail_available:It().default(!1),patch_summary:vN.nullable().default(null),session_ids:nt(E()).default([]),timestamp:E(),accent:ut(["primary","secondary","muted"]),attachments:nt(Jw).default([])}),u6=e=>(e==null?void 0:e.kind)==="user"&&(e.body.trim().length>0||Array.isArray(e.attachments)&&e.attachments.length>0),d6=e=>{for(let t=e.length-1;t>=0;t-=1)if(u6(e[t]))return t;return-1},bN=e=>{const t=d6(e);if(t<0)return!1;for(let i=0;i<t;i+=1)if(u6(e[i]))return!0;return!1},xN=ut(["tail","full_compact"]),f6=Te({session_id:E(),generated_at:E(),view:xN,anchor_entry_id:E().nullable().default(null),has_earlier_entries:It().default(!1),entries:nt(rh)}),SN=ut(["app-server","rollout-fallback"]),jN=ut(["running","completed"]),wN=ut(["add","delete","update"]),U0=Te({path:E(),kind:wN,move_path:E().nullable(),additions:Ve(),deletions:Ve(),diff:E(),item_id:E().nullable()}),NN=U0.omit({diff:!0}).extend({diff_available:It().default(!1)}),h6=Te({id:E(),session_id:E(),turn_id:E(),source:SN,status:jN,started_at:E(),completed_at:E().nullable(),updated_at:E(),aggregated_diff:E(),files:nt(U0)}),m6=h6.omit({aggregated_diff:!0,files:!0}).extend({aggregated_diff_available:It().default(!1),files:nt(NN)}),kN=Te({session_id:E(),change_set_id:E(),file:U0,empty_message:E().default("此变更没有可展示的补丁内容")}),EN=Te({path:E(),status:ut(["modified","added","deleted","renamed"]),additions:Ve(),deletions:Ve()}),p6=ut(["modified","added","deleted","renamed","untracked"]),CN=Te({path:E(),previous_path:E().nullable().default(null),status:p6,additions:Ve().int().nonnegative(),deletions:Ve().int().nonnegative()}),TN=Te({session_id:E(),project_id:E(),path:E(),previous_path:E().nullable().default(null),additions:Ve().int().nonnegative(),deletions:Ve().int().nonnegative(),diff:E()}),z0=Te({session_id:E(),project_id:E(),branch:E(),branches:nt(E()),upstream_branch:E().nullable().default(null),ahead_count:Ve().int().nonnegative(),behind_count:Ve().int().nonnegative(),files:nt(CN),updated_at:E()}),MN=Te({path:E(),previous_path:E().nullable().default(null),status:p6}),RN=Te({oid:E(),short_oid:E(),subject:E(),author_name:E(),authored_at:E(),committed_at:E(),parent_oids:nt(E()).default([]),refs:nt(E()).default([]),files:nt(MN)}),AN=Te({session_id:E(),project_id:E(),commit_oid:E(),path:E(),previous_path:E().nullable().default(null),additions:Ve().int().nonnegative(),deletions:Ve().int().nonnegative(),diff:E()}),IN=Te({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:nt(RN),updated_at:E()});ut(["discard-file","discard-all","commit-all","switch-branch","push"]);const DN=Te({ok:yo(!0),workspace:z0});ut(["rollback"]);const ON=Te({ok:yo(!0),turn_id:E(),change_set_id:E(),workspace:z0}),LN=ut(["directory","file"]),g6=ut(["markdown","code","text","image","binary"]),PN=Te({path:E(),name:E(),kind:LN,has_children:It(),extension:E().nullable().default(null),file_kind:g6.nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null)}),UN=Te({session_id:E(),project_id:E(),root_path:E(),parent_path:E().nullable().default(null),nodes:nt(PN),loaded_at:E()}),zN=Te({session_id:E(),project_id:E(),path:E(),name:E(),extension:E().nullable().default(null),file_kind:g6,mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),encoding:ut(["utf8","base64"]).nullable().default(null),is_truncated:It(),content_text:E().nullable().default(null),content_base64:E().nullable().default(null),loaded_at:E()}),_6=ut(["auto","powershell","cmd","bash"]),BN=ut(["user","codex"]),$N=Te({id:E(),name:E(),description:E().nullable().default(null),command:E(),kill_command:E().nullable().default(null),cwd:E().nullable().default(null),shell:_6.default("auto"),node_version:E().nullable().default(null),port:Ve().int().positive().nullable().default(null),source:BN.default("user"),created_at:E(),updated_at:E()}),HN=Te({name:E(),description:E().nullable().default(null),command:E(),kill_command:E().nullable().default(null),cwd:E().nullable().default(null),shell:_6.default("auto"),node_version:E().nullable().default(null),port:Ve().int().positive().nullable().default(null)}),B0=Te({session_id:E(),project_id:E(),config_path:E(),commands:nt($N),updated_at:E()}),FN=ut(["user","codex"]),qN=Te({id:E(),name:E(),description:E().nullable().default(null),url:E(),source:FN.default("user"),created_at:E(),updated_at:E()}),WN=Te({name:E(),description:E().nullable().default(null),url:E()}),$0=Te({session_id:E(),project_id:E(),config_path:E(),websites:nt(qN),updated_at:E()}),KN=ut(["queued","running","completed","failed","stopped"]),QN=ut(["stdout","stderr","system"]),GN=Te({cursor:Ve().int().nonnegative(),stream:QN,text:E(),timestamp:E()}),H0=Te({id:E(),session_id:E(),project_id:E(),command_id:E().nullable().default(null),title:E(),command:E(),cwd:E(),status:KN,exit_code:Ve().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:Ve().int().nonnegative(),preview:E().nullable().default(null)}),F0=Te({session_id:E(),project_id:E(),active_terminal_id:E().nullable().default(null),terminals:nt(H0),updated_at:E()}),YN=Te({session_id:E(),project_id:E(),terminal:H0,chunks:nt(GN),next_cursor:Ve().int().nonnegative(),truncated:It().default(!1)}),y6=Te({run_state:Z2.optional(),run_state_changed_at:E().nullable().optional(),summary:E().optional(),latest_assistant_message:E().nullable().optional(),last_event_at:E().optional(),context_usage:o6.nullable().optional()}),VN=Te({session_id:E(),recovered_at:E(),session_patch:y6,timeline:nt(rh),interactions:nt(L0),plan_snapshot:O0.nullable().default(null),change_sets:nt(h6),terminal_snapshot:F0.nullable().default(null)}),v6=Te({manager:ut(["none","nvm-windows"]).default("none"),versions:nt(E()).default([]),error:E().nullable().default(null)}),b6=Te({command_catalog:B0,website_catalog:$0,node_runtime:v6,terminal_snapshot:F0}),XN=Te({session_id:E(),generated_at:E(),session_patch:y6,timeline:f6,interactions:nt(L0),plan_snapshot:O0.nullable().default(null),run_workbench:b6.nullable().default(null),change_sets:nt(m6).default([])}),ZN=Te({catalog:B0}),JN=Te({catalog:$0}),ek=Te({commands:nt(HN),reason:E().nullable().default(null)}),tk=Te({generation:ek,catalog:B0}),nk=Te({websites:nt(WN),reason:E().nullable().default(null)}),sk=Te({generation:nk,catalog:$0}),ak=Te({snapshot:F0,terminal:H0.nullable().default(null)}),ik=ut(["dev-hub","dev-agent","dev-web","release-hub","release-agent"]),rk=ut(["unknown","running","stopped","degraded"]),lk=ut(["process","windows-service"]),ok=ut(["missing","running","stopped","unknown"]),ck=ut(["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"]),uk=ut(["running","succeeded","failed"]),dk=ut(["info","success","warn","error"]),x6=Te({repo_path:E().nullable().default(null),nvm_version:E().nullable().default(null),dev_hub_port:Ve().int().positive().nullable().default(null),dev_hub_args:E().default(""),dev_agent_port:Ve().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:Ve().int().positive().nullable().default(null),dev_web_hub_url:E().default(""),dev_web_args:E().default(""),release_hub_port:Ve().int().positive().nullable().default(null),release_hub_service_name:E().default("PandaHub"),release_hub_args:E().default(""),release_agent_port:Ve().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)}),fk=x6.extend({npm_token:E().nullable().default(null),clear_npm_token:It().default(!1)}),hk=Te({has_npm_token:It(),npm_token_hint:E().nullable().default(null)}),mk=Te({checked_at:E(),url:E().nullable().default(null),ok:It(),status_code:Ve().int().nullable().default(null),duration_ms:Ve().int().nonnegative().nullable().default(null),message:E().nullable().default(null)}),pk=Te({key:ik,label:E(),status:rk,manager:lk.default("process"),service_name:E().nullable().default(null),service_registered:It().default(!1),service_status:ok.nullable().default(null),configured_port:Ve().int().positive().nullable().default(null),detected_pids:nt(Ve().int().positive()).default([]),probe:mk.nullable().default(null)}),gk=Te({id:E(),timestamp:E(),level:dk,message:E()}),S6=Te({id:E(),kind:ck,title:E(),status:uk,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:It().default(!1),logs:nt(gk).default([])}),_k=Te({artifact_id:E(),file_name:E(),size_bytes:Ve().int().nonnegative(),built_at:E(),published_at:E().nullable().default(null),version_name:E().nullable().default(null),version_code:Ve().int().nullable().default(null),download_path:E()}),K_=Te({generated_at:E(),config:x6,credentials:hk,node_runtime:v6,services:nt(pk),current_version:E().nullable().default(null),apk_artifact:_k.nullable().default(null),jobs:nt(S6).default([])});Te({action:ut(["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 yk=Te({ok:yo(!0),snapshot:K_,job:S6.nullable().default(null)}),vk=Te({id:E(),name:E(),command:E(),port:Ve().nullable(),status:ut(["running","stopped","degraded"]),log_excerpt:E()}),bk=Te({id:E(),label:E(),url:E(),status:ut(["ready","starting","stopped"])}),j6=Te({path:E(),name:E(),has_children:It()}),xk=Te({directory:j6}),Sk=Te({id:E(),title:E(),description:E(),status:ut(["pending","approved","rejected"])}),jk=Te({project_id:E(),visible_session_count:Ve().int().nonnegative(),archived_session_count:Ve().int().nonnegative(),hidden_history_count:Ve().int().nonnegative()}),wk=P0.pick({id:!0,agent_id:!0,name:!0,display_name:!0,pinned:!0,path:!0}),Nk=Xp.pick({id:!0,name:!0,display_name:!0,status:!0}),w6=Nh.pick({id:!0,agent_id:!0,project_id:!0,provider:!0,archived:!0,title:!0,last_event_at:!0,pinned:!0,run_state:!0,run_state_changed_at:!0,subagent:!0}),N6=Nh.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}),kk=Te({generated_at:E(),session:N6}),u4=Te({generated_at:E(),session:N6,turns:nt(tN).default([])}),Ek=Te({generated_at:E(),agents:nt(Xp)}),Ck=Nh.pick({id:!0,title:!0,run_state:!0,run_state_changed_at:!0,latest_assistant_message:!0}),Tk=Te({generated_at:E(),recent_sessions:nt(Ck)}),Mk=Te({session_id:E(),agent_id:E(),project_id:E(),direct_base_url:E(),ws_base_url:E()}),Rk=Te({generated_at:E(),agent:Nk.nullable().default(null),projects:nt(wk),project_stats:nt(jk).default([]),sessions:nt(w6),active_session_id:E()}),k6=ut(["archived","history"]),Ak=Te({bucket:k6,project_id:E().nullable().default(null),sessions:nt(w6),next_cursor:E().nullable().default(null),total_count:Ve().int().nonnegative()}),Ik=Te({session_id:E(),entry_id:E(),command_entry:rh,output_entries:nt(rh).default([])}),Dk=Te({generated_at:E(),agents:nt(Xp),projects:nt(P0),sessions:nt(Nh),active_session_id:E(),timeline:nt(rh),changed_files:nt(EN),runtime_processes:nt(vk),previews:nt(bk),approvals:nt(Sk)});Te({agent:Xp,projects:nt(P0),sessions:nt(Nh),active_session_id:E().default(""),generated_at:E()});const d4=Te({ok:yo(!0),agent_id:E(),heartbeat_interval_ms:Ve().int().positive(),heartbeat_timeout_ms:Ve().int().positive(),registered_at:E(),received_at:E()}),Ok=ut(["rename","delete"]);Te({action:Ok,display_name:E().nullable().default(null)});const Lk=Te({ok:yo(!0)}),q0=Te({completion_notifications_enabled:It().default(!1)}),Pk=Te({p256dh:E(),auth:E()}),Uk=Te({endpoint:E().url(),expirationTime:Ve().nullable().default(null),keys:Pk}),zk=Te({label:E().nullable().default(null),user_agent:E().nullable().default(null)});Te({subscription:Uk,settings:q0.default({}),device:zk.default({})});const Bk=Te({endpoint:E().url()}),$k=Te({endpoint:E().url()}),Hk=Te({supported:It(),vapid_public_key:E().nullable().default(null),subject:E().nullable().default(null),reason:E().nullable().default(null)}),Fk=Te({ok:yo(!0),subscription_id:E(),endpoint:E().url(),settings:q0,created_at:E(),updated_at:E()}),qk=Te({ok:yo(!0),endpoint:E().url(),delivered_at:E()}),Wk=Te({type:ut(["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:Cp(Pw())}),Kk=Te({width:Ve().nonnegative(),height:Ve().nonnegative(),device_pixel_ratio:Ve().nonnegative(),visual_width:Ve().nonnegative().nullable().default(null),visual_height:Ve().nonnegative().nullable().default(null),screen_width:Ve().nonnegative().nullable().default(null),screen_height:Ve().nonnegative().nullable().default(null)}),Qk=Te({user_agent:E(),language:E().nullable().default(null),languages:nt(E()).default([]),platform:E().nullable().default(null),vendor:E().nullable().default(null),online:It().nullable().default(null),cookie_enabled:It().nullable().default(null),secure_context:It(),standalone_display_mode:It(),hardware_concurrency:Ve().int().nonnegative().nullable().default(null),device_memory_gb:Ve().nonnegative().nullable().default(null),max_touch_points:Ve().int().nonnegative().nullable().default(null)}),Gk=Te({href:E(),pathname:E(),referrer:E().nullable().default(null),visibility_state:E().nullable().default(null)}),Yk=Te({scope:E(),active_script_url:E().nullable().default(null),waiting_script_url:E().nullable().default(null),installing_script_url:E().nullable().default(null)}),Vk=Te({supported:It(),controller:It(),registrations:nt(Yk).default([])}),Xk=Te({supported:It(),keys:nt(E()).default([])}),Zk=Te({href:E().nullable().default(null),rel:E().nullable().default(null)}),Jk=Te({href:E().nullable().default(null),owner_node:E().nullable().default(null),media:E().nullable().default(null),disabled:It(),css_rule_count:Ve().int().nonnegative().nullable().default(null)}),eE=Te({url:E(),kind:ut(["stylesheet","script","manifest","icon","other"]),ok:It(),status:Ve().int().nonnegative().nullable().default(null),content_type:E().nullable().default(null),cache_control:E().nullable().default(null),error:E().nullable().default(null)}),tE=Te({name:E(),initiator_type:E().nullable().default(null),duration_ms:Ve().nonnegative().nullable().default(null),transfer_size:Ve().nonnegative().nullable().default(null),decoded_body_size:Ve().nonnegative().nullable().default(null)}),nE=Te({x:Ve(),y:Ve(),width:Ve().nonnegative(),height:Ve().nonnegative()}),sE=Te({selector:E(),found:It(),text_preview:E().nullable().default(null),rect:nE.nullable().default(null),computed:Cp(E()).default({})});Te({captured_at:E(),page:Gk,environment:Qk,viewport:Kk,feature_support:Cp(It()).default({}),service_worker:Vk,cache:Xk,manifest:Zk,stylesheets:nt(Jk).default([]),resource_probes:nt(eE).default([]),performance_entries:nt(tE).default([]),theme_variables:Cp(E()).default({}),element_snapshots:nt(sE).default([]),notes:nt(E()).default([])});const aE=/^(?:image|img|photo|picture|screenshot|图片|照片|截图)(?:[-_ ]?\d+)?\.(?:avif|bmp|gif|heic|heif|jpe?g|png|svg|webp)$/i,ia=e=>(e==null?void 0:e.trim())??"",f4="\0",h4=e=>{const t=ia(e);return t?aE.test(t)?1:2+Math.min(t.length,64)/100:0},iE=(e,t)=>{const i=h4(e),r=h4(t);if(r>i)return ia(t)||null;if(i>r)return ia(e)||null;const o=ia(e),u=ia(t);return u.length>o.length?u||null:o||null},rE=e=>{const t=ia(e.content_url);return t?[e.kind,"content",t].join(f4):[e.kind,"meta",ia(e.mime_type).toLowerCase(),typeof e.size_bytes=="number"&&Number.isFinite(e.size_bytes)?String(Math.max(0,Math.round(e.size_bytes))):"",ia(e.name).toLowerCase()].join(f4)},lE=(e,t)=>{const i=ia(e.name),r=ia(t.name),o=ia(e.mime_type),u=ia(t.mime_type);return{id:e.id||t.id,kind:e.kind==="image"||t.kind==="image"?"image":e.kind,name:iE(i,r),mime_type:o||u||null,size_bytes:e.size_bytes??t.size_bytes??null,content_url:ia(e.content_url)||ia(t.content_url)||null}},E6=e=>{if(!e||e.length===0)return[];const t=[],i=new Map;for(const r of e){const o=rE(r),u=i.get(o);if(u===void 0){i.set(o,t.length),t.push({...r,name:ia(r.name)||null,mime_type:ia(r.mime_type)||null,size_bytes:typeof r.size_bytes=="number"&&Number.isFinite(r.size_bytes)?Math.max(0,Math.round(r.size_bytes)):null,content_url:ia(r.content_url)||null});continue}t[u]=lE(t[u],r)}return t},C6=(e,t)=>E6([...e??[],...t??[]]),$a=e=>new Date(e).toISOString(),oE=()=>({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:$a("2026-03-18T10:30:00+08:00"),last_seen_at:$a("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:$a("2026-03-18T10:20:00+08:00"),last_seen_at:$a("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:$a("2026-03-18T10:58:00+08:00"),pinned:!1,run_state:"running",run_state_changed_at:$a("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:$a("2026-03-18T10:48:00+08:00"),pinned:!1,run_state:"completed",run_state_changed_at:$a("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:$a("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:$a("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:$a("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:$a("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:$a("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:$a("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"}]}),cE=()=>oE(),uE=()=>cE(),T6=e=>{const t=new URL(e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.pathname="/ws",t.toString()};class dE{constructor(t,i=T6(t)){this.baseUrl=t,this.wsBaseUrl=i}getConnectionKey(){return`${this.baseUrl}::${this.wsBaseUrl}`}async readJson(t,i){const r=await fetch(t);if(!r.ok)throw new Error(`Request failed with ${r.status}`);return i.parse(await r.json())}async postJson(t,i,r){const o=await fetch(new URL(t,this.baseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i)}),u=await o.json().catch(()=>null);if(!o.ok)throw new Error((u==null?void 0:u.error)??`Request failed with ${o.status}`);return r?r.parse(u):u}async getPhaseOneSnapshot(t){const{fallbackToMock:i=!0,fallbackSnapshot:r=uE}=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 Dk.parse(u)}catch(o){if(!i)throw o;return r()}}async getHubDirectory(){return this.readJson(new URL("/api/hub/directory",this.baseUrl),Ek)}async getHubRecentSessions(){return this.readJson(new URL("/api/hub/recent-sessions",this.baseUrl),Tk)}async getSessionLocation(t){return this.readJson(new URL(`/api/sessions/${t}/location`,this.baseUrl),Mk)}async getWorkspaceDirectory(t){const i=new URL("/api/workspace",this.baseUrl);return t!=null&&t.selectedSessionId&&i.searchParams.set("selectedSessionId",t.selectedSessionId),this.readJson(i,Rk)}async getWorkspaceSessionPage(t){const i=new URL("/api/workspace/sessions",this.baseUrl);return i.searchParams.set("bucket",k6.parse(t.bucket)),t.projectId&&i.searchParams.set("projectId",t.projectId),t.projectless&&i.searchParams.set("projectless","1"),t.cursor&&i.searchParams.set("cursor",t.cursor),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(Math.max(1,Math.floor(t.limit)))),t.selectedSessionId&&i.searchParams.set("selectedSessionId",t.selectedSessionId),this.readJson(i,Ak)}async getWorkspaceSessionDetail(t){const i=new URL("/api/workspace/session-detail",this.baseUrl);return i.searchParams.set("sessionId",t),this.readJson(i,kk)}async getSessionTimeline(t,i){const r=new URL(`/api/sessions/${t}/timeline`,this.baseUrl);return i!=null&&i.view&&r.searchParams.set("view",i.view),this.readJson(r,f6)}async getSessionChangeSets(t){return this.readJson(new URL(`/api/sessions/${t}/change-sets`,this.baseUrl),{parse:i=>Array.isArray(i)?i.map(r=>m6.parse(r)):[]})}async getSessionBootstrap(t){return this.readJson(new URL(`/api/sessions/${t}/bootstrap`,this.baseUrl),XN)}async getSessionToolCallDetail(t,i){const r=new URL(`/api/sessions/${t}/tool-detail`,this.baseUrl);return r.searchParams.set("entryId",i),this.readJson(r,Ik)}async getSessionChangeSetFileDiff(t,i){const r=new URL(`/api/sessions/${t}/change-set-file-diff`,this.baseUrl);return r.searchParams.set("changeSetId",i.changeSetId),r.searchParams.set("path",i.path),i.itemId&&r.searchParams.set("itemId",i.itemId),this.readJson(r,kN)}async getSessionGitWorkspace(t){return this.readJson(new URL(`/api/sessions/${t}/git-workspace`,this.baseUrl),z0)}async getSessionGitWorkspaceFileDiff(t,i){const r=new URL(`/api/sessions/${t}/git-workspace/file-diff`,this.baseUrl);return r.searchParams.set("path",i.path),i.previousPath&&r.searchParams.set("previousPath",i.previousPath),this.readJson(r,TN)}async getSessionGitHistory(t){return this.readJson(new URL(`/api/sessions/${t}/git/history`,this.baseUrl),IN)}async getSessionFilePreviewTree(t,i){var u;const r=new URL(`/api/sessions/${t}/file-preview/tree`,this.baseUrl),o=(u=i==null?void 0:i.path)==null?void 0:u.trim();return o&&r.searchParams.set("path",o),this.readJson(r,UN)}async getSessionFilePreviewContent(t,i){const r=new URL(`/api/sessions/${t}/file-preview/content`,this.baseUrl);return r.searchParams.set("path",i.path),this.readJson(r,zN)}async getSessionGitHistoryFileDiff(t,i){const r=new URL(`/api/sessions/${t}/git/history/file-diff`,this.baseUrl);return r.searchParams.set("commitOid",i.commitOid),r.searchParams.set("path",i.path),i.previousPath&&r.searchParams.set("previousPath",i.previousPath),this.readJson(r,AN)}async getSessionRunWorkbench(t){return this.readJson(new URL(`/api/sessions/${t}/run-workbench`,this.baseUrl),b6)}async saveSessionRunCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/run-commands`,{action:t.action,commandId:t.commandId??null,command:t.command??null},ZN)}async generateSessionRunCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/run-commands/generate`,{prompt:t.prompt,model:t.model},tk)}async saveSessionRunWebsite(t){return this.postJson(`/api/sessions/${t.sessionId}/run-websites`,{action:t.action,websiteId:t.websiteId??null,website:t.website??null},JN)}async generateSessionRunWebsite(t){return this.postJson(`/api/sessions/${t.sessionId}/run-websites/generate`,{prompt:t.prompt,model:t.model},sk)}async executeSessionTerminalAction(t){return this.postJson(`/api/sessions/${t.sessionId}/terminals`,{action:t.action,commandId:t.commandId??null,terminalId:t.terminalId??null},ak)}async getSessionTerminalOutput(t){const i=new URL(`/api/sessions/${t.sessionId}/terminals/${t.terminalId}/output`,this.baseUrl);return typeof t.cursor=="number"&&Number.isFinite(t.cursor)&&i.searchParams.set("cursor",String(Math.max(0,Math.floor(t.cursor)))),this.readJson(i,YN)}async getSessionPlan(t){return this.readJson(new URL(`/api/sessions/${t}/plan`,this.baseUrl),{parse:i=>i==null?null:O0.parse(i)})}async getSessionInteractions(t){return this.readJson(new URL(`/api/sessions/${t}/interactions`,this.baseUrl),{parse:i=>Array.isArray(i)?i.map(r=>L0.parse(r)):[]})}async getSessionRecoverySnapshot(t){return this.readJson(new URL(`/api/sessions/${t}/recovery`,this.baseUrl),VN)}async getProjectSkills(t){return this.readJson(new URL(`/api/projects/${t}/skills`,this.baseUrl),{parse:i=>Array.isArray(i)?i.map(r=>cN.parse(r)):[]})}async getCodexCommands(){return this.readJson(new URL("/api/codex/commands",this.baseUrl),o4)}async refreshCodexCommands(){return this.postJson("/api/codex/commands/refresh",{},o4)}async listDirectories(t){const i=new URL("/api/directories",this.baseUrl);return t.agentId&&i.searchParams.set("agentId",t.agentId),t.path&&i.searchParams.set("path",t.path),this.readJson(i,{parse:r=>Array.isArray(r)?r.map(o=>j6.parse(o)):[]})}async createDirectory(t){return this.postJson("/api/directories",t,xk)}async createProject(t){return this.postJson("/api/projects",t)}async createSession(t){var i;return this.postJson("/api/sessions",{...t,attachments:(i=t.attachments)==null?void 0:i.map(r=>U1.parse(r)),serviceTier:t.serviceTier,planMode:t.planMode,yoloMode:t.yoloMode})}async createChat(t){var i;return this.postJson("/api/chats",{...t,attachments:(i=t.attachments)==null?void 0:i.map(r=>U1.parse(r)),serviceTier:t.serviceTier,planMode:t.planMode,yoloMode:t.yoloMode})}async getImageProviderSettings(){return this.readJson(new URL("/api/image-provider/settings",this.baseUrl),r4)}async saveImageProviderSettings(t){return this.postJson("/api/image-provider/settings",l4.parse(t),r4)}async testImageProviderSettings(t){return this.postJson("/api/image-provider/test",l4.parse({active_channel_id:(t==null?void 0:t.active_channel_id)??null,channels:(t==null?void 0:t.channels)??[]}),aN)}async listImageProviderModels(t){return this.postJson("/api/image-provider/models",iN.parse(t),rN)}async createImageSession(t){return this.postJson("/api/image-sessions",lN.parse(t??{}))}async getImageSessionDetail(t){return this.readJson(new URL(`/api/image-sessions/${t}`,this.baseUrl),u4)}async submitImageSessionPrompt(t){return this.postJson(`/api/image-sessions/${t.sessionId}/submit`,oN.parse({prompt:t.prompt,append_to_turn_id:t.append_to_turn_id,model:t.model,quality:t.quality,size:t.size,input_fidelity:t.input_fidelity,aspect_ratio:t.aspect_ratio,output_format:t.output_format,output_compression:t.output_compression,background:t.background,moderation:t.moderation,n:t.n,sources:t.sources}),u4)}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 i;return this.postJson(`/api/sessions/${t.sessionId}/input`,{input:t.input,attachments:(i=t.attachments)==null?void 0:i.map(r=>U1.parse(r)),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},c4)}async respondToSessionCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/commands/respond`,{panelId:t.panelId,optionId:t.optionId??null,text:t.text??null},c4)}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,d4)}async heartbeatAgent(t){return this.postJson("/api/agents/heartbeat",t,d4)}async updateAgent(t){return this.postJson(`/api/agents/${t.agentId}/actions`,{action:t.action,display_name:t.displayName??null},Lk)}async getWebPushPublicConfig(){return this.readJson(new URL("/api/push/public-key",this.baseUrl),Hk)}async upsertWebPushSubscription(t){return this.postJson("/api/push/subscriptions",{subscription:t.subscription,settings:q0.parse(t.settings),device:t.device??null},Fk)}async removeWebPushSubscription(t){return this.postJson("/api/push/subscriptions/remove",Bk.parse(t))}async sendWebPushTest(t){return this.postJson("/api/push/test",$k.parse(t),qk)}async executeSessionGitAction(t){return this.postJson(`/api/sessions/${t.sessionId}/git/actions`,{action:t.action,path:t.path,branch:t.branch,message:t.message},DN)}async executeSessionTurnAction(t){return this.postJson(`/api/sessions/${t.sessionId}/turns/${t.turnId}/actions`,{action:t.action},ON)}async getDevManagerSnapshot(t){const i=new URL("/api/dev-manager",this.baseUrl);return t!=null&&t.includeServiceProbe&&i.searchParams.set("includeServiceProbe","1"),this.readJson(i,K_)}async saveDevManagerConfig(t){return this.postJson("/api/dev-manager/config",fk.parse(t),K_)}async executeDevManagerAction(t){return this.postJson("/api/dev-manager/actions",t,yk)}createEventStream(t,i){var Ce;let m=null,y=((Ce=i==null?void 0:i.sessionId)==null?void 0:Ce.trim())??"",g="",b=!1,p=0,v=null,w=!1,N=!1,j=!1,T=0;const M=typeof document<"u"&&typeof document.visibilityState=="string",P=()=>M&&document.visibilityState==="hidden",I=(i==null?void 0:i.reconnectWhenHidden)===!0,k=R=>(R==null?void 0:R.readyState)===WebSocket.OPEN||(R==null?void 0:R.readyState)===WebSocket.CONNECTING,O=()=>{v!==null&&(globalThis.clearTimeout(v),v=null)},Q=(R,X)=>{var le;(le=i==null?void 0:i.onStatus)==null||le.call(i,{state:R,attempt:p,maxAttempts:5,error:X})},J=R=>{const X=m;!X||X.readyState!==WebSocket.OPEN||(g&&g!==R&&(X.send(JSON.stringify({type:"session.unsubscribe",sessionId:g})),g=""),!(!R||g===R)&&(g=R,X.send(JSON.stringify({type:"session.subscribe",sessionId:R}))))},F=R=>{if(b||w)return;if(!I&&P()){w=!1,j=!0,O(),Q("failed",R);return}if(p+=1,!I&&p>5){p=5,j=!0,Q("failed",R);return}w=!0,j=!1,Q("reconnecting",R),O();const X=I?Math.min(p,5):p,le=Math.min(1e4,1200*2**Math.max(0,X-1));v=globalThis.setTimeout(()=>{w=!1,B()},le)},B=()=>{if(b||k(m))return;O(),w=!1,j=!1;const R=new WebSocket(this.wsBaseUrl);m=R,R.addEventListener("open",()=>{b||m!==R||(w=!1,N=!1,p=0,Q("connected"),J(y))}),R.addEventListener("message",X=>{if(m!==R)return;const le=Wk.safeParse(JSON.parse(X.data));le.success&&t(le.data)}),R.addEventListener("error",()=>{if(b||m!==R)return;const X=`鏃犳硶杩炴帴鍒?${this.wsBaseUrl}`;R.readyState!==WebSocket.OPEN&&F(X)}),R.addEventListener("close",X=>{var ue;if(m===R&&(m=null),b||m!==null)return;const le=((ue=X.reason)==null?void 0:ue.trim())||`WebSocket disconnected (code ${X.code||"unknown"})`;F(le)})},G=R=>{if(b||k(m)||N)return;const X=Date.now();X-T<1500||(T=X,N=!0,p=0,w=!1,j=!1,O(),Q("reconnecting",R),B())},Z=()=>{document.visibilityState==="visible"&&(j||!k(m))&&G("App returned to foreground; reconnecting.")},ae=()=>{(j||!k(m))&&G("Page became visible again; reconnecting.")},he=()=>{(j||!k(m))&&G("Window focused again; reconnecting.")},ne=()=>{(j||!k(m))&&G("缃戠粶宸叉仮澶嶏紝姝e湪閲嶆柊杩炴帴")};return typeof window<"u"&&(window.addEventListener("pageshow",ae),window.addEventListener("focus",he),window.addEventListener("online",ne)),typeof document<"u"&&document.addEventListener("visibilitychange",Z),B(),{setSessionId:R=>{y=(R==null?void 0:R.trim())??"",!b&&J(y)},close:()=>{b=!0,w=!1,N=!1,j=!1,O(),typeof window<"u"&&(window.removeEventListener("pageshow",ae),window.removeEventListener("focus",he),window.removeEventListener("online",ne)),typeof document<"u"&&document.removeEventListener("visibilitychange",Z);const R=m;if((R==null?void 0:R.readyState)===WebSocket.OPEN&&g&&R.send(JSON.stringify({type:"session.unsubscribe",sessionId:g})),g="",m=null,(R==null?void 0:R.readyState)===WebSocket.CONNECTING){const X=()=>{try{R.close()}catch{}};R.addEventListener("open",X,{once:!0});return}R==null||R.close()}}}connectEvents(t,i){const r=this.createEventStream(t,i);return()=>{r.close()}}}const M6=(e,t)=>new dE(e,(t==null?void 0:t.wsBaseUrl)??T6(e)),R6=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return null;try{const i=new URL(t);return i.port?`${i.hostname}:${i.port}`:i.hostname}catch{return t.replace(/\/+$/,"")||null}},Cc=e=>{var t;return((t=e.display_name)==null?void 0:t.trim())||e.name.trim()||R6(e.direct_base_url)||"未命名节点"},fE=e=>{var i;const t=((i=e.display_name)==null?void 0:i.trim())??"";return!t||t===e.name?null:e.name},z1=e=>R6(e.direct_base_url)||e.host||e.tailscale_ip||e.tailscale_dns_name||e.direct_base_url,Tp="panda:last-agent-id",Mp="panda:last-session-id",lh="panda:pending-session-id",oh="panda:pending-project-id",ch="panda:pending-directory-picker",fd="panda:pending-session-handoff",uh="panda:selected-agent-connection-hint",hE=3e4,mE=1800*1e3,$f=e=>typeof e=="object"&&e!==null,pE=e=>{if(!$f(e))return null;const{sessionId:t,agentId:i,projectId:r,createdAt:o,session:u,project:d,optimisticEntry:m}=e;return typeof t!="string"||typeof i!="string"||typeof r!="string"||typeof o!="string"||!$f(u)||u.id!==t||u.agent_id!==i||u.project_id!==r||d!==null&&(!$f(d)||d.id!==r||d.agent_id!==i||typeof d.name!="string"||typeof d.path!="string")||m!==null&&(!$f(m)||typeof m.id!="string"||typeof m.kind!="string"||typeof m.body!="string"||typeof m.timestamp!="string")?null:{sessionId:t,agentId:i,projectId:r,createdAt:o,session:u,project:d??null,optimisticEntry:m??null}},gE=e=>{const t=new Date(e.createdAt).getTime();return Number.isFinite(t)?Date.now()-t>hE:!0},_E=e=>{if(!$f(e))return null;const{agentId:t,name:i,displayName:r,directBaseUrl:o,wsBaseUrl:u,createdAt:d}=e;return typeof t!="string"||typeof i!="string"||r!==null&&typeof r!="string"||typeof o!="string"||typeof u!="string"||typeof d!="string"?null:{agentId:t,name:i,displayName:r,directBaseUrl:o,wsBaseUrl:u,createdAt:d}},yE=e=>{const t=new Date(e.createdAt).getTime();return Number.isFinite(t)?Date.now()-t>mE:!0},vE=e=>{if(!(typeof window>"u"))try{if(!e){window.sessionStorage.removeItem(fd);return}window.sessionStorage.setItem(fd,JSON.stringify(e))}catch{}},W0=e=>{if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(fd);if(!t)return null;const i=pE(JSON.parse(t));return!i||gE(i)?(window.sessionStorage.removeItem(fd),null):e&&i.sessionId!==e?null:i}catch{return null}},bE=e=>{if(!(typeof window>"u"))try{const t=W0();if(e&&(t!=null&&t.sessionId)&&t.sessionId!==e)return;window.sessionStorage.removeItem(fd)}catch{}},xE=e=>{if(!(typeof window>"u"))try{if(!e){window.sessionStorage.removeItem(uh);return}window.sessionStorage.setItem(uh,JSON.stringify(e))}catch{}},kh=e=>{if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(uh);if(!t)return null;const i=_E(JSON.parse(t));return!i||yE(i)?(window.sessionStorage.removeItem(uh),null):e&&i.agentId!==e?null:i}catch{return null}},vo=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(Tp)}catch{return null}},fr=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Tp,e);return}window.localStorage.removeItem(Tp)}catch{}},Rp=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(Mp)}catch{return null}},Ea=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Mp,e);return}window.localStorage.removeItem(Mp)}catch{}},sl=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(lh,e);return}window.sessionStorage.removeItem(lh)}catch{}},SE=()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem(lh);return e&&window.sessionStorage.removeItem(lh),e}catch{return null}},Hu=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(oh,e);return}window.sessionStorage.removeItem(oh)}catch{}},jE=()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem(oh);return e&&window.sessionStorage.removeItem(oh),e}catch{return null}},Hf=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(ch,"1");return}window.sessionStorage.removeItem(ch)}catch{}},wE=()=>{if(typeof window>"u")return!1;try{const e=window.sessionStorage.getItem(ch);return e&&window.sessionStorage.removeItem(ch),e==="1"}catch{return!1}},A6=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(Tp),window.localStorage.removeItem(Mp),window.sessionStorage.removeItem(lh),window.sessionStorage.removeItem(oh),window.sessionStorage.removeItem(ch),window.sessionStorage.removeItem(fd),window.sessionStorage.removeItem(uh)}catch{}},Ap=Ac("Preferences",{web:()=>cl(()=>import("./web-CiNw0NeJ.js"),[]).then(e=>new e.PreferencesWeb)}),NE=new Set(["4173","4174"]),kE="PandaMobile",I6="hub_url",D6="onboarding_completed",Q_=new Set;let dr={platform:rd(),hubUrl:"",onboardingCompleted:!1};const O6=()=>{for(const e of Q_)e()},EE=e=>(Q_.add(e),()=>{Q_.delete(e)}),Tc=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";try{return new URL(t).toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}},CE=()=>typeof window>"u"?null:window.location.origin||null,L6=e=>{if(typeof window>"u")return`http://localhost:${e}`;const t=window.location.protocol==="https:"?"https:":"http:",i=window.location.hostname||"localhost";return`${t}//${i}:${e}`},TE=()=>Tc(L6(4242)),ME=()=>{const e=Tc(void 0);if(e)return e;const t=CE();if(!t)return"http://localhost:4343";const i=window.location.port.trim();return NE.has(i)?L6(4343):Tc(t)},RE=()=>Tc(void 0),AE=()=>!1,IE=()=>{const e=rd();if(e==="web")return{platform:e,hubUrl:ME(),onboardingCompleted:!0};const t=RE();return{platform:e,hubUrl:t,onboardingCompleted:!!t}},m4=async e=>{if(ba()){const{value:t}=await Ap.get({key:e});return t}if(typeof window>"u")return null;try{return window.localStorage.getItem(`panda:runtime:${e}`)}catch{return null}},p4=async(e,t)=>{if(ba()){if(t===null){await Ap.remove({key:e});return}await Ap.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{}},DE=async()=>{const e=IE();ba()&&await Ap.configure({group:kE});const[t,i]=await Promise.all([m4(I6),m4(D6)]),r=e.platform==="web"?e.hubUrl:Tc(t)||e.hubUrl,o=e.platform==="web"?!0:i==="true"||!!(r&&e.onboardingCompleted);return dr={platform:e.platform,hubUrl:r,onboardingCompleted:o},O6(),dr},G_=()=>dr,OE=()=>Tc(dr.hubUrl),LE=()=>{const e=G_();return e.platform==="web"?AE():!e.hubUrl||!e.onboardingCompleted},P6=async e=>{const t=e.hubUrl===void 0?dr.hubUrl:Tc(e.hubUrl),i=e.onboardingCompleted??dr.onboardingCompleted;return dr={...dr,hubUrl:t,onboardingCompleted:i},dr.platform!=="web"&&await Promise.all([p4(I6,t||null),p4(D6,i?"true":"false")]),O6(),dr},Zp=()=>_.useSyncExternalStore(EE,G_,G_),PE=new Set(["localhost","127.0.0.1","::1"]),U6=()=>TE(),bd=()=>OE(),g4=new Map,UE={direct:"Agent 直连",hub:"Hub 聚合"},zE=1e4,BE=1e4,z6=1e4,$E=1e4,_4=1200,y4=5e3;let np=null,Y_=0,Uu=null,Fu=null,Ip=0,zu=null,sp=null,V_=0,Bu=null;const X_=new Map,ap=new Map,ip=new Map,bi=e=>(e==null?void 0:e.trim())??"",B6=e=>{const t=(e==null?void 0:e.trim())??"";return t?t.replace(/^\[|\]$/g,"").replace(/\.+$/,"").toLowerCase():""},$6=e=>PE.has(B6(e)),hd=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";try{const i=new URL(t),r=B6(i.hostname);return r&&(i.hostname=r),i.toString().replace(/\/+$/,"")}catch{return t}},md=()=>typeof window>"u"||ba()?!1:$6(window.location.hostname),HE=e=>{const t=e.trim();if(!t)return _4;try{const i=new URL(t);return $6(i.hostname)?_4:y4}catch{return y4}},pd=async e=>{const t=e.trim();if(!t)return!1;const i=ip.get(t),r=Date.now();if(i&&r-i.checkedAt<$E)return i.reachable;const o=new AbortController,u=globalThis.setTimeout(()=>o.abort(),HE(t));try{const m=(await fetch(`${t}/health`,{signal:o.signal})).ok;return ip.set(t,{reachable:m,checkedAt:Date.now()}),m}catch{return ip.set(t,{reachable:!1,checkedAt:Date.now()}),!1}finally{clearTimeout(u)}},xd=(e,t)=>{const i=`${e}::${(t==null?void 0:t.trim())??""}`,r=g4.get(i);if(r)return r;const o=M6(e,{wsBaseUrl:t});return g4.set(i,o),o},v4=()=>xd(H6()),b4=e=>{const t=e(Fu);Fu=t,Ip=t?Date.now():0},K0=(e,t,i)=>({mode:"direct",label:e,baseUrl:t,client:xd(t,i)}),H6=()=>{const e=bd();if(!e)throw new Error("尚未配置 Panda Hub 地址,请先完成应用连接设置。");return e},Xf=e=>{const t=e==="hub"?H6():U6();return{mode:e,label:UE[e],baseUrl:t,client:xd(t)}},F6=e=>hd(e.direct_base_url),FE=e=>hd(e.ws_base_url),x4=e=>{const t=F6(e)||e.tailscale_dns_name||e.tailscale_ip||e.host;return`无法直连节点 ${Cc(e)}(${t})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`},qE=async()=>{if(!md())return null;const e=Date.now();if(sp&&e-V_<z6)return sp;if(Bu)return Bu;Bu=(async()=>{const t=U6();if(!await pd(t))return null;const i=await xd(t).getPhaseOneSnapshot({fallbackToMock:!1});return sp=i,V_=Date.now(),i})().catch(()=>null);try{return await Bu}finally{Bu=null}},q6=async e=>{var r,o;const t=await qE(),i=((o=(r=t==null?void 0:t.agents[0])==null?void 0:r.id)==null?void 0:o.trim())??"";return!!(i&&i===e.trim())},W6=async e=>{if(await q6(e.id))return{...Xf("direct"),label:`Agent 直连 · ${Cc(e)}(本机)`};const t=F6(e),i=FE(e);return K0(`Agent 直连 · ${Cc(e)}`,t,i||void 0)},WE=async e=>{if(await q6(e.agent_id))return{...Xf("direct"),label:`Agent 直连 · ${e.agent_id}(本机)`};const t=hd(e.direct_base_url),i=hd(e.ws_base_url);return K0(`Agent 直连 · ${e.agent_id}`,t,i||void 0)},K6=e=>{var r;const t=bi(e.agentId);if(!t)return null;const i=kh(t);return i!=null&&i.directBaseUrl.trim()?K0(`Agent 直连 · ${((r=i.displayName)==null?void 0:r.trim())||i.name.trim()||t}`,hd(i.directBaseUrl),hd(i.wsBaseUrl)||void 0):null},S4=async e=>{const t=K6(e);if(t!=null&&t.baseUrl&&(await pd(t.baseUrl)||!md()))return t;const i=await G6(),r=i?Q6(i,e):null;if(!r)return null;const o=await W6(r);return o.baseUrl&&(await pd(o.baseUrl)||!md())?o:null},Q6=(e,t)=>{const i=bi(t.agentId);return i?e.agents.find(r=>r.id===i)??null:null},KE=e=>{const t=bi(e.sessionId),i=bi(e.projectId),r=bi(e.agentId);return r?`agent:${r}`:i?`project:${i}`:t?`session:${t}`:""},G6=async()=>{const e=Date.now();if(Fu&&e-Ip<z6)return Fu;if(zu)return zu;zu=(async()=>{const t=bd();if(!t)return null;const i=await xd(t).getHubDirectory();return Fu=i,Ip=Date.now(),i})().catch(()=>null);try{return await zu}finally{zu=null}},QE=async()=>{if(!md())return Xf("hub");const e=Date.now();if(np&&e-Y_<zE)return np;if(Uu)return Uu;Uu=(async()=>{const t=bd(),i=t&&await pd(t)?Xf("hub"):Xf("direct");return np=i,Y_=Date.now(),i})();try{return await Uu}finally{Uu=null}},GE=async e=>{const t=KE(e),i=Date.now(),r=t?X_.get(t):null;if(r&&i-r.cachedAt<BE)return r.target;const o=t?ap.get(t):null;if(o)return o;const u=(async()=>{const d=bi(e.sessionId),m=bi(e.agentId),y=K6(e),g=bd();if(!g&&!y&&!m)throw new Error("尚未配置 Panda Hub 地址,请先完成应用连接设置。");const b=g?xd(g):null;if(m){const N=await S4(e);if(N)return N}if(d){const N=b?await b.getSessionLocation(d).catch(()=>null):null;if(!N){const T=m?await S4(e):null;if(T)return T;throw new Error("Hub 未返回目标会话位置,无法建立直连。")}const j=await WE(N);if(!j.baseUrl)throw new Error(`无法直连节点 ${N.agent_id}(${N.direct_base_url||N.ws_base_url||"unknown"})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`);if(await pd(j.baseUrl)||!md())return j;throw new Error(`无法直连节点 ${N.agent_id}(${N.direct_base_url||N.ws_base_url||"unknown"})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`)}if(bi(e.projectId)&&!bi(e.agentId))throw new Error("Project-scoped connection resolution now requires agentId.");const p=await G6(),v=p?Q6(p,e):null;if(!v)throw new Error("Hub 未返回目标节点信息,无法建立直连。");const w=await W6(v);if(!w.baseUrl)throw new Error(x4(v));if(await pd(w.baseUrl)||!md())return w;throw new Error(x4(v))})();t&&ap.set(t,u);try{const d=await u;return t&&X_.set(t,{target:d,cachedAt:Date.now()}),d}finally{t&&ap.delete(t)}},cn=async e=>!(bi(e==null?void 0:e.sessionId)||bi(e==null?void 0:e.projectId)||bi(e==null?void 0:e.agentId))?QE():GE(e??{}),YE=()=>{np=null,Y_=0,Uu=null,Fu=null,Ip=0,zu=null,sp=null,V_=0,Bu=null,X_.clear(),ap.clear(),ip.clear()},Y6="panda:notification-settings",V6="panda:notified-completions",Q0="panda:web-push-subscription-state",VE=280,X6="session-completions",B1={completionNotificationsEnabled:!1};let dh=ba()?"default":"unsupported";const Eh=()=>{const e=bd();if(!e)throw new Error("尚未配置 Panda Hub 地址。");return M6(e)},Z6=e=>({completionNotificationsEnabled:(e==null?void 0:e.completionNotificationsEnabled)===!0}),XE=(e,t)=>e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`,J6=()=>{if(typeof window>"u")return{};try{const e=window.localStorage.getItem(V6);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(i=>typeof i[0]=="string"&&typeof i[1]=="string"))}catch{return{}}},ZE=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(V6,JSON.stringify(e))}catch{}},JE=e=>{if(!e||typeof e!="object")return null;const t=typeof e.endpoint=="string"?e.endpoint.trim():"",i=typeof e.updatedAt=="string"?e.updatedAt.trim():"";return!t||!i?null:{completionNotificationsEnabled:e.completionNotificationsEnabled===!0,endpoint:t,updatedAt:i}},e3=()=>{if(typeof window>"u")return null;try{return JE(JSON.parse(window.localStorage.getItem(Q0)??"null"))}catch{return null}},t3=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Q0,JSON.stringify(e))}catch{}},Dp=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(Q0)}catch{}},n3=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))throw new Error("当前环境没有可用的 Service Worker。");return navigator.serviceWorker.ready},eC=e=>{const t="=".repeat((4-e.length%4)%4),i=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(i),o=new Uint8Array(r.length);for(let u=0;u<r.length;u+=1)o[u]=r.charCodeAt(u);return o},G0=async()=>{const e=await n3();return"pushManager"in e?e.pushManager.getSubscription():null},s3=e=>{var u,d;const t=e.toJSON(),i=e.endpoint.trim(),r=typeof((u=t.keys)==null?void 0:u.p256dh)=="string"?t.keys.p256dh.trim():"",o=typeof((d=t.keys)==null?void 0:d.auth)=="string"?t.keys.auth.trim():"";if(!i||!r||!o)throw new Error("浏览器返回的推送订阅信息不完整。");return{endpoint:i,expirationTime:typeof e.expirationTime=="number"?e.expirationTime:null,keys:{p256dh:r,auth:o}}},a3=async()=>{try{return await Eh().getWebPushPublicConfig()}catch(e){throw new Error(e instanceof Error?e.message:"无法读取 Hub Web Push 配置。")}},Z_=()=>{if(typeof window>"u")return B1;try{const e=window.localStorage.getItem(Y6);return e?Z6(JSON.parse(e)):B1}catch{return B1}},sc=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Y6,JSON.stringify(Z6(e)))}catch{}},Ch=()=>ba()?!0:typeof window>"u"?!1:window.isSecureContext&&"Notification"in window&&"serviceWorker"in navigator,gd=()=>ba()||!Ch()?!1:"PushManager"in window,qu=()=>ba()?dh:Ch()?Notification.permission:"unsupported",i3=e=>e==="granted"?"granted":e==="denied"?"denied":e==="prompt"?"default":"unsupported",r3=async()=>{Yp()&&await wh.createChannel({id:X6,name:"任务完成提醒",description:"Panda 对话和任务完成提醒",importance:4,visibility:1,vibration:!0,lights:!0}).catch(()=>{})},Y0=async()=>{if(ba()){const e=await wh.checkPermissions();return dh=i3(e.display),dh}return Ch()?Notification.permission:"unsupported"},J_=async()=>{if(ba()){await r3();const e=await wh.requestPermissions();return dh=i3(e.display),dh}return Ch()?Notification.requestPermission():"unsupported"},e0=()=>{var e;return((e=e3())==null?void 0:e.completionNotificationsEnabled)===!0},tC=async e=>{if(!e.completionNotificationsEnabled||qu()!=="granted")return{synced:!1,reason:"notifications-disabled"};if(!gd())return{synced:!1,reason:"unsupported"};const t=await a3();if(!t.supported||!t.vapid_public_key)return Dp(),{synced:!1,reason:"hub-unsupported"};const i=await G0();if(!i)return Dp(),{synced:!1,reason:"missing-browser-subscription"};const r=await Eh().upsertWebPushSubscription({subscription:s3(i),settings:{completion_notifications_enabled:e.completionNotificationsEnabled},device:{label:$u()?"installed-pwa":"browser-tab",user_agent:typeof navigator<"u"?navigator.userAgent:null}});return t3({completionNotificationsEnabled:r.settings.completion_notifications_enabled,endpoint:r.endpoint,updatedAt:r.updated_at}),{synced:!0,endpoint:r.endpoint}},j4=async e=>{if(!gd())throw new Error("当前环境不支持 Web Push。");const t=await a3();if(!t.supported||!t.vapid_public_key)throw new Error(t.reason??"Hub 当前没有可用的 Web Push 配置。");const i=await n3(),o=await i.pushManager.getSubscription()??null??await i.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:eC(t.vapid_public_key)}),u=await Eh().upsertWebPushSubscription({subscription:s3(o),settings:{completion_notifications_enabled:e.completionNotificationsEnabled},device:{label:$u()?"installed-pwa":"browser-tab",user_agent:typeof navigator<"u"?navigator.userAgent:null}});return t3({completionNotificationsEnabled:u.settings.completion_notifications_enabled,endpoint:u.endpoint,updatedAt:u.updated_at}),u},nC=async()=>{if(!gd())return Dp(),{removed:!1};const e=await G0();if(e){try{await Eh().removeWebPushSubscription({endpoint:e.endpoint})}catch{}try{await e.unsubscribe()}catch{}}return Dp(),{removed:!!e}},sC=async()=>{var r,o;if(!gd())throw new Error("当前环境不支持 Web Push。");if(qu()!=="granted")throw new Error("请先授予系统通知权限。");const e=await G0(),t=e3(),i=((r=e==null?void 0:e.endpoint)==null?void 0:r.trim())||((o=t==null?void 0:t.endpoint)==null?void 0:o.trim())||"";if(!i)throw new Error("当前设备还没有可用的 Web Push 订阅。");return await Eh().sendWebPushTest({endpoint:i}),{ok:!0,endpoint:i}},$u=()=>{if(typeof window>"u")return!1;const e=navigator;return window.matchMedia("(display-mode: standalone)").matches||e.standalone===!0},w4=()=>typeof navigator>"u"?!1:/Android/i.test(navigator.userAgent),aC=e=>{if(typeof e!="string")return"";const t=e.replace(/\r\n/g,`
|
|
66
|
+
*/var Tb;function v7(){if(Tb)return R1;Tb=1;var e=jh(),t=y7();function i(g,b){return g===b&&(g!==0||1/g===1/b)||g!==g&&b!==b}var r=typeof Object.is=="function"?Object.is:i,o=t.useSyncExternalStore,u=e.useRef,d=e.useEffect,m=e.useMemo,y=e.useDebugValue;return R1.useSyncExternalStoreWithSelector=function(g,b,p,v,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 M(Q){if(!P){if(P=!0,I=Q,Q=v(Q),w!==void 0&&j.hasValue){var J=j.value;if(w(J,Q))return k=J}return k=Q}if(J=k,r(I,Q))return J;var F=v(Q);return w!==void 0&&w(J,F)?(I=Q,J):(I=Q,k=F)}var P=!1,I,k,O=p===void 0?null:p;return[function(){return M(b())},O===null?void 0:function(){return M(O())}]},[b,p,v,w]);var T=o(g,N[0],N[1]);return d(function(){j.hasValue=!0,j.value=T},[T]),y(T),T},R1}var Mb;function b7(){return Mb||(Mb=1,M1.exports=v7()),M1.exports}var x7=b7();function S7(e,t){return e===t}function j7(e,t,i=S7){const r=_.useCallback(d=>{if(!e)return()=>{};const{unsubscribe:m}=e.subscribe(d);return m},[e]),o=_.useCallback(()=>e==null?void 0:e.get(),[e]);return x7.useSyncExternalStoreWithSelector(r,o,o,t,i)}function ai(e){const t=xi({warn:(e==null?void 0:e.router)===void 0}),i=(e==null?void 0:e.router)||t,r=_.useRef(void 0);return j7(i.__store,o=>{if(e!=null&&e.select){if(e.structuralSharing??i.options.defaultStructuralSharing){const u=oc(r.current,e.select(o));return r.current=u,u}return e.select(o)}return o})}var Gp=_.createContext(void 0),w7=_.createContext(void 0);function _o(e){const t=_.useContext(e.from?w7:Gp);return ai({select:i=>{const r=i.matches.find(o=>e.from?e.from===o.routeId:o.id===t);if(po(!((e.shouldThrow??!0)&&!r),`Could not find ${e.from?`an active match from "${e.from}"`:"a nearest match!"}`),r!==void 0)return e.select?e.select(r):r},structuralSharing:e.structuralSharing})}function M0(e){return _o({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function R0(e){const{select:t,...i}=e;return _o({...i,select:r=>t?t(r.loaderDeps):r.loaderDeps})}function Mc(e){return _o({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{const i=e.strict===!1?t.params:t._strictParams;return e.select?e.select(i):i}})}function A0(e){return _o({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function Hi(e){const t=xi();return _.useCallback(i=>t.navigate({...i,from:i.from??(e==null?void 0:e.from)}),[e==null?void 0:e.from,t])}function I0(e){return _o({...e,select:t=>e.select?e.select(t.context):t.context})}var ra=d2();function N7(e,t){const i=xi(),r=YS(t),{activeProps:o,inactiveProps:u,activeOptions:d,to:m,preload:y,preloadDelay:g,hashScrollIntoView:b,replace:p,startTransition:v,resetScroll:w,viewTransition:N,children:j,target:T,disabled:M,style:P,className:I,onClick:k,onBlur:O,onFocus:Q,onMouseEnter:J,onMouseLeave:F,onTouchStart:B,ignoreBlocker:G,params:Z,search:ae,hash:he,state:ne,mask:Ce,reloadDocument:R,unsafeRelative:X,from:le,_fromLocation:ue,...ye}=e,D=z2(),oe=ai({select:lt=>{const Et=lt.matches[lt.matches.length-1];return{search:Et==null?void 0:Et.search,hash:lt.location.hash,path:Et==null?void 0:Et.pathname}},structuralSharing:!0}),je=e.from,z=_.useMemo(()=>({...e,from:je}),[i,oe,je,e._fromLocation,e.hash,e.to,e.search,e.params,e.state,e.mask,e.unsafeRelative]),be=_.useMemo(()=>i.buildLocation({...z}),[i,z]),De=be.maskedLocation?be.maskedLocation.publicHref:be.publicHref,se=be.maskedLocation?be.maskedLocation.external:be.external,pe=_.useMemo(()=>R7(De,se,i.history,M),[M,se,De,i.history]),ke=_.useMemo(()=>{if(pe!=null&&pe.external)return hp(pe.href,i.protocolAllowlist)?void 0:pe.href;if(!A7(m)&&!(typeof m!="string"||m.indexOf(":")===-1))try{return new URL(m),hp(m,i.protocolAllowlist)?void 0:m}catch{}},[m,pe,i.protocolAllowlist]),Ze=ai({select:lt=>{if(ke)return!1;if(d!=null&&d.exact){if(!mj(lt.location.pathname,be.pathname,i.basepath))return!1}else{const Et=pp(lt.location.pathname,i.basepath),rt=pp(be.pathname,i.basepath);if(!(Et.startsWith(rt)&&(Et.length===rt.length||Et[rt.length]==="/")))return!1}return((d==null?void 0:d.includeSearch)??!0)&&!bc(lt.location.search,be.search,{partial:!(d!=null&&d.exact),ignoreUndefined:!(d!=null&&d.explicitUndefined)})?!1:d!=null&&d.includeHash?D&<.location.hash===be.hash:!0}}),zt=Ze?oo(o,{})??k7:D1,Fe=Ze?D1:oo(u,{})??D1,kt=[I,zt.className,Fe.className].filter(Boolean).join(" "),Bt=(P||zt.style||Fe.style)&&{...P,...zt.style,...Fe.style},[Gt,Xt]=_.useState(!1),Ft=_.useRef(!1),qe=e.reloadDocument||ke?!1:y??i.options.defaultPreload,dt=g??i.options.defaultPreloadDelay??0,un=_.useCallback(()=>{i.preloadRoute({...z,_builtLocation:be}).catch(lt=>{console.warn(lt),console.warn(f7)})},[i,z,be]);GS(r,_.useCallback(lt=>{lt!=null&<.isIntersecting&&un()},[un]),M7,{disabled:!!M||qe!=="viewport"}),_.useEffect(()=>{Ft.current||!M&&qe==="render"&&(un(),Ft.current=!0)},[M,un,qe]);const $t=lt=>{const Et=lt.currentTarget.getAttribute("target"),rt=T!==void 0?T:Et;if(!M&&!I7(lt)&&!lt.defaultPrevented&&(!rt||rt==="_self")&<.button===0){lt.preventDefault(),ra.flushSync(()=>{Xt(!0)});const st=i.subscribe("onResolved",()=>{st(),Xt(!1)});i.navigate({...z,replace:p,resetScroll:w,hashScrollIntoView:b,startTransition:v,viewTransition:N,ignoreBlocker:G})}};if(ke)return{...ye,ref:r,href:ke,...j&&{children:j},...T&&{target:T},...M&&{disabled:M},...P&&{style:P},...I&&{className:I},...k&&{onClick:k},...O&&{onBlur:O},...Q&&{onFocus:Q},...J&&{onMouseEnter:J},...F&&{onMouseLeave:F},...B&&{onTouchStart:B}};const An=lt=>{if(M||qe!=="intent")return;if(!dt){un();return}const Et=lt.currentTarget;if(Df.has(Et))return;const rt=setTimeout(()=>{Df.delete(Et),un()},dt);Df.set(Et,rt)},Nn=lt=>{M||qe!=="intent"||un()},Tt=lt=>{if(M||!qe||!dt)return;const Et=lt.currentTarget,rt=Df.get(Et);rt&&(clearTimeout(rt),Df.delete(Et))};return{...ye,...zt,...Fe,href:pe==null?void 0:pe.href,ref:r,onClick:Eu([k,$t]),onBlur:Eu([O,Tt]),onFocus:Eu([Q,An]),onMouseEnter:Eu([J,An]),onMouseLeave:Eu([F,Tt]),onTouchStart:Eu([B,Nn]),disabled:!!M,target:T,...Bt&&{style:Bt},...kt&&{className:kt},...M&&E7,...Ze&&C7,...D&&Gt&&T7}}var D1={},k7={className:"active"},E7={role:"link","aria-disabled":!0},C7={"data-status":"active","aria-current":"page"},T7={"data-transitioning":"transitioning"},Df=new WeakMap,M7={rootMargin:"100px"},Eu=e=>t=>{for(const i of e)if(i){if(t.defaultPrevented)return;i(t)}};function R7(e,t,i,r){if(!r)return t?{href:e,external:!0}:{href:i.createHref(e)||"/",external:!1}}function A7(e){if(typeof e!="string")return!1;const t=e.charCodeAt(0);return t===47?e.charCodeAt(1)!==47:t===46}var bp=_.forwardRef((e,t)=>{const{_asChild:i,...r}=e,{type:o,...u}=N7(r,t),d=typeof r.children=="function"?r.children({isActive:u["data-status"]==="active"}):r.children;if(!i){const{disabled:m,...y}=u;return _.createElement("a",y,d)}return _.createElement(i,u,d)});function I7(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}var D7=class extends U2{constructor(e){super(e),this.useMatch=t=>_o({select:t==null?void 0:t.select,from:this.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>I0({...t,from:this.id}),this.useSearch=t=>A0({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useParams=t=>Mc({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useLoaderDeps=t=>R0({...t,from:this.id}),this.useLoaderData=t=>M0({...t,from:this.id}),this.useNavigate=()=>Hi({from:this.fullPath}),this.Link=tl.forwardRef((t,i)=>a.jsx(bp,{ref:i,from:this.fullPath,...t})),this.$$typeof=Symbol.for("react.memo")}};function Rc(e){return new D7(e)}var O7=class extends h7{constructor(e){super(e),this.useMatch=t=>_o({select:t==null?void 0:t.select,from:this.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>I0({...t,from:this.id}),this.useSearch=t=>A0({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useParams=t=>Mc({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.id}),this.useLoaderDeps=t=>R0({...t,from:this.id}),this.useLoaderData=t=>M0({...t,from:this.id}),this.useNavigate=()=>Hi({from:this.fullPath}),this.Link=tl.forwardRef((t,i)=>a.jsx(bp,{ref:i,from:this.fullPath,...t})),this.$$typeof=Symbol.for("react.memo")}};function L7(e){return new O7(e)}function Rb(e){return typeof e=="object"?new Ab(e,{silent:!0}).createRoute(e):new Ab(e,{silent:!0}).createRoute}var Ab=class{constructor(e,t){this.path=e,this.createRoute=i=>{const r=Rc(i);return r.isRoot=!1,r},this.silent=t==null?void 0:t.silent}},Ib=class{constructor(e){this.useMatch=t=>_o({select:t==null?void 0:t.select,from:this.options.id,structuralSharing:t==null?void 0:t.structuralSharing}),this.useRouteContext=t=>I0({...t,from:this.options.id}),this.useSearch=t=>A0({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.options.id}),this.useParams=t=>Mc({select:t==null?void 0:t.select,structuralSharing:t==null?void 0:t.structuralSharing,from:this.options.id}),this.useLoaderDeps=t=>R0({...t,from:this.options.id}),this.useLoaderData=t=>M0({...t,from:this.options.id}),this.useNavigate=()=>Hi({from:xi().routesById[this.options.id].fullPath}),this.options=e,this.$$typeof=Symbol.for("react.memo")}};function Db(e){return typeof e=="object"?new Ib(e):t=>new Ib({id:e,...t})}function P7(e){const t=ai({select:i=>`not-found-${i.location.pathname}-${i.status}`});return a.jsx(C0,{getResetKey:()=>t,onCatch:(i,r)=>{var o;if(Ca(i))(o=e.onCatch)==null||o.call(e,i,r);else throw i},errorComponent:({error:i})=>{var r;if(Ca(i))return(r=e.fallback)==null?void 0:r.call(e,i);throw i},children:e.children})}function U7(){return a.jsx("p",{children:"Not Found"})}function Lu(e){return a.jsx(a.Fragment,{children:e.children})}function $2(e,t,i){return t.options.notFoundComponent?a.jsx(t.options.notFoundComponent,{...i}):e.options.defaultNotFoundComponent?a.jsx(e.options.defaultNotFoundComponent,{...i}):a.jsx(U7,{})}function z7(){return xi().isScrollRestoring,null}var H2=_.memo(function({matchId:t}){var N,j;const i=xi(),r=ai({select:T=>{var I;const M=T.matches.findIndex(k=>k.id===t),P=T.matches[M];return po(P),{routeId:P.routeId,ssr:P.ssr,_displayPending:P._displayPending,resetKey:T.loadedAt,parentRouteId:(I=T.matches[M-1])==null?void 0:I.routeId}},structuralSharing:!0}),o=i.routesById[r.routeId],u=o.options.pendingComponent??i.options.defaultPendingComponent,d=u?a.jsx(u,{}):null,m=o.options.errorComponent??i.options.defaultErrorComponent,y=o.options.onCatch??i.options.defaultOnCatch,g=o.isRoot?o.options.notFoundComponent??((N=i.options.notFoundRoute)==null?void 0:N.options.component):o.options.notFoundComponent,b=r.ssr===!1||r.ssr==="data-only",p=(!o.isRoot||o.options.wrapInSuspense||b)&&(o.options.wrapInSuspense??u??(((j=o.options.errorComponent)==null?void 0:j.preload)||b))?_.Suspense:Lu,v=m?C0:Lu,w=g?P7:Lu;return a.jsxs(o.isRoot?o.options.shellComponent??Lu:Lu,{children:[a.jsx(Gp.Provider,{value:t,children:a.jsx(p,{fallback:d,children:a.jsx(v,{getResetKey:()=>r.resetKey,errorComponent:m||T0,onCatch:(T,M)=>{if(Ca(T))throw T;y==null||y(T,M)},children:a.jsx(w,{fallback:T=>{if(!g||T.routeId&&T.routeId!==r.routeId||!T.routeId&&!o.isRoot)throw T;return _.createElement(g,T)},children:b||r._displayPending?a.jsx(p7,{fallback:d,children:a.jsx(Ob,{matchId:t})}):a.jsx(Ob,{matchId:t})})})})}),r.parentRouteId===xc&&i.options.scrollRestoration?a.jsxs(a.Fragment,{children:[a.jsx(B7,{}),a.jsx(z7,{})]}):null]})});function B7(){const e=xi(),t=_.useRef(void 0);return a.jsx("script",{suppressHydrationWarning:!0,ref:i=>{i&&(t.current===void 0||t.current.href!==e.latestLocation.href)&&(e.emit({type:"onRendered",...jc(e.state)}),t.current=e.latestLocation)}},e.latestLocation.state.__TSR_key)}var Ob=_.memo(function({matchId:t}){var y,g,b,p;const i=xi(),{match:r,key:o,routeId:u}=ai({select:v=>{var T;const w=v.matches.find(M=>M.id===t),N=w.routeId,j=(T=i.routesById[N].options.remountDeps??i.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}),d=i.routesById[u],m=_.useMemo(()=>{const v=d.options.component??i.options.defaultComponent;return v?a.jsx(v,{},o):a.jsx(F2,{})},[o,d.options.component,i.options.defaultComponent]);if(r._displayPending)throw(y=i.getMatch(r.id))==null?void 0:y._nonReactive.displayPendingPromise;if(r._forcePending)throw(g=i.getMatch(r.id))==null?void 0:g._nonReactive.minPendingPromise;if(r.status==="pending"){const v=d.options.pendingMinMs??i.options.defaultPendingMinMs;if(v){const w=i.getMatch(r.id);if(w&&!w._nonReactive.minPendingPromise){const N=ad();w._nonReactive.minPendingPromise=N,setTimeout(()=>{N.resolve(),w._nonReactive.minPendingPromise=void 0},v)}}throw(b=i.getMatch(r.id))==null?void 0:b._nonReactive.loadPromise}if(r.status==="notFound")return po(Ca(r.error)),$2(i,d,r.error);if(r.status==="redirected")throw po(Wa(r.error)),(p=i.getMatch(r.id))==null?void 0:p._nonReactive.loadPromise;if(r.status==="error")throw r.error;return m}),F2=_.memo(function(){const t=xi(),i=_.useContext(Gp),r=ai({select:g=>{var b;return(b=g.matches.find(p=>p.id===i))==null?void 0:b.routeId}}),o=t.routesById[r],u=ai({select:g=>{const b=g.matches.find(p=>p.id===i);return po(b),b.globalNotFound}}),d=ai({select:g=>{var p;const b=g.matches;return(p=b[b.findIndex(v=>v.id===i)+1])==null?void 0:p.id}}),m=t.options.defaultPendingComponent?a.jsx(t.options.defaultPendingComponent,{}):null;if(u)return $2(t,o,void 0);if(!d)return null;const y=a.jsx(H2,{matchId:d});return r===xc?a.jsx(_.Suspense,{fallback:m,children:y}):y});function $7(){const e=xi(),t=_.useRef({router:e,mounted:!1}),[i,r]=_.useState(!1),{hasPendingMatches:o,isLoading:u}=ai({select:p=>({isLoading:p.isLoading,hasPendingMatches:p.matches.some(v=>v.status==="pending")}),structuralSharing:!0}),d=w1(u),m=u||i||o,y=w1(m),g=u||o,b=w1(g);return e.startTransition=p=>{r(!0),_.startTransition(()=>{p(),r(!1)})},_.useEffect(()=>{const p=e.history.subscribe(e.load),v=e.buildLocation({to:e.latestLocation.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});return fo(e.latestLocation.publicHref)!==fo(v.publicHref)&&e.commitLocation({...v,replace:!0}),()=>{p()}},[e,e.history]),Dm(()=>{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(v){console.error(v)}})()},[e]),Dm(()=>{d&&!u&&e.emit({type:"onLoad",...jc(e.state)})},[d,e,u]),Dm(()=>{b&&!g&&e.emit({type:"onBeforeRouteMount",...jc(e.state)})},[g,b,e]),Dm(()=>{if(y&&!m){const p=jc(e.state);e.emit({type:"onResolved",...p}),e.__store.setState(v=>({...v,status:"idle",resolvedLocation:v.location})),p.hrefChanged&&wj(e)}},[m,y,e]),null}function H7(){const e=xi(),t=e.routesById[xc].options.pendingComponent??e.options.defaultPendingComponent,i=t?a.jsx(t,{}):null,r=a.jsxs(typeof document<"u"&&e.ssr?Lu:_.Suspense,{fallback:i,children:[a.jsx($7,{}),a.jsx(F7,{})]});return e.options.InnerWrap?a.jsx(e.options.InnerWrap,{children:r}):r}function F7(){const e=xi(),t=ai({select:o=>{var u;return(u=o.matches[0])==null?void 0:u.id}}),i=ai({select:o=>o.loadedAt}),r=t?a.jsx(H2,{matchId:t}):null;return a.jsx(Gp.Provider,{value:t,children:e.options.disableGlobalCatchBoundary?r:a.jsx(C0,{getResetKey:()=>i,errorComponent:T0,onCatch:void 0,children:r})})}var q7=e=>new W7(e),W7=class extends i7{constructor(e){super(e)}};typeof globalThis<"u"?(globalThis.createFileRoute=Rb,globalThis.createLazyFileRoute=Db):typeof window<"u"&&(window.createFileRoute=Rb,window.createLazyFileRoute=Db);function K7({router:e,children:t,...i}){Object.keys(i).length>0&&e.update({...e.options,...i,context:{...e.options.context,...i.context}});const r=a.jsx(B2.Provider,{value:e,children:t});return e.options.Wrap?a.jsx(e.options.Wrap,{children:r}):r}function Q7({router:e,...t}){return a.jsx(K7,{router:e,...t,children:a.jsx(H7,{})})}/*! Capacitor: https://capacitorjs.com/ - MIT License */var id;(function(e){e.Unimplemented="UNIMPLEMENTED",e.Unavailable="UNAVAILABLE"})(id||(id={}));class O1 extends Error{constructor(t,i,r){super(t),this.message=t,this.code=i,this.data=r}}const G7=e=>{var t,i;return e!=null&&e.androidBridge?"android":!((i=(t=e==null?void 0:e.webkit)===null||t===void 0?void 0:t.messageHandlers)===null||i===void 0)&&i.bridge?"ios":"web"},Y7=e=>{const t=e.CapacitorCustomPlatform||null,i=e.Capacitor||{},r=i.Plugins=i.Plugins||{},o=()=>t!==null?t.name:G7(e),u=()=>o()!=="web",d=p=>{const v=g.get(p);return!!(v!=null&&v.platforms.has(o())||m(p))},m=p=>{var v;return(v=i.PluginHeaders)===null||v===void 0?void 0:v.find(w=>w.name===p)},y=p=>e.console.error(p),g=new Map,b=(p,v={})=>{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 M=async()=>(!T&&N in v?T=typeof v[N]=="function"?T=await v[N]():T=v[N]:t!==null&&!T&&"web"in v&&(T=typeof v.web=="function"?T=await v.web():T=v.web),T),P=(F,B)=>{var G,Z;if(j){const ae=j==null?void 0:j.methods.find(he=>B===he.name);if(ae)return ae.rtype==="promise"?he=>i.nativePromise(p,B.toString(),he):(he,ne)=>i.nativeCallback(p,B.toString(),he,ne);if(F)return(G=F[B])===null||G===void 0?void 0:G.bind(F)}else{if(F)return(Z=F[B])===null||Z===void 0?void 0:Z.bind(F);throw new O1(`"${p}" plugin is not implemented on ${N}`,id.Unimplemented)}},I=F=>{let B;const G=(...Z)=>{const ae=M().then(he=>{const ne=P(he,F);if(ne){const Ce=ne(...Z);return B=Ce==null?void 0:Ce.remove,Ce}else throw new O1(`"${p}.${F}()" is not implemented on ${N}`,id.Unimplemented)});return F==="addListener"&&(ae.remove=async()=>B()),ae};return G.toString=()=>`${F.toString()}() { [capacitor code] }`,Object.defineProperty(G,"name",{value:F,writable:!1,configurable:!1}),G},k=I("addListener"),O=I("removeListener"),Q=(F,B)=>{const G=k({eventName:F},B),Z=async()=>{const he=await G;O({eventName:F,callbackId:he},B)},ae=new Promise(he=>G.then(()=>he({remove:Z})));return ae.remove=async()=>{console.warn("Using addListener() without 'await' is deprecated."),await Z()},ae},J=new Proxy({},{get(F,B){switch(B){case"$$typeof":return;case"toJSON":return()=>({});case"addListener":return j?Q:k;case"removeListener":return O;default:return I(B)}}});return r[p]=J,g.set(p,{name:p,proxy:J,platforms:new Set([...Object.keys(v),...j?[N]:[]])}),J};return i.convertFileSrc||(i.convertFileSrc=p=>p),i.getPlatform=o,i.handleError=y,i.isNativePlatform=u,i.isPluginAvailable=d,i.registerPlugin=b,i.Exception=O1,i.DEBUG=!!i.DEBUG,i.isLoggingEnabled=!!i.isLoggingEnabled,i},V7=e=>e.Capacitor=Y7(e),il=V7(typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}),Ac=il.registerPlugin;class q2{constructor(){this.listeners={},this.retainedEventArguments={},this.windowListeners={}}addListener(t,i){let r=!1;this.listeners[t]||(this.listeners[t]=[],r=!0),this.listeners[t].push(i);const u=this.windowListeners[t];u&&!u.registered&&this.addWindowListener(u),r&&this.sendRetainedArgumentsForEvent(t);const d=async()=>this.removeListener(t,i);return Promise.resolve({remove:d})}async removeAllListeners(){this.listeners={};for(const t in this.windowListeners)this.removeWindowListener(this.windowListeners[t]);this.windowListeners={}}notifyListeners(t,i,r){const o=this.listeners[t];if(!o){if(r){let u=this.retainedEventArguments[t];u||(u=[]),u.push(i),this.retainedEventArguments[t]=u}return}o.forEach(u=>u(i))}hasListeners(t){var i;return!!(!((i=this.listeners[t])===null||i===void 0)&&i.length)}registerWindowListener(t,i){this.windowListeners[i]={registered:!1,windowEventName:t,pluginEventName:i,handler:r=>{this.notifyListeners(i,r)}}}unimplemented(t="not implemented"){return new il.Exception(t,id.Unimplemented)}unavailable(t="not available"){return new il.Exception(t,id.Unavailable)}async removeListener(t,i){const r=this.listeners[t];if(!r)return;const o=r.indexOf(i);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 i=this.retainedEventArguments[t];i&&(delete this.retainedEventArguments[t],i.forEach(r=>{this.notifyListeners(t,r)}))}}const Lb=e=>encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape),Pb=e=>e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent);class X7 extends q2{async getCookies(){const t=document.cookie,i={};return t.split(";").forEach(r=>{if(r.length<=0)return;let[o,u]=r.replace(/=/,"CAP_COOKIE").split("CAP_COOKIE");o=Pb(o).trim(),u=Pb(u).trim(),i[o]=u}),i}async setCookie(t){try{const i=Lb(t.key),r=Lb(t.value),o=t.expires?`; expires=${t.expires.replace("expires=","")}`:"",u=(t.path||"/").replace("path=",""),d=t.url!=null&&t.url.length>0?`domain=${t.url}`:"";document.cookie=`${i}=${r||""}${o}; path=${u}; ${d};`}catch(i){return Promise.reject(i)}}async deleteCookie(t){try{document.cookie=`${t.key}=; Max-Age=0`}catch(i){return Promise.reject(i)}}async clearCookies(){try{const t=document.cookie.split(";")||[];for(const i of t)document.cookie=i.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)}}}Ac("CapacitorCookies",{web:()=>new X7});const Z7=async e=>new Promise((t,i)=>{const r=new FileReader;r.onload=()=>{const o=r.result;t(o.indexOf(",")>=0?o.split(",")[1]:o)},r.onerror=o=>i(o),r.readAsDataURL(e)}),J7=(e={})=>{const t=Object.keys(e);return Object.keys(e).map(o=>o.toLocaleLowerCase()).reduce((o,u,d)=>(o[u]=e[t[d]],o),{})},ew=(e,t=!0)=>e?Object.entries(e).reduce((r,o)=>{const[u,d]=o;let m,y;return Array.isArray(d)?(y="",d.forEach(g=>{m=t?encodeURIComponent(g):g,y+=`${u}=${m}&`}),y.slice(0,-1)):(m=t?encodeURIComponent(d):d,y=`${u}=${m}`),`${r}&${y}`},"").substr(1):null,tw=(e,t={})=>{const i=Object.assign({method:e.method||"GET",headers:e.headers},t),o=J7(e.headers)["content-type"]||"";if(typeof e.data=="string")i.body=e.data;else if(o.includes("application/x-www-form-urlencoded")){const u=new URLSearchParams;for(const[d,m]of Object.entries(e.data||{}))u.set(d,m);i.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]);i.body=u;const d=new Headers(i.headers);d.delete("content-type"),i.headers=d}else(o.includes("application/json")||typeof e.data=="object")&&(i.body=JSON.stringify(e.data));return i};class nw extends q2{async request(t){const i=tw(t,t.webFetchExtra),r=ew(t.params,t.shouldEncodeUrlParams),o=r?`${t.url}?${r}`:t.url,u=await fetch(o,i),d=u.headers.get("content-type")||"";let{responseType:m="text"}=u.ok?t:{};d.includes("application/json")&&(m="json");let y,g;switch(m){case"arraybuffer":case"blob":g=await u.blob(),y=await Z7(g);break;case"json":y=await u.json();break;case"document":case"text":default:y=await u.text()}const b={};return u.headers.forEach((p,v)=>{b[v]=p}),{data:y,headers:b,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"}))}}Ac("CapacitorHttp",{web:()=>new nw});var D_;(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"})(D_||(D_={}));var Ub;(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"})(Ub||(Ub={}));var O_;(function(e){e[e["640x480"]=0]="640x480",e[e["1280x720"]=1]="1280x720",e[e["1920x1080"]=2]="1920x1080",e[e["3840x2160"]=3]="3840x2160"})(O_||(O_={}));var L_;(function(e){e.Front="FRONT",e.Back="BACK"})(L_||(L_={}));var zb;(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"})(zb||(zb={}));var Bb;(function(e){e[e.HOME=0]="HOME",e[e.UNKNOWN=1]="UNKNOWN",e[e.WORK=2]="WORK"})(Bb||(Bb={}));var $b;(function(e){e[e.HOME=0]="HOME",e[e.UNKNOWN=1]="UNKNOWN",e[e.WORK=2]="WORK"})($b||($b={}));var Hb;(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"})(Hb||(Hb={}));var Fb;(function(e){e[e.OPEN=1]="OPEN",e[e.WEP=2]="WEP",e[e.WPA=3]="WPA"})(Fb||(Fb={}));const Jo=Ac("BarcodeScanner",{web:()=>cl(()=>import("./web-BBYipy_G.js"),[]).then(e=>new e.BarcodeScannerWeb)}),sw=8e3,xp=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";const i=t.replace(/\/+$/,"");try{const r=new URL(i);return r.pathname==="/health"&&(r.pathname="",r.search="",r.hash=""),r.toString().replace(/\/+$/,"")}catch{return i.replace(/\/health$/i,"")}},W2=e=>new Error(`连接探测超时(${e} ms),请确认手机能直接访问该 Hub 地址。`),aw=(e,t)=>{if(!(e instanceof Error))return"连接失败";const i=e.message.trim();return e.name==="AbortError"||e.name==="TimeoutError"||/aborted/i.test(i)?W2(t).message:i||"连接失败"},P_=async(e,t)=>{const i=xp(e),r=new Date().toISOString();if(!i)return{url:"",healthOk:!1,latencyMs:null,checkedAt:r,error:"地址为空"};const o=sw,u=`${i}/health`,d=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now(),m=new AbortController,y=window.setTimeout(()=>m.abort(W2(o)),o);try{const g=await fetch(u,{cache:"no-store",signal:m.signal}),b=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();return{url:i,healthOk:g.ok,latencyMs:b-d,checkedAt:r,error:g.ok?null:`HTTP ${g.status}`}}catch(g){return{url:i,healthOk:!1,latencyMs:null,checkedAt:r,error:aw(g,o)}}finally{clearTimeout(y)}},iw=()=>{var e;try{const t=(e=il.getPlatform)==null?void 0:e.call(il);if(t==="android"||t==="ios")return t}catch{}return"web"},rd=()=>iw(),K2=()=>{var e;try{return((e=il.isNativePlatform)==null?void 0:e.call(il))===!0}catch{return!1}},Yp=()=>rd()==="android"&&K2(),rw=()=>rd()==="ios"&&K2(),ba=()=>Yp()||rw(),qb=e=>typeof e!="number"||!Number.isFinite(e)?"未测得":`${Math.max(0,Math.round(e))} ms`,lw=e=>{const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},L1=e=>{var r;const t=e.trim();if(!t)return"";try{const o=new URL(t);if(o.protocol==="http:"||o.protocol==="https:")return xp(o.toString())}catch{}const i=(r=t.match(/https?:\/\/[^\s]+/i))==null?void 0:r[0];return i?xp(i):""},ow=e=>{var i;const t=[e.rawValue,e.displayValue,(i=e.urlBookmark)==null?void 0:i.url];for(const r of t){const o=(r==null?void 0:r.trim())??"";if(o)try{const u=new URL(o);return u.protocol==="panda:"&&u.searchParams.get("url")?L1(u.searchParams.get("url")??""):L1(u.toString())}catch{return L1(o)}}return""},cw=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"M8 9.25h8M8 12h8M8 14.75h5"})]}),uw=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M6 6 18 18M18 6 6 18"})}),Q2=({title:e,description:t,currentHubUrl:i,initialHubUrl:r,hint:o,saveLabel:u,savingLabel:d,saveDescription:m,saveSuccessMessage:y,onSaveSuccess:g})=>{const[b,p]=_.useState(r),[v,w]=_.useState({loading:!1,result:null}),[N,j]=_.useState({saving:!1}),[T,M]=_.useState(null),[P,I]=_.useState({active:!1,starting:!1}),k=_.useRef([]),O=xp(b),Q=ba();_.useEffect(()=>{p(r)},[r]),_.useEffect(()=>{if(!(typeof document>"u"))return document.documentElement.classList.toggle("hub-scanner-active",P.active),document.body.classList.toggle("hub-scanner-active",P.active),()=>{document.documentElement.classList.remove("hub-scanner-active"),document.body.classList.remove("hub-scanner-active")}},[P.active]),_.useEffect(()=>()=>{(async()=>(await Promise.all(k.current.map(he=>he.remove().catch(()=>{}))),k.current=[],await Jo.stopScan().catch(()=>{})))()},[]);const J=async()=>{const he=[...k.current];k.current=[],await Promise.all(he.map(ne=>ne.remove().catch(()=>{})))},F=async()=>{I(he=>({...he,active:!1})),await J(),await Jo.stopScan().catch(()=>{})},B=async()=>{if(!O){M({tone:"danger",text:"请先输入可访问的 Hub 地址。"});return}M(null),w({loading:!0,result:null});const he=await P_(O);w({loading:!1,result:he}),M({tone:he.healthOk?"success":"danger",text:he.healthOk?`连接成功,延迟 ${qb(he.latencyMs)}。`:he.error??"连接测试失败。"})},G=async()=>{var he;if(!O){M({tone:"danger",text:"请先输入可访问的 Hub 地址。"});return}M(null),j({saving:!0});try{const ne=((he=v.result)==null?void 0:he.url)===O?v.result:await P_(O);if(w({loading:!1,result:ne}),!ne.healthOk){M({tone:"danger",text:ne.error??"请先确认 Hub 地址可访问,再继续保存。"});return}await g(ne),M({tone:"success",text:y})}catch(ne){M({tone:"danger",text:ne instanceof Error?ne.message:"保存 Hub 地址失败。"})}finally{j({saving:!1})}},Z=async()=>{if(Q){M(null),I({active:!1,starting:!0});try{if(!(await Jo.isSupported()).supported){M({tone:"danger",text:"当前设备不支持扫码填入,请手动输入地址。"});return}const ne=await Jo.requestPermissions();if(ne.camera!=="granted"&&ne.camera!=="limited"){M({tone:"danger",text:"需要相机权限才能扫码,请在系统设置中允许 Panda 使用相机。"});return}const Ce=await Promise.all([Jo.addListener("barcodesScanned",R=>{const X=R.barcodes.map(ow).find(Boolean);if(!X){M({tone:"danger",text:"二维码已识别,但没有拿到可用的 Hub 地址。"}),F();return}p(X),w({loading:!1,result:null}),M({tone:"success",text:"已通过扫码填入地址,可以直接测试或保存。"}),F()}),Jo.addListener("scanError",R=>{M({tone:"danger",text:R.message||"扫码失败,请稍后重试。"}),F()})]);k.current=Ce,I({active:!0,starting:!1}),await Jo.startScan({formats:[D_.QrCode],lensFacing:L_.Back,resolution:O_["1280x720"]})}catch(he){await F(),M({tone:"danger",text:he instanceof Error?he.message:"无法启动扫码,请稍后重试。"})}finally{I(he=>({...he,starting:!1}))}}},ae=P.active&&typeof document<"u"?ra.createPortal(a.jsx("div",{className:"hub-scanner-sheet",role:"dialog","aria-modal":"true","aria-label":"扫描 Hub 地址二维码",children:a.jsxs("div",{className:"hub-scanner-sheet__content",children:[a.jsxs("div",{className:"hub-scanner-sheet__topbar",children:[a.jsx("span",{className:"hub-scanner-sheet__badge",children:"扫码填入"}),a.jsx("button",{type:"button",className:"hub-scanner-sheet__close",onClick:()=>{F()},"aria-label":"关闭扫码",children:a.jsx(uw,{})})]}),a.jsxs("div",{className:"hub-scanner-sheet__frame","aria-hidden":"true",children:[a.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--tl"}),a.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--tr"}),a.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--bl"}),a.jsx("span",{className:"hub-scanner-sheet__corner hub-scanner-sheet__corner--br"})]}),a.jsxs("div",{className:"hub-scanner-sheet__footer",children:[a.jsx("p",{children:"把电脑端显示的 Hub 二维码放进取景框,识别后会自动填入地址。"}),a.jsx("button",{type:"button",className:"settings-ghost-button hub-scanner-sheet__cancel",onClick:()=>{F()},children:"取消扫码"})]})]})}),document.body):null;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"hub-connection-form",children:[a.jsxs("div",{className:"hub-connection-form__header",children:[a.jsxs("div",{className:"hub-connection-form__copy",children:[a.jsx("h3",{className:"hub-connection-form__title",children:e}),a.jsx("p",{className:"hub-connection-form__description",children:t})]}),i?a.jsxs("div",{className:"hub-connection-form__current",children:[a.jsx("span",{children:"当前"}),a.jsx("strong",{children:i})]}):null]}),a.jsxs("label",{className:"hub-connection-form__field",children:[a.jsx("span",{className:"hub-connection-form__label",children:"Hub 地址"}),a.jsxs("span",{className:"hub-connection-form__input-shell",children:[a.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:b,onChange:he=>{p(he.target.value),w({loading:!1,result:null}),M(null)}}),Q?a.jsxs("button",{type:"button",className:"hub-connection-form__scan",onClick:()=>{Z()},disabled:P.starting||N.saving||v.loading,"aria-label":"扫码填入 Hub 地址",children:[a.jsx(cw,{}),a.jsx("span",{children:P.starting?"启动中":"扫码"})]}):null]})]}),a.jsx("p",{className:"hub-connection-form__hint",children:o}),a.jsxs("div",{className:"hub-connection-form__actions",children:[a.jsxs("button",{type:"button",className:"settings-action hub-connection-form__save",onClick:()=>{G()},disabled:!O||N.saving||P.starting,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:N.saving?d:u}),a.jsx("span",{children:m})]}),a.jsx("span",{className:"settings-action__state",children:N.saving?"处理中…":"→"})]}),a.jsx("button",{type:"button",className:"settings-ghost-button hub-connection-form__test",onClick:()=>{B()},disabled:!O||v.loading||N.saving||P.starting,children:v.loading?"测试中…":"测试连接"})]}),v.result?a.jsxs("div",{className:"hub-connection-form__probe",children:[a.jsxs("div",{className:"hub-connection-form__probe-item",children:[a.jsx("span",{children:"探测地址"}),a.jsx("strong",{children:v.result.url})]}),a.jsxs("div",{className:"hub-connection-form__probe-item",children:[a.jsx("span",{children:"连通结果"}),a.jsx("strong",{className:v.result.healthOk?"is-ok":"is-danger",children:v.result.healthOk?"Hub 在线":v.result.error??"无法连接"})]}),a.jsxs("div",{className:"hub-connection-form__probe-item",children:[a.jsx("span",{children:"延迟"}),a.jsx("strong",{children:qb(v.result.latencyMs)})]}),a.jsxs("div",{className:"hub-connection-form__probe-item",children:[a.jsx("span",{children:"最近探测"}),a.jsx("strong",{children:lw(v.result.checkedAt)})]})]}):null,T?a.jsx("p",{className:`hub-connection-form__notice is-${T.tone}`,children:T.text}):null]}),ae]})};var Wb;(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"})(Wb||(Wb={}));const wh=Ac("LocalNotifications",{web:()=>cl(()=>import("./web-D9nPg8kF.js"),[]).then(e=>new e.LocalNotificationsWeb)});var Rn;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function i(o){throw new Error}e.assertNever=i,e.arrayToEnum=o=>{const u={};for(const d of o)u[d]=d;return u},e.getValidEnumValues=o=>{const u=e.objectKeys(o).filter(m=>typeof o[o[m]]!="number"),d={};for(const m of u)d[m]=o[m];return e.objectValues(d)},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 d in o)Object.prototype.hasOwnProperty.call(o,d)&&u.push(d);return u},e.find=(o,u)=>{for(const d of o)if(u(d))return d},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,u=" | "){return o.map(d=>typeof d=="string"?`'${d}'`:d).join(u)}e.joinValues=r,e.jsonStringifyReplacer=(o,u)=>typeof u=="bigint"?u.toString():u})(Rn||(Rn={}));var Kb;(function(e){e.mergeShapes=(t,i)=>({...t,...i})})(Kb||(Kb={}));const mt=Rn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Xl=e=>{switch(typeof e){case"undefined":return mt.undefined;case"string":return mt.string;case"number":return Number.isNaN(e)?mt.nan:mt.number;case"boolean":return mt.boolean;case"function":return mt.function;case"bigint":return mt.bigint;case"symbol":return mt.symbol;case"object":return Array.isArray(e)?mt.array:e===null?mt.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?mt.promise:typeof Map<"u"&&e instanceof Map?mt.map:typeof Set<"u"&&e instanceof Set?mt.set:typeof Date<"u"&&e instanceof Date?mt.date:mt.object;default:return mt.unknown}},We=Rn.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 ol extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const i=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,i):this.__proto__=i,this.name="ZodError",this.issues=t}format(t){const i=t||function(u){return u.message},r={_errors:[]},o=u=>{for(const d of u.issues)if(d.code==="invalid_union")d.unionErrors.map(o);else if(d.code==="invalid_return_type")o(d.returnTypeError);else if(d.code==="invalid_arguments")o(d.argumentsError);else if(d.path.length===0)r._errors.push(i(d));else{let m=r,y=0;for(;y<d.path.length;){const g=d.path[y];y===d.path.length-1?(m[g]=m[g]||{_errors:[]},m[g]._errors.push(i(d))):m[g]=m[g]||{_errors:[]},m=m[g],y++}}};return o(this),r}static assert(t){if(!(t instanceof ol))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Rn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=i=>i.message){const i={},r=[];for(const o of this.issues)if(o.path.length>0){const u=o.path[0];i[u]=i[u]||[],i[u].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:i}}get formErrors(){return this.flatten()}}ol.create=e=>new ol(e);const U_=(e,t)=>{let i;switch(e.code){case We.invalid_type:e.received===mt.undefined?i="Required":i=`Expected ${e.expected}, received ${e.received}`;break;case We.invalid_literal:i=`Invalid literal value, expected ${JSON.stringify(e.expected,Rn.jsonStringifyReplacer)}`;break;case We.unrecognized_keys:i=`Unrecognized key(s) in object: ${Rn.joinValues(e.keys,", ")}`;break;case We.invalid_union:i="Invalid input";break;case We.invalid_union_discriminator:i=`Invalid discriminator value. Expected ${Rn.joinValues(e.options)}`;break;case We.invalid_enum_value:i=`Invalid enum value. Expected ${Rn.joinValues(e.options)}, received '${e.received}'`;break;case We.invalid_arguments:i="Invalid function arguments";break;case We.invalid_return_type:i="Invalid function return type";break;case We.invalid_date:i="Invalid date";break;case We.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(i=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(i=`${i} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?i=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?i=`Invalid input: must end with "${e.validation.endsWith}"`:Rn.assertNever(e.validation):e.validation!=="regex"?i=`Invalid ${e.validation}`:i="Invalid";break;case We.too_small:e.type==="array"?i=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?i=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?i=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?i=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?i=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:i="Invalid input";break;case We.too_big:e.type==="array"?i=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?i=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?i=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?i=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?i=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:i="Invalid input";break;case We.custom:i="Invalid input";break;case We.invalid_intersection_types:i="Intersection results could not be merged";break;case We.not_multiple_of:i=`Number must be a multiple of ${e.multipleOf}`;break;case We.not_finite:i="Number must be finite";break;default:i=t.defaultError,Rn.assertNever(e)}return{message:i}};let dw=U_;function fw(){return dw}const hw=e=>{const{data:t,path:i,errorMaps:r,issueData:o}=e,u=[...i,...o.path||[]],d={...o,path:u};if(o.message!==void 0)return{...o,path:u,message:o.message};let m="";const y=r.filter(g=>!!g).slice().reverse();for(const g of y)m=g(d,{data:t,defaultError:m}).message;return{...o,path:u,message:m}};function it(e,t){const i=fw(),r=hw({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,i,i===U_?void 0:U_].filter(o=>!!o)});e.common.issues.push(r)}class Ta{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,i){const r=[];for(const o of i){if(o.status==="aborted")return Ht;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,i){const r=[];for(const o of i){const u=await o.key,d=await o.value;r.push({key:u,value:d})}return Ta.mergeObjectSync(t,r)}static mergeObjectSync(t,i){const r={};for(const o of i){const{key:u,value:d}=o;if(u.status==="aborted"||d.status==="aborted")return Ht;u.status==="dirty"&&t.dirty(),d.status==="dirty"&&t.dirty(),u.value!=="__proto__"&&(typeof d.value<"u"||o.alwaysSet)&&(r[u.value]=d.value)}return{status:t.value,value:r}}}const Ht=Object.freeze({status:"aborted"}),Bf=e=>({status:"dirty",value:e}),Si=e=>({status:"valid",value:e}),Qb=e=>e.status==="aborted",Gb=e=>e.status==="dirty",ld=e=>e.status==="valid",Sp=e=>typeof Promise<"u"&&e instanceof Promise;var yt;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t==null?void 0:t.message})(yt||(yt={}));class mr{constructor(t,i,r,o){this._cachedPath=[],this.parent=t,this.data=i,this._path=r,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 Yb=(e,t)=>{if(ld(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 i=new ol(e.common.issues);return this._error=i,this._error}}};function Vt(e){if(!e)return{};const{errorMap:t,invalid_type_error:i,required_error:r,description:o}=e;if(t&&(i||r))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:(d,m)=>{const{message:y}=e;return d.code==="invalid_enum_value"?{message:y??m.defaultError}:typeof m.data>"u"?{message:y??r??m.defaultError}:d.code!=="invalid_type"?{message:m.defaultError}:{message:y??i??m.defaultError}},description:o}}class xn{get description(){return this._def.description}_getType(t){return Xl(t.data)}_getOrReturnCtx(t,i){return i||{common:t.parent.common,data:t.data,parsedType:Xl(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:Xl(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const i=this._parse(t);if(Sp(i))throw new Error("Synchronous parse encountered promise.");return i}_parseAsync(t){const i=this._parse(t);return Promise.resolve(i)}parse(t,i){const r=this.safeParse(t,i);if(r.success)return r.data;throw r.error}safeParse(t,i){const r={common:{issues:[],async:(i==null?void 0:i.async)??!1,contextualErrorMap:i==null?void 0:i.errorMap},path:(i==null?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xl(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Yb(r,o)}"~validate"(t){var r,o;const i={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xl(t)};if(!this["~standard"].async)try{const u=this._parseSync({data:t,path:[],parent:i});return ld(u)?{value:u.value}:{issues:i.common.issues}}catch(u){(o=(r=u==null?void 0:u.message)==null?void 0:r.toLowerCase())!=null&&o.includes("encountered")&&(this["~standard"].async=!0),i.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:i}).then(u=>ld(u)?{value:u.value}:{issues:i.common.issues})}async parseAsync(t,i){const r=await this.safeParseAsync(t,i);if(r.success)return r.data;throw r.error}async safeParseAsync(t,i){const r={common:{issues:[],contextualErrorMap:i==null?void 0:i.errorMap,async:!0},path:(i==null?void 0:i.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Xl(t)},o=this._parse({data:t,path:r.path,parent:r}),u=await(Sp(o)?o:Promise.resolve(o));return Yb(r,u)}refine(t,i){const r=o=>typeof i=="string"||typeof i>"u"?{message:i}:typeof i=="function"?i(o):i;return this._refinement((o,u)=>{const d=t(o),m=()=>u.addIssue({code:We.custom,...r(o)});return typeof Promise<"u"&&d instanceof Promise?d.then(y=>y?!0:(m(),!1)):d?!0:(m(),!1)})}refinement(t,i){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof i=="function"?i(r,o):i),!1))}_refinement(t){return new ud({schema:this,typeName:Ut.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:i=>this["~validate"](i)}}optional(){return mo.create(this,this._def)}nullable(){return dd.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return hr.create(this)}promise(){return Ep.create(this,this._def)}or(t){return wp.create([this,t],this._def)}and(t){return Np.create(this,t,this._def)}transform(t){return new ud({...Vt(this._def),schema:this,typeName:Ut.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const i=typeof t=="function"?t:()=>t;return new F_({...Vt(this._def),innerType:this,defaultValue:i,typeName:Ut.ZodDefault})}brand(){return new Lw({typeName:Ut.ZodBranded,type:this,...Vt(this._def)})}catch(t){const i=typeof t=="function"?t:()=>t;return new q_({...Vt(this._def),innerType:this,catchValue:i,typeName:Ut.ZodCatch})}describe(t){const i=this.constructor;return new i({...this._def,description:t})}pipe(t){return D0.create(this,t)}readonly(){return W_.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const mw=/^c[^\s-]{8,}$/i,pw=/^[0-9a-z]+$/,gw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,_w=/^[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,yw=/^[a-z0-9_-]{21}$/i,vw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bw=/^[-+]?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)?)??$/,xw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Sw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let P1;const jw=/^(?:(?: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])$/,ww=/^(?:(?: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])$/,Nw=/^(([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]))$/,kw=/^(([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])$/,Ew=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Cw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,G2="((\\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])))",Tw=new RegExp(`^${G2}$`);function Y2(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);const i=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${i}`}function Mw(e){return new RegExp(`^${Y2(e)}$`)}function Rw(e){let t=`${G2}T${Y2(e)}`;const i=[];return i.push(e.local?"Z?":"Z"),e.offset&&i.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${i.join("|")})`,new RegExp(`^${t}$`)}function Aw(e,t){return!!((t==="v4"||!t)&&jw.test(e)||(t==="v6"||!t)&&Nw.test(e))}function Iw(e,t){if(!vw.test(e))return!1;try{const[i]=e.split(".");if(!i)return!1;const r=i.replace(/-/g,"+").replace(/_/g,"/").padEnd(i.length+(4-i.length%4)%4,"="),o=JSON.parse(atob(r));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 Dw(e,t){return!!((t==="v4"||!t)&&ww.test(e)||(t==="v6"||!t)&&kw.test(e))}class nl extends xn{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==mt.string){const u=this._getOrReturnCtx(t);return it(u,{code:We.invalid_type,expected:mt.string,received:u.parsedType}),Ht}const r=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),it(o,{code:We.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),r.dirty());else if(u.kind==="max")t.data.length>u.value&&(o=this._getOrReturnCtx(t,o),it(o,{code:We.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!1,message:u.message}),r.dirty());else if(u.kind==="length"){const d=t.data.length>u.value,m=t.data.length<u.value;(d||m)&&(o=this._getOrReturnCtx(t,o),d?it(o,{code:We.too_big,maximum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}):m&&it(o,{code:We.too_small,minimum:u.value,type:"string",inclusive:!0,exact:!0,message:u.message}),r.dirty())}else if(u.kind==="email")xw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"email",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="emoji")P1||(P1=new RegExp(Sw,"u")),P1.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"emoji",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="uuid")_w.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"uuid",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="nanoid")yw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"nanoid",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="cuid")mw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"cuid",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="cuid2")pw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"cuid2",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="ulid")gw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"ulid",code:We.invalid_string,message:u.message}),r.dirty());else if(u.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),it(o,{validation:"url",code:We.invalid_string,message:u.message}),r.dirty()}else u.kind==="regex"?(u.regex.lastIndex=0,u.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"regex",code:We.invalid_string,message:u.message}),r.dirty())):u.kind==="trim"?t.data=t.data.trim():u.kind==="includes"?t.data.includes(u.value,u.position)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:{includes:u.value,position:u.position},message:u.message}),r.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),it(o,{code:We.invalid_string,validation:{startsWith:u.value},message:u.message}),r.dirty()):u.kind==="endsWith"?t.data.endsWith(u.value)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:{endsWith:u.value},message:u.message}),r.dirty()):u.kind==="datetime"?Rw(u).test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:"datetime",message:u.message}),r.dirty()):u.kind==="date"?Tw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:"date",message:u.message}),r.dirty()):u.kind==="time"?Mw(u).test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{code:We.invalid_string,validation:"time",message:u.message}),r.dirty()):u.kind==="duration"?bw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"duration",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="ip"?Aw(t.data,u.version)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"ip",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="jwt"?Iw(t.data,u.alg)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"jwt",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="cidr"?Dw(t.data,u.version)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"cidr",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="base64"?Ew.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"base64",code:We.invalid_string,message:u.message}),r.dirty()):u.kind==="base64url"?Cw.test(t.data)||(o=this._getOrReturnCtx(t,o),it(o,{validation:"base64url",code:We.invalid_string,message:u.message}),r.dirty()):Rn.assertNever(u);return{status:r.value,value:t.data}}_regex(t,i,r){return this.refinement(o=>t.test(o),{validation:i,code:We.invalid_string,...yt.errToObj(r)})}_addCheck(t){return new nl({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...yt.errToObj(t)})}url(t){return this._addCheck({kind:"url",...yt.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...yt.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...yt.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...yt.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...yt.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...yt.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...yt.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...yt.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...yt.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...yt.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...yt.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...yt.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,...yt.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,...yt.errToObj(t==null?void 0:t.message)})}duration(t){return this._addCheck({kind:"duration",...yt.errToObj(t)})}regex(t,i){return this._addCheck({kind:"regex",regex:t,...yt.errToObj(i)})}includes(t,i){return this._addCheck({kind:"includes",value:t,position:i==null?void 0:i.position,...yt.errToObj(i==null?void 0:i.message)})}startsWith(t,i){return this._addCheck({kind:"startsWith",value:t,...yt.errToObj(i)})}endsWith(t,i){return this._addCheck({kind:"endsWith",value:t,...yt.errToObj(i)})}min(t,i){return this._addCheck({kind:"min",value:t,...yt.errToObj(i)})}max(t,i){return this._addCheck({kind:"max",value:t,...yt.errToObj(i)})}length(t,i){return this._addCheck({kind:"length",value:t,...yt.errToObj(i)})}nonempty(t){return this.min(1,yt.errToObj(t))}trim(){return new nl({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new nl({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new nl({...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 i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t}get maxLength(){let t=null;for(const i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t}}nl.create=e=>new nl({checks:[],typeName:Ut.ZodString,coerce:(e==null?void 0:e.coerce)??!1,...Vt(e)});function Ow(e,t){const i=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=i>r?i:r,u=Number.parseInt(e.toFixed(o).replace(".","")),d=Number.parseInt(t.toFixed(o).replace(".",""));return u%d/10**o}class od extends xn{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)!==mt.number){const u=this._getOrReturnCtx(t);return it(u,{code:We.invalid_type,expected:mt.number,received:u.parsedType}),Ht}let r;const o=new Ta;for(const u of this._def.checks)u.kind==="int"?Rn.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),it(r,{code:We.invalid_type,expected:"integer",received:"float",message:u.message}),o.dirty()):u.kind==="min"?(u.inclusive?t.data<u.value:t.data<=u.value)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.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)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.too_big,maximum:u.value,type:"number",inclusive:u.inclusive,exact:!1,message:u.message}),o.dirty()):u.kind==="multipleOf"?Ow(t.data,u.value)!==0&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.not_multiple_of,multipleOf:u.value,message:u.message}),o.dirty()):u.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),it(r,{code:We.not_finite,message:u.message}),o.dirty()):Rn.assertNever(u);return{status:o.value,value:t.data}}gte(t,i){return this.setLimit("min",t,!0,yt.toString(i))}gt(t,i){return this.setLimit("min",t,!1,yt.toString(i))}lte(t,i){return this.setLimit("max",t,!0,yt.toString(i))}lt(t,i){return this.setLimit("max",t,!1,yt.toString(i))}setLimit(t,i,r,o){return new od({...this._def,checks:[...this._def.checks,{kind:t,value:i,inclusive:r,message:yt.toString(o)}]})}_addCheck(t){return new od({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:yt.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:yt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:yt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:yt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:yt.toString(t)})}multipleOf(t,i){return this._addCheck({kind:"multipleOf",value:t,message:yt.toString(i)})}finite(t){return this._addCheck({kind:"finite",message:yt.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:yt.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:yt.toString(t)})}get minValue(){let t=null;for(const i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t}get maxValue(){let t=null;for(const i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Rn.isInteger(t.value))}get isFinite(){let t=null,i=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(i===null||r.value>i)&&(i=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(i)&&Number.isFinite(t)}}od.create=e=>new od({checks:[],typeName:Ut.ZodNumber,coerce:(e==null?void 0:e.coerce)||!1,...Vt(e)});class ah extends xn{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)!==mt.bigint)return this._getInvalidInput(t);let r;const o=new Ta;for(const u of this._def.checks)u.kind==="min"?(u.inclusive?t.data<u.value:t.data<=u.value)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.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)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.too_big,type:"bigint",maximum:u.value,inclusive:u.inclusive,message:u.message}),o.dirty()):u.kind==="multipleOf"?t.data%u.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),it(r,{code:We.not_multiple_of,multipleOf:u.value,message:u.message}),o.dirty()):Rn.assertNever(u);return{status:o.value,value:t.data}}_getInvalidInput(t){const i=this._getOrReturnCtx(t);return it(i,{code:We.invalid_type,expected:mt.bigint,received:i.parsedType}),Ht}gte(t,i){return this.setLimit("min",t,!0,yt.toString(i))}gt(t,i){return this.setLimit("min",t,!1,yt.toString(i))}lte(t,i){return this.setLimit("max",t,!0,yt.toString(i))}lt(t,i){return this.setLimit("max",t,!1,yt.toString(i))}setLimit(t,i,r,o){return new ah({...this._def,checks:[...this._def.checks,{kind:t,value:i,inclusive:r,message:yt.toString(o)}]})}_addCheck(t){return new ah({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:yt.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:yt.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:yt.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:yt.toString(t)})}multipleOf(t,i){return this._addCheck({kind:"multipleOf",value:t,message:yt.toString(i)})}get minValue(){let t=null;for(const i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t}get maxValue(){let t=null;for(const i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t}}ah.create=e=>new ah({checks:[],typeName:Ut.ZodBigInt,coerce:(e==null?void 0:e.coerce)??!1,...Vt(e)});class z_ extends xn{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==mt.boolean){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.boolean,received:r.parsedType}),Ht}return Si(t.data)}}z_.create=e=>new z_({typeName:Ut.ZodBoolean,coerce:(e==null?void 0:e.coerce)||!1,...Vt(e)});class jp extends xn{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==mt.date){const u=this._getOrReturnCtx(t);return it(u,{code:We.invalid_type,expected:mt.date,received:u.parsedType}),Ht}if(Number.isNaN(t.data.getTime())){const u=this._getOrReturnCtx(t);return it(u,{code:We.invalid_date}),Ht}const r=new Ta;let o;for(const u of this._def.checks)u.kind==="min"?t.data.getTime()<u.value&&(o=this._getOrReturnCtx(t,o),it(o,{code:We.too_small,message:u.message,inclusive:!0,exact:!1,minimum:u.value,type:"date"}),r.dirty()):u.kind==="max"?t.data.getTime()>u.value&&(o=this._getOrReturnCtx(t,o),it(o,{code:We.too_big,message:u.message,inclusive:!0,exact:!1,maximum:u.value,type:"date"}),r.dirty()):Rn.assertNever(u);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new jp({...this._def,checks:[...this._def.checks,t]})}min(t,i){return this._addCheck({kind:"min",value:t.getTime(),message:yt.toString(i)})}max(t,i){return this._addCheck({kind:"max",value:t.getTime(),message:yt.toString(i)})}get minDate(){let t=null;for(const i of this._def.checks)i.kind==="min"&&(t===null||i.value>t)&&(t=i.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const i of this._def.checks)i.kind==="max"&&(t===null||i.value<t)&&(t=i.value);return t!=null?new Date(t):null}}jp.create=e=>new jp({checks:[],coerce:(e==null?void 0:e.coerce)||!1,typeName:Ut.ZodDate,...Vt(e)});class Vb extends xn{_parse(t){if(this._getType(t)!==mt.symbol){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.symbol,received:r.parsedType}),Ht}return Si(t.data)}}Vb.create=e=>new Vb({typeName:Ut.ZodSymbol,...Vt(e)});class Xb extends xn{_parse(t){if(this._getType(t)!==mt.undefined){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.undefined,received:r.parsedType}),Ht}return Si(t.data)}}Xb.create=e=>new Xb({typeName:Ut.ZodUndefined,...Vt(e)});class Zb extends xn{_parse(t){if(this._getType(t)!==mt.null){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.null,received:r.parsedType}),Ht}return Si(t.data)}}Zb.create=e=>new Zb({typeName:Ut.ZodNull,...Vt(e)});class B_ extends xn{constructor(){super(...arguments),this._any=!0}_parse(t){return Si(t.data)}}B_.create=e=>new B_({typeName:Ut.ZodAny,...Vt(e)});class Jb extends xn{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Si(t.data)}}Jb.create=e=>new Jb({typeName:Ut.ZodUnknown,...Vt(e)});class go extends xn{_parse(t){const i=this._getOrReturnCtx(t);return it(i,{code:We.invalid_type,expected:mt.never,received:i.parsedType}),Ht}}go.create=e=>new go({typeName:Ut.ZodNever,...Vt(e)});class e4 extends xn{_parse(t){if(this._getType(t)!==mt.undefined){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.void,received:r.parsedType}),Ht}return Si(t.data)}}e4.create=e=>new e4({typeName:Ut.ZodVoid,...Vt(e)});class hr extends xn{_parse(t){const{ctx:i,status:r}=this._processInputParams(t),o=this._def;if(i.parsedType!==mt.array)return it(i,{code:We.invalid_type,expected:mt.array,received:i.parsedType}),Ht;if(o.exactLength!==null){const d=i.data.length>o.exactLength.value,m=i.data.length<o.exactLength.value;(d||m)&&(it(i,{code:d?We.too_big:We.too_small,minimum:m?o.exactLength.value:void 0,maximum:d?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&i.data.length<o.minLength.value&&(it(i,{code:We.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&i.data.length>o.maxLength.value&&(it(i,{code:We.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),i.common.async)return Promise.all([...i.data].map((d,m)=>o.type._parseAsync(new mr(i,d,i.path,m)))).then(d=>Ta.mergeArray(r,d));const u=[...i.data].map((d,m)=>o.type._parseSync(new mr(i,d,i.path,m)));return Ta.mergeArray(r,u)}get element(){return this._def.type}min(t,i){return new hr({...this._def,minLength:{value:t,message:yt.toString(i)}})}max(t,i){return new hr({...this._def,maxLength:{value:t,message:yt.toString(i)}})}length(t,i){return new hr({...this._def,exactLength:{value:t,message:yt.toString(i)}})}nonempty(t){return this.min(1,t)}}hr.create=(e,t)=>new hr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ut.ZodArray,...Vt(t)});function Pu(e){if(e instanceof Ds){const t={};for(const i in e.shape){const r=e.shape[i];t[i]=mo.create(Pu(r))}return new Ds({...e._def,shape:()=>t})}else return e instanceof hr?new hr({...e._def,type:Pu(e.element)}):e instanceof mo?mo.create(Pu(e.unwrap())):e instanceof dd?dd.create(Pu(e.unwrap())):e instanceof Ec?Ec.create(e.items.map(t=>Pu(t))):e}class Ds extends xn{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(),i=Rn.objectKeys(t);return this._cached={shape:t,keys:i},this._cached}_parse(t){if(this._getType(t)!==mt.object){const g=this._getOrReturnCtx(t);return it(g,{code:We.invalid_type,expected:mt.object,received:g.parsedType}),Ht}const{status:r,ctx:o}=this._processInputParams(t),{shape:u,keys:d}=this._getCached(),m=[];if(!(this._def.catchall instanceof go&&this._def.unknownKeys==="strip"))for(const g in o.data)d.includes(g)||m.push(g);const y=[];for(const g of d){const b=u[g],p=o.data[g];y.push({key:{status:"valid",value:g},value:b._parse(new mr(o,p,o.path,g)),alwaysSet:g in o.data})}if(this._def.catchall instanceof go){const g=this._def.unknownKeys;if(g==="passthrough")for(const b of m)y.push({key:{status:"valid",value:b},value:{status:"valid",value:o.data[b]}});else if(g==="strict")m.length>0&&(it(o,{code:We.unrecognized_keys,keys:m}),r.dirty());else if(g!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const g=this._def.catchall;for(const b of m){const p=o.data[b];y.push({key:{status:"valid",value:b},value:g._parse(new mr(o,p,o.path,b)),alwaysSet:b in o.data})}}return o.common.async?Promise.resolve().then(async()=>{const g=[];for(const b of y){const p=await b.key,v=await b.value;g.push({key:p,value:v,alwaysSet:b.alwaysSet})}return g}).then(g=>Ta.mergeObjectSync(r,g)):Ta.mergeObjectSync(r,y)}get shape(){return this._def.shape()}strict(t){return yt.errToObj,new Ds({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(i,r)=>{var u,d;const o=((d=(u=this._def).errorMap)==null?void 0:d.call(u,i,r).message)??r.defaultError;return i.code==="unrecognized_keys"?{message:yt.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new Ds({...this._def,unknownKeys:"strip"})}passthrough(){return new Ds({...this._def,unknownKeys:"passthrough"})}extend(t){return new Ds({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new Ds({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ut.ZodObject})}setKey(t,i){return this.augment({[t]:i})}catchall(t){return new Ds({...this._def,catchall:t})}pick(t){const i={};for(const r of Rn.objectKeys(t))t[r]&&this.shape[r]&&(i[r]=this.shape[r]);return new Ds({...this._def,shape:()=>i})}omit(t){const i={};for(const r of Rn.objectKeys(this.shape))t[r]||(i[r]=this.shape[r]);return new Ds({...this._def,shape:()=>i})}deepPartial(){return Pu(this)}partial(t){const i={};for(const r of Rn.objectKeys(this.shape)){const o=this.shape[r];t&&!t[r]?i[r]=o:i[r]=o.optional()}return new Ds({...this._def,shape:()=>i})}required(t){const i={};for(const r of Rn.objectKeys(this.shape))if(t&&!t[r])i[r]=this.shape[r];else{let u=this.shape[r];for(;u instanceof mo;)u=u._def.innerType;i[r]=u}return new Ds({...this._def,shape:()=>i})}keyof(){return V2(Rn.objectKeys(this.shape))}}Ds.create=(e,t)=>new Ds({shape:()=>e,unknownKeys:"strip",catchall:go.create(),typeName:Ut.ZodObject,...Vt(t)});Ds.strictCreate=(e,t)=>new Ds({shape:()=>e,unknownKeys:"strict",catchall:go.create(),typeName:Ut.ZodObject,...Vt(t)});Ds.lazycreate=(e,t)=>new Ds({shape:e,unknownKeys:"strip",catchall:go.create(),typeName:Ut.ZodObject,...Vt(t)});class wp extends xn{_parse(t){const{ctx:i}=this._processInputParams(t),r=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 i.common.issues.push(...m.ctx.common.issues),m.result;const d=u.map(m=>new ol(m.ctx.common.issues));return it(i,{code:We.invalid_union,unionErrors:d}),Ht}if(i.common.async)return Promise.all(r.map(async u=>{const d={...i,common:{...i.common,issues:[]},parent:null};return{result:await u._parseAsync({data:i.data,path:i.path,parent:d}),ctx:d}})).then(o);{let u;const d=[];for(const y of r){const g={...i,common:{...i.common,issues:[]},parent:null},b=y._parseSync({data:i.data,path:i.path,parent:g});if(b.status==="valid")return b;b.status==="dirty"&&!u&&(u={result:b,ctx:g}),g.common.issues.length&&d.push(g.common.issues)}if(u)return i.common.issues.push(...u.ctx.common.issues),u.result;const m=d.map(y=>new ol(y));return it(i,{code:We.invalid_union,unionErrors:m}),Ht}}get options(){return this._def.options}}wp.create=(e,t)=>new wp({options:e,typeName:Ut.ZodUnion,...Vt(t)});function $_(e,t){const i=Xl(e),r=Xl(t);if(e===t)return{valid:!0,data:e};if(i===mt.object&&r===mt.object){const o=Rn.objectKeys(t),u=Rn.objectKeys(e).filter(m=>o.indexOf(m)!==-1),d={...e,...t};for(const m of u){const y=$_(e[m],t[m]);if(!y.valid)return{valid:!1};d[m]=y.data}return{valid:!0,data:d}}else if(i===mt.array&&r===mt.array){if(e.length!==t.length)return{valid:!1};const o=[];for(let u=0;u<e.length;u++){const d=e[u],m=t[u],y=$_(d,m);if(!y.valid)return{valid:!1};o.push(y.data)}return{valid:!0,data:o}}else return i===mt.date&&r===mt.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class Np extends xn{_parse(t){const{status:i,ctx:r}=this._processInputParams(t),o=(u,d)=>{if(Qb(u)||Qb(d))return Ht;const m=$_(u.value,d.value);return m.valid?((Gb(u)||Gb(d))&&i.dirty(),{status:i.value,value:m.data}):(it(r,{code:We.invalid_intersection_types}),Ht)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([u,d])=>o(u,d)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}Np.create=(e,t,i)=>new Np({left:e,right:t,typeName:Ut.ZodIntersection,...Vt(i)});class Ec extends xn{_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.parsedType!==mt.array)return it(r,{code:We.invalid_type,expected:mt.array,received:r.parsedType}),Ht;if(r.data.length<this._def.items.length)return it(r,{code:We.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Ht;!this._def.rest&&r.data.length>this._def.items.length&&(it(r,{code:We.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),i.dirty());const u=[...r.data].map((d,m)=>{const y=this._def.items[m]||this._def.rest;return y?y._parse(new mr(r,d,r.path,m)):null}).filter(d=>!!d);return r.common.async?Promise.all(u).then(d=>Ta.mergeArray(i,d)):Ta.mergeArray(i,u)}get items(){return this._def.items}rest(t){return new Ec({...this._def,rest:t})}}Ec.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Ec({items:e,typeName:Ut.ZodTuple,rest:null,...Vt(t)})};class kp extends xn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.parsedType!==mt.object)return it(r,{code:We.invalid_type,expected:mt.object,received:r.parsedType}),Ht;const o=[],u=this._def.keyType,d=this._def.valueType;for(const m in r.data)o.push({key:u._parse(new mr(r,m,r.path,m)),value:d._parse(new mr(r,r.data[m],r.path,m)),alwaysSet:m in r.data});return r.common.async?Ta.mergeObjectAsync(i,o):Ta.mergeObjectSync(i,o)}get element(){return this._def.valueType}static create(t,i,r){return i instanceof xn?new kp({keyType:t,valueType:i,typeName:Ut.ZodRecord,...Vt(r)}):new kp({keyType:nl.create(),valueType:t,typeName:Ut.ZodRecord,...Vt(i)})}}class t4 extends xn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.parsedType!==mt.map)return it(r,{code:We.invalid_type,expected:mt.map,received:r.parsedType}),Ht;const o=this._def.keyType,u=this._def.valueType,d=[...r.data.entries()].map(([m,y],g)=>({key:o._parse(new mr(r,m,r.path,[g,"key"])),value:u._parse(new mr(r,y,r.path,[g,"value"]))}));if(r.common.async){const m=new Map;return Promise.resolve().then(async()=>{for(const y of d){const g=await y.key,b=await y.value;if(g.status==="aborted"||b.status==="aborted")return Ht;(g.status==="dirty"||b.status==="dirty")&&i.dirty(),m.set(g.value,b.value)}return{status:i.value,value:m}})}else{const m=new Map;for(const y of d){const g=y.key,b=y.value;if(g.status==="aborted"||b.status==="aborted")return Ht;(g.status==="dirty"||b.status==="dirty")&&i.dirty(),m.set(g.value,b.value)}return{status:i.value,value:m}}}}t4.create=(e,t,i)=>new t4({valueType:t,keyType:e,typeName:Ut.ZodMap,...Vt(i)});class ih extends xn{_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.parsedType!==mt.set)return it(r,{code:We.invalid_type,expected:mt.set,received:r.parsedType}),Ht;const o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(it(r,{code:We.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),i.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(it(r,{code:We.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),i.dirty());const u=this._def.valueType;function d(y){const g=new Set;for(const b of y){if(b.status==="aborted")return Ht;b.status==="dirty"&&i.dirty(),g.add(b.value)}return{status:i.value,value:g}}const m=[...r.data.values()].map((y,g)=>u._parse(new mr(r,y,r.path,g)));return r.common.async?Promise.all(m).then(y=>d(y)):d(m)}min(t,i){return new ih({...this._def,minSize:{value:t,message:yt.toString(i)}})}max(t,i){return new ih({...this._def,maxSize:{value:t,message:yt.toString(i)}})}size(t,i){return this.min(t,i).max(t,i)}nonempty(t){return this.min(1,t)}}ih.create=(e,t)=>new ih({valueType:e,minSize:null,maxSize:null,typeName:Ut.ZodSet,...Vt(t)});class n4 extends xn{get schema(){return this._def.getter()}_parse(t){const{ctx:i}=this._processInputParams(t);return this._def.getter()._parse({data:i.data,path:i.path,parent:i})}}n4.create=(e,t)=>new n4({getter:e,typeName:Ut.ZodLazy,...Vt(t)});class H_ extends xn{_parse(t){if(t.data!==this._def.value){const i=this._getOrReturnCtx(t);return it(i,{received:i.data,code:We.invalid_literal,expected:this._def.value}),Ht}return{status:"valid",value:t.data}}get value(){return this._def.value}}H_.create=(e,t)=>new H_({value:e,typeName:Ut.ZodLiteral,...Vt(t)});function V2(e,t){return new cd({values:e,typeName:Ut.ZodEnum,...Vt(t)})}class cd extends xn{_parse(t){if(typeof t.data!="string"){const i=this._getOrReturnCtx(t),r=this._def.values;return it(i,{expected:Rn.joinValues(r),received:i.parsedType,code:We.invalid_type}),Ht}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){const i=this._getOrReturnCtx(t),r=this._def.values;return it(i,{received:i.data,code:We.invalid_enum_value,options:r}),Ht}return Si(t.data)}get options(){return this._def.values}get enum(){const t={};for(const i of this._def.values)t[i]=i;return t}get Values(){const t={};for(const i of this._def.values)t[i]=i;return t}get Enum(){const t={};for(const i of this._def.values)t[i]=i;return t}extract(t,i=this._def){return cd.create(t,{...this._def,...i})}exclude(t,i=this._def){return cd.create(this.options.filter(r=>!t.includes(r)),{...this._def,...i})}}cd.create=V2;class s4 extends xn{_parse(t){const i=Rn.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==mt.string&&r.parsedType!==mt.number){const o=Rn.objectValues(i);return it(r,{expected:Rn.joinValues(o),received:r.parsedType,code:We.invalid_type}),Ht}if(this._cache||(this._cache=new Set(Rn.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){const o=Rn.objectValues(i);return it(r,{received:r.data,code:We.invalid_enum_value,options:o}),Ht}return Si(t.data)}get enum(){return this._def.values}}s4.create=(e,t)=>new s4({values:e,typeName:Ut.ZodNativeEnum,...Vt(t)});class Ep extends xn{unwrap(){return this._def.type}_parse(t){const{ctx:i}=this._processInputParams(t);if(i.parsedType!==mt.promise&&i.common.async===!1)return it(i,{code:We.invalid_type,expected:mt.promise,received:i.parsedType}),Ht;const r=i.parsedType===mt.promise?i.data:Promise.resolve(i.data);return Si(r.then(o=>this._def.type.parseAsync(o,{path:i.path,errorMap:i.common.contextualErrorMap})))}}Ep.create=(e,t)=>new Ep({type:e,typeName:Ut.ZodPromise,...Vt(t)});class ud extends xn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ut.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:i,ctx:r}=this._processInputParams(t),o=this._def.effect||null,u={addIssue:d=>{it(r,d),d.fatal?i.abort():i.dirty()},get path(){return r.path}};if(u.addIssue=u.addIssue.bind(u),o.type==="preprocess"){const d=o.transform(r.data,u);if(r.common.async)return Promise.resolve(d).then(async m=>{if(i.value==="aborted")return Ht;const y=await this._def.schema._parseAsync({data:m,path:r.path,parent:r});return y.status==="aborted"?Ht:y.status==="dirty"||i.value==="dirty"?Bf(y.value):y});{if(i.value==="aborted")return Ht;const m=this._def.schema._parseSync({data:d,path:r.path,parent:r});return m.status==="aborted"?Ht:m.status==="dirty"||i.value==="dirty"?Bf(m.value):m}}if(o.type==="refinement"){const d=m=>{const y=o.refinement(m,u);if(r.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(r.common.async===!1){const m=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return m.status==="aborted"?Ht:(m.status==="dirty"&&i.dirty(),d(m.value),{status:i.value,value:m.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(m=>m.status==="aborted"?Ht:(m.status==="dirty"&&i.dirty(),d(m.value).then(()=>({status:i.value,value:m.value}))))}if(o.type==="transform")if(r.common.async===!1){const d=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ld(d))return Ht;const m=o.transform(d.value,u);if(m instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:i.value,value:m}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(d=>ld(d)?Promise.resolve(o.transform(d.value,u)).then(m=>({status:i.value,value:m})):Ht);Rn.assertNever(o)}}ud.create=(e,t,i)=>new ud({schema:e,typeName:Ut.ZodEffects,effect:t,...Vt(i)});ud.createWithPreprocess=(e,t,i)=>new ud({schema:t,effect:{type:"preprocess",transform:e},typeName:Ut.ZodEffects,...Vt(i)});class mo extends xn{_parse(t){return this._getType(t)===mt.undefined?Si(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}mo.create=(e,t)=>new mo({innerType:e,typeName:Ut.ZodOptional,...Vt(t)});class dd extends xn{_parse(t){return this._getType(t)===mt.null?Si(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}dd.create=(e,t)=>new dd({innerType:e,typeName:Ut.ZodNullable,...Vt(t)});class F_ extends xn{_parse(t){const{ctx:i}=this._processInputParams(t);let r=i.data;return i.parsedType===mt.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:i.path,parent:i})}removeDefault(){return this._def.innerType}}F_.create=(e,t)=>new F_({innerType:e,typeName:Ut.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Vt(t)});class q_ extends xn{_parse(t){const{ctx:i}=this._processInputParams(t),r={...i,common:{...i.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Sp(o)?o.then(u=>({status:"valid",value:u.status==="valid"?u.value:this._def.catchValue({get error(){return new ol(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ol(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}q_.create=(e,t)=>new q_({innerType:e,typeName:Ut.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Vt(t)});class a4 extends xn{_parse(t){if(this._getType(t)!==mt.nan){const r=this._getOrReturnCtx(t);return it(r,{code:We.invalid_type,expected:mt.nan,received:r.parsedType}),Ht}return{status:"valid",value:t.data}}}a4.create=e=>new a4({typeName:Ut.ZodNaN,...Vt(e)});class Lw extends xn{_parse(t){const{ctx:i}=this._processInputParams(t),r=i.data;return this._def.type._parse({data:r,path:i.path,parent:i})}unwrap(){return this._def.type}}class D0 extends xn{_parse(t){const{status:i,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{const u=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?Ht:u.status==="dirty"?(i.dirty(),Bf(u.value)):this._def.out._parseAsync({data:u.value,path:r.path,parent:r})})();{const o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Ht:o.status==="dirty"?(i.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,i){return new D0({in:t,out:i,typeName:Ut.ZodPipeline})}}class W_ extends xn{_parse(t){const i=this._def.innerType._parse(t),r=o=>(ld(o)&&(o.value=Object.freeze(o.value)),o);return Sp(i)?i.then(o=>r(o)):r(i)}unwrap(){return this._def.innerType}}W_.create=(e,t)=>new W_({innerType:e,typeName:Ut.ZodReadonly,...Vt(t)});var Ut;(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"})(Ut||(Ut={}));const E=nl.create,Ve=od.create,It=z_.create,Pw=B_.create;go.create;const nt=hr.create,Te=Ds.create;wp.create;Np.create;Ec.create;const Cp=kp.create,yo=H_.create,ut=cd.create;Ep.create;mo.create;dd.create;const X2=ut(["codex","claude","image"]),Uw=ut(["managed","attached-live","history-only"]),zw=ut(["active","idle","attention","offline"]),Z2=ut(["idle","running","completed"]),J2=ut(["image","file"]),Bw=ut(["user","repo","system","admin"]),$w=ut(["openai","xai","gemini"]),Vp=E().trim().min(1).max(120),e6=ut(["auto","low","medium","high"]),t6=ut(["auto","1024x1024","1536x1024","1024x1536","2048x2048","2048x1152","1152x2048","3840x2160","2160x3840"]),n6=ut(["low","high"]),s6=ut(["png","jpeg","webp"]),a6=ut(["auto","opaque"]),i6=ut(["auto","low"]),r6=ut(["auto","1:1","4:3","3:4","16:9","9:16"]),Hw=ut(["generated","source","mask"]),Fw=ut(["upload","session_asset"]),qw=ut(["pending","completed","failed"]),Ww=ut(["generate","edit"]),l6=Te({id:Vp,vendor:$w.default("openai"),label:E().trim().min(1).max(160),enabled:It().default(!0)}),Kw=Te({can_stream_live:It(),can_send_input:It(),can_interrupt:It(),can_approve:It(),can_reject:It(),can_show_git:It(),can_show_terminal:It()}),o6=Te({used_tokens:Ve(),total_tokens:Ve(),remaining_tokens:Ve(),percent_used:Ve(),cached_input_tokens:Ve(),output_tokens:Ve(),reasoning_output_tokens:Ve(),updated_at:E()}),Qw=ut(["pending","in_progress","completed"]),Gw=Te({id:E(),step:E(),status:Qw}),O0=Te({session_id:E(),turn_id:E().nullable(),source:ut(["rollout","app-server"]),updated_at:E(),explanation:E().nullable().default(null),steps:nt(Gw),completed_count:Ve().int().nonnegative(),total_count:Ve().int().nonnegative(),is_active:It()}),Yw=Te({parent_session_id:E(),root_session_id:E().nullable().default(null),nickname:E().nullable().default(null),role:E().nullable().default(null),depth:Ve().int().nonnegative()}),Vw=ut(["user_input","command_execution_approval","file_change_approval","permissions_approval","mcp_elicitation"]),Xw=ut(["pending","submitting","resolved"]),c6=Te({id:E(),label:E(),description:E().nullable().default(null),emphasis:ut(["default","primary","danger"]).default("default")}),Zw=Te({id:E(),header:E().nullable().default(null),question:E(),options:nt(c6).default([]),allow_other:It().default(!1),is_secret:It().default(!1)}),L0=Te({id:E(),session_id:E(),turn_id:E().nullable().default(null),item_id:E().nullable().default(null),kind:Vw,status:Xw,title:E(),description:E().nullable().default(null),created_at:E(),updated_at:E(),options:nt(c6).default([]),questions:nt(Zw).default([]),allow_freeform:It().default(!1),freeform_placeholder:E().nullable().default(null),submit_label:E().nullable().default(null)}),Jw=Te({id:E(),kind:J2,name:E().nullable().default(null),mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),content_url:E().nullable().default(null)}),U1=Te({id:E(),kind:J2,name:E(),mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),data_url:E()}),i4=Te({id:E(),session_id:E(),turn_id:E().nullable().default(null),kind:Hw,name:E(),mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),width:Ve().int().positive().nullable().default(null),height:Ve().int().positive().nullable().default(null),content_url:E(),created_at:E()}),eN=Te({id:E(),kind:Fw,name:E(),mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),data_url:E().nullable().default(null),asset_id:E().nullable().default(null),mask_data_url:E().nullable().default(null)}),tN=Te({id:E(),session_id:E(),created_at:E(),completed_at:E().nullable().default(null),prompt:E(),prompt_suffix:E().nullable().default(null),operation:Ww,status:qw,error:E().nullable().default(null),model:Vp,quality:e6,size:t6,input_fidelity:n6.nullable().default(null),aspect_ratio:r6,output_format:s6.default("png"),output_compression:Ve().int().min(0).max(100).nullable().default(null),background:a6.default("auto"),moderation:i6.default("auto"),n:Ve().int().min(1).max(10).default(1),sources:nt(i4).default([]),outputs:nt(i4).default([])}),nN=Te({id:E(),remark:E(),base_url:E(),models:nt(l6).default([]),resolved_api_key_source:ut(["stored","env","missing"]).default("missing"),has_stored_api_key:It().default(!1),updated_at:E().nullable().default(null)}),sN=Te({id:E(),remark:E().trim().min(1).max(80),base_url:E(),models:nt(l6).default([]),api_key:E().optional().nullable(),api_key_mode:ut(["keep","set","clear"]).default("keep")}),r4=Te({active_channel_id:E().nullable().default(null),base_url:E(),channels:nt(nN).default([]),model:Vp.default("gpt-image-2"),resolved_api_key_source:ut(["stored","env","missing"]).default("missing"),has_stored_api_key:It().default(!1),updated_at:E().nullable().default(null)}),l4=Te({active_channel_id:E().nullable().default(null),channels:nt(sN).default([])}),aN=Te({ok:It(),message:E(),model_available:It().default(!1),resolved_base_url:E()}),iN=Te({base_url:E(),api_key:E().optional().nullable(),api_key_mode:ut(["keep","set","clear"]).default("keep"),channel_id:E().nullable().default(null)}),rN=Te({models:nt(Te({id:E(),label:E()}))}),lN=Te({title:E().trim().min(1).max(80).optional()}),oN=Te({prompt:E(),append_to_turn_id:E().nullable().default(null),model:Vp.default("gpt-image-2"),quality:e6.default("auto"),size:t6.default("1024x1024"),input_fidelity:n6.nullable().default(null),aspect_ratio:r6.default("auto"),output_format:s6.default("png"),output_compression:Ve().int().min(0).max(100).nullable().default(null),background:a6.default("auto"),moderation:i6.default("auto"),n:Ve().int().min(1).max(10).default(1),sources:nt(eN).default([])}),cN=Te({name:E(),description:E(),path:E(),scope:Bw,enabled:It()}),uN=ut(["supported","unsupported"]),dN=Te({name:E(),description:E(),availability:uN.default("supported")}),o4=Te({cli_version:E().nullable().default(null),loaded_at:E(),cache_ttl_ms:Ve().int().nonnegative(),commands:nt(dN)});Te({id:E(),label:E(),description:E(),isDefault:It(),defaultReasoningEffort:E().nullable().default(null),supportedReasoningEfforts:nt(E()).default([])});const fN=ut(["running","awaiting_input","completed","failed"]),hN=ut(["none","choice","text"]),mN=Te({id:E(),label:E(),description:E().nullable().default(null)}),pN=Te({type:yo("set_session_model"),model:E(),reasoning_effort:E().nullable().default(null)}).nullable().default(null),gN=Te({panel_id:E(),session_id:E(),command_name:E(),command_text:E(),title:E(),description:E().nullable().default(null),status:fN,body:E(),submitted_at:E(),updated_at:E(),input_type:hN,options:nt(mN).default([]),input_placeholder:E().nullable().default(null),submit_label:E().nullable().default(null),effect:pN}),c4=Te({panel:gN}),_N=ut(["online","offline"]),Xp=Te({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:_N,provider_availability:nt(X2),project_count:Ve(),session_count:Ve(),transport:ut(["direct-agent","hub-routed"]),version:E().nullable().default(null),registered_at:E().nullable().default(null),last_seen_at:E().nullable().default(null)}),P0=Te({id:E(),agent_id:E(),name:E(),display_name:E().nullable(),pinned:It(),path:E(),branch:E(),worktree:E(),runtime_profiles:nt(E()),preview_url:E().nullable()}),Nh=Te({id:E(),agent_id:E(),project_id:E(),provider:X2.default("codex"),archived:It(),title:E(),mode:Uw,health:zw,branch:E(),worktree:E(),summary:E(),latest_assistant_message:E().nullable().default(null),last_event_at:E(),pinned:It(),run_state:Z2,run_state_changed_at:E().nullable(),context_usage:o6.nullable().default(null),subagent:Yw.nullable().default(null),capability:Kw}),yN=Te({path:E(),additions:Ve(),deletions:Ve()}),vN=Te({files:nt(yN),additions:Ve(),deletions:Ve()}),rh=Te({id:E(),kind:ut(["user","assistant","thinking","tool","system"]),title:E(),body:E(),body_truncated:It().default(!1),detail_available:It().default(!1),patch_summary:vN.nullable().default(null),session_ids:nt(E()).default([]),timestamp:E(),accent:ut(["primary","secondary","muted"]),attachments:nt(Jw).default([])}),u6=e=>(e==null?void 0:e.kind)==="user"&&(e.body.trim().length>0||Array.isArray(e.attachments)&&e.attachments.length>0),d6=e=>{for(let t=e.length-1;t>=0;t-=1)if(u6(e[t]))return t;return-1},bN=e=>{const t=d6(e);if(t<0)return!1;for(let i=0;i<t;i+=1)if(u6(e[i]))return!0;return!1},xN=ut(["tail","full_compact"]),f6=Te({session_id:E(),generated_at:E(),view:xN,anchor_entry_id:E().nullable().default(null),has_earlier_entries:It().default(!1),entries:nt(rh)}),SN=ut(["app-server","rollout-fallback"]),jN=ut(["running","completed"]),wN=ut(["add","delete","update"]),U0=Te({path:E(),kind:wN,move_path:E().nullable(),additions:Ve(),deletions:Ve(),diff:E(),item_id:E().nullable()}),NN=U0.omit({diff:!0}).extend({diff_available:It().default(!1)}),h6=Te({id:E(),session_id:E(),turn_id:E(),source:SN,status:jN,started_at:E(),completed_at:E().nullable(),updated_at:E(),aggregated_diff:E(),files:nt(U0)}),m6=h6.omit({aggregated_diff:!0,files:!0}).extend({aggregated_diff_available:It().default(!1),files:nt(NN)}),kN=Te({session_id:E(),change_set_id:E(),file:U0,empty_message:E().default("此变更没有可展示的补丁内容")}),EN=Te({path:E(),status:ut(["modified","added","deleted","renamed"]),additions:Ve(),deletions:Ve()}),p6=ut(["modified","added","deleted","renamed","untracked"]),CN=Te({path:E(),previous_path:E().nullable().default(null),status:p6,additions:Ve().int().nonnegative(),deletions:Ve().int().nonnegative()}),TN=Te({session_id:E(),project_id:E(),path:E(),previous_path:E().nullable().default(null),additions:Ve().int().nonnegative(),deletions:Ve().int().nonnegative(),diff:E()}),z0=Te({session_id:E(),project_id:E(),branch:E(),branches:nt(E()),upstream_branch:E().nullable().default(null),ahead_count:Ve().int().nonnegative(),behind_count:Ve().int().nonnegative(),files:nt(CN),updated_at:E()}),MN=Te({path:E(),previous_path:E().nullable().default(null),status:p6}),RN=Te({oid:E(),short_oid:E(),subject:E(),author_name:E(),authored_at:E(),committed_at:E(),parent_oids:nt(E()).default([]),refs:nt(E()).default([]),files:nt(MN)}),AN=Te({session_id:E(),project_id:E(),commit_oid:E(),path:E(),previous_path:E().nullable().default(null),additions:Ve().int().nonnegative(),deletions:Ve().int().nonnegative(),diff:E()}),IN=Te({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:nt(RN),updated_at:E()});ut(["discard-file","discard-all","commit-all","switch-branch","push"]);const DN=Te({ok:yo(!0),workspace:z0});ut(["rollback"]);const ON=Te({ok:yo(!0),turn_id:E(),change_set_id:E(),workspace:z0}),LN=ut(["directory","file"]),g6=ut(["markdown","code","text","image","binary"]),PN=Te({path:E(),name:E(),kind:LN,has_children:It(),extension:E().nullable().default(null),file_kind:g6.nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null)}),UN=Te({session_id:E(),project_id:E(),root_path:E(),parent_path:E().nullable().default(null),nodes:nt(PN),loaded_at:E()}),zN=Te({session_id:E(),project_id:E(),path:E(),name:E(),extension:E().nullable().default(null),file_kind:g6,mime_type:E().nullable().default(null),size_bytes:Ve().int().nonnegative().nullable().default(null),encoding:ut(["utf8","base64"]).nullable().default(null),is_truncated:It(),content_text:E().nullable().default(null),content_base64:E().nullable().default(null),loaded_at:E()}),_6=ut(["auto","powershell","cmd","bash"]),BN=ut(["user","codex"]),$N=Te({id:E(),name:E(),description:E().nullable().default(null),command:E(),kill_command:E().nullable().default(null),cwd:E().nullable().default(null),shell:_6.default("auto"),node_version:E().nullable().default(null),port:Ve().int().positive().nullable().default(null),source:BN.default("user"),created_at:E(),updated_at:E()}),HN=Te({name:E(),description:E().nullable().default(null),command:E(),kill_command:E().nullable().default(null),cwd:E().nullable().default(null),shell:_6.default("auto"),node_version:E().nullable().default(null),port:Ve().int().positive().nullable().default(null)}),B0=Te({session_id:E(),project_id:E(),config_path:E(),commands:nt($N),updated_at:E()}),FN=ut(["user","codex"]),qN=Te({id:E(),name:E(),description:E().nullable().default(null),url:E(),source:FN.default("user"),created_at:E(),updated_at:E()}),WN=Te({name:E(),description:E().nullable().default(null),url:E()}),$0=Te({session_id:E(),project_id:E(),config_path:E(),websites:nt(qN),updated_at:E()}),KN=ut(["queued","running","completed","failed","stopped"]),QN=ut(["stdout","stderr","system"]),GN=Te({cursor:Ve().int().nonnegative(),stream:QN,text:E(),timestamp:E()}),H0=Te({id:E(),session_id:E(),project_id:E(),command_id:E().nullable().default(null),title:E(),command:E(),cwd:E(),status:KN,exit_code:Ve().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:Ve().int().nonnegative(),preview:E().nullable().default(null)}),F0=Te({session_id:E(),project_id:E(),active_terminal_id:E().nullable().default(null),terminals:nt(H0),updated_at:E()}),YN=Te({session_id:E(),project_id:E(),terminal:H0,chunks:nt(GN),next_cursor:Ve().int().nonnegative(),truncated:It().default(!1)}),y6=Te({run_state:Z2.optional(),run_state_changed_at:E().nullable().optional(),summary:E().optional(),latest_assistant_message:E().nullable().optional(),last_event_at:E().optional(),context_usage:o6.nullable().optional()}),VN=Te({session_id:E(),recovered_at:E(),session_patch:y6,timeline:nt(rh),interactions:nt(L0),plan_snapshot:O0.nullable().default(null),change_sets:nt(h6),terminal_snapshot:F0.nullable().default(null)}),v6=Te({manager:ut(["none","nvm-windows"]).default("none"),versions:nt(E()).default([]),error:E().nullable().default(null)}),b6=Te({command_catalog:B0,website_catalog:$0,node_runtime:v6,terminal_snapshot:F0}),XN=Te({session_id:E(),generated_at:E(),session_patch:y6,timeline:f6,interactions:nt(L0),plan_snapshot:O0.nullable().default(null),run_workbench:b6.nullable().default(null),change_sets:nt(m6).default([])}),ZN=Te({catalog:B0}),JN=Te({catalog:$0}),ek=Te({commands:nt(HN),reason:E().nullable().default(null)}),tk=Te({generation:ek,catalog:B0}),nk=Te({websites:nt(WN),reason:E().nullable().default(null)}),sk=Te({generation:nk,catalog:$0}),ak=Te({snapshot:F0,terminal:H0.nullable().default(null)}),ik=ut(["dev-hub","dev-agent","dev-web","release-hub","release-agent"]),rk=ut(["unknown","running","stopped","degraded"]),lk=ut(["process","windows-service"]),ok=ut(["missing","running","stopped","unknown"]),ck=ut(["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"]),uk=ut(["running","succeeded","failed"]),dk=ut(["info","success","warn","error"]),x6=Te({repo_path:E().nullable().default(null),nvm_version:E().nullable().default(null),dev_hub_port:Ve().int().positive().nullable().default(null),dev_hub_args:E().default(""),dev_agent_port:Ve().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:Ve().int().positive().nullable().default(null),dev_web_hub_url:E().default(""),dev_web_args:E().default(""),release_hub_port:Ve().int().positive().nullable().default(null),release_hub_service_name:E().default("PandaHub"),release_hub_args:E().default(""),release_agent_port:Ve().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)}),fk=x6.extend({npm_token:E().nullable().default(null),clear_npm_token:It().default(!1)}),hk=Te({has_npm_token:It(),npm_token_hint:E().nullable().default(null)}),mk=Te({checked_at:E(),url:E().nullable().default(null),ok:It(),status_code:Ve().int().nullable().default(null),duration_ms:Ve().int().nonnegative().nullable().default(null),message:E().nullable().default(null)}),pk=Te({key:ik,label:E(),status:rk,manager:lk.default("process"),service_name:E().nullable().default(null),service_registered:It().default(!1),service_status:ok.nullable().default(null),configured_port:Ve().int().positive().nullable().default(null),detected_pids:nt(Ve().int().positive()).default([]),probe:mk.nullable().default(null)}),gk=Te({id:E(),timestamp:E(),level:dk,message:E()}),S6=Te({id:E(),kind:ck,title:E(),status:uk,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:It().default(!1),logs:nt(gk).default([])}),_k=Te({artifact_id:E(),file_name:E(),size_bytes:Ve().int().nonnegative(),built_at:E(),published_at:E().nullable().default(null),version_name:E().nullable().default(null),version_code:Ve().int().nullable().default(null),download_path:E()}),K_=Te({generated_at:E(),config:x6,credentials:hk,node_runtime:v6,services:nt(pk),current_version:E().nullable().default(null),apk_artifact:_k.nullable().default(null),jobs:nt(S6).default([])});Te({action:ut(["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 yk=Te({ok:yo(!0),snapshot:K_,job:S6.nullable().default(null)}),vk=Te({id:E(),name:E(),command:E(),port:Ve().nullable(),status:ut(["running","stopped","degraded"]),log_excerpt:E()}),bk=Te({id:E(),label:E(),url:E(),status:ut(["ready","starting","stopped"])}),j6=Te({path:E(),name:E(),has_children:It()}),xk=Te({directory:j6}),Sk=Te({id:E(),title:E(),description:E(),status:ut(["pending","approved","rejected"])}),jk=Te({project_id:E(),visible_session_count:Ve().int().nonnegative(),archived_session_count:Ve().int().nonnegative(),hidden_history_count:Ve().int().nonnegative()}),wk=P0.pick({id:!0,agent_id:!0,name:!0,display_name:!0,pinned:!0,path:!0}),Nk=Xp.pick({id:!0,name:!0,display_name:!0,status:!0}),w6=Nh.pick({id:!0,agent_id:!0,project_id:!0,provider:!0,archived:!0,title:!0,last_event_at:!0,pinned:!0,run_state:!0,run_state_changed_at:!0,subagent:!0}),N6=Nh.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}),kk=Te({generated_at:E(),session:N6}),u4=Te({generated_at:E(),session:N6,turns:nt(tN).default([])}),Ek=Te({generated_at:E(),agents:nt(Xp)}),Ck=Nh.pick({id:!0,title:!0,run_state:!0,run_state_changed_at:!0,latest_assistant_message:!0}),Tk=Te({generated_at:E(),recent_sessions:nt(Ck)}),Mk=Te({session_id:E(),agent_id:E(),project_id:E(),direct_base_url:E(),ws_base_url:E()}),Rk=Te({generated_at:E(),agent:Nk.nullable().default(null),projects:nt(wk),project_stats:nt(jk).default([]),sessions:nt(w6),active_session_id:E()}),k6=ut(["archived","history"]),Ak=Te({bucket:k6,project_id:E().nullable().default(null),sessions:nt(w6),next_cursor:E().nullable().default(null),total_count:Ve().int().nonnegative()}),Ik=Te({session_id:E(),entry_id:E(),command_entry:rh,output_entries:nt(rh).default([])}),Dk=Te({generated_at:E(),agents:nt(Xp),projects:nt(P0),sessions:nt(Nh),active_session_id:E(),timeline:nt(rh),changed_files:nt(EN),runtime_processes:nt(vk),previews:nt(bk),approvals:nt(Sk)});Te({agent:Xp,projects:nt(P0),sessions:nt(Nh),active_session_id:E().default(""),generated_at:E()});const d4=Te({ok:yo(!0),agent_id:E(),heartbeat_interval_ms:Ve().int().positive(),heartbeat_timeout_ms:Ve().int().positive(),registered_at:E(),received_at:E()}),Ok=ut(["rename","delete"]);Te({action:Ok,display_name:E().nullable().default(null)});const Lk=Te({ok:yo(!0)}),q0=Te({completion_notifications_enabled:It().default(!1)}),Pk=Te({p256dh:E(),auth:E()}),Uk=Te({endpoint:E().url(),expirationTime:Ve().nullable().default(null),keys:Pk}),zk=Te({label:E().nullable().default(null),user_agent:E().nullable().default(null)});Te({subscription:Uk,settings:q0.default({}),device:zk.default({})});const Bk=Te({endpoint:E().url()}),$k=Te({endpoint:E().url()}),Hk=Te({supported:It(),vapid_public_key:E().nullable().default(null),subject:E().nullable().default(null),reason:E().nullable().default(null)}),Fk=Te({ok:yo(!0),subscription_id:E(),endpoint:E().url(),settings:q0,created_at:E(),updated_at:E()}),qk=Te({ok:yo(!0),endpoint:E().url(),delivered_at:E()}),Wk=Te({type:ut(["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:Cp(Pw())}),Kk=Te({width:Ve().nonnegative(),height:Ve().nonnegative(),device_pixel_ratio:Ve().nonnegative(),visual_width:Ve().nonnegative().nullable().default(null),visual_height:Ve().nonnegative().nullable().default(null),screen_width:Ve().nonnegative().nullable().default(null),screen_height:Ve().nonnegative().nullable().default(null)}),Qk=Te({user_agent:E(),language:E().nullable().default(null),languages:nt(E()).default([]),platform:E().nullable().default(null),vendor:E().nullable().default(null),online:It().nullable().default(null),cookie_enabled:It().nullable().default(null),secure_context:It(),standalone_display_mode:It(),hardware_concurrency:Ve().int().nonnegative().nullable().default(null),device_memory_gb:Ve().nonnegative().nullable().default(null),max_touch_points:Ve().int().nonnegative().nullable().default(null)}),Gk=Te({href:E(),pathname:E(),referrer:E().nullable().default(null),visibility_state:E().nullable().default(null)}),Yk=Te({scope:E(),active_script_url:E().nullable().default(null),waiting_script_url:E().nullable().default(null),installing_script_url:E().nullable().default(null)}),Vk=Te({supported:It(),controller:It(),registrations:nt(Yk).default([])}),Xk=Te({supported:It(),keys:nt(E()).default([])}),Zk=Te({href:E().nullable().default(null),rel:E().nullable().default(null)}),Jk=Te({href:E().nullable().default(null),owner_node:E().nullable().default(null),media:E().nullable().default(null),disabled:It(),css_rule_count:Ve().int().nonnegative().nullable().default(null)}),eE=Te({url:E(),kind:ut(["stylesheet","script","manifest","icon","other"]),ok:It(),status:Ve().int().nonnegative().nullable().default(null),content_type:E().nullable().default(null),cache_control:E().nullable().default(null),error:E().nullable().default(null)}),tE=Te({name:E(),initiator_type:E().nullable().default(null),duration_ms:Ve().nonnegative().nullable().default(null),transfer_size:Ve().nonnegative().nullable().default(null),decoded_body_size:Ve().nonnegative().nullable().default(null)}),nE=Te({x:Ve(),y:Ve(),width:Ve().nonnegative(),height:Ve().nonnegative()}),sE=Te({selector:E(),found:It(),text_preview:E().nullable().default(null),rect:nE.nullable().default(null),computed:Cp(E()).default({})});Te({captured_at:E(),page:Gk,environment:Qk,viewport:Kk,feature_support:Cp(It()).default({}),service_worker:Vk,cache:Xk,manifest:Zk,stylesheets:nt(Jk).default([]),resource_probes:nt(eE).default([]),performance_entries:nt(tE).default([]),theme_variables:Cp(E()).default({}),element_snapshots:nt(sE).default([]),notes:nt(E()).default([])});const aE=/^(?:image|img|photo|picture|screenshot|图片|照片|截图)(?:[-_ ]?\d+)?\.(?:avif|bmp|gif|heic|heif|jpe?g|png|svg|webp)$/i,ia=e=>(e==null?void 0:e.trim())??"",f4="\0",h4=e=>{const t=ia(e);return t?aE.test(t)?1:2+Math.min(t.length,64)/100:0},iE=(e,t)=>{const i=h4(e),r=h4(t);if(r>i)return ia(t)||null;if(i>r)return ia(e)||null;const o=ia(e),u=ia(t);return u.length>o.length?u||null:o||null},rE=e=>{const t=ia(e.content_url);return t?[e.kind,"content",t].join(f4):[e.kind,"meta",ia(e.mime_type).toLowerCase(),typeof e.size_bytes=="number"&&Number.isFinite(e.size_bytes)?String(Math.max(0,Math.round(e.size_bytes))):"",ia(e.name).toLowerCase()].join(f4)},lE=(e,t)=>{const i=ia(e.name),r=ia(t.name),o=ia(e.mime_type),u=ia(t.mime_type);return{id:e.id||t.id,kind:e.kind==="image"||t.kind==="image"?"image":e.kind,name:iE(i,r),mime_type:o||u||null,size_bytes:e.size_bytes??t.size_bytes??null,content_url:ia(e.content_url)||ia(t.content_url)||null}},E6=e=>{if(!e||e.length===0)return[];const t=[],i=new Map;for(const r of e){const o=rE(r),u=i.get(o);if(u===void 0){i.set(o,t.length),t.push({...r,name:ia(r.name)||null,mime_type:ia(r.mime_type)||null,size_bytes:typeof r.size_bytes=="number"&&Number.isFinite(r.size_bytes)?Math.max(0,Math.round(r.size_bytes)):null,content_url:ia(r.content_url)||null});continue}t[u]=lE(t[u],r)}return t},C6=(e,t)=>E6([...e??[],...t??[]]),$a=e=>new Date(e).toISOString(),oE=()=>({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:$a("2026-03-18T10:30:00+08:00"),last_seen_at:$a("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:$a("2026-03-18T10:20:00+08:00"),last_seen_at:$a("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:$a("2026-03-18T10:58:00+08:00"),pinned:!1,run_state:"running",run_state_changed_at:$a("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:$a("2026-03-18T10:48:00+08:00"),pinned:!1,run_state:"completed",run_state_changed_at:$a("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:$a("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:$a("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:$a("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:$a("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:$a("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:$a("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"}]}),cE=()=>oE(),uE=()=>cE(),T6=e=>{const t=new URL(e);return t.protocol=t.protocol==="https:"?"wss:":"ws:",t.pathname="/ws",t.toString()};class dE{constructor(t,i=T6(t)){this.baseUrl=t,this.wsBaseUrl=i}getConnectionKey(){return`${this.baseUrl}::${this.wsBaseUrl}`}async readJson(t,i){const r=await fetch(t);if(!r.ok)throw new Error(`Request failed with ${r.status}`);return i.parse(await r.json())}async postJson(t,i,r){const o=await fetch(new URL(t,this.baseUrl),{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(i)}),u=await o.json().catch(()=>null);if(!o.ok)throw new Error((u==null?void 0:u.error)??`Request failed with ${o.status}`);return r?r.parse(u):u}async getPhaseOneSnapshot(t){const{fallbackToMock:i=!0,fallbackSnapshot:r=uE}=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 Dk.parse(u)}catch(o){if(!i)throw o;return r()}}async getHubDirectory(){return this.readJson(new URL("/api/hub/directory",this.baseUrl),Ek)}async getHubRecentSessions(){return this.readJson(new URL("/api/hub/recent-sessions",this.baseUrl),Tk)}async getSessionLocation(t){return this.readJson(new URL(`/api/sessions/${t}/location`,this.baseUrl),Mk)}async getWorkspaceDirectory(t){const i=new URL("/api/workspace",this.baseUrl);return t!=null&&t.selectedSessionId&&i.searchParams.set("selectedSessionId",t.selectedSessionId),this.readJson(i,Rk)}async getWorkspaceSessionPage(t){const i=new URL("/api/workspace/sessions",this.baseUrl);return i.searchParams.set("bucket",k6.parse(t.bucket)),t.projectId&&i.searchParams.set("projectId",t.projectId),t.projectless&&i.searchParams.set("projectless","1"),t.cursor&&i.searchParams.set("cursor",t.cursor),typeof t.limit=="number"&&Number.isFinite(t.limit)&&i.searchParams.set("limit",String(Math.max(1,Math.floor(t.limit)))),t.selectedSessionId&&i.searchParams.set("selectedSessionId",t.selectedSessionId),this.readJson(i,Ak)}async getWorkspaceSessionDetail(t){const i=new URL("/api/workspace/session-detail",this.baseUrl);return i.searchParams.set("sessionId",t),this.readJson(i,kk)}async getSessionTimeline(t,i){const r=new URL(`/api/sessions/${t}/timeline`,this.baseUrl);return i!=null&&i.view&&r.searchParams.set("view",i.view),this.readJson(r,f6)}async getSessionChangeSets(t){return this.readJson(new URL(`/api/sessions/${t}/change-sets`,this.baseUrl),{parse:i=>Array.isArray(i)?i.map(r=>m6.parse(r)):[]})}async getSessionBootstrap(t){return this.readJson(new URL(`/api/sessions/${t}/bootstrap`,this.baseUrl),XN)}async getSessionToolCallDetail(t,i){const r=new URL(`/api/sessions/${t}/tool-detail`,this.baseUrl);return r.searchParams.set("entryId",i),this.readJson(r,Ik)}async getSessionChangeSetFileDiff(t,i){const r=new URL(`/api/sessions/${t}/change-set-file-diff`,this.baseUrl);return r.searchParams.set("changeSetId",i.changeSetId),r.searchParams.set("path",i.path),i.itemId&&r.searchParams.set("itemId",i.itemId),this.readJson(r,kN)}async getSessionGitWorkspace(t){return this.readJson(new URL(`/api/sessions/${t}/git-workspace`,this.baseUrl),z0)}async getSessionGitWorkspaceFileDiff(t,i){const r=new URL(`/api/sessions/${t}/git-workspace/file-diff`,this.baseUrl);return r.searchParams.set("path",i.path),i.previousPath&&r.searchParams.set("previousPath",i.previousPath),this.readJson(r,TN)}async getSessionGitHistory(t){return this.readJson(new URL(`/api/sessions/${t}/git/history`,this.baseUrl),IN)}async getSessionFilePreviewTree(t,i){var u;const r=new URL(`/api/sessions/${t}/file-preview/tree`,this.baseUrl),o=(u=i==null?void 0:i.path)==null?void 0:u.trim();return o&&r.searchParams.set("path",o),this.readJson(r,UN)}async getSessionFilePreviewContent(t,i){const r=new URL(`/api/sessions/${t}/file-preview/content`,this.baseUrl);return r.searchParams.set("path",i.path),this.readJson(r,zN)}async getSessionGitHistoryFileDiff(t,i){const r=new URL(`/api/sessions/${t}/git/history/file-diff`,this.baseUrl);return r.searchParams.set("commitOid",i.commitOid),r.searchParams.set("path",i.path),i.previousPath&&r.searchParams.set("previousPath",i.previousPath),this.readJson(r,AN)}async getSessionRunWorkbench(t){return this.readJson(new URL(`/api/sessions/${t}/run-workbench`,this.baseUrl),b6)}async saveSessionRunCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/run-commands`,{action:t.action,commandId:t.commandId??null,command:t.command??null},ZN)}async generateSessionRunCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/run-commands/generate`,{prompt:t.prompt,model:t.model},tk)}async saveSessionRunWebsite(t){return this.postJson(`/api/sessions/${t.sessionId}/run-websites`,{action:t.action,websiteId:t.websiteId??null,website:t.website??null},JN)}async generateSessionRunWebsite(t){return this.postJson(`/api/sessions/${t.sessionId}/run-websites/generate`,{prompt:t.prompt,model:t.model},sk)}async executeSessionTerminalAction(t){return this.postJson(`/api/sessions/${t.sessionId}/terminals`,{action:t.action,commandId:t.commandId??null,terminalId:t.terminalId??null},ak)}async getSessionTerminalOutput(t){const i=new URL(`/api/sessions/${t.sessionId}/terminals/${t.terminalId}/output`,this.baseUrl);return typeof t.cursor=="number"&&Number.isFinite(t.cursor)&&i.searchParams.set("cursor",String(Math.max(0,Math.floor(t.cursor)))),this.readJson(i,YN)}async getSessionPlan(t){return this.readJson(new URL(`/api/sessions/${t}/plan`,this.baseUrl),{parse:i=>i==null?null:O0.parse(i)})}async getSessionInteractions(t){return this.readJson(new URL(`/api/sessions/${t}/interactions`,this.baseUrl),{parse:i=>Array.isArray(i)?i.map(r=>L0.parse(r)):[]})}async getSessionRecoverySnapshot(t){return this.readJson(new URL(`/api/sessions/${t}/recovery`,this.baseUrl),VN)}async getProjectSkills(t){return this.readJson(new URL(`/api/projects/${t}/skills`,this.baseUrl),{parse:i=>Array.isArray(i)?i.map(r=>cN.parse(r)):[]})}async getCodexCommands(){return this.readJson(new URL("/api/codex/commands",this.baseUrl),o4)}async refreshCodexCommands(){return this.postJson("/api/codex/commands/refresh",{},o4)}async listDirectories(t){const i=new URL("/api/directories",this.baseUrl);return t.agentId&&i.searchParams.set("agentId",t.agentId),t.path&&i.searchParams.set("path",t.path),this.readJson(i,{parse:r=>Array.isArray(r)?r.map(o=>j6.parse(o)):[]})}async createDirectory(t){return this.postJson("/api/directories",t,xk)}async createProject(t){return this.postJson("/api/projects",t)}async createSession(t){var i;return this.postJson("/api/sessions",{...t,attachments:(i=t.attachments)==null?void 0:i.map(r=>U1.parse(r)),serviceTier:t.serviceTier,planMode:t.planMode,yoloMode:t.yoloMode})}async createChat(t){var i;return this.postJson("/api/chats",{...t,attachments:(i=t.attachments)==null?void 0:i.map(r=>U1.parse(r)),serviceTier:t.serviceTier,planMode:t.planMode,yoloMode:t.yoloMode})}async getImageProviderSettings(){return this.readJson(new URL("/api/image-provider/settings",this.baseUrl),r4)}async saveImageProviderSettings(t){return this.postJson("/api/image-provider/settings",l4.parse(t),r4)}async testImageProviderSettings(t){return this.postJson("/api/image-provider/test",l4.parse({active_channel_id:(t==null?void 0:t.active_channel_id)??null,channels:(t==null?void 0:t.channels)??[]}),aN)}async listImageProviderModels(t){return this.postJson("/api/image-provider/models",iN.parse(t),rN)}async createImageSession(t){return this.postJson("/api/image-sessions",lN.parse(t??{}))}async getImageSessionDetail(t){return this.readJson(new URL(`/api/image-sessions/${t}`,this.baseUrl),u4)}async submitImageSessionPrompt(t){return this.postJson(`/api/image-sessions/${t.sessionId}/submit`,oN.parse({prompt:t.prompt,append_to_turn_id:t.append_to_turn_id,model:t.model,quality:t.quality,size:t.size,input_fidelity:t.input_fidelity,aspect_ratio:t.aspect_ratio,output_format:t.output_format,output_compression:t.output_compression,background:t.background,moderation:t.moderation,n:t.n,sources:t.sources}),u4)}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 i;return this.postJson(`/api/sessions/${t.sessionId}/input`,{input:t.input,attachments:(i=t.attachments)==null?void 0:i.map(r=>U1.parse(r)),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},c4)}async respondToSessionCommand(t){return this.postJson(`/api/sessions/${t.sessionId}/commands/respond`,{panelId:t.panelId,optionId:t.optionId??null,text:t.text??null},c4)}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,d4)}async heartbeatAgent(t){return this.postJson("/api/agents/heartbeat",t,d4)}async updateAgent(t){return this.postJson(`/api/agents/${t.agentId}/actions`,{action:t.action,display_name:t.displayName??null},Lk)}async getWebPushPublicConfig(){return this.readJson(new URL("/api/push/public-key",this.baseUrl),Hk)}async upsertWebPushSubscription(t){return this.postJson("/api/push/subscriptions",{subscription:t.subscription,settings:q0.parse(t.settings),device:t.device??null},Fk)}async removeWebPushSubscription(t){return this.postJson("/api/push/subscriptions/remove",Bk.parse(t))}async sendWebPushTest(t){return this.postJson("/api/push/test",$k.parse(t),qk)}async executeSessionGitAction(t){return this.postJson(`/api/sessions/${t.sessionId}/git/actions`,{action:t.action,path:t.path,branch:t.branch,message:t.message},DN)}async executeSessionTurnAction(t){return this.postJson(`/api/sessions/${t.sessionId}/turns/${t.turnId}/actions`,{action:t.action},ON)}async getDevManagerSnapshot(t){const i=new URL("/api/dev-manager",this.baseUrl);return t!=null&&t.includeServiceProbe&&i.searchParams.set("includeServiceProbe","1"),this.readJson(i,K_)}async saveDevManagerConfig(t){return this.postJson("/api/dev-manager/config",fk.parse(t),K_)}async executeDevManagerAction(t){return this.postJson("/api/dev-manager/actions",t,yk)}createEventStream(t,i){var Ce;let m=null,y=((Ce=i==null?void 0:i.sessionId)==null?void 0:Ce.trim())??"",g="",b=!1,p=0,v=null,w=!1,N=!1,j=!1,T=0;const M=typeof document<"u"&&typeof document.visibilityState=="string",P=()=>M&&document.visibilityState==="hidden",I=(i==null?void 0:i.reconnectWhenHidden)===!0,k=R=>(R==null?void 0:R.readyState)===WebSocket.OPEN||(R==null?void 0:R.readyState)===WebSocket.CONNECTING,O=()=>{v!==null&&(globalThis.clearTimeout(v),v=null)},Q=(R,X)=>{var le;(le=i==null?void 0:i.onStatus)==null||le.call(i,{state:R,attempt:p,maxAttempts:5,error:X})},J=R=>{const X=m;!X||X.readyState!==WebSocket.OPEN||(g&&g!==R&&(X.send(JSON.stringify({type:"session.unsubscribe",sessionId:g})),g=""),!(!R||g===R)&&(g=R,X.send(JSON.stringify({type:"session.subscribe",sessionId:R}))))},F=R=>{if(b||w)return;if(!I&&P()){w=!1,j=!0,O(),Q("failed",R);return}if(p+=1,!I&&p>5){p=5,j=!0,Q("failed",R);return}w=!0,j=!1,Q("reconnecting",R),O();const X=I?Math.min(p,5):p,le=Math.min(1e4,1200*2**Math.max(0,X-1));v=globalThis.setTimeout(()=>{w=!1,B()},le)},B=()=>{if(b||k(m))return;O(),w=!1,j=!1;const R=new WebSocket(this.wsBaseUrl);m=R,R.addEventListener("open",()=>{b||m!==R||(w=!1,N=!1,p=0,Q("connected"),J(y))}),R.addEventListener("message",X=>{if(m!==R)return;const le=Wk.safeParse(JSON.parse(X.data));le.success&&t(le.data)}),R.addEventListener("error",()=>{if(b||m!==R)return;const X=`鏃犳硶杩炴帴鍒?${this.wsBaseUrl}`;R.readyState!==WebSocket.OPEN&&F(X)}),R.addEventListener("close",X=>{var ue;if(m===R&&(m=null),b||m!==null)return;const le=((ue=X.reason)==null?void 0:ue.trim())||`WebSocket disconnected (code ${X.code||"unknown"})`;F(le)})},G=R=>{if(b||k(m)||N)return;const X=Date.now();X-T<1500||(T=X,N=!0,p=0,w=!1,j=!1,O(),Q("reconnecting",R),B())},Z=()=>{document.visibilityState==="visible"&&(j||!k(m))&&G("App returned to foreground; reconnecting.")},ae=()=>{(j||!k(m))&&G("Page became visible again; reconnecting.")},he=()=>{(j||!k(m))&&G("Window focused again; reconnecting.")},ne=()=>{(j||!k(m))&&G("缃戠粶宸叉仮澶嶏紝姝e湪閲嶆柊杩炴帴")};return typeof window<"u"&&(window.addEventListener("pageshow",ae),window.addEventListener("focus",he),window.addEventListener("online",ne)),typeof document<"u"&&document.addEventListener("visibilitychange",Z),B(),{setSessionId:R=>{y=(R==null?void 0:R.trim())??"",!b&&J(y)},close:()=>{b=!0,w=!1,N=!1,j=!1,O(),typeof window<"u"&&(window.removeEventListener("pageshow",ae),window.removeEventListener("focus",he),window.removeEventListener("online",ne)),typeof document<"u"&&document.removeEventListener("visibilitychange",Z);const R=m;if((R==null?void 0:R.readyState)===WebSocket.OPEN&&g&&R.send(JSON.stringify({type:"session.unsubscribe",sessionId:g})),g="",m=null,(R==null?void 0:R.readyState)===WebSocket.CONNECTING){const X=()=>{try{R.close()}catch{}};R.addEventListener("open",X,{once:!0});return}R==null||R.close()}}}connectEvents(t,i){const r=this.createEventStream(t,i);return()=>{r.close()}}}const M6=(e,t)=>new dE(e,(t==null?void 0:t.wsBaseUrl)??T6(e)),R6=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return null;try{const i=new URL(t);return i.port?`${i.hostname}:${i.port}`:i.hostname}catch{return t.replace(/\/+$/,"")||null}},Cc=e=>{var t;return((t=e.display_name)==null?void 0:t.trim())||e.name.trim()||R6(e.direct_base_url)||"未命名节点"},fE=e=>{var i;const t=((i=e.display_name)==null?void 0:i.trim())??"";return!t||t===e.name?null:e.name},z1=e=>R6(e.direct_base_url)||e.host||e.tailscale_ip||e.tailscale_dns_name||e.direct_base_url,Tp="panda:last-agent-id",Mp="panda:last-session-id",lh="panda:pending-session-id",oh="panda:pending-project-id",ch="panda:pending-directory-picker",fd="panda:pending-session-handoff",uh="panda:selected-agent-connection-hint",hE=3e4,mE=1800*1e3,$f=e=>typeof e=="object"&&e!==null,pE=e=>{if(!$f(e))return null;const{sessionId:t,agentId:i,projectId:r,createdAt:o,session:u,project:d,optimisticEntry:m}=e;return typeof t!="string"||typeof i!="string"||typeof r!="string"||typeof o!="string"||!$f(u)||u.id!==t||u.agent_id!==i||u.project_id!==r||d!==null&&(!$f(d)||d.id!==r||d.agent_id!==i||typeof d.name!="string"||typeof d.path!="string")||m!==null&&(!$f(m)||typeof m.id!="string"||typeof m.kind!="string"||typeof m.body!="string"||typeof m.timestamp!="string")?null:{sessionId:t,agentId:i,projectId:r,createdAt:o,session:u,project:d??null,optimisticEntry:m??null}},gE=e=>{const t=new Date(e.createdAt).getTime();return Number.isFinite(t)?Date.now()-t>hE:!0},_E=e=>{if(!$f(e))return null;const{agentId:t,name:i,displayName:r,directBaseUrl:o,wsBaseUrl:u,createdAt:d}=e;return typeof t!="string"||typeof i!="string"||r!==null&&typeof r!="string"||typeof o!="string"||typeof u!="string"||typeof d!="string"?null:{agentId:t,name:i,displayName:r,directBaseUrl:o,wsBaseUrl:u,createdAt:d}},yE=e=>{const t=new Date(e.createdAt).getTime();return Number.isFinite(t)?Date.now()-t>mE:!0},vE=e=>{if(!(typeof window>"u"))try{if(!e){window.sessionStorage.removeItem(fd);return}window.sessionStorage.setItem(fd,JSON.stringify(e))}catch{}},W0=e=>{if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(fd);if(!t)return null;const i=pE(JSON.parse(t));return!i||gE(i)?(window.sessionStorage.removeItem(fd),null):e&&i.sessionId!==e?null:i}catch{return null}},bE=e=>{if(!(typeof window>"u"))try{const t=W0();if(e&&(t!=null&&t.sessionId)&&t.sessionId!==e)return;window.sessionStorage.removeItem(fd)}catch{}},xE=e=>{if(!(typeof window>"u"))try{if(!e){window.sessionStorage.removeItem(uh);return}window.sessionStorage.setItem(uh,JSON.stringify(e))}catch{}},kh=e=>{if(typeof window>"u")return null;try{const t=window.sessionStorage.getItem(uh);if(!t)return null;const i=_E(JSON.parse(t));return!i||yE(i)?(window.sessionStorage.removeItem(uh),null):e&&i.agentId!==e?null:i}catch{return null}},vo=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(Tp)}catch{return null}},fr=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Tp,e);return}window.localStorage.removeItem(Tp)}catch{}},Rp=()=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(Mp)}catch{return null}},Ea=e=>{if(!(typeof window>"u"))try{if(e){window.localStorage.setItem(Mp,e);return}window.localStorage.removeItem(Mp)}catch{}},sl=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(lh,e);return}window.sessionStorage.removeItem(lh)}catch{}},SE=()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem(lh);return e&&window.sessionStorage.removeItem(lh),e}catch{return null}},Hu=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(oh,e);return}window.sessionStorage.removeItem(oh)}catch{}},jE=()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem(oh);return e&&window.sessionStorage.removeItem(oh),e}catch{return null}},Hf=e=>{if(!(typeof window>"u"))try{if(e){window.sessionStorage.setItem(ch,"1");return}window.sessionStorage.removeItem(ch)}catch{}},wE=()=>{if(typeof window>"u")return!1;try{const e=window.sessionStorage.getItem(ch);return e&&window.sessionStorage.removeItem(ch),e==="1"}catch{return!1}},A6=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(Tp),window.localStorage.removeItem(Mp),window.sessionStorage.removeItem(lh),window.sessionStorage.removeItem(oh),window.sessionStorage.removeItem(ch),window.sessionStorage.removeItem(fd),window.sessionStorage.removeItem(uh)}catch{}},Ap=Ac("Preferences",{web:()=>cl(()=>import("./web-OEcsiG9z.js"),[]).then(e=>new e.PreferencesWeb)}),NE=new Set(["4173","4174"]),kE="PandaMobile",I6="hub_url",D6="onboarding_completed",Q_=new Set;let dr={platform:rd(),hubUrl:"",onboardingCompleted:!1};const O6=()=>{for(const e of Q_)e()},EE=e=>(Q_.add(e),()=>{Q_.delete(e)}),Tc=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";try{return new URL(t).toString().replace(/\/+$/,"")}catch{return t.replace(/\/+$/,"")}},CE=()=>typeof window>"u"?null:window.location.origin||null,L6=e=>{if(typeof window>"u")return`http://localhost:${e}`;const t=window.location.protocol==="https:"?"https:":"http:",i=window.location.hostname||"localhost";return`${t}//${i}:${e}`},TE=()=>Tc(L6(4242)),ME=()=>{const e=Tc(void 0);if(e)return e;const t=CE();if(!t)return"http://localhost:4343";const i=window.location.port.trim();return NE.has(i)?L6(4343):Tc(t)},RE=()=>Tc(void 0),AE=()=>!1,IE=()=>{const e=rd();if(e==="web")return{platform:e,hubUrl:ME(),onboardingCompleted:!0};const t=RE();return{platform:e,hubUrl:t,onboardingCompleted:!!t}},m4=async e=>{if(ba()){const{value:t}=await Ap.get({key:e});return t}if(typeof window>"u")return null;try{return window.localStorage.getItem(`panda:runtime:${e}`)}catch{return null}},p4=async(e,t)=>{if(ba()){if(t===null){await Ap.remove({key:e});return}await Ap.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{}},DE=async()=>{const e=IE();ba()&&await Ap.configure({group:kE});const[t,i]=await Promise.all([m4(I6),m4(D6)]),r=e.platform==="web"?e.hubUrl:Tc(t)||e.hubUrl,o=e.platform==="web"?!0:i==="true"||!!(r&&e.onboardingCompleted);return dr={platform:e.platform,hubUrl:r,onboardingCompleted:o},O6(),dr},G_=()=>dr,OE=()=>Tc(dr.hubUrl),LE=()=>{const e=G_();return e.platform==="web"?AE():!e.hubUrl||!e.onboardingCompleted},P6=async e=>{const t=e.hubUrl===void 0?dr.hubUrl:Tc(e.hubUrl),i=e.onboardingCompleted??dr.onboardingCompleted;return dr={...dr,hubUrl:t,onboardingCompleted:i},dr.platform!=="web"&&await Promise.all([p4(I6,t||null),p4(D6,i?"true":"false")]),O6(),dr},Zp=()=>_.useSyncExternalStore(EE,G_,G_),PE=new Set(["localhost","127.0.0.1","::1"]),U6=()=>TE(),bd=()=>OE(),g4=new Map,UE={direct:"Agent 直连",hub:"Hub 聚合"},zE=1e4,BE=1e4,z6=1e4,$E=1e4,_4=1200,y4=5e3;let np=null,Y_=0,Uu=null,Fu=null,Ip=0,zu=null,sp=null,V_=0,Bu=null;const X_=new Map,ap=new Map,ip=new Map,bi=e=>(e==null?void 0:e.trim())??"",B6=e=>{const t=(e==null?void 0:e.trim())??"";return t?t.replace(/^\[|\]$/g,"").replace(/\.+$/,"").toLowerCase():""},$6=e=>PE.has(B6(e)),hd=e=>{const t=(e==null?void 0:e.trim())??"";if(!t)return"";try{const i=new URL(t),r=B6(i.hostname);return r&&(i.hostname=r),i.toString().replace(/\/+$/,"")}catch{return t}},md=()=>typeof window>"u"||ba()?!1:$6(window.location.hostname),HE=e=>{const t=e.trim();if(!t)return _4;try{const i=new URL(t);return $6(i.hostname)?_4:y4}catch{return y4}},pd=async e=>{const t=e.trim();if(!t)return!1;const i=ip.get(t),r=Date.now();if(i&&r-i.checkedAt<$E)return i.reachable;const o=new AbortController,u=globalThis.setTimeout(()=>o.abort(),HE(t));try{const m=(await fetch(`${t}/health`,{signal:o.signal})).ok;return ip.set(t,{reachable:m,checkedAt:Date.now()}),m}catch{return ip.set(t,{reachable:!1,checkedAt:Date.now()}),!1}finally{clearTimeout(u)}},xd=(e,t)=>{const i=`${e}::${(t==null?void 0:t.trim())??""}`,r=g4.get(i);if(r)return r;const o=M6(e,{wsBaseUrl:t});return g4.set(i,o),o},v4=()=>xd(H6()),b4=e=>{const t=e(Fu);Fu=t,Ip=t?Date.now():0},K0=(e,t,i)=>({mode:"direct",label:e,baseUrl:t,client:xd(t,i)}),H6=()=>{const e=bd();if(!e)throw new Error("尚未配置 Panda Hub 地址,请先完成应用连接设置。");return e},Xf=e=>{const t=e==="hub"?H6():U6();return{mode:e,label:UE[e],baseUrl:t,client:xd(t)}},F6=e=>hd(e.direct_base_url),FE=e=>hd(e.ws_base_url),x4=e=>{const t=F6(e)||e.tailscale_dns_name||e.tailscale_ip||e.host;return`无法直连节点 ${Cc(e)}(${t})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`},qE=async()=>{if(!md())return null;const e=Date.now();if(sp&&e-V_<z6)return sp;if(Bu)return Bu;Bu=(async()=>{const t=U6();if(!await pd(t))return null;const i=await xd(t).getPhaseOneSnapshot({fallbackToMock:!1});return sp=i,V_=Date.now(),i})().catch(()=>null);try{return await Bu}finally{Bu=null}},q6=async e=>{var r,o;const t=await qE(),i=((o=(r=t==null?void 0:t.agents[0])==null?void 0:r.id)==null?void 0:o.trim())??"";return!!(i&&i===e.trim())},W6=async e=>{if(await q6(e.id))return{...Xf("direct"),label:`Agent 直连 · ${Cc(e)}(本机)`};const t=F6(e),i=FE(e);return K0(`Agent 直连 · ${Cc(e)}`,t,i||void 0)},WE=async e=>{if(await q6(e.agent_id))return{...Xf("direct"),label:`Agent 直连 · ${e.agent_id}(本机)`};const t=hd(e.direct_base_url),i=hd(e.ws_base_url);return K0(`Agent 直连 · ${e.agent_id}`,t,i||void 0)},K6=e=>{var r;const t=bi(e.agentId);if(!t)return null;const i=kh(t);return i!=null&&i.directBaseUrl.trim()?K0(`Agent 直连 · ${((r=i.displayName)==null?void 0:r.trim())||i.name.trim()||t}`,hd(i.directBaseUrl),hd(i.wsBaseUrl)||void 0):null},S4=async e=>{const t=K6(e);if(t!=null&&t.baseUrl&&(await pd(t.baseUrl)||!md()))return t;const i=await G6(),r=i?Q6(i,e):null;if(!r)return null;const o=await W6(r);return o.baseUrl&&(await pd(o.baseUrl)||!md())?o:null},Q6=(e,t)=>{const i=bi(t.agentId);return i?e.agents.find(r=>r.id===i)??null:null},KE=e=>{const t=bi(e.sessionId),i=bi(e.projectId),r=bi(e.agentId);return r?`agent:${r}`:i?`project:${i}`:t?`session:${t}`:""},G6=async()=>{const e=Date.now();if(Fu&&e-Ip<z6)return Fu;if(zu)return zu;zu=(async()=>{const t=bd();if(!t)return null;const i=await xd(t).getHubDirectory();return Fu=i,Ip=Date.now(),i})().catch(()=>null);try{return await zu}finally{zu=null}},QE=async()=>{if(!md())return Xf("hub");const e=Date.now();if(np&&e-Y_<zE)return np;if(Uu)return Uu;Uu=(async()=>{const t=bd(),i=t&&await pd(t)?Xf("hub"):Xf("direct");return np=i,Y_=Date.now(),i})();try{return await Uu}finally{Uu=null}},GE=async e=>{const t=KE(e),i=Date.now(),r=t?X_.get(t):null;if(r&&i-r.cachedAt<BE)return r.target;const o=t?ap.get(t):null;if(o)return o;const u=(async()=>{const d=bi(e.sessionId),m=bi(e.agentId),y=K6(e),g=bd();if(!g&&!y&&!m)throw new Error("尚未配置 Panda Hub 地址,请先完成应用连接设置。");const b=g?xd(g):null;if(m){const N=await S4(e);if(N)return N}if(d){const N=b?await b.getSessionLocation(d).catch(()=>null):null;if(!N){const T=m?await S4(e):null;if(T)return T;throw new Error("Hub 未返回目标会话位置,无法建立直连。")}const j=await WE(N);if(!j.baseUrl)throw new Error(`无法直连节点 ${N.agent_id}(${N.direct_base_url||N.ws_base_url||"unknown"})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`);if(await pd(j.baseUrl)||!md())return j;throw new Error(`无法直连节点 ${N.agent_id}(${N.direct_base_url||N.ws_base_url||"unknown"})。请确认当前浏览器已加入 Tailscale 网络,且目标 agent 在线。`)}if(bi(e.projectId)&&!bi(e.agentId))throw new Error("Project-scoped connection resolution now requires agentId.");const p=await G6(),v=p?Q6(p,e):null;if(!v)throw new Error("Hub 未返回目标节点信息,无法建立直连。");const w=await W6(v);if(!w.baseUrl)throw new Error(x4(v));if(await pd(w.baseUrl)||!md())return w;throw new Error(x4(v))})();t&&ap.set(t,u);try{const d=await u;return t&&X_.set(t,{target:d,cachedAt:Date.now()}),d}finally{t&&ap.delete(t)}},cn=async e=>!(bi(e==null?void 0:e.sessionId)||bi(e==null?void 0:e.projectId)||bi(e==null?void 0:e.agentId))?QE():GE(e??{}),YE=()=>{np=null,Y_=0,Uu=null,Fu=null,Ip=0,zu=null,sp=null,V_=0,Bu=null,X_.clear(),ap.clear(),ip.clear()},Y6="panda:notification-settings",V6="panda:notified-completions",Q0="panda:web-push-subscription-state",VE=280,X6="session-completions",B1={completionNotificationsEnabled:!1};let dh=ba()?"default":"unsupported";const Eh=()=>{const e=bd();if(!e)throw new Error("尚未配置 Panda Hub 地址。");return M6(e)},Z6=e=>({completionNotificationsEnabled:(e==null?void 0:e.completionNotificationsEnabled)===!0}),XE=(e,t)=>e.length<=t?e:`${e.slice(0,t-1).trimEnd()}…`,J6=()=>{if(typeof window>"u")return{};try{const e=window.localStorage.getItem(V6);if(!e)return{};const t=JSON.parse(e);return!t||typeof t!="object"?{}:Object.fromEntries(Object.entries(t).filter(i=>typeof i[0]=="string"&&typeof i[1]=="string"))}catch{return{}}},ZE=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(V6,JSON.stringify(e))}catch{}},JE=e=>{if(!e||typeof e!="object")return null;const t=typeof e.endpoint=="string"?e.endpoint.trim():"",i=typeof e.updatedAt=="string"?e.updatedAt.trim():"";return!t||!i?null:{completionNotificationsEnabled:e.completionNotificationsEnabled===!0,endpoint:t,updatedAt:i}},e3=()=>{if(typeof window>"u")return null;try{return JE(JSON.parse(window.localStorage.getItem(Q0)??"null"))}catch{return null}},t3=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Q0,JSON.stringify(e))}catch{}},Dp=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(Q0)}catch{}},n3=async()=>{if(typeof navigator>"u"||!("serviceWorker"in navigator))throw new Error("当前环境没有可用的 Service Worker。");return navigator.serviceWorker.ready},eC=e=>{const t="=".repeat((4-e.length%4)%4),i=(e+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(i),o=new Uint8Array(r.length);for(let u=0;u<r.length;u+=1)o[u]=r.charCodeAt(u);return o},G0=async()=>{const e=await n3();return"pushManager"in e?e.pushManager.getSubscription():null},s3=e=>{var u,d;const t=e.toJSON(),i=e.endpoint.trim(),r=typeof((u=t.keys)==null?void 0:u.p256dh)=="string"?t.keys.p256dh.trim():"",o=typeof((d=t.keys)==null?void 0:d.auth)=="string"?t.keys.auth.trim():"";if(!i||!r||!o)throw new Error("浏览器返回的推送订阅信息不完整。");return{endpoint:i,expirationTime:typeof e.expirationTime=="number"?e.expirationTime:null,keys:{p256dh:r,auth:o}}},a3=async()=>{try{return await Eh().getWebPushPublicConfig()}catch(e){throw new Error(e instanceof Error?e.message:"无法读取 Hub Web Push 配置。")}},Z_=()=>{if(typeof window>"u")return B1;try{const e=window.localStorage.getItem(Y6);return e?Z6(JSON.parse(e)):B1}catch{return B1}},sc=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Y6,JSON.stringify(Z6(e)))}catch{}},Ch=()=>ba()?!0:typeof window>"u"?!1:window.isSecureContext&&"Notification"in window&&"serviceWorker"in navigator,gd=()=>ba()||!Ch()?!1:"PushManager"in window,qu=()=>ba()?dh:Ch()?Notification.permission:"unsupported",i3=e=>e==="granted"?"granted":e==="denied"?"denied":e==="prompt"?"default":"unsupported",r3=async()=>{Yp()&&await wh.createChannel({id:X6,name:"任务完成提醒",description:"Panda 对话和任务完成提醒",importance:4,visibility:1,vibration:!0,lights:!0}).catch(()=>{})},Y0=async()=>{if(ba()){const e=await wh.checkPermissions();return dh=i3(e.display),dh}return Ch()?Notification.permission:"unsupported"},J_=async()=>{if(ba()){await r3();const e=await wh.requestPermissions();return dh=i3(e.display),dh}return Ch()?Notification.requestPermission():"unsupported"},e0=()=>{var e;return((e=e3())==null?void 0:e.completionNotificationsEnabled)===!0},tC=async e=>{if(!e.completionNotificationsEnabled||qu()!=="granted")return{synced:!1,reason:"notifications-disabled"};if(!gd())return{synced:!1,reason:"unsupported"};const t=await a3();if(!t.supported||!t.vapid_public_key)return Dp(),{synced:!1,reason:"hub-unsupported"};const i=await G0();if(!i)return Dp(),{synced:!1,reason:"missing-browser-subscription"};const r=await Eh().upsertWebPushSubscription({subscription:s3(i),settings:{completion_notifications_enabled:e.completionNotificationsEnabled},device:{label:$u()?"installed-pwa":"browser-tab",user_agent:typeof navigator<"u"?navigator.userAgent:null}});return t3({completionNotificationsEnabled:r.settings.completion_notifications_enabled,endpoint:r.endpoint,updatedAt:r.updated_at}),{synced:!0,endpoint:r.endpoint}},j4=async e=>{if(!gd())throw new Error("当前环境不支持 Web Push。");const t=await a3();if(!t.supported||!t.vapid_public_key)throw new Error(t.reason??"Hub 当前没有可用的 Web Push 配置。");const i=await n3(),o=await i.pushManager.getSubscription()??null??await i.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:eC(t.vapid_public_key)}),u=await Eh().upsertWebPushSubscription({subscription:s3(o),settings:{completion_notifications_enabled:e.completionNotificationsEnabled},device:{label:$u()?"installed-pwa":"browser-tab",user_agent:typeof navigator<"u"?navigator.userAgent:null}});return t3({completionNotificationsEnabled:u.settings.completion_notifications_enabled,endpoint:u.endpoint,updatedAt:u.updated_at}),u},nC=async()=>{if(!gd())return Dp(),{removed:!1};const e=await G0();if(e){try{await Eh().removeWebPushSubscription({endpoint:e.endpoint})}catch{}try{await e.unsubscribe()}catch{}}return Dp(),{removed:!!e}},sC=async()=>{var r,o;if(!gd())throw new Error("当前环境不支持 Web Push。");if(qu()!=="granted")throw new Error("请先授予系统通知权限。");const e=await G0(),t=e3(),i=((r=e==null?void 0:e.endpoint)==null?void 0:r.trim())||((o=t==null?void 0:t.endpoint)==null?void 0:o.trim())||"";if(!i)throw new Error("当前设备还没有可用的 Web Push 订阅。");return await Eh().sendWebPushTest({endpoint:i}),{ok:!0,endpoint:i}},$u=()=>{if(typeof window>"u")return!1;const e=navigator;return window.matchMedia("(display-mode: standalone)").matches||e.standalone===!0},w4=()=>typeof navigator>"u"?!1:/Android/i.test(navigator.userAgent),aC=e=>{if(typeof e!="string")return"";const t=e.replace(/\r\n/g,`
|
|
67
67
|
`).replace(/\s+/g," ").trim();return t?XE(t,VE):""},iC=(e,t)=>J6()[e]===t,$1=(e,t)=>{const i=J6();i[e]!==t&&ZE({...i,[e]:t})},l3=async e=>{if(!Ch())return!1;if(ba()){if(await Y0()!=="granted")return!1;await r3();try{return await wh.schedule({notifications:[{id:Math.abs(Array.from(`${e.sessionId}:${e.completedAt}`).reduce((i,r)=>i*31+r.charCodeAt(0)|0,17)),title:e.title,body:e.body,channelId:X6,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 i=new Notification(e.title,t);return i.onclick=()=>{window.focus(),window.location.assign(e.url)},!0}catch{return!1}}},rC=async e=>{if(!ba())return()=>{};const t=await wh.addListener("localNotificationActionPerformed",i=>{var o;const r=typeof((o=i.notification.extra)==null?void 0:o.url)=="string"?i.notification.extra.url.trim():"";r&&e(r)});return()=>{t.remove()}},o3=1,lC=10080*60*1e3,c3="panda-web-cache",_d="app-state",u3="react-query",N4="panda:storage-persist-result",oC=new Set(["directory","bootstrap","timeline","timeline-optimistic","change-sets","plan","interactions","codex-commands","project-skills","settings-connection"]),V0=()=>typeof window<"u"&&typeof window.indexedDB<"u",cC=e=>typeof e[0]=="string"&&oC.has(e[0]),d3=async()=>V0()?await new Promise((e,t)=>{const i=window.indexedDB.open(c3,1);i.onupgradeneeded=()=>{const r=i.result;r.objectStoreNames.contains(_d)||r.createObjectStore(_d)},i.onsuccess=()=>e(i.result),i.onerror=()=>t(i.error??new Error("Unable to open Panda cache database."))}):null,uC=async()=>{const e=await d3();if(!e)return null;try{return await new Promise((t,i)=>{const u=e.transaction(_d,"readonly").objectStore(_d).get(u3);u.onsuccess=()=>t(u.result??null),u.onerror=()=>i(u.error??new Error("Unable to read Panda cache record."))})}finally{e.close()}},dC=async e=>{const t=await d3();if(t)try{await new Promise((i,r)=>{const o=t.transaction(_d,"readwrite");o.objectStore(_d).put(e,u3),o.oncomplete=()=>i(),o.onerror=()=>r(o.error??new Error("Unable to write Panda cache record.")),o.onabort=()=>r(o.error??new Error("Writing Panda cache record was aborted."))})}finally{t.close()}},Op=async()=>{V0()&&await new Promise(e=>{const t=window.indexedDB.deleteDatabase(c3);t.onsuccess=()=>e(),t.onerror=()=>e(),t.onblocked=()=>e()})},fC=async e=>{if(V0())try{const t=await uC();if(!t)return;const i=Date.now()-t.persistedAt>lC;if(t.version!==o3||i){await Op();return}xS(e,t.clientState)}catch{await Op().catch(()=>{})}},hC=async()=>{if(!(typeof navigator>"u"||typeof window>"u"||!("storage"in navigator)||typeof navigator.storage.persist!="function"))try{if(window.localStorage.getItem(N4))return;const t=await navigator.storage.persist();window.localStorage.setItem(N4,t?"granted":"denied")}catch{}},mC=e=>{if(typeof window>"u")return()=>{};hC();let t=null,i=null,r=!1,o=!1;const u=async()=>{if(!o){if(i){r=!0;return}i=(async()=>{const b=bS(e,{shouldDehydrateQuery:p=>cC(p.queryKey)});await dC({version:o3,persistedAt:Date.now(),clientState:b})})();try{await i}catch{}finally{i=null,r&&(r=!1,u())}}},d=(b=!1)=>{if(!o){if(t!==null&&(window.clearTimeout(t),t=null),b){u();return}t=window.setTimeout(()=>{t=null,u()},1200)}},m=e.getQueryCache().subscribe(()=>{d(!1)}),y=()=>{document.visibilityState==="hidden"&&d(!0)},g=()=>{d(!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)}},f3=async e=>{YE(),A6(),await Op().catch(()=>{}),e.removeQueries({predicate:t=>typeof t.queryKey[0]=="string"&&t.queryKey[0]!=="pwa-install-diagnostics"})},pC=()=>{const e=Hi(),t=Ka(),i=Zp();return a.jsx("main",{className:"runtime-onboarding",children:a.jsxs("div",{className:"runtime-onboarding__shell",children:[a.jsxs("section",{className:"runtime-onboarding__hero",children:[a.jsx("span",{className:"runtime-onboarding__eyebrow",children:"首次连接"}),a.jsx("h1",{className:"runtime-onboarding__title",children:"输入 Panda 访问地址"}),a.jsx("p",{className:"runtime-onboarding__summary",children:"填一次,之后打开就能直接进入。也支持扫码。"})]}),a.jsx("section",{className:"settings-panel runtime-onboarding__panel",children:a.jsx(Q2,{title:"Hub 地址",description:"填写电脑上显示的访问地址。",initialHubUrl:i.hubUrl,hint:"手机能直接打开这个地址就可以。",saveLabel:"保存并进入",savingLabel:"连接中",saveDescription:"保存后立即进入,之后也能在设置里修改。",saveSuccessMessage:"地址已保存,正在进入 Panda。",onSaveSuccess:async r=>{await P6({hubUrl:r.url,onboardingCompleted:!0}),ba()&&await J_().catch(()=>"unsupported")==="granted"&&sc({completionNotificationsEnabled:!0}),await f3(t),await e({to:"/nodes",replace:!0})}})})]})})},lr=["directory","hub"],gC=["directory","hub","recent-sessions"],hs=["directory","workspace"],_C=["bootstrap","hub"],yC=hs,k4=e=>{if(e==null||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},vC=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(!X0(e[i],t[i]))return!1;return!0},X0=(e,t)=>{if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return vC(e,t);if(k4(e)&&k4(t)){const i=Object.keys(e),r=Object.keys(t);if(i.length!==r.length)return!1;for(const o of i)if(!(o in t)||!X0(e[o],t[o]))return!1;return!0}return!1},Zf=(e,t)=>e!==void 0&&X0(e,t)?e:t,rp=(e,t,i)=>{if(!e||e.length===0)return t;const r=new Map(e.map(u=>[i(u),u])),o=t.map(u=>Zf(r.get(i(u)),u));return e.length===o.length&&e.every((u,d)=>u===o[d])?e:o},E4=(e,t,i,r=new Date().toISOString())=>{if(!e)return e;let o=!1;const u=e.agents.map(d=>{if(d.id!==t||!Object.entries(i).some(([g,b])=>d[g]!==b))return d;const y={...d,...i};return o=!0,y});return o?{...e,generated_at:r,agents:u}:e},h3=(e,t)=>{if(!e)return t;const i=rp(e.agents,t.agents,o=>o.id),r=Zf(e.generated_at,t.generated_at);return e.agents===i&&e.generated_at===r?e:{...t,generated_at:r,agents:i}},bC=180,xC=()=>{const e=Ka(),{hubUrl:t}=Zp(),i=_.useRef(null),r=vo(),o=kh(r),u=!!(r&&o);return _.useEffect(()=>{if(!t||u)return;let d=!1,m,y=!1,g=!1,b=!1;const p=()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null)},v=(T,M)=>{const P=new Date().toISOString();e.setQueryData(lr,I=>E4(I,T,{status:M},P)??I),b4(I=>E4(I,T,{status:M},P)??I)},w=async()=>{try{const T=await v4().getHubDirectory();if(d)return;b4(()=>T),e.setQueryData(lr,M=>h3(M,T))}catch{}},N=()=>{p(),i.current=window.setTimeout(()=>{i.current=null,w()},bC)},j=T=>{var M,P;if(T.type==="agent.online"){if(b){b=!1;return}const I=typeof((M=T.payload)==null?void 0:M.agentId)=="string"?T.payload.agentId.trim():"";if(!I)return;v(I,"online"),N();return}if(T.type==="agent.offline"){const I=typeof((P=T.payload)==null?void 0:P.agentId)=="string"?T.payload.agentId.trim():"";if(!I)return;v(I,"offline"),N();return}T.type==="snapshot.changed"&&N()};w();try{m=v4().connectEvents(j,{reconnectWhenHidden:!0,onStatus:T=>{if(T.state==="connected"){b=!0,y&&g&&(g=!1,N()),y=!0;return}y&&(g=!0)}})}catch{}return()=>{d=!0,p(),m==null||m()}},[t,e,u]),null},Pm="",Th=e=>[...e].sort((t,i)=>{const r=Number(i.pinned)-Number(t.pinned);return r!==0?r:+new Date(i.last_event_at)-+new Date(t.last_event_at)}),bo=e=>{var i,r;if(!e)return e;const t=new Map(e.project_stats.map(o=>[o.project_id,o]));return{...e,project_stats:[...e.projects.map(o=>{const u=e.sessions.filter(m=>m.project_id===o.id),d=t.get(o.id);return{project_id:o.id,visible_session_count:u.filter(m=>!m.archived).length,archived_session_count:(d==null?void 0:d.archived_session_count)??0,hidden_history_count:(d==null?void 0:d.hidden_history_count)??0}}),{project_id:Pm,visible_session_count:e.sessions.filter(o=>o.project_id===Pm&&!o.archived).length,archived_session_count:((i=t.get(Pm))==null?void 0:i.archived_session_count)??0,hidden_history_count:((r=t.get(Pm))==null?void 0:r.hidden_history_count)??0}]}},SC=e=>({id:e.id,agent_id:e.agent_id,project_id:e.project_id,provider:e.provider,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}),jC=e=>({id:e.id,agent_id:e.agent_id,name:e.name,display_name:e.display_name,pinned:e.pinned,path:e.path}),t0=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),typeof e.provider=="string"&&(t.provider=e.provider),(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},Lp=(e,t)=>!!(e!=null&&e.sessions.some(i=>i.id===t)),Pp=(e,t,i)=>!e||!Lp(e,t)?e:bo({...e,sessions:Th(e.sessions.map(r=>r.id===t?{...r,...i}:r))}),n0=(e,t,i)=>{if(!e)return e;const r=e.sessions.find(d=>d.id===t);if(!r)return e;const o=new Date(i).getTime(),u=new Date(r.last_event_at).getTime();return!Number.isFinite(o)||Number.isFinite(u)&&o<=u?e:Pp(e,t,{last_event_at:i})},Ff=(e,t,i)=>{if(!e)return e;const{last_event_at:r,...o}=i;let u=Pp(e,t,o);return typeof r=="string"&&r.trim()&&(u=n0(u,t,r)),u},m3=(e,t,i)=>{if(!e||t.length===0)return e;const r=new Set(t);return bo({...e,sessions:Th(e.sessions.map(o=>r.has(o.id)?{...o,...i}:o))})},p3=(e,t)=>{var u;if(!e||t.length===0)return e;const i=new Set(t),r=e.sessions.filter(d=>!i.has(d.id)),o=i.has(e.active_session_id)?((u=r[0])==null?void 0:u.id)??"":e.active_session_id;return bo({...e,active_session_id:o,sessions:Th(r)})},Wu=(e,t,i)=>!e||!e.projects.some(r=>r.id===t)?e:bo({...e,projects:e.projects.map(r=>r.id===t?{...r,...i}:r)}),Up=(e,t)=>{if(!e||t.length===0||e.projects.length<=1)return e;const i=new Map(e.projects.map(u=>[u.id,u])),r=new Set,o=[];for(const u of t){const d=i.get(u);!d||r.has(u)||(r.add(u),o.push(d))}for(const u of e.projects)r.has(u.id)||o.push(u);return o.every((u,d)=>{var m;return u.id===((m=e.projects[d])==null?void 0:m.id)})?e:bo({...e,projects:o})},zp=(e,t)=>{var o;if(!e)return e;const i=e.sessions.filter(u=>u.project_id!==t),r=i.some(u=>u.id===e.active_session_id)?e.active_session_id:((o=i[0])==null?void 0:o.id)??"";return bo({...e,active_session_id:r,projects:e.projects.filter(u=>u.id!==t),sessions:Th(i)})},Bp=(e,t)=>{if(!e)return e;const i=SC(t),r=[i,...e.sessions.filter(o=>o.id!==i.id)];return bo({...e,generated_at:new Date().toISOString(),active_session_id:i.id,sessions:Th(r)})},wC=(e,t)=>{if(!e)return e;const i=jC(t),r=[i,...e.projects.filter(o=>o.id!==i.id)];return bo({...e,generated_at:new Date().toISOString(),projects:r})},NC=(e,t)=>{if(!e)return t;const i=t.agent?Zf(e.agent??void 0,t.agent):e.agent===null?e.agent:null,r=rp(e.projects,t.projects,y=>y.id),o=rp(e.project_stats,t.project_stats,y=>y.project_id),u=rp(e.sessions,t.sessions,y=>y.id),d=Zf(e.generated_at,t.generated_at),m=Zf(e.active_session_id,t.active_session_id);return e.agent===i&&e.projects===r&&e.project_stats===o&&e.sessions===u&&e.generated_at===d&&e.active_session_id===m?e:{...t,generated_at:d,agent:i,projects:r,project_stats:o,sessions:u,active_session_id:m}},kC=async()=>{const e=await cn();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()},EC=async()=>{const e=await cn();if(e.mode==="direct"){const t=await e.client.getPhaseOneSnapshot({fallbackToMock:!1});return{generated_at:t.generated_at,recent_sessions:[...t.sessions].sort((i,r)=>+new Date(r.last_event_at)-+new Date(i.last_event_at)).slice(0,24).map(i=>({id:i.id,title:i.title,run_state:i.run_state,run_state_changed_at:i.run_state_changed_at,latest_assistant_message:i.latest_assistant_message}))}}return e.client.getHubRecentSessions()},CC=async e=>(await cn(e==null?void 0:e.scope)).client.getWorkspaceDirectory({selectedSessionId:(e==null?void 0:e.selectedSessionId)??null}),TC=(e,t)=>h3(e,t),MC=(e,t)=>NC(e,t),s0=e=>{var t,i,r;return[...hs,((t=e==null?void 0:e.scope)==null?void 0:t.agentId)??"",(i=e==null?void 0:e.scope)!=null&&i.agentId?"":((r=e==null?void 0:e.scope)==null?void 0:r.sessionId)??""]},g3=e=>({queryKey:lr,enabled:(e==null?void 0:e.enabled)??!0,queryFn:kC,structuralSharing:TC,staleTime:3e4,refetchInterval:3e5,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1}),RC=()=>({queryKey:gC,queryFn:EC,staleTime:3e4,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1}),_3=e=>({queryKey:s0(e),enabled:(e==null?void 0:e.enabled)??!0,queryFn:()=>CC(e),placeholderData:cS,structuralSharing:MC,staleTime:1e4,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1}),y3=async e=>e.fetchQuery(g3()),AC=async e=>e.fetchQuery(RC()),qf=async(e,t)=>e.fetchQuery(_3(t)),IC=1200,DC=e=>typeof document>"u"?!1:document.visibilityState==="visible"&&Rp()===e,v3=e=>{var t;return((t=e==null?void 0:e.title)==null?void 0:t.trim())||"当前会话"},OC=e=>e.run_state!=="completed"?null:(typeof e.run_state_changed_at=="string"?e.run_state_changed_at.trim():"")||null,LC=(e,t)=>{if(!e||(typeof e.completionReason=="string"?e.completionReason:"completed")!=="completed")return null;const r=typeof e.sessionId=="string"?e.sessionId.trim():"",o=typeof e.completedAt=="string"?e.completedAt.trim():"";if(!r||!o)return null;const u=(t==null?void 0:t.recent_sessions.find(y=>y.id===r))??null,d=typeof e.sessionTitle=="string"&&e.sessionTitle.trim()||v3(u),m=(typeof e.finalReply=="string"?e.finalReply:"")||(u==null?void 0:u.latest_assistant_message)||"";return{sessionId:r,completedAt:o,sessionTitle:d,finalReply:m}},PC=(e,t)=>{const i=new Map(((e==null?void 0:e.recent_sessions)??[]).map(r=>[r.id,r]));return t.recent_sessions.flatMap(r=>{var m;const o=OC(r);if(!o)return[];const u=((m=r.latest_assistant_message)==null?void 0:m.trim())??"";if(!u)return[];const d=i.get(r.id);return(d==null?void 0:d.run_state)==="completed"&&d.run_state_changed_at===o?[]:[{sessionId:r.id,completedAt:o,sessionTitle:v3(r),finalReply:u}]})},UC=(e,t,i)=>{if(!e||!i)return e;let r=!1;const o=e.recent_sessions.map(u=>{if(u.id!==t)return u;const d=i.run_state==="idle"||i.run_state==="running"||i.run_state==="completed"?i.run_state:null,m={...u,...typeof i.title=="string"?{title:i.title}:null,...d?{run_state:d}:null,...i.run_state_changed_at===null||typeof i.run_state_changed_at=="string"?{run_state_changed_at:i.run_state_changed_at}:null,...i.latest_assistant_message===null||typeof i.latest_assistant_message=="string"?{latest_assistant_message:i.latest_assistant_message}:null};return r=r||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 r?{...e,recent_sessions:o}:e},zC=({})=>{const e=Ka(),t=_.useRef(void 0),i=_.useRef(new Set),r=_.useRef(null),o=_.useRef(!1),u=vo(),d=kh(u),m=u&&d?u:null;return _.useEffect(()=>{const y=async I=>{const k=Z_();if(!ba()&&!k.completionNotificationsEnabled||qu()!=="granted")return;if(e0()){$1(I.sessionId,I.completedAt);return}const O=`${I.sessionId}:${I.completedAt}`;if(!i.current.has(O)&&!iC(I.sessionId,I.completedAt)){if(DC(I.sessionId)){$1(I.sessionId,I.completedAt);return}i.current.add(O);try{await l3({sessionId:I.sessionId,completedAt:I.completedAt,title:I.sessionTitle,body:aC(I.finalReply),url:`/session/${I.sessionId}`})&&$1(I.sessionId,I.completedAt)}finally{i.current.delete(O)}}},g=async I=>{for(const k of I)await y(k)};let b=!1,p,v=!1,w=!1,N=!1;const j=async()=>{if(!m)return AC(e);const k=await(await cn({agentId:m})).client.getPhaseOneSnapshot({fallbackToMock:!1});return{generated_at:k.generated_at,recent_sessions:[...k.sessions].sort((O,Q)=>+new Date(Q.last_event_at)-+new Date(O.last_event_at)).slice(0,24).map(O=>({id:O.id,title:O.title,run_state:O.run_state,run_state_changed_at:O.run_state_changed_at,latest_assistant_message:O.latest_assistant_message}))}};j().then(I=>{b||(t.current=I)}).catch(()=>{});const T=async()=>{if(!o.current){o.current=!0;try{const I=await j();if(b)return;const k=t.current;if(t.current=I,!k)return;await g(PC(k,I))}catch{}finally{o.current=!1}}},M=()=>{r.current!==null&&clearTimeout(r.current),r.current=setTimeout(()=>{r.current=null,T()},IC)},P=I=>{var k,O;if(I.type==="turn.completed"){const Q=LC(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():"",J=(O=I.payload)!=null&&O.sessionPatch&&typeof I.payload.sessionPatch=="object"?I.payload.sessionPatch:null;Q&&J&&(t.current=UC(t.current,Q,J));return}I.type==="agent.online"&&N&&(N=!1)};return cn(m?{agentId:m}:void 0).then(I=>{b||(p=I.client.connectEvents(P,{reconnectWhenHidden:!0,onStatus:k=>{if(k.state==="connected"){N=!0,v&&w&&(w=!1,M()),v=!0;return}v&&(w=!0)}}))}),()=>{b=!0,r.current!==null&&(clearTimeout(r.current),r.current=null),p==null||p()}},[e,m]),null};/**
|
|
68
68
|
* @license lucide-react v0.577.0 - ISC
|
|
69
69
|
*
|
|
@@ -190,7 +190,7 @@ Error generating stack: `+c.message+`
|
|
|
190
190
|
* This source code is licensed under the ISC license.
|
|
191
191
|
* See the LICENSE file in the root directory of this source tree.
|
|
192
192
|
*/const vT=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],hh=la("x",vT),J0=e=>e.replace(/[\\/]+$/,""),Hp=e=>J0(e).replace(/\\/g,"/").toLowerCase(),bT=e=>{const t=J0(e.trim());if(!t)return"新线程";const i=t.split(/[\\/]+/).filter(Boolean),r=i[i.length-1];return r?r.endsWith(":")?t:r:t},x3=e=>{if(!e)return null;const t=e.trim();if(!t||t==="/"||/^[A-Za-z]:[\\/]?$/.test(t))return null;const i=J0(t),r=Math.max(i.lastIndexOf("/"),i.lastIndexOf("\\"));if(r<0)return null;const o=i.slice(0,r);return o?/^[A-Za-z]:$/.test(o)?`${o}\\`:o:i.startsWith("/")?"/":null},S3=async e=>(await cn({agentId:e.agentId})).client.listDirectories(e),xT=async e=>(await cn({agentId:e.agentId})).client.createDirectory(e),ST=async e=>{const t=e.bootstrapQueryKey??["bootstrap"],i=e.projects.find(u=>u.agent_id===e.agentId&&Hp(u.path)===Hp(e.path));if(i)return i;const o=await(await cn({agentId:e.agentId})).client.createProject({agentId:e.agentId,name:bT(e.path),path:e.path});return e.queryClient.invalidateQueries({queryKey:t}),o.project},M4=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.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"})}),jT=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m9 6 6 6-6 6"})}),wT=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m5 12 4.5 4.5L19 7"})}),R4=e=>!!(e&&/^[A-Za-z]:[\\/]?$/.test(e.trim())),NT=({agentId:e,initialPath:t=null,title:i="选择开发版代码目录",subtitle:r="按需展开目录,只在你进入某一层时加载它的子目录。",confirmLabel:o="使用这个目录",onClose:u,onSelect:d})=>{const[m,y]=_.useState(t),[g,b]=_.useState(t),[p,v]=_.useState([]),[w,N]=_.useState(!0),[j,T]=_.useState(null);_.useEffect(()=>{y(t),b(t)},[t]),_.useEffect(()=>{let O=!1;return N(!0),T(null),S3({agentId:e,path:m}).then(Q=>{O||v(Q)}).catch(Q=>{O||(T(Q instanceof Error?Q.message:"目录列表加载失败。"),v([]))}).finally(()=>{O||N(!1)}),()=>{O=!0}},[e,m]);const M=x3(m),P=M!==null||R4(m),I=()=>{if(M!==null){y(M),b(M);return}R4(m)&&(y(null),b(null))},k=O=>{y(O),b(O)};return a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true","aria-label":i,children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim","aria-label":"关闭目录选择",onClick:u}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsx("section",{className:"directory-picker settings-directory-picker",children:a.jsxs("div",{className:"directory-picker__panel",children:[a.jsx("header",{className:"directory-picker__header",children:a.jsxs("div",{className:"directory-picker__heading",children:[a.jsx("h2",{children:i}),r?a.jsx("p",{children:r}):null]})}),a.jsxs("div",{className:"directory-picker__field",children:[a.jsx("span",{className:"directory-picker__field-label",children:"当前路径"}),a.jsxs("button",{type:"button",className:`directory-picker__path ${g===m?"is-selected":""}`,onClick:()=>{m&&b(m)},disabled:!m,"aria-pressed":g===m,children:[a.jsx("span",{className:"directory-picker__path-icon",children:a.jsx(M4,{})}),a.jsx("span",{className:"directory-picker__path-value",children:m??"根目录"})]})]}),a.jsxs("div",{className:"directory-picker__field",children:[a.jsx("span",{className:"directory-picker__field-label",children:"目录"}),a.jsx("div",{className:"directory-picker__list",role:"listbox","aria-label":"目录列表",children:w?a.jsx("div",{className:"directory-picker__state",children:"正在读取目录…"}):j?a.jsx("div",{className:"directory-picker__state is-error",children:j}):p.length===0?a.jsx("div",{className:"directory-picker__state",children:"当前目录下没有可用子目录"}):p.map(O=>{const Q=g===O.path;return a.jsxs("div",{className:`directory-picker__row ${Q?"is-selected":""}`,children:[a.jsxs("button",{type:"button",className:"directory-picker__row-main",onClick:()=>{b(O.path)},onDoubleClick:()=>{O.has_children&&k(O.path)},"aria-selected":Q,children:[a.jsx("span",{className:"directory-picker__row-icon",children:a.jsx(M4,{})}),a.jsx("span",{className:"directory-picker__row-name",children:O.name}),Q?a.jsx("span",{className:"directory-picker__row-check",children:a.jsx(wT,{})}):null]}),O.has_children?a.jsx("button",{type:"button",className:"directory-picker__row-enter-button","aria-label":`进入 ${O.name}`,onClick:()=>k(O.path),children:a.jsx("span",{className:"directory-picker__row-enter","aria-hidden":"true",children:a.jsx(jT,{})})}):null]},O.path)})})]}),a.jsx("footer",{className:"directory-picker__footer",children:a.jsxs("div",{className:"directory-picker__footer-actions",children:[P?a.jsx("button",{type:"button",className:"directory-picker__secondary",onClick:I,children:a.jsx("span",{children:"返回上级"})}):null,a.jsx("button",{type:"button",className:"directory-picker__secondary",onClick:u,children:a.jsx("span",{children:"取消"})}),a.jsx("button",{type:"button",className:"directory-picker__primary",disabled:!g,onClick:()=>{g&&d(g)},children:o})]})})]})})})]})},j3="panda-dev-manager-last-apk-download",kT=9e4,Um=e=>{if(!e)return"未记录";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},ET=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`,CT=()=>{if(typeof window>"u")return null;try{const e=window.localStorage.getItem(j3);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}},TT=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(j3,JSON.stringify({artifactId:e,triggeredAt:Date.now()}))}catch{}},ec=e=>e==="succeeded"?"通过":e==="failed"?"异常":"进行中",Cu=e=>e==="succeeded"?"is-success":e==="failed"?"is-danger":"is-muted",A4=e=>e==null?"未测试":e?"通过":"异常",I4=e=>e==null?"is-muted":e?"is-success":"is-danger",MT=e=>e?e==="running"?"运行中":e==="stopped"?"已停止":e==="missing"?"未注册":"未知":"未注册",Wl=e=>e?`http://127.0.0.1:${e}`:"",zm=e=>e?`ws://127.0.0.1:${e}/ws`:"",D4=e=>({...e}),H1=(e,t)=>{if(!e||e.config.updated_at!==t.config.updated_at)return t;const i=new Map(e.services.map(r=>[r.key,r]));return{...t,services:t.services.map(r=>{if(r.probe)return r;const o=i.get(r.key);return o!=null&&o.probe?{...r,probe:o.probe}:r})}},RT=({isActive:e,agentId:t})=>{var je;const i=Ka(),[r,o]=_.useState(null),[u,d]=_.useState(null),[m,y]=_.useState(""),[g,b]=_.useState(!1),[p,v]=_.useState(null),[w,N]=_.useState(!1),j=t?{agentId:t}:void 0,T=["settings-dev-manager",t??"no-agent"],M=cs({queryKey:T,queryFn:async()=>{const z=await cn(j),be=i.getQueryData(T),De=await z.client.getDevManagerSnapshot({includeServiceProbe:!1});return{baseUrl:z.baseUrl,snapshot:H1(be==null?void 0:be.snapshot,De)}},enabled:e&&!!t,refetchOnWindowFocus:!1,staleTime:0,refetchInterval:z=>{const be=z.state.data;return be!=null&&be.snapshot.jobs.some(De=>De.status==="running")?2e3:!1}});_.useEffect(()=>{var be;const z=(be=M.data)==null?void 0:be.snapshot.config;z&&(r&&u===z.updated_at||(o(D4(z)),d(z.updated_at),y(""),b(!1)))},[M.data,r,u]);const P=Gn({mutationFn:async()=>{if(!j)throw new Error("当前没有可用的开发节点,暂时无法保存开发版配置。");if(!r)throw new Error("开发版配置还没有加载完成。");return(await cn(j)).client.saveDevManagerConfig({...r,npm_token:m||null,clear_npm_token:g})},onSuccess:z=>{i.setQueryData(T,be=>({baseUrl:(be==null?void 0:be.baseUrl)??"",snapshot:H1(be==null?void 0:be.snapshot,z)})),o(D4(z.config)),d(z.config.updated_at),y(""),b(!1),v("开发版配置已保存。")},onError:z=>{v(z instanceof Error?z.message:"保存配置失败。")}}),I=Gn({mutationFn:async z=>{if(!j)throw new Error("当前没有可用的开发节点,暂时无法执行开发版管理操作。");return(await cn(j)).client.executeDevManagerAction({action:z})},onSuccess:(z,be)=>{var De,se,pe,ke;i.setQueryData(T,Ze=>({baseUrl:(Ze==null?void 0:Ze.baseUrl)??"",snapshot:H1(Ze==null?void 0:Ze.snapshot,z.snapshot)})),v(be==="restart-release-services"?"后台重启助手已启动,当前连接会短时断开,请等待正式版自动恢复。":be==="install-latest-release"?"后台升级助手已启动,当前连接会短时断开,请等待正式版自动恢复。":be==="install-latest-release-package"?((De=z.job)==null?void 0:De.summary)??"正式版 npm 安装任务已启动。":be==="install-release-services"?((se=z.job)==null?void 0:se.summary)??"正式版服务注册任务已启动。":be==="uninstall-release-services"?((pe=z.job)==null?void 0:pe.summary)??"正式版服务移除任务已启动。":((ke=z.job)==null?void 0:ke.summary)??"任务已启动。")},onError:z=>{v(z instanceof Error?z.message:"执行操作失败。")}}),k=((je=M.data)==null?void 0:je.snapshot)??null,O=(k==null?void 0:k.jobs[0])??null,Q=(k==null?void 0:k.jobs.find(z=>z.status==="running"))??null,J=(k==null?void 0:k.jobs.find(z=>z.kind==="npm-publish"))??null,F=(k==null?void 0:k.jobs.find(z=>z.kind==="release-service-install"))??null,B=(k==null?void 0:k.jobs.find(z=>z.kind==="release-service-uninstall"))??null,G=(k==null?void 0:k.jobs.find(z=>z.kind==="release-install-package"))??null,Z=(k==null?void 0:k.jobs.find(z=>z.kind==="release-restart"))??(k==null?void 0:k.jobs.find(z=>z.kind==="release-install-run"))??null,ae=O,he=_.useMemo(()=>(k==null?void 0:k.services.filter(z=>z.key.startsWith("dev-")))??[],[k]),ne=_.useMemo(()=>(k==null?void 0:k.services.filter(z=>z.key.startsWith("release-")))??[],[k]),Ce=_.useMemo(()=>he.some(z=>z.status==="running")?"部分或全部运行中":he.some(z=>z.status==="degraded")?"存在异常":"未运行",[he]),R=(z,be)=>{o(De=>De&&{...De,[z]:be})},X=(z,be)=>{const De=Number(be)||null;o(se=>{if(!se)return se;const pe={...se,[z]:De};if(z==="dev_hub_port"){const ke=Wl(se.dev_hub_port),Ze=Wl(De);se.dev_agent_hub_url===ke&&(pe.dev_agent_hub_url=Ze),se.dev_web_hub_url===ke&&(pe.dev_web_hub_url=Ze)}if(z==="dev_agent_port"){const ke=Wl(se.dev_agent_port),Ze=Wl(De),zt=zm(se.dev_agent_port),Fe=zm(De);se.dev_agent_direct_base_url===ke&&(pe.dev_agent_direct_base_url=Ze),se.dev_agent_ws_base_url===zt&&(pe.dev_agent_ws_base_url=Fe)}if(z==="release_hub_port"){const ke=Wl(se.release_hub_port),Ze=Wl(De);se.release_agent_hub_url===ke&&(pe.release_agent_hub_url=Ze)}if(z==="release_agent_port"){const ke=Wl(se.release_agent_port),Ze=Wl(De),zt=zm(se.release_agent_port),Fe=zm(De);se.release_agent_direct_base_url===ke&&(pe.release_agent_direct_base_url=Ze),se.release_agent_ws_base_url===zt&&(pe.release_agent_ws_base_url=Fe)}return pe})},le=async()=>{if(!(k!=null&&k.apk_artifact)){v("当前还没有可下载的 APK。");return}if(!j){v("当前没有可用的开发节点,暂时无法下载 APK。");return}const z=CT();if((z==null?void 0:z.artifactId)===k.apk_artifact.artifact_id&&Date.now()-z.triggeredAt<kT){v("同一个 APK 刚刚已经触发过下载。如果安装确认没有弹出,请先查看系统下载列表或等待浏览器处理完成。");return}const be=await cn(j),De=new URL(k.apk_artifact.download_path,be.baseUrl).toString();TT(k.apk_artifact.artifact_id),window.open(De,"_blank","noopener,noreferrer"),v("APK 下载已触发。")},ue=z=>{R("repo_path",z),N(!1),v(`已选中开发版目录:${z}`)},ye=I.isPending;if(M.isLoading&&!k)return a.jsx("p",{className:"settings-block__status",children:"正在加载开发版管理信息…"});if(M.error instanceof Error)return a.jsx("p",{className:"settings-block__status",children:M.error.message});if(!t)return a.jsx("p",{className:"settings-block__status",children:"当前没有可用的代码线程节点,请先在会话里连接到目标 agent,再使用开发版管理。"});if(!k||!r)return a.jsx("p",{className:"settings-block__status",children:"当前还没有可用的开发版管理数据。"});const D=I.variables,oe=k.node_runtime.versions.length>0;return a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"开发版与正式版双环境"}),a.jsx("p",{className:"settings-panel__subtitle",children:"正式版保持默认可用,开发版走独立端口和独立命令。首屏只读取轻量快照,状态测试按端口连通性快测。"})]})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"开发版代码"}),a.jsx("strong",{children:k.config.repo_path??"未配置"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"正式版版本"}),a.jsx("strong",{children:k.current_version??"未检测到"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"开发版状态"}),a.jsx("strong",{children:Ce})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"最新 APK"}),a.jsx("strong",{children:k.apk_artifact?Um(k.apk_artifact.built_at):"尚未生成"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"基础配置"}),a.jsx("p",{className:"settings-panel__subtitle",children:"保存开发版路径、nvm 版本、启动参数,以及正式版升级后自动恢复所需配置。"})]}),a.jsx("div",{className:"settings-actions-row",children:a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void P.mutateAsync(),disabled:P.isPending,children:P.isPending?"保存中…":"保存配置"})})]}),a.jsxs("div",{className:"dev-manager-form-grid",children:[a.jsxs("div",{className:"dev-manager-form-section dev-manager-field--wide",children:[a.jsx("strong",{children:"开发版运行配置"}),a.jsx("p",{children:"这些配置直接用于启动、重启、停止开发版 Hub + Agent + Web。启动参数会追加到对应启动命令末尾。"})]}),a.jsxs("div",{className:"settings-field dev-manager-field--wide",children:[a.jsx("span",{children:"开发版代码路径"}),a.jsx("input",{type:"text",className:`dev-manager-path-display ${r.repo_path?"is-selected":""}`,value:r.repo_path??"",placeholder:t?"点击下方按钮选择目录":"当前没有可用节点,暂时无法浏览目录",readOnly:!0,onClick:()=>{t&&N(!0)}}),a.jsxs("div",{className:"settings-actions-row dev-manager-path-actions",children:[a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>N(!0),disabled:!t,children:"选择目录"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>R("repo_path",null),disabled:!r.repo_path,children:"清空"})]}),a.jsx("small",{className:"dev-manager-field-hint",children:"使用内置目录弹层懒加载浏览;这里只保存最终选中的开发版仓库路径。"})]}),a.jsxs("div",{className:"settings-field",children:[a.jsx("span",{children:"Node 版本"}),a.jsxs("select",{value:r.nvm_version??"",onChange:z=>R("nvm_version",z.target.value||null),children:[a.jsx("option",{value:"",children:"保持系统默认"}),k.node_runtime.versions.map(z=>a.jsx("option",{value:z,children:z},z))]}),a.jsx("small",{className:`dev-manager-field-hint ${oe?"":"is-danger"}`,children:oe?k.node_runtime.manager==="nvm-windows"?"下拉内容包含当前正在运行的 Node 版本,以及这台电脑上 nvm-windows 已安装的版本。":"下拉内容至少包含当前正在运行的 Node 版本;如果这台电脑安装了 nvm-windows,也会一并列出。":k.node_runtime.error||"当前没有检测到可用的 Node 版本。"})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"npm 令牌"}),a.jsx("input",{type:"password",value:m,onChange:z=>{b(!1),y(z.target.value)},placeholder:k.credentials.has_npm_token?`已保存:${k.credentials.npm_token_hint??"******"}`:"输入新的 npm token"})]}),a.jsx("div",{className:"settings-actions-row dev-manager-token-actions",children:a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>{y(""),b(!0)},children:"清空令牌"})}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"开发版 Hub 端口"}),a.jsx("input",{type:"number",value:r.dev_hub_port??"",onChange:z=>X("dev_hub_port",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"开发版 Agent 端口"}),a.jsx("input",{type:"number",value:r.dev_agent_port??"",onChange:z=>X("dev_agent_port",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"开发版 Web 端口"}),a.jsx("input",{type:"number",value:r.dev_web_port??"",onChange:z=>X("dev_web_port",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"开发版 Agent -> Hub URL"}),a.jsx("input",{type:"text",value:r.dev_agent_hub_url,onChange:z=>R("dev_agent_hub_url",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"开发版 Agent 直连 URL"}),a.jsx("input",{type:"text",value:r.dev_agent_direct_base_url,onChange:z=>R("dev_agent_direct_base_url",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"开发版 Agent WS URL"}),a.jsx("input",{type:"text",value:r.dev_agent_ws_base_url,onChange:z=>R("dev_agent_ws_base_url",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"开发版 Agent 名称"}),a.jsx("input",{type:"text",value:r.dev_agent_name,onChange:z=>R("dev_agent_name",z.target.value),placeholder:"留空后默认显示为直连地址 host:port"})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"开发版 Web -> Hub URL"}),a.jsx("input",{type:"text",value:r.dev_web_hub_url,onChange:z=>R("dev_web_hub_url",z.target.value)})]}),a.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[a.jsx("span",{children:"开发版 Hub 追加参数"}),a.jsx("textarea",{value:r.dev_hub_args,onChange:z=>R("dev_hub_args",z.target.value),placeholder:"会直接追加到 corepack pnpm dev:hub 后面"})]}),a.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[a.jsx("span",{children:"开发版 Agent 追加参数"}),a.jsx("textarea",{value:r.dev_agent_args,onChange:z=>R("dev_agent_args",z.target.value),placeholder:"会直接追加到 corepack pnpm dev:agent 后面"})]}),a.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[a.jsx("span",{children:"开发版 Web 追加参数"}),a.jsx("textarea",{value:r.dev_web_args,onChange:z=>R("dev_web_args",z.target.value),placeholder:"会直接追加到开发版 Web 的 vite 命令后面"})]}),a.jsxs("div",{className:"dev-manager-form-section dev-manager-field--wide",children:[a.jsx("strong",{children:"正式版自动恢复配置"}),a.jsx("p",{children:"这些配置不是给当前已运行的正式版实时改端口,而是点击“重启正式版”后,后台助手用它重新拉起正式版 Hub + Agent。"})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"正式版 Hub 端口(自动恢复)"}),a.jsx("input",{type:"number",value:r.release_hub_port??"",onChange:z=>X("release_hub_port",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"正式版 Agent 端口(自动恢复)"}),a.jsx("input",{type:"number",value:r.release_agent_port??"",onChange:z=>X("release_agent_port",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"正式版 Hub 服务名"}),a.jsx("input",{type:"text",value:r.release_hub_service_name,onChange:z=>R("release_hub_service_name",z.target.value),placeholder:"PandaHub"})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"正式版 Agent 服务名"}),a.jsx("input",{type:"text",value:r.release_agent_service_name,onChange:z=>R("release_agent_service_name",z.target.value),placeholder:"PandaAgent"})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"正式版 Agent -> Hub URL(自动恢复)"}),a.jsx("input",{type:"text",value:r.release_agent_hub_url,onChange:z=>R("release_agent_hub_url",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"正式版 Agent 直连 URL(自动恢复)"}),a.jsx("input",{type:"text",value:r.release_agent_direct_base_url,onChange:z=>R("release_agent_direct_base_url",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"正式版 Agent WS URL(自动恢复)"}),a.jsx("input",{type:"text",value:r.release_agent_ws_base_url,onChange:z=>R("release_agent_ws_base_url",z.target.value)})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"正式版 Agent 名称(自动恢复)"}),a.jsx("input",{type:"text",value:r.release_agent_name,onChange:z=>R("release_agent_name",z.target.value),placeholder:"留空后默认显示为直连地址 host:port"})]}),a.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[a.jsx("span",{children:"正式版 Hub 追加参数(自动恢复)"}),a.jsx("textarea",{value:r.release_hub_args,onChange:z=>R("release_hub_args",z.target.value),placeholder:"会直接追加到 panda hub 后面"})]}),a.jsxs("label",{className:"settings-field dev-manager-field--wide",children:[a.jsx("span",{children:"正式版 Agent 追加参数(自动恢复)"}),a.jsx("textarea",{value:r.release_agent_args,onChange:z=>R("release_agent_args",z.target.value),placeholder:"会直接注入 panda agent 命令后面"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"开发版运行控制"}),a.jsx("p",{className:"settings-panel__subtitle",children:"启动、重启、停止开发版 Hub / Agent / Web。进入页面默认不做探测,点击状态测试后仅按端口连通性快速判断。"})]}),a.jsxs("div",{className:"settings-actions-row",children:[a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("start-development"),disabled:ye,children:D==="start-development"&&I.isPending?"启动中…":"启动"}),a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("restart-development"),disabled:ye,children:D==="restart-development"&&I.isPending?"重启中…":"重启"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("stop-development"),disabled:ye,children:D==="stop-development"&&I.isPending?"停止中…":"停止"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("probe-development"),disabled:ye,children:D==="probe-development"&&I.isPending?"测试中…":"状态测试"})]})]}),a.jsx("div",{className:"dev-manager-service-grid",children:he.map(z=>{var be,De;return a.jsxs("article",{className:`settings-diagnostic-list__item dev-manager-service-card is-${z.status}`,children:[a.jsx("strong",{children:z.label}),a.jsxs("span",{children:["上次测试:"," ",a.jsx("strong",{className:I4((be=z.probe)==null?void 0:be.ok),children:A4((De=z.probe)==null?void 0:De.ok)})]}),a.jsxs("span",{children:["端口:",z.configured_port??"未配置"]}),z.detected_pids.length>0?a.jsxs("span",{children:["PID:",z.detected_pids.join(", ")]}):null]},z.key)})})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"npm 发布、安装与正式版恢复"}),a.jsx("p",{className:"settings-panel__subtitle",children:"发布最新 npm 包后,可以单独安装正式版包,再按服务优先重启正式版 Hub + Agent。"})]}),a.jsxs("div",{className:"settings-actions-row",children:[a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("publish-npm"),disabled:I.isPending,children:D==="publish-npm"&&I.isPending?"发布中…":"发布"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("install-latest-release-package"),disabled:I.isPending,children:D==="install-latest-release-package"&&I.isPending?"安装中…":"安装"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("restart-release-services"),disabled:I.isPending,children:D==="restart-release-services"&&I.isPending?"重启中…":"重启"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("install-release-services"),disabled:I.isPending,children:D==="install-release-services"&&I.isPending?"注册中…":"注册/更新服务"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void I.mutateAsync("uninstall-release-services"),disabled:I.isPending,children:D==="uninstall-release-services"&&I.isPending?"移除中…":"移除服务"})]})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前正式版版本"}),a.jsx("span",{children:k.current_version??"未检测到"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近 npm 发布"}),a.jsx("span",{className:J?Cu(J.status):"is-muted",children:J?ec(J.status):"未执行"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近正式版安装"}),a.jsx("span",{className:G?Cu(G.status):"is-muted",children:G?ec(G.status):"未执行"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近正式版恢复"}),a.jsx("span",{className:Z?Cu(Z.status):"is-muted",children:Z?ec(Z.status):"未执行"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近服务注册"}),a.jsx("span",{className:F?Cu(F.status):"is-muted",children:F?ec(F.status):"未执行"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近服务移除"}),a.jsx("span",{className:B?Cu(B.status):"is-muted",children:B?ec(B.status):"未执行"})]}),ne.map(z=>{var be,De;return a.jsxs("article",{className:`settings-diagnostic-list__item dev-manager-service-card is-${z.status}`,children:[a.jsx("strong",{children:z.label}),a.jsxs("span",{children:["当前模式:"," ",a.jsx("strong",{children:z.manager==="windows-service"?"Windows 服务":"普通进程"})]}),a.jsxs("span",{children:["服务名:",z.service_name??"未配置"]}),a.jsxs("span",{children:["服务控制器:"," ",a.jsx("strong",{className:z.service_registered?"":"is-muted",children:MT(z.service_registered?z.service_status:"missing")})]}),a.jsxs("span",{children:["探测结果:"," ",a.jsx("strong",{className:I4((be=z.probe)==null?void 0:be.ok),children:A4((De=z.probe)==null?void 0:De.ok)})]}),a.jsxs("span",{children:["端口:",z.configured_port??"未配置"]})]},z.key)})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"APK 编译与下载"}),a.jsx("p",{className:"settings-panel__subtitle",children:"直接用开发版源码产出 release APK,并提供下载入口。"})]}),a.jsxs("div",{className:"settings-actions-row",children:[a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void I.mutateAsync("build-apk"),disabled:I.isPending,children:D==="build-apk"&&I.isPending?"编译中…":"编译 APK"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>void le(),disabled:!k.apk_artifact,children:"下载 APK"})]})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近构建时间"}),a.jsx("span",{children:k.apk_artifact?Um(k.apk_artifact.built_at):"尚未构建"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"版本"}),a.jsx("span",{children:k.apk_artifact?`${k.apk_artifact.version_name??"未知"}${k.apk_artifact.version_code?` (${k.apk_artifact.version_code})`:""}`:"尚未构建"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"文件大小"}),a.jsx("span",{children:k.apk_artifact?ET(k.apk_artifact.size_bytes):"尚未构建"})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"任务日志"}),a.jsx("p",{className:"settings-panel__subtitle",children:"这里只显示最近一次任务的日志;更早的历史记录仍会保留在后台状态文件中。"})]})}),p?a.jsx("p",{className:"settings-block__status",children:p}):null,Q?a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前运行中"}),a.jsxs("span",{children:[Q.title," · ",ec(Q.status)]})]}):null,ae?a.jsx("div",{className:"settings-log-list",children:a.jsxs("article",{className:"settings-log-item dev-manager-job",children:[a.jsxs("div",{className:"settings-log-item__meta",children:[a.jsx("strong",{children:ae.title}),a.jsx("span",{children:Um(ae.started_at??ae.created_at)})]}),a.jsxs("div",{className:`settings-log-item__kind ${Cu(ae.status)}`,children:[ec(ae.status),ae.disconnect_expected?" · 会中断连接":""]}),ae.summary?a.jsx("div",{className:"dev-manager-job__summary",children:ae.summary}):null,ae.logs.length>0?a.jsx("pre",{className:"settings-log-item__detail",children:ae.logs.slice(-16).map(z=>`[${Um(z.timestamp)}] ${z.message}`).join(`
|
|
193
|
-
`)}):null]},ae.id)}):a.jsx("p",{className:"settings-block__status",children:"还没有开发版管理任务记录。"})]}),w&&t?a.jsx(NT,{agentId:t,initialPath:r.repo_path,onClose:()=>N(!1),onSelect:ue}):null]})},w3=Ac("App",{web:()=>cl(()=>import("./web-Cg2SPsir.js"),[]).then(e=>new e.AppWeb)}),AT=Ac("Browser",{web:()=>cl(()=>import("./web-CcQ2B2v6.js"),[]).then(e=>new e.BrowserWeb)}),IT=e=>{const t=(e==null?void 0:e.trim())??"";return t?t.replace(/\/+$/,""):""},DT=async()=>{if(!Yp())return{platform:rd(),version:null,build:null,appId:null};const e=await w3.getInfo();return{platform:rd(),version:e.version??null,build:e.build??null,appId:e.id??null}},N3=e=>{const t=IT(e);return t?new URL("/downloads/android/latest.json",t).toString():""},OT=async e=>{const t=N3(e);if(!t)throw new Error("当前还没有配置可用的 Hub 地址。");const i=await fetch(t,{cache:"no-store"});if(!i.ok)throw new Error(`更新清单请求失败(HTTP ${i.status})。`);const r=await i.json(),o=Array.isArray(r.release_notes)?r.release_notes.filter(d=>typeof d=="string"&&d.trim().length>0):[];if(r.platform!=="android"||typeof r.version_name!="string"||typeof r.version_code!="number"||typeof r.published_at!="string"||typeof r.apk_url!="string")throw new Error("Hub 返回的 Android 更新清单格式无效。");const u=new URL(r.apk_url,t).toString();return{platform:"android",version_name:r.version_name,version_code:r.version_code,published_at:r.published_at,apk_url:u,release_notes:o}},LT=e=>{const t=Number(e);return Number.isFinite(t)?t:null},PT=(e,t)=>{if(!e||!t)return!1;const i=LT(e.build);return typeof i=="number"?t.version_code>i:t.version_name!==e.version},UT=async e=>{if(!e.trim())throw new Error("当前没有可用的 APK 下载地址。");await AT.open({url:e})},k3="panda:session-model",E3="panda:command-execution-model",C3="panda:title-generation-model",ey="panda:session-model-options",a0="panda:session-model-options-updated",T3="panda:session-reasoning",M3="panda:session-fast-mode",R3="panda:session-plan-mode",A3="panda:session-yolo-mode",yd=[{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"}],mh=[{label:"低",value:"low"},{label:"中",value:"medium"},{label:"高",value:"high"},{label:"极高",value:"xhigh"}];var u2;const I3=((u2=yd[0])==null?void 0:u2.value)??"gpt-5.4",O4="gpt-5.4-mini",L4="gpt-5.4-mini",zT=mh[2].value,el=e=>typeof e=="string"?e.trim():"",BT=(e,t)=>{if(!e||typeof e!="object")return null;const i=e,r=el(i.value),o=el(i.label)||r,u=el(i.id)||r||`custom-model-${t+1}`;if(!o||!r)return null;const d=el(i.description);return{id:u,label:o,value:r,description:d||null}},$T=e=>{const t=new Set,i=new Set;return e.flatMap(r=>{const o=r.value.toLowerCase();if(i.has(o))return[];i.add(o);let u=r.id,d=2;for(;t.has(u);)u=`${r.id}-${d}`,d+=1;return t.add(u),[{...r,id:u}]})},D3=e=>{if(!Array.isArray(e))return yd;const t=$T(e.flatMap((i,r)=>{const o=BT(i,r);return o?[o]:[]}));return t.length>0?t:yd},Sd=e=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}},HT=()=>{typeof window>"u"||window.dispatchEvent(new Event(a0))},jd=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}},ty=(e,t=!1)=>{const i=Sd(e);return i==="true"?!0:i==="false"?!1:t},ny=(e,t)=>{jd(e,t?"true":"false")},wd=(e,t)=>{const i=t==null?void 0:t.trim();return i?`${e}:${i}`:null},Of=e=>{const t=el(e==null?void 0:e.value)||"",i=el(e==null?void 0:e.label)||t;return{id:el(e==null?void 0:e.id)||el(e==null?void 0:e.value)||`custom-model-${Date.now()}`,label:i,value:t,description:el(e==null?void 0:e.description)||null}},FT=()=>Mh().map(({id:e,...t})=>t),Mh=()=>{const e=Sd(ey);if(!e)return yd;try{return D3(JSON.parse(e))}catch{return yd}},qT=e=>{const t=D3(e);jd(ey,JSON.stringify(t)),HT()},WT=e=>mh.some(t=>t.value===e),sy=()=>{var i;const e=Sd(k3),t=Mh();return t.some(r=>r.value===e)?e:((i=t[0])==null?void 0:i.value)??I3},lp=()=>{const e=Sd(E3),t=Mh();if(t.some(r=>r.value===e))return e;const i=t.find(r=>r.value===O4)??t[0];return(i==null?void 0:i.value)??O4},O3=()=>{const e=Sd(C3),t=Mh();if(t.some(r=>r.value===e))return e;const i=t.find(r=>r.value===L4)??t[0];return(i==null?void 0:i.value)??L4},L3=()=>{const e=Sd(T3);return WT(e)?e:zT},Jf=e=>{jd(k3,e)},F1=e=>{jd(E3,e)},q1=e=>{jd(C3,e)},P3=e=>{jd(T3,e)},P4=e=>{const t=wd(M3,e);return t?ty(t):!1},U4=e=>{const t=wd(R3,e);return t?ty(t):!1},z4=e=>{const t=wd(A3,e);return t?ty(t):!1},U3=(e,t)=>{const i=wd(M3,e);i&&ny(i,t)},z3=(e,t)=>{const i=wd(R3,e);i&&ny(i,t)},B3=(e,t)=>{const i=wd(A3,e);i&&ny(i,t)},KT=(e,t)=>{U3(e,t.isFastModeEnabled),z3(e,t.isPlanModeEnabled),B3(e,t.isYoloModeEnabled)},Fp=(e,t=FT())=>{var i,r;return((i=t.find(o=>o.value===e))==null?void 0:i.label)??(typeof e=="string"&&e.trim()?e.trim():((r=t[0])==null?void 0:r.label)??I3)},QT=e=>{var t;return((t=mh.find(i=>i.value===e))==null?void 0:t.label)??mh[2].label},GT=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"}}]'),YT={themes:GT},$3="panda:theme-settings",VT=13,XT=12,H3="codex",ay="codex",ZT='-apple-system, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI", sans-serif',JT='ui-monospace, "SFMono-Regular", "SF Mono", "Cascadia Mono", "Cascadia Code", Consolas, monospace',eM=/\b(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|emoji|math|fangsong|ui-serif|ui-sans-serif|ui-monospace|ui-rounded)\b/i,B4=(e,t)=>{const i=e==null?void 0:e.trim();return i?eM.test(i)?i:`${i}, ${t}`:t},tM={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"},Nd=(e,t,i)=>Math.min(i,Math.max(t,e)),ac=(e,t)=>{const r=e.trim().match(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i);if(!r)return t;const[,o]=r;return`#${(o.length===3?o.split("").map(d=>`${d}${d}`).join(""):o).toUpperCase()}`},Qr=e=>{const t=ac(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)}},nM=(e,t,i)=>`#${[e,t,i].map(r=>Nd(Math.round(r),0,255).toString(16).padStart(2,"0")).join("").toUpperCase()}`,Ct=(e,t,i)=>{const r=Qr(e),o=Qr(t),u=Nd(i,0,1);return nM(r.r+(o.r-r.r)*u,r.g+(o.g-r.g)*u,r.b+(o.b-r.b)*u)},sM=e=>{const{r:t,g:i,b:r}=Qr(e),o=u=>{const d=u/255;return d<=.03928?d/12.92:((d+.055)/1.055)**2.4};return o(t)*.2126+o(i)*.7152+o(r)*.0722},aM=e=>sM(e)>.5?"#0D1117":"#FFFFFF",qr=(e,t)=>{const i=Math.round(Nd(t,0,1)*100);return i>=100?e:`color-mix(in srgb, ${e} ${i}%, transparent)`},F3=YT.themes,q3=(e,t)=>{var r,o;const i=t==="light"?e.light:e.dark;return i?{id:e.id,label:tM[e.id]??e.id,codeThemeId:i.codeThemeId,variant:t,accent:ac(i.theme.accent,"#0169CC"),background:ac(i.theme.surface,"#FFFFFF"),foreground:ac(i.theme.ink,"#0D0D0D"),contrast:Nd(Number(i.theme.contrast),0,100),opaqueWindows:!!i.theme.opaqueWindows,semanticColors:{diffAdded:ac(i.theme.semanticColors.diffAdded,"#00A240"),diffRemoved:ac(i.theme.semanticColors.diffRemoved,"#E02E2A"),skill:ac(i.theme.semanticColors.skill,"#751ED9")},fonts:{ui:((r=i.theme.fonts.ui)==null?void 0:r.trim())||null,code:((o=i.theme.fonts.code)==null?void 0:o.trim())||null}}:null},i0=F3.map(e=>q3(e,"light")).filter(e=>!!e),ph=F3.map(e=>q3(e,"dark")).filter(e=>!!e);ph.find(e=>e.id===ay)??ph[0];const wc={mode:"system",lightThemeId:H3,darkThemeId:ay,uiFontSize:VT,codeFontSize:XT},W3=e=>Nd(Number(e),11,18),K3=e=>Nd(Number(e),10,18),iy=()=>typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",Jp=e=>i0.find(t=>t.id===e)??i0[0],eg=e=>ph.find(t=>t.id===e)??ph[0],$4=(e,t=wc,i="light")=>i==="dark"?{...t,darkThemeId:eg(e).id}:{...t,lightThemeId:Jp(e).id},Zl=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:wc.mode,lightThemeId:Jp((e==null?void 0:e.lightThemeId)??H3).id,darkThemeId:eg((e==null?void 0:e.darkThemeId)??ay).id,uiFontSize:W3((e==null?void 0:e.uiFontSize)??wc.uiFontSize),codeFontSize:K3((e==null?void 0:e.codeFontSize)??wc.codeFontSize)}),Q3=()=>{if(typeof window>"u")return wc;try{const e=window.localStorage.getItem($3);return e?Zl(JSON.parse(e)):wc}catch{return wc}},Lf=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem($3,JSON.stringify(Zl(e)))}catch{}},iM=(e,t)=>e==="system"?t:e,Kr=(e,t=iy())=>{const i=Zl(e),r=iM(i.mode,t),o=Jp(i.lightThemeId),u=eg(i.darkThemeId),d=r==="dark"?u:o;return{...i,appearance:r,lightTheme:o,darkTheme:u,activeTheme:d,uiFontFamily:B4(d.fonts.ui,ZT),codeFontFamily:B4(d.fonts.code,JT)}},rM=e=>{if(typeof window>"u")return()=>{};const t=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>{e(t.matches?"dark":"light")};return i(),t.addEventListener("change",i),()=>{t.removeEventListener("change",i)}},lM=(e,t)=>{const i=Kr(e,t),r=i.activeTheme,o=t==="dark",u=(r.contrast-(o?60:45))/100,d=r.semanticColors.diffAdded,m=r.semanticColors.diffRemoved,y=r.semanticColors.skill,g=Qr(d),b=Qr(m),p=Qr(y),v=Qr(r.accent),w=Qr(r.background),N=Qr(r.foreground),j=r.background,T=o?Ct(r.background,"#FFFFFF",.05+u*.08):Ct(r.background,"#FFFFFF",.42+u*.16),M=o?Ct(r.background,"#FFFFFF",.07+u*.08):Ct(r.background,"#FFFFFF",.78+u*.1),P=o?Ct(r.background,"#FFFFFF",.1+u*.08):Ct(r.background,"#FFFFFF",.56+u*.14),I=o?Ct(r.background,"#FFFFFF",.14+u*.08):Ct(r.background,r.foreground,.1+u*.12),k=o?Ct(r.background,"#000000",.08-u*.06):Ct(r.background,r.foreground,.03+u*.08),O=o?Ct(r.background,"#FFFFFF",.08+u*.06):Ct(r.background,r.foreground,.06+u*.08),Q=o?Ct(r.background,"#FFFFFF",.14+u*.08):Ct(r.background,r.foreground,.14+u*.1),J=o?Ct(r.background,"#FFFFFF",.22+u*.08):Ct(r.background,r.foreground,.22+u*.1),F=o?Ct(r.background,"#FFFFFF",.08+u*.04):Ct(r.background,r.foreground,.1+u*.08),B=r.foreground,G=o?Ct(r.foreground,r.background,.28-u*.1):Ct(r.foreground,r.background,.5-u*.14),Z=o?Ct(r.foreground,r.background,.46-u*.1):Ct(r.foreground,r.background,.64-u*.14),ae=Ct(r.foreground,r.background,o?.58:.74),he=r.accent,ne=o?Ct(r.accent,"#FFFFFF",.18):Ct(r.accent,"#FFFFFF",.24),Ce=o?Ct(r.accent,r.background,.78):Ct(r.accent,r.background,.88),R=o?Ct(r.accent,r.background,.84):Ct(r.accent,r.background,.92),X=aM(he),le=o?Ct(r.background,"#FFFFFF",.1):Ct(r.background,r.foreground,.08),ue=o?Ct(r.background,"#000000",.06):Ct(r.background,r.foreground,.035),ye=o?Ct(r.background,"#FFFFFF",.05):Ct(r.background,r.foreground,.06),D=o?Ct(r.background,"#FFFFFF",.03):Ct(r.background,r.foreground,.085),oe=o?Ct(r.background,"#FFFFFF",.065):Ct(r.background,r.foreground,.05),je=Ct(r.foreground,r.background,o?.42:.68),z=o?Ct(r.background,"#FFFFFF",.08):Ct(r.foreground,r.background,.18),be=o?Ct(r.background,"#FFFFFF",.08):Ct(r.background,r.foreground,.06),De=o?Ct(r.background,"#FFFFFF",.12):Ct(r.background,r.foreground,.1),se=o?Ct(r.background,"#FFFFFF",.14+u*.05):Ct(r.background,r.foreground,.12+u*.08),pe=r.opaqueWindows?1:o?.92:.95,ke=r.opaqueWindows?1:o?.94:.965,Ze=r.opaqueWindows?1:.94;return{"--theme-id":r.id,"--theme-code-theme-id":r.codeThemeId,"--theme-window-opaque":r.opaqueWindows?"1":"0","--theme-accent":he,"--theme-accent-rgb":`${v.r} ${v.g} ${v.b}`,"--theme-background":r.background,"--theme-background-rgb":`${w.r} ${w.g} ${w.b}`,"--theme-foreground":r.foreground,"--theme-foreground-rgb":`${N.r} ${N.g} ${N.b}`,"--theme-shadow-rgb":o?"0 0 0":"39 28 17","--theme-ui-font":i.uiFontFamily,"--theme-code-font":i.codeFontFamily,"--theme-ui-font-size":`${i.uiFontSize}px`,"--theme-code-font-size":`${i.codeFontSize}px`,"--color-surface-base":j,"--color-surface-elevated":T,"--color-surface-panel":M,"--color-surface-raised":P,"--color-surface-panel-strong":I,"--color-surface-sidebar":qr(k,ke),"--color-surface-sidebar-elevated":qr(O,ke),"--color-surface-border":Q,"--color-surface-border-strong":J,"--color-surface-border-soft":F,"--color-surface-overlay":qr(I,pe),"--color-surface-floating":qr(M,pe),"--color-surface-tooltip":qr(z,Ze),"--color-surface-code":ue,"--color-surface-code-muted":ye,"--color-surface-code-gutter":D,"--color-surface-code-meta":oe,"--color-surface-inline-code":le,"--color-surface-hover":be,"--color-surface-pressed":De,"--color-surface-danger-soft":qr(m,o?.14:.08),"--color-surface-success-soft":qr(d,o?.14:.08),"--color-text-primary":B,"--color-text-secondary":G,"--color-text-muted":Z,"--color-text-tertiary":ae,"--color-text-on-accent":X,"--color-text-link":he,"--color-text-link-hover":ne,"--color-text-danger":m,"--color-text-success":d,"--color-accent-primary":he,"--color-accent-primary-soft":Ce,"--color-accent-secondary":ne,"--color-accent-secondary-soft":R,"--color-accent-contrast":X,"--color-accent-primary-rgb":`${v.r} ${v.g} ${v.b}`,"--color-success":d,"--color-warning":Ct(r.accent,d,.35),"--color-danger":m,"--color-status-online":he,"--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":he,"--color-code-string":Ct(d,r.foreground,o?.26:.18),"--color-code-number":Ct(y,he,.36),"--color-code-comment":Ct(r.foreground,r.background,o?.52:.72),"--color-code-meta-text":je,"--color-code-add":d,"--color-code-add-rgb":`${g.r} ${g.g} ${g.b}`,"--color-code-add-bg":qr(d,o?.16:.11),"--color-code-remove":m,"--color-code-remove-rgb":`${b.r} ${b.g} ${b.b}`,"--color-code-remove-bg":qr(m,o?.18:.11),"--color-divider":se,"--color-overlay-scrim":r.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":i.uiFontFamily,"--font-sans":i.uiFontFamily,"--font-mono":i.codeFontFamily,"--font-size-ui-base":`${i.uiFontSize}px`,"--font-size-code-base":`${i.codeFontSize}px`}},G3=(e,t=iy())=>{if(typeof document>"u")return;const i=Kr(e,t),r=lM(i,i.appearance),o=document.documentElement;o.dataset.theme=i.appearance,o.dataset.uiTheme=i.appearance,o.dataset.themeId=i.activeTheme.id,o.dataset.codeThemeId=i.activeTheme.codeThemeId,o.dataset.windowStyle=i.activeTheme.opaqueWindows?"opaque":"soft",o.style.colorScheme=i.appearance;for(const[u,d]of Object.entries(r))o.style.setProperty(u,d)},oM=async()=>{if(await Op().catch(()=>{}),"serviceWorker"in navigator){const t=await navigator.serviceWorker.getRegistrations();await Promise.all(t.map(i=>i.unregister()))}if("caches"in window){const t=await window.caches.keys();await Promise.all(t.map(i=>window.caches.delete(i)))}const e=window.indexedDB;if(typeof e.databases=="function"){const t=await e.databases();await Promise.all(t.map(i=>i.name).filter(i=>!!i).map(i=>new Promise(r=>{const o=e.deleteDatabase(i);o.onsuccess=()=>r(),o.onerror=()=>r(),o.onblocked=()=>r()})))}window.localStorage.clear(),window.sessionStorage.clear()},ry="panda:pwa-install-log",cM=48,Ys=e=>((e==null?void 0:e.trim())??"")||null,Y3=()=>{if(typeof window>"u")return[];try{const e=window.localStorage.getItem(ry);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.map(i=>{if(!i||typeof i!="object")return null;const r=i;return typeof r.id!="string"||typeof r.timestamp!="string"||typeof r.kind!="string"||typeof r.message!="string"?null:{id:r.id,timestamp:r.timestamp,kind:r.kind,message:r.message,detail:Ys(r.detail)}}).filter(i=>!!i).sort((i,r)=>+new Date(r.timestamp)-+new Date(i.timestamp)):[]}catch{return[]}},uM=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(ry,JSON.stringify(e.slice(0,cM)))}catch{}},dM=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(ry)}catch{}},Kl=e=>{const t=Y3(),i={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),kind:e.kind,message:e.message.trim(),detail:Ys(e.detail)};return uM([i,...t]),i},H4=(e,t)=>{var i;return((i=e.find(r=>r.kind===t))==null?void 0:i.timestamp)??null},fM=async e=>{const t=await fetch(e,{cache:"no-store"});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()},hM=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"}}},mM=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=Ys(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 i=await fM(t),r=Array.isArray(i.icons)?i.icons:[],o=await Promise.all(r.slice(0,8).map(async u=>{const d=u,m=Ys(typeof d.src=="string"?d.src:null);if(!m)return{src:"(missing)",purpose:Ys(typeof d.purpose=="string"?d.purpose:null),sizes:Ys(typeof d.sizes=="string"?d.sizes:null),type:Ys(typeof d.type=="string"?d.type:null),ok:!1,status:null,error:"Icon src is missing."};const y=new URL(m,t).toString(),g=await hM(y);return{src:y,purpose:Ys(typeof d.purpose=="string"?d.purpose:null),sizes:Ys(typeof d.sizes=="string"?d.sizes:null),type:Ys(typeof d.type=="string"?d.type:null),ok:g.ok,status:g.status,error:g.error}}));return{href:t,present:!0,ok:!0,error:null,id:Ys(typeof i.id=="string"?i.id:null),name:Ys(typeof i.name=="string"?i.name:null),shortName:Ys(typeof i.short_name=="string"?i.short_name:null),startUrl:Ys(typeof i.start_url=="string"?i.start_url:null),scope:Ys(typeof i.scope=="string"?i.scope:null),display:Ys(typeof i.display=="string"?i.display:null),displayOverride:Array.isArray(i.display_override)?i.display_override.filter(u=>typeof u=="string"):[],themeColor:Ys(typeof i.theme_color=="string"?i.theme_color:null),backgroundColor:Ys(typeof i.background_color=="string"?i.background_color:null),icons:o}}catch(i){return{href:t,present:!0,ok:!1,error:i instanceof Error?i.message:"Manifest fetch failed.",id:null,name:null,shortName:null,startUrl:null,scope:null,display:null,displayOverride:[],themeColor:null,backgroundColor:null,icons:[]}}},pM=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 i,r,o;return{scope:t.scope,activeScriptUrl:((i=t.active)==null?void 0:i.scriptURL)??null,waitingScriptUrl:((r=t.waiting)==null?void 0:r.scriptURL)??null,installingScriptUrl:((o=t.installing)==null?void 0:o.scriptURL)??null}})}}catch{return{supported:!0,controller:!!navigator.serviceWorker.controller,registrations:[]}}},gM=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:"浏览器当前没有给出可用的安装事件,页面更像普通标签页或只能走“添加到主屏幕”的快捷方式链路。"}},_M=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 r=e.manifest.icons.some(d=>d.ok&&(d.sizes??"").includes("192x192")),o=e.manifest.icons.some(d=>d.ok&&(d.sizes??"").includes("512x512"));(!r||!o)&&t.push("manifest 图标里缺少可访问的 192x192 或 512x512 图标,Android 安装链路可能会退化。");const u=e.manifest.icons.filter(d=>!d.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(r=>{var o;return r.kind==="install-choice"&&((o=r.detail)==null?void 0:o.toLowerCase().includes("accepted"))})&&!e.appInstalledSeen&&t.push("站点记录到用户接受过安装请求,但没有后续 appinstalled 事件,更像是浏览器回退成快捷方式,或系统级安装没有完成。"),e.launchedStandalone&&!e.appInstalledSeen&&t.push("当前虽然是独立窗口形态,但没有观测到 appinstalled,不能把它视为已经完成系统级安装。"),t},yM=async e=>{const t=Y3(),[i,r]=await Promise.all([mM(),pM()]),o=navigator,u=typeof window<"u"&&window.matchMedia("(display-mode: standalone)").matches,d=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,b=u||d,p=[];window.isSecureContext&&p.push("当前是安全上下文。"),i.ok&&p.push("manifest 可读取。"),r.registrations.length>0&&p.push(`检测到 ${r.registrations.length} 个 Service Worker 注册。`),g&&p.push("浏览器已提供可调用的安装事件。"),y&&p.push("站点本地记录到过 appinstalled 事件。");const v=["从桌面图标打开后,确认没有浏览器地址栏或标签栏。","到 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:d},promptState:{installPromptAvailable:g,beforeInstallPromptSeen:m,appInstalledSeen:y,lastBeforeInstallPromptAt:H4(t,"beforeinstallprompt"),lastAppInstalledAt:H4(t,"appinstalled")},manifest:i,serviceWorker:r,assessment:gM({standaloneDisplayMode:u,navigatorStandalone:d,installPromptAvailable:g,beforeInstallPromptSeen:m,appInstalledSeen:y}),failureReasons:_M({secureContext:typeof window<"u"?window.isSecureContext:!1,manifest:i,serviceWorker:r,installPromptAvailable:g,appInstalledSeen:y,launchedStandalone:b,logs:t}),successSignals:p,confirmationChecklist:v,logs:t}},vM=e=>{if(typeof window>"u")return()=>{};const t=r=>{(r.key===null||r.key===ey)&&e()},i=()=>{e()};return window.addEventListener("storage",t),window.addEventListener(a0,i),()=>{window.removeEventListener("storage",t),window.removeEventListener(a0,i)}},bM=()=>Mh(),xM=()=>yd,ly=()=>_.useSyncExternalStore(vM,bM,xM);function oy(e){return cs(g3(e))}const V3=e=>{var t,i,r;return["codex-commands",((t=e==null?void 0:e.agentId)==null?void 0:t.trim())??"",((i=e==null?void 0:e.projectId)==null?void 0:i.trim())??"",((r=e==null?void 0:e.sessionId)==null?void 0:r.trim())??""]},X3=e=>{const t=(e==null?void 0:e.enabled)??!0;return cs({queryKey:V3(e==null?void 0:e.scope),enabled:t,queryFn:async()=>(await cn(e==null?void 0:e.scope)).client.getCodexCommands(),staleTime:0,gcTime:30*6e4,refetchOnWindowFocus:!1,retry:1})},F4=e=>{let t;const i=new Set,r=(g,b)=>{const p=typeof g=="function"?g(t):g;if(!Object.is(p,t)){const v=t;t=b??(typeof p!="object"||p===null)?p:Object.assign({},t,p),i.forEach(w=>w(t,v))}},o=()=>t,m={setState:r,getState:o,getInitialState:()=>y,subscribe:g=>(i.add(g),()=>i.delete(g))},y=t=e(r,o,m);return m},SM=(e=>e?F4(e):F4),jM=e=>e;function wM(e,t=jM){const i=tl.useSyncExternalStore(e.subscribe,tl.useCallback(()=>t(e.getState()),[e,t]),tl.useCallback(()=>t(e.getInitialState()),[e,t]));return tl.useDebugValue(i),i}const q4=e=>{const t=SM(e),i=r=>wM(t,r);return Object.assign(i,t),i},NM=(e=>e?q4(e):q4),W4=Q3(),K4=iy(),qa=NM(e=>({panelTab:"git",composerText:"",activeSessionId:null,bottomNavVisible:!0,isSettingsOverlayOpen:!1,themeSettings:W4,systemAppearance:K4,resolvedTheme:Kr(W4,K4),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(i=>{const r=Zl({...i.themeSettings,mode:t});return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setLightThemeId:t=>e(i=>{const r=Zl($4(Jp(t).id,i.themeSettings,"light"));return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setDarkThemeId:t=>e(i=>{const r=Zl({...$4(eg(t).id,i.themeSettings,"dark")});return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setUiFontSize:t=>e(i=>{const r=Zl({...i.themeSettings,uiFontSize:t});return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setCodeFontSize:t=>e(i=>{const r=Zl({...i.themeSettings,codeFontSize:t});return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setSystemAppearance:t=>e(i=>({systemAppearance:t,resolvedTheme:Kr(i.themeSettings,t)}))})),Q4=980,$i={id:"gpt-image-2",vendor:"openai",label:"gpt-image-2",enabled:!0},Z3=[{value:"openai",label:"OpenAI"},{value:"xai",label:"xAI"}],kM=["settings-image-provider"],Bm=[{id:"theme",title:"主题",description:"调整界面的颜色风格。",icon:"theme"},{id:"models",title:"模型维护",description:"维护可选模型、默认模型和展示顺序。",icon:"models"},{id:"image",title:"绘图",description:"维护生图渠道、API Key 和可选模型。",icon:"image"},{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"}],EM=[{id:"appearance",label:"外观与模型",sections:["theme","models","image","cache"]},{id:"notifications",label:"提醒与安装",sections:["notifications","installation"]},{id:"connection",label:"连接与设备",sections:["connection","dev-manager"]}],CM=[{value:"light",label:"浅色",icon:"sun"},{value:"dark",label:"深色",icon:"moon"},{value:"system",label:"系统",icon:"system"}],W1=e=>({id:(e==null?void 0:e.id)??(typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`image-channel-${Date.now()}`),remark:(e==null?void 0:e.remark)??"Image Provider",base_url:(e==null?void 0:e.base_url)??"https://api.openai.com/v1",models:e!=null&&e.models.length?e.models:[$i],api_key:""}),K1=e=>({id:(e==null?void 0:e.id)??$i.id,label:(e==null?void 0:e.label)??(e==null?void 0:e.id)??$i.label,vendor:(e==null?void 0:e.vendor)??$i.vendor,enabled:(e==null?void 0:e.enabled)??!0}),TM=(e,t,i)=>({active_channel_id:e,channels:t.map(r=>({id:r.id,remark:r.remark.trim()||"Image Provider",base_url:r.base_url.trim(),models:i.length?i:[$i],api_key:r.api_key.trim()||null,api_key_mode:r.api_key.trim()?"set":"keep"}))}),MM=e=>{var t;return((t=Z3.find(i=>i.value===e))==null?void 0:t.label)??e},RM=(e,t,i,r)=>["const pandaTheme = {",` codeThemeId: "${e}",`,` accent: "${t.toLowerCase()}",`,` contrast: ${i},`,` opaqueWindows: ${r},`,"}"],AM=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m15 6-6 6 6 6"})}),IM=({open:e})=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:e?"m6 9 6 6 6-6":"m9 6 6 6-6 6"})}),DM=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01"})}),Q1=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M12 5v14M5 12h14"})}),OM=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"m13.5 6.5 4 4"})]}),LM=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M4.5 7h15"}),a.jsx("path",{d:"M9.5 4.5h5"}),a.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"}),a.jsx("path",{d:"M10 10.5v5.2"}),a.jsx("path",{d:"M14 10.5v5.2"})]}),PM=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6 18 18"}),a.jsx("path",{d:"M18 6 6 18"})]}),UM=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m12 6-5 5M12 6l5 5M12 6v12"})}),zM=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m12 18-5-5M12 18l5-5M12 18V6"})}),G4=({icon:e})=>e==="cache"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"M5 8.5v7c0 1.93 3.13 3.5 7 3.5s7-1.57 7-3.5v-7"}),a.jsx("path",{d:"M5 12c0 1.93 3.13 3.5 7 3.5s7-1.57 7-3.5"})]}):e==="models"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M5 7.5h14M5 12h14M5 16.5h14"}),a.jsx("path",{d:"M8 5.5h.01M8 10h.01M8 14.5h.01"})]}):e==="image"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2.4"}),a.jsx("path",{d:"m7.5 15 3.2-3.2 2.3 2.3 1.5-1.5 2 2.4"}),a.jsx("circle",{cx:"15.5",cy:"9.2",r:"1.1"})]}):e==="connection"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.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"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 3.75v4.5"}),a.jsx("path",{d:"M12 15.75v4.5"}),a.jsx("path",{d:"M3.75 12h4.5"}),a.jsx("path",{d:"M15.75 12h4.5"}),a.jsx("path",{d:"m6.7 6.7 3.1 3.1"}),a.jsx("path",{d:"m14.2 14.2 3.1 3.1"}),a.jsx("path",{d:"m17.3 6.7-3.1 3.1"}),a.jsx("path",{d:"m9.8 14.2-3.1 3.1"}),a.jsx("circle",{cx:"12",cy:"12",r:"2.9"})]}):e==="notifications"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"M10 18.25a2.1 2.1 0 0 0 4 0"})]}):e==="installation"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 3.75v10.5"}),a.jsx("path",{d:"m8.5 10.75 3.5 3.5 3.5-3.5"}),a.jsx("path",{d:"M5.25 16.75h13.5"}),a.jsx("path",{d:"M6 19.25h12"})]}):a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("circle",{cx:"12",cy:"12",r:"3.85"})]}),BM=({icon:e,active:t})=>{const i=t?2:1.8;return e==="sun"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"4.1"}),a.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"?a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.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"})}):a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"3.5",y:"5",width:"17",height:"12",rx:"2.4"}),a.jsx("path",{d:"M8 19h8"})]})},$M=({title:e,caption:t,accent:i,background:r,foreground:o,lines:u})=>a.jsxs("div",{className:"theme-preview-panel",style:{"--preview-accent":i,"--preview-background":r,"--preview-foreground":o},children:[a.jsxs("div",{className:"theme-preview-panel__meta",children:[a.jsx("span",{children:e}),a.jsx("span",{children:t})]}),a.jsx("pre",{className:"theme-preview-panel__code","aria-label":`${e} 主题预览`,children:u.map(d=>a.jsx("code",{children:d},d))})]}),Tu=({label:e,value:t})=>a.jsxs("div",{className:"settings-row settings-row--token",children:[a.jsx("div",{className:"settings-row__copy",children:a.jsx("span",{className:"settings-row__label",children:e})}),a.jsxs("div",{className:"theme-token",children:[a.jsx("span",{className:"theme-token__swatch",style:{"--token-color":t}}),a.jsx("span",{children:t})]})]}),$m=({label:e,value:t})=>a.jsxs("div",{className:"settings-row settings-row--token",children:[a.jsx("div",{className:"settings-row__copy",children:a.jsx("span",{className:"settings-row__label",children:e})}),a.jsx("div",{className:"theme-token",children:t})]}),Y4=({label:e,value:t,mono:i})=>a.jsxs("div",{className:"settings-row settings-row--token",children:[a.jsx("div",{className:"settings-row__copy",children:a.jsx("span",{className:"settings-row__label",children:e})}),a.jsx("div",{className:`theme-token theme-token--font ${i?"is-mono":""}`,children:t})]}),V4=({label:e,value:t,onChange:i,min:r,max:o})=>a.jsxs("div",{className:"settings-row settings-row--size",children:[a.jsx("div",{className:"settings-row__copy",children:a.jsx("span",{className:"settings-row__label",children:e})}),a.jsxs("div",{className:"theme-stepper",children:[a.jsx("button",{type:"button",className:"theme-stepper__button",onClick:()=>i(t-1),"aria-label":`${e} 减小 1px`,children:"-"}),a.jsxs("label",{className:"theme-stepper__input-wrap",children:[a.jsx("input",{className:"theme-stepper__input",type:"number",min:r,max:o,step:1,value:t,onChange:u=>i(Number(u.target.value))}),a.jsx("span",{children:"px"})]}),a.jsx("button",{type:"button",className:"theme-stepper__button",onClick:()=>i(t+1),"aria-label":`${e} 增大 1px`,children:"+"})]})]}),X4=(e,t,i,r)=>{if(t===i)return e;const o=e.findIndex(b=>b.id===t),u=e.findIndex(b=>b.id===i);if(o<0||u<0)return e;const d=[...e],[m]=d.splice(o,1);if(!m)return e;const y=d.findIndex(b=>b.id===i),g=r==="before"?y:y+1;return d.splice(g,0,m),d},Mu=e=>{if(!e)return"未记录";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},Hm=e=>typeof e!="number"||!Number.isFinite(e)?"未测得":`${Math.max(0,Math.round(e))} ms`,G1=async(e,t)=>{const i=await P_(t);return{label:e,...i}},J3=({mode:e="page",onRequestClose:t}={})=>{var _r,Ga;const i=Hi(),r=Ka(),o=Zp(),{data:u}=oy(),[d,m]=_.useState(!1),[y,g]=_.useState(null),[b,p]=_.useState(null),[v,w]=_.useState("theme"),[N,j]=_.useState(null),[T,M]=_.useState(()=>typeof window<"u"&&window.innerWidth>=Q4),[P,I]=_.useState(()=>Z_()),[k,O]=_.useState(()=>qu()),[Q,J]=_.useState(()=>gd()),[F,B]=_.useState(()=>e0()),[G,Z]=_.useState(!1),[ae,he]=_.useState(!1),[ne,Ce]=_.useState(null),[R,X]=_.useState(!1),[le,ue]=_.useState(()=>$u()),[ye,D]=_.useState(()=>w4()),[oe,je]=_.useState(0),z=qa(C=>C.themeSettings),be=qa(C=>C.resolvedTheme),De=qa(C=>C.systemAppearance),se=qa(C=>C.setThemeMode),pe=qa(C=>C.setLightThemeId),ke=qa(C=>C.setDarkThemeId),Ze=qa(C=>C.setUiFontSize),zt=qa(C=>C.setCodeFontSize),Fe=ly(),[kt,Bt]=_.useState(()=>sy()),[Gt,Xt]=_.useState(()=>lp()),[Ft,qe]=_.useState(()=>O3()),[dt,un]=_.useState(null),[$t,An]=_.useState(()=>Of()),[Nn,Tt]=_.useState(null),[lt,Et]=_.useState(null),[rt,st]=_.useState(null),[Dt,an]=_.useState([]),[re,we]=_.useState(null),[Re,te]=_.useState([K1($i)]),[ve,V]=_.useState(null),[q,de]=_.useState(null),[ce,Ae]=_.useState(null),[Ee,$e]=_.useState(null),Pe=typeof window>"u"?null:vo(),ht=typeof window>"u"?null:Rp(),Xe=(u==null?void 0:u.agents.find(C=>C.id===Pe))??(u==null?void 0:u.agents[0]),tn=((_r=Xe==null?void 0:Xe.direct_base_url)==null?void 0:_r.trim().replace(/\/+$/,""))??"",Le=o.platform!=="web",rn=v==="cache"||N==="cache",hn=Xe!=null&&Xe.id?{agentId:Xe.id}:void 0,ns=Xe!=null&&Xe.id?{agentId:Xe.id}:void 0,Xs=V3(hn),$s=[...kM,(ns==null?void 0:ns.agentId)??""],oa=Dt.find(C=>C.id===re)??Dt[0]??null,On=Re.filter(C=>C.enabled).map(({id:C,label:W,vendor:He})=>({id:C,label:W,vendor:He,enabled:!0})),Ss=cs({queryKey:$s,queryFn:async()=>(await cn(ns)).client.getImageProviderSettings(),enabled:!!ns&&(v==="image"||N==="image")}),Kt=cs({queryKey:["settings-connection",o.hubUrl,(Xe==null?void 0:Xe.id)??"",tn],queryFn:async()=>{const C=await cn(),[W,He,tt]=await Promise.all([G1(C.label,C.baseUrl),G1("Panda Hub",bd()),tn?G1((Xe==null?void 0:Xe.name)??"当前节点",tn):Promise.resolve(null)]);return{modeLabel:C.mode==="hub"?"通过 Panda Hub":"直接连接",backendLabel:C.label,backendUrl:C.baseUrl,healthOk:W.healthOk,latencyMs:W.latencyMs,checkedAt:W.checkedAt,activeProbe:W,hubProbe:He,agentProbe:tt}},enabled:v==="connection"||N==="connection",staleTime:0,refetchOnWindowFocus:!1}),Zs=cs({queryKey:["installed-app-info",o.platform],queryFn:()=>DT(),enabled:Le,staleTime:3e4,refetchOnWindowFocus:!1}),us=cs({queryKey:["android-release-manifest",o.hubUrl],queryFn:()=>OT(o.hubUrl),enabled:o.platform==="android"&&!!o.hubUrl&&(v==="connection"||N==="connection"),staleTime:0,refetchOnWindowFocus:!1}),Ln=X3({enabled:rn&&!!hn,scope:hn}),Ot=()=>{je(C=>C+1)},Wn=cs({queryKey:["pwa-install-diagnostics",oe,!!ne,le],queryFn:async()=>yM({installPromptAvailable:!!ne}),enabled:v==="installation"||N==="installation",staleTime:0,refetchOnWindowFocus:!1}),Sn=Gn({mutationFn:async C=>{if(!ns)throw new Error("当前没有可用节点,暂时无法保存绘图渠道。");return(await cn(ns)).client.saveImageProviderSettings(C)},onSuccess:C=>{var He,tt,Rt;r.setQueryData($s,C),an(C.channels.map(ct=>W1(ct))),we(C.active_channel_id??((He=C.channels[0])==null?void 0:He.id)??null);const W=((tt=C.channels.find(ct=>ct.id===C.active_channel_id))==null?void 0:tt.models)??((Rt=C.channels[0])==null?void 0:Rt.models)??[$i];te((W.length?W:[$i]).map(ct=>K1(ct))),V("绘图设置已保存。")},onError:C=>{V(C instanceof Error?C.message:"保存绘图设置失败。")}}),Jn=Gn({mutationFn:async()=>{if(!hn)throw new Error("当前没有可用节点,无法刷新命令目录。");return(await cn(hn)).client.refreshCodexCommands()},onMutate:()=>{g(null)},onSuccess:C=>{r.setQueryData(Xs,C),g(`命令目录已刷新,共 ${C.commands.length} 条,CLI 版本 ${C.cli_version??"未知"}。`)},onError:C=>{g(C instanceof Error?C.message:"刷新命令目录失败。")}});_.useEffect(()=>{var He,tt,Rt;const C=Ss.data;if(!C)return;an(C.channels.map(ct=>W1(ct))),we(C.active_channel_id??((He=C.channels[0])==null?void 0:He.id)??null);const W=((tt=C.channels.find(ct=>ct.id===C.active_channel_id))==null?void 0:tt.models)??((Rt=C.channels[0])==null?void 0:Rt.models)??[$i];te((W.length?W:[$i]).map(ct=>K1(ct)))},[Ss.data]),_.useEffect(()=>{if(typeof window>"u")return;const C=()=>{const W=window.innerWidth>=Q4;M(W)};return C(),window.addEventListener("resize",C),()=>{window.removeEventListener("resize",C)}},[]),_.useEffect(()=>{g(null)},[(Ga=Kt.data)==null?void 0:Ga.backendUrl]),_.useEffect(()=>{T&&j(v)},[v,T]),_.useEffect(()=>{Tt(null)},[v]),_.useEffect(()=>{if(typeof window>"u")return;const C=tt=>{tt.preventDefault(),Ce(tt),Kl({kind:"beforeinstallprompt",message:"浏览器提供了可调用的安装事件。",detail:window.location.href}),Ot()},W=()=>{Ce(null),ue(!0),p("应用已安装到桌面。"),Kl({kind:"appinstalled",message:"站点收到 appinstalled 事件。",detail:"浏览器报告安装流程已经完成或被接受。"}),Ot()},He=()=>{O(qu()),I(Z_()),ue($u()),D(w4()),Kl({kind:"visibilitychange",message:`页面切换为 ${document.visibilityState}。`,detail:`standalone=${$u()?"yes":"no"}`}),Ot()};return window.addEventListener("beforeinstallprompt",C),window.addEventListener("appinstalled",W),document.addEventListener("visibilitychange",He),()=>{window.removeEventListener("beforeinstallprompt",C),window.removeEventListener("appinstalled",W),document.removeEventListener("visibilitychange",He)}},[]),_.useEffect(()=>{if(Fe.length===0||Fe.some(W=>W.value===kt))return;const C=Fe[0].value;Jf(C),Bt(C)},[Fe,kt]),_.useEffect(()=>{var W;if(Fe.length===0||Fe.some(He=>He.value===Gt))return;const C=((W=Fe.find(He=>He.value==="gpt-5.4-mini"))==null?void 0:W.value)??Fe[0].value;F1(C),Xt(C)},[Gt,Fe]),_.useEffect(()=>{var W;if(Fe.length===0||Fe.some(He=>He.value===Ft))return;const C=((W=Fe.find(He=>He.value==="gpt-5.4-mini"))==null?void 0:W.value)??Fe[0].value;q1(C),qe(C)},[Fe,Ft]),_.useEffect(()=>{const C=()=>{Y0().then(W=>{O(W)}).catch(()=>{O(qu())}),J(gd()),B(e0())};return C(),window.addEventListener("focus",C),document.addEventListener("visibilitychange",C),()=>{window.removeEventListener("focus",C),document.removeEventListener("visibilitychange",C)}},[]),_.useEffect(()=>{if(k!=="granted"||!P.completionNotificationsEnabled||!Q)return;let C=!1;return Z(!0),tC(P).then(W=>{C||B(W.synced)}).catch(()=>{C||B(!1)}).finally(()=>{C||Z(!1)}),()=>{C=!0}},[Q,k,P]);const js=()=>{if(e==="overlay"){t==null||t();return}if(ht){fr((Xe==null?void 0:Xe.id)??null),Ea(ht),i({to:"/"});return}i({to:"/nodes"})},Hs=C=>{e==="overlay"&&(t==null||t()),i({to:C})},ca=async()=>{g(null),m(!0);try{await oM(),g("缓存已清理,正在重新载入…"),window.setTimeout(()=>{window.location.replace(`/settings?cache-reset=${Date.now()}`)},180)}catch{m(!1),g("清理失败,请在浏览器设置中手动清理站点数据。")}},Fs=async()=>{if(p(null),Le){if(k==="granted"){p("当前已经拿到系统通知权限;完成提醒会自动跟随系统权限生效。");return}const C=await J_();if(O(C),C==="granted"){const W={completionNotificationsEnabled:!0};sc(W),I(W),p("系统通知已开启,后续任务完成会直接走原生通知。");return}if(C==="denied"){p("系统通知已被拒绝,请到系统设置里重新开启。");return}p("还没有拿到通知权限,可以稍后再试一次。");return}if(k!=="granted"){const C=await J_();if(O(C),C==="granted"){if(!Q){const W={completionNotificationsEnabled:!0};sc(W),I(W),p(Le?"系统通知已开启,任务完成时会直接走原生通知。":"系统通知已开启,但当前环境不支持后台 Web Push。");return}Z(!0);try{const W={completionNotificationsEnabled:!0};await j4(W),sc(W),I(W),B(!0),p("系统通知和后台 Web Push 都已开启。");return}catch(W){B(!1),p(W instanceof Error?W.message:"通知权限已开启,但 Web Push 订阅失败。");return}finally{Z(!1)}}if(C==="denied"){p("系统通知已被拒绝,请到浏览器或系统设置里重新开启。");return}p("还没有拿到通知权限,可以稍后再试一次。");return}if(P.completionNotificationsEnabled){Z(!0);try{await nC();const C={completionNotificationsEnabled:!1};sc(C),I(C),B(!1),p("完成提醒已关闭,后台推送订阅也已移除。")}catch(C){p(C instanceof Error?C.message:"关闭 Web Push 订阅失败。")}finally{Z(!1)}return}if(!Q){const C={completionNotificationsEnabled:!0};sc(C),I(C),p(Le?"原生通知已开启,后续会沿用当前 App 的在线事件提醒。":"当前环境不支持后台 Web Push,只能在页面在线时提醒。");return}Z(!0);try{const C={completionNotificationsEnabled:!0};await j4(C),sc(C),I(C),B(!0),p("完成提醒已开启,Hub 会在会话完成后推送到这台手机。")}catch(C){B(!1),p(C instanceof Error?C.message:"开启 Web Push 失败。")}finally{Z(!1)}},Js=async()=>{p(null),he(!0);try{if(Le){await l3({sessionId:"settings-test",completedAt:new Date().toISOString(),title:"Panda 测试提醒",body:"这是一条来自 Android 壳的本地通知测试。",url:"/settings"}),p("测试通知已发出,请看当前设备的系统通知栏。");return}await sC(),p("测试推送已发出,请看手机或当前设备的通知栏。")}catch(C){p(C instanceof Error?C.message:"发送测试推送失败。")}finally{he(!1)}},ua=async()=>{if(!ne){Kl({kind:"install-unavailable",message:"当前页面没有可用的安装事件。",detail:ye?"浏览器没有下发 beforeinstallprompt,只能走菜单里的安装应用或添加到主屏幕。":"当前浏览器没有提供可调用的安装对话框。"}),Ot(),p(ye?"请在浏览器菜单里选择“安装应用”或“添加到主屏幕”。":"当前浏览器没有提供安装弹窗,请使用浏览器的“添加到主屏幕”。");return}X(!0),p(null),Kl({kind:"install-button-click",message:"用户点击了设置页里的安装按钮。",detail:"准备调用浏览器安装对话框。"}),Ot();try{Kl({kind:"install-prompt-shown",message:"已调用浏览器安装对话框。",detail:"等待用户在系统安装弹窗里做出选择。"}),await ne.prompt();const C=await ne.userChoice;Kl({kind:"install-choice",message:C.outcome==="accepted"?"用户接受了安装请求。":"用户取消了安装请求。",detail:`outcome=${C.outcome}; platform=${C.platform}`}),Ot(),C.outcome==="accepted"?p("安装请求已提交,请回到桌面查看。"):p("你取消了这次安装。")}catch(C){Kl({kind:"install-error",message:"调用浏览器安装流程时报错。",detail:C instanceof Error?C.message:"Unknown install error"}),Ot(),p("浏览器没有完成安装流程,请查看下方安装诊断。")}finally{Ce(null),X(!1),ue($u()),Ot()}},da=()=>{const C={...W1(),models:On.length?On:[$i]};Ae("create"),$e(C),V(null)},fa=C=>{const W=Dt.find(He=>He.id===C);W&&(Ae("edit"),$e({...W}),V(null))},In=()=>{Ae(null),$e(null)},ws=async(C,W,He=Re)=>{await Sn.mutateAsync(TM(W,C,He))},Os=async()=>{if(!Ee)return;const C={...Ee,remark:Ee.remark.trim(),base_url:Ee.base_url.trim()};if(!C.remark){V("请填写渠道备注名称。");return}const W=ce==="edit"?Dt.map(He=>He.id===C.id?C:He):[...Dt,C];try{await ws(W,re??C.id),In()}catch{return}},ee=async C=>{var tt;const W=Dt.filter(Rt=>Rt.id!==C),He=re===C?((tt=W[0])==null?void 0:tt.id)??null:re;try{await ws(W,He)}catch{return}},Be=()=>{de({originalId:null,vendor:"openai",modelId:""}),V(null)},Ke=C=>{const W=Re.find(He=>He.id===C);W&&(de({originalId:W.id,vendor:W.vendor,modelId:W.id}),V(null))},Lt=async()=>{const C=q,W=(C==null?void 0:C.modelId.trim())??"";if(!C||!W){V("请输入绘图模型 ID。");return}const He={id:W,label:W,vendor:C.vendor,enabled:!0};if(Re.find(ct=>ct.id===He.id&&ct.id!==C.originalId)){V("这个绘图模型已经存在。");return}const Rt=C.originalId===null?[...Re,{...He,enabled:!0}]:Re.map(ct=>ct.id===C.originalId?{...He,enabled:ct.enabled}:ct);try{await ws(Dt,re,Rt.map(({id:ct,label:Nt,vendor:Yn,enabled:Kn})=>({id:ct,label:Nt,vendor:Yn,enabled:Kn}))),de(null)}catch{return}},Zt=async C=>{const W=Re.find(tt=>tt.id===C);if(!W)return;if(W.enabled&&Re.filter(tt=>tt.enabled).length<=1){V("至少保留一个启用中的绘图模型。");return}const He=Re.map(tt=>tt.id===C?{...tt,enabled:!tt.enabled}:tt);try{await ws(Dt,re,He.map(({id:tt,label:Rt,vendor:ct,enabled:Nt})=>({id:tt,label:Rt,vendor:ct,enabled:Nt})))}catch{return}},Pt=async C=>{const W=Re.find(tt=>tt.id===C);if(!W)return;if(W.enabled&&Re.filter(tt=>tt.enabled).length<=1){V("至少保留一个启用中的绘图模型。");return}const He=Re.filter(tt=>tt.id!==C);try{await ws(Dt,re,He.map(({id:tt,label:Rt,vendor:ct,enabled:Nt})=>({id:tt,label:Rt,vendor:ct,enabled:Nt})))}catch{return}},At=async C=>{if(C!==re)try{await ws(Dt,C)}catch{return}},mn=C=>{var W,He,tt,Rt,ct;if(qT(C),!C.some(Nt=>Nt.value===kt)){const Nt=((W=C[0])==null?void 0:W.value)??"";Nt&&(Jf(Nt),Bt(Nt))}if(!C.some(Nt=>Nt.value===Gt)){const Nt=((He=C.find(Yn=>Yn.value==="gpt-5.4-mini"))==null?void 0:He.value)??((tt=C[0])==null?void 0:tt.value)??"";Nt&&(F1(Nt),Xt(Nt))}if(!C.some(Nt=>Nt.value===Ft)){const Nt=((Rt=C.find(Yn=>Yn.value==="gpt-5.4-mini"))==null?void 0:Rt.value)??((ct=C[0])==null?void 0:ct.value)??"";Nt&&(q1(Nt),qe(Nt))}},jn=()=>{un("new"),An(Of()),Tt(null)},kn=C=>{un(C.id),An({...C}),Tt(null)},pn=()=>{un(null),An(Of()),Tt(null)},U=()=>{var ct;const C=$t.label.trim(),W=$t.value.trim();if(!C||!W){Tt("请填写显示名和模型 ID。");return}if(Fe.find(Nt=>Nt.value.toLowerCase()===W.toLowerCase()&&Nt.id!==dt)){Tt(`模型 ID ${W} 已存在。`);return}const tt={...$t,label:C,value:W,description:((ct=$t.description)==null?void 0:ct.trim())||null},Rt=dt==="new"?[...Fe,tt]:Fe.map(Nt=>Nt.id===dt?tt:Nt);mn(Rt),un(null),An(Of()),Tt(dt==="new"?"模型已添加。":"模型已更新。")},Ne=C=>{const W=Fe.filter(He=>He.id!==C);if(W.length===0){Tt("至少保留一个模型。");return}mn(W),dt===C&&(un(null),An(Of())),Tt("模型已删除。")},Ue=C=>{Jf(C),Bt(C),Tt(`默认模型已切换为 ${C}。`)},Qe=C=>{F1(C),Xt(C),Tt(`命令执行模型已切换为 ${C}。`)},at=C=>{q1(C),qe(C),Tt(`标题生成模型已切换为 ${C}。`)},Je=(C,W)=>{const He=Fe.findIndex(ct=>ct.id===C);if(He<0)return;const tt=W==="up"?He-1:He+1;if(tt<0||tt>=Fe.length)return;const Rt=Fe[tt];Rt&&mn(X4(Fe,C,Rt.id,W==="up"?"before":"after"))},vt=(C,W)=>{Et(W),st(null),C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",W)},ot=(C,W)=>{if(!lt||lt===W)return;C.preventDefault();const He=C.currentTarget.getBoundingClientRect(),tt=C.clientY<He.top+He.height/2?"before":"after";st(Rt=>(Rt==null?void 0:Rt.modelId)===W&&Rt.position===tt?Rt:{modelId:W,position:tt})},nn=C=>{!lt||!rt||rt.modelId!==C||(mn(X4(Fe,lt,C,rt.position)),Et(null),st(null))},Jt=()=>{Et(null),st(null)},qt=be.appearance,St=qt==="light"?i0:ph,En=qt==="light"?z.lightThemeId:z.darkThemeId,gt=St.find(C=>C.id===En)??St[0],ss=be.activeTheme,Ns=RM(gt.codeThemeId,gt.accent,gt.contrast,gt.opaqueWindows),ks=z.mode==="system"?`当前跟随系统:${De==="dark"?"深色":"浅色"}`:`当前固定为${be.appearance==="dark"?"深色":"浅色"}模式`,as="当前正在显示",Es=gt.opaqueWindows?"不透明窗口":"半透明窗口",is=Bm.find(C=>C.id===v)??Bm[0],Cs={"--settings-mobile-sticky-safe-area":Le?"0px":"var(--app-safe-area-top)"},es=`${gt.label} · ${Es} · 对比度 ${gt.contrast}`,qs=Fe.find(C=>C.value===kt)??Fe[0]??null,Ws=Fe.find(C=>C.value===Gt)??Fe.find(C=>C.value==="gpt-5.4-mini")??Fe[0]??null,Ks=Fe.find(C=>C.value===Ft)??Fe.find(C=>C.value==="gpt-5.4-mini")??Fe[0]??null,pr=C=>{var W;return C==="theme"?be.activeTheme.label:C==="models"?(qs==null?void 0:qs.label)??`${Fe.length} 个模型`:C==="image"?(oa==null?void 0:oa.remark)??`${Dt.length} 个渠道`:C==="cache"?y||(Ln.data?`${Ln.data.commands.length} 条命令`:"站点与命令目录"):C==="notifications"?P.completionNotificationsEnabled?"已开启":"未开启":C==="installation"?le?"已安装":"检查状态":(W=Kt.data)!=null&&W.healthOk?Kt.data.modeLabel:(Xe==null?void 0:Xe.name)??"查看链路"},Fi=()=>a.jsx("div",{className:"settings-mobile-layout",children:a.jsx("div",{className:"settings-mobile-sections",role:"list","aria-label":"设置分组",children:EM.map(C=>a.jsx("section",{className:"settings-mobile-group","aria-label":C.label,children:C.sections.map(W=>{const He=Bm.find(ct=>ct.id===W);if(!He)return null;const tt=N===He.id,Rt=pr(He.id);return a.jsxs(_.Fragment,{children:[a.jsxs("button",{type:"button",className:`settings-mobile-row ${tt?"is-active":""}`,"data-section":He.id,onClick:()=>{w(He.id),j(ct=>ct===He.id?null:He.id)},"aria-expanded":tt,"aria-controls":`settings-mobile-detail-${He.id}`,children:[a.jsx("span",{className:"settings-mobile-row__icon","data-section":He.id,"aria-hidden":"true",children:a.jsx(G4,{icon:He.icon})}),a.jsx("span",{className:"settings-mobile-row__copy",children:a.jsx("span",{className:"settings-mobile-row__title",children:He.title})}),a.jsx("span",{className:"settings-mobile-row__summary",children:Rt}),a.jsx("span",{className:"settings-mobile-row__chevron","aria-hidden":"true",children:a.jsx(IM,{open:!1})})]}),tt?a.jsx("section",{className:"settings-mobile-detail settings-mobile-detail--inline",id:`settings-mobile-detail-${He.id}`,children:Ni(He.id)}):null]},He.id)})},C.id))})}),qi=()=>a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"外观"}),a.jsx("p",{className:"settings-panel__subtitle",children:"先选浅色或深色,再挑一个你喜欢的风格。"})]})}),a.jsx("div",{className:"settings-control-grid",children:a.jsxs("div",{className:"settings-control-block settings-control-block--full",children:[a.jsx("span",{className:"settings-control-block__label",children:"显示方式"}),a.jsx("div",{className:"theme-mode-switch",role:"tablist","aria-label":"主题模式",children:CM.map(C=>{const W=C.value===z.mode;return a.jsxs("button",{type:"button",className:`theme-mode-switch__button ${W?"is-active":""}`,onClick:()=>se(C.value),role:"tab","aria-selected":W,children:[a.jsx(BM,{icon:C.icon,active:W}),a.jsx("span",{children:C.label})]},C.value)})}),a.jsx("p",{className:"settings-control-block__hint",children:ks})]})})]}),a.jsxs("div",{className:"settings-theme-layout",children:[a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:qt==="light"?"浅色风格":"深色风格"})})}),a.jsxs("div",{className:"settings-theme-selector",children:[a.jsx("label",{className:"settings-select settings-select--wide",children:a.jsx("select",{value:gt.id,onChange:C=>{if(qt==="light"){pe(C.target.value);return}ke(C.target.value)},"aria-label":qt==="light"?"选择浅色主题":"选择深色主题",children:St.map(C=>a.jsx("option",{value:C.id,children:C.label},`${C.variant}-${C.id}`))})}),a.jsxs("div",{className:"settings-theme-selector__summary",children:[a.jsxs("div",{className:"settings-theme-selector__swatches","aria-hidden":"true",children:[a.jsx("span",{style:{"--theme-card-color":gt.background}}),a.jsx("span",{style:{"--theme-card-color":gt.foreground}}),a.jsx("span",{style:{"--theme-card-color":gt.accent}}),a.jsx("span",{style:{"--theme-card-color":gt.semanticColors.diffAdded}}),a.jsx("span",{style:{"--theme-card-color":gt.semanticColors.diffRemoved}})]}),a.jsxs("div",{className:"settings-theme-selector__copy",children:[a.jsx("strong",{children:gt.label}),a.jsx("span",{children:es})]}),gt.id===ss.id&>.variant===be.appearance?a.jsx("span",{className:"settings-theme-selector__badge",children:"当前"}):a.jsx("span",{className:"settings-theme-selector__badge is-muted",children:"已选"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"风格细节"})}),a.jsx("div",{className:"theme-status-badge",children:as})]}),a.jsx($M,{title:qt==="light"?"浅色预览":"深色预览",caption:gt.label,accent:gt.accent,background:gt.background,foreground:gt.foreground,lines:Ns}),a.jsxs("div",{className:"settings-list",children:[a.jsx($m,{label:"代码风格",value:gt.codeThemeId}),a.jsx($m,{label:"当前模式",value:gt.variant}),a.jsx($m,{label:"对比度",value:String(gt.contrast)}),a.jsx($m,{label:"面板质感",value:Es}),a.jsx(Tu,{label:"强调色",value:gt.accent}),a.jsx(Tu,{label:"背景色",value:gt.background}),a.jsx(Tu,{label:"文字色",value:gt.foreground}),a.jsx(Tu,{label:"新增颜色",value:gt.semanticColors.diffAdded}),a.jsx(Tu,{label:"删除颜色",value:gt.semanticColors.diffRemoved}),a.jsx(Tu,{label:"特殊强调",value:gt.semanticColors.skill}),a.jsx(Y4,{label:"界面字体",value:gt.fonts.ui??"null"}),a.jsx(Y4,{label:"代码字体",value:gt.fonts.code??"null",mono:!0})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"字号"})})}),a.jsxs("div",{className:"settings-list",children:[a.jsx(V4,{label:"界面字号",value:z.uiFontSize,onChange:C=>Ze(W3(C)),min:11,max:18}),a.jsx(V4,{label:"代码字号",value:z.codeFontSize,onChange:C=>zt(K3(C)),min:10,max:18})]})]})]}),Wi=()=>a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"渠道列表"}),a.jsx("p",{className:"settings-panel__subtitle",children:"列表保持极简:只显示备注名称、编辑、删除和启用开关。"})]}),a.jsx("div",{className:"settings-actions-row",children:a.jsxs("button",{type:"button",className:"settings-inline-action",onClick:da,disabled:Sn.isPending,children:[a.jsx(Q1,{}),"新增渠道"]})})]}),ve?a.jsx("div",{className:"settings-inline-status",role:"alert",children:ve}):null,Dt.length?a.jsx("div",{className:"settings-image-channel-list",role:"list","aria-label":"绘图渠道列表",children:Dt.map(C=>{const W=C.id===re,He=C.remark.trim()||"未命名渠道";return a.jsx("article",{className:`settings-image-channel-card ${W?"is-active":""}`,role:"listitem",children:a.jsxs("div",{className:"settings-image-channel-card__row",children:[a.jsxs("div",{className:"settings-image-channel-card__meta",children:[a.jsx("strong",{children:He}),W?a.jsx("span",{className:"settings-image-channel-card__badge",children:"当前启用"}):null]}),a.jsxs("div",{className:"settings-image-channel-card__actions",children:[a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>fa(C.id),disabled:Sn.isPending,"aria-label":`编辑 ${He}`,title:`编辑 ${He}`,children:a.jsx(fh,{size:16,strokeWidth:1.9})}),a.jsx("button",{type:"button",className:"settings-icon-button is-danger",onClick:()=>void ee(C.id),disabled:Sn.isPending,"aria-label":`删除 ${He}`,title:`删除 ${He}`,children:a.jsx($p,{size:16,strokeWidth:1.9})}),a.jsx("button",{type:"button",className:`settings-switch ${W?"is-on":""}`,role:"switch","aria-checked":W,"aria-label":`启用渠道 ${He}`,onClick:()=>void At(C.id),disabled:Sn.isPending,children:a.jsx("span",{className:"settings-switch__track",children:a.jsx("span",{className:"settings-switch__thumb"})})})]})]})},C.id)})}):a.jsx("p",{className:"settings-block__status",children:"还没有绘图渠道,先新增一个渠道。"})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"共享绘图模型"}),a.jsx("p",{className:"settings-panel__subtitle",children:"当前渠道共用同一组模型,列表结构和渠道一致。"})]}),a.jsx("div",{className:"settings-actions-row",children:a.jsxs("button",{type:"button",className:"settings-inline-action",onClick:Be,children:[a.jsx(Q1,{}),"新增模型"]})})]}),Re.length?a.jsx("div",{className:"settings-image-channel-list",role:"list","aria-label":"绘图模型列表",children:Re.map(C=>a.jsx("article",{className:`settings-image-channel-card ${C.enabled?"is-active":""}`,role:"listitem",children:a.jsxs("div",{className:"settings-image-channel-card__row",children:[a.jsxs("div",{className:"settings-image-model-card__meta",children:[a.jsx("strong",{children:C.label}),a.jsx("span",{className:"settings-image-model-card__vendor",children:MM(C.vendor)})]}),a.jsxs("div",{className:"settings-image-channel-card__actions",children:[a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>Ke(C.id),disabled:Sn.isPending,"aria-label":`编辑 ${C.label}`,title:`编辑 ${C.label}`,children:a.jsx(fh,{size:16,strokeWidth:1.9})}),a.jsx("button",{type:"button",className:"settings-icon-button is-danger",onClick:()=>void Pt(C.id),disabled:Sn.isPending,"aria-label":`删除 ${C.label}`,title:`删除 ${C.label}`,children:a.jsx($p,{size:16,strokeWidth:1.9})}),a.jsx("button",{type:"button",className:`settings-switch ${C.enabled?"is-on":""}`,role:"switch","aria-checked":C.enabled,"aria-label":`${C.enabled?"停用":"启用"}模型 ${C.label}`,onClick:()=>void Zt(C.id),disabled:Sn.isPending,children:a.jsx("span",{className:"settings-switch__track",children:a.jsx("span",{className:"settings-switch__thumb"})})})]})]})},C.id))}):a.jsx("p",{className:"settings-block__status",children:"还没有绘图模型,先新增一个模型。"}),q?a.jsxs("div",{className:"settings-model-editor settings-image-model-picker",children:[a.jsx("div",{className:"settings-model-editor__header",children:a.jsx("strong",{children:q.originalId===null?"新增绘图模型":"编辑绘图模型"})}),a.jsxs("div",{className:"settings-model-editor__grid",children:[a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"模型厂商"}),a.jsx("select",{value:q.vendor,onChange:C=>de(W=>W&&{...W,vendor:C.target.value}),children:Z3.map(C=>a.jsx("option",{value:C.value,children:C.label},C.value))})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"模型 ID"}),a.jsx("input",{type:"text",value:q.modelId,onChange:C=>de(W=>W&&{...W,modelId:C.target.value}),placeholder:"gpt-image-2"})]})]}),a.jsxs("div",{className:"settings-model-editor__actions",children:[a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>de(null),disabled:Sn.isPending,children:"取消"}),a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void Lt(),disabled:Sn.isPending,children:Sn.isPending?"保存中…":"保存模型"})]})]}):null]})]}),ea=Ee&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered image-options-sheet settings-image-channel-sheet",role:"dialog","aria-modal":"true","aria-label":ce==="create"?"新增绘图渠道":"编辑绘图渠道",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:In,"aria-label":"关闭绘图渠道弹窗"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"image-options-panel image-options-panel--compact settings-image-dialog",children:[a.jsx("div",{className:"image-options-panel__handle"}),a.jsxs("div",{className:"image-options-panel__header",children:[a.jsxs("div",{className:"image-options-panel__header-copy",children:[a.jsx("span",{className:"image-options-panel__eyebrow",children:"绘图渠道"}),a.jsx("h2",{children:ce==="create"?"新增渠道":"编辑渠道"}),a.jsx("p",{children:"保持列表简洁,只在这里维护备注、Base URL 和 API Key。"})]}),a.jsx("button",{type:"button",className:"image-options-panel__close",onClick:In,"aria-label":"关闭绘图渠道弹窗",children:a.jsx(PM,{})})]}),a.jsxs("div",{className:"settings-image-dialog__body",children:[a.jsxs("label",{className:"settings-form-field",children:[a.jsx("span",{className:"settings-form-field__label",children:"备注名称"}),a.jsx("input",{className:"settings-form-field__input",type:"text",value:Ee.remark,placeholder:"例如:OpenAI 官方 / 中转 A",onChange:C=>$e(W=>W&&{...W,remark:C.target.value}),autoFocus:!0})]}),a.jsxs("label",{className:"settings-form-field",children:[a.jsx("span",{className:"settings-form-field__label",children:"Base URL"}),a.jsx("input",{className:"settings-form-field__input",type:"text",value:Ee.base_url,placeholder:"https://api.openai.com/v1",onChange:C=>$e(W=>W&&{...W,base_url:C.target.value})}),a.jsx("span",{className:"settings-form-field__hint",children:"支持兼容 OpenAI Images API 的地址前缀,例如 `xxx/v1`。"})]}),a.jsxs("label",{className:"settings-form-field",children:[a.jsx("span",{className:"settings-form-field__label",children:"API Key"}),a.jsx("input",{className:"settings-form-field__input",type:"password",value:Ee.api_key,onChange:C=>$e(W=>W&&{...W,api_key:C.target.value}),placeholder:"留空则沿用已保存的 Key 或环境变量"}),a.jsx("span",{className:"settings-form-field__hint",children:"填写后会覆盖当前渠道的 Key;留空则保持现状。"})]})]}),a.jsxs("div",{className:"image-options-panel__footer",children:[a.jsx("button",{type:"button",onClick:In,disabled:Sn.isPending,children:"取消"}),a.jsx("button",{type:"button",className:"is-primary",onClick:()=>void Os(),disabled:!Ee.remark.trim()||Sn.isPending,children:Sn.isPending?"保存中…":"确认"})]})]})})]}),document.body):null,Ma=()=>{var C;return a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"模型列表"}),a.jsx("p",{className:"settings-panel__subtitle",children:"保持简洁,但把默认模型、命令执行和标题生成的角色关系看得更清楚。"})]}),a.jsxs("button",{type:"button",className:"settings-inline-action",onClick:jn,children:[a.jsx(Q1,{}),"新增模型"]})]}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"首位模型"}),a.jsx("strong",{children:((C=Fe[0])==null?void 0:C.label)??"未配置"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前默认"}),a.jsx("strong",{children:(qs==null?void 0:qs.label)??"未配置"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"命令执行模型"}),a.jsx("strong",{children:(Ws==null?void 0:Ws.label)??"未配置"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"标题生成模型"}),a.jsx("strong",{children:(Ks==null?void 0:Ks.label)??"未配置"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"模型角色"}),a.jsx("p",{className:"settings-panel__subtitle",children:"三个角色分开配置,避免平时切换时看不出差别。"})]})}),a.jsxs("div",{className:"settings-model-role-grid",children:[a.jsxs("label",{className:"settings-model-role-card",children:[a.jsx("span",{className:"settings-model-role-card__eyebrow",children:"默认模型"}),a.jsx("strong",{className:"settings-model-role-card__value",children:(qs==null?void 0:qs.label)??"未配置"}),a.jsx("select",{value:kt,onChange:W=>Ue(W.target.value),children:Fe.map(W=>a.jsx("option",{value:W.value,children:W.label},W.id))})]}),a.jsxs("label",{className:"settings-model-role-card",children:[a.jsx("span",{className:"settings-model-role-card__eyebrow",children:"命令执行"}),a.jsx("strong",{className:"settings-model-role-card__value",children:(Ws==null?void 0:Ws.label)??"未配置"}),a.jsx("select",{value:Gt,onChange:W=>Qe(W.target.value),children:Fe.map(W=>a.jsx("option",{value:W.value,children:W.label},W.id))})]}),a.jsxs("label",{className:"settings-model-role-card",children:[a.jsx("span",{className:"settings-model-role-card__eyebrow",children:"标题生成"}),a.jsx("strong",{className:"settings-model-role-card__value",children:(Ks==null?void 0:Ks.label)??"未配置"}),a.jsx("select",{value:Ft,onChange:W=>at(W.target.value),children:Fe.map(W=>a.jsx("option",{value:W.value,children:W.label},W.id))})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"维护模型"}),a.jsx("p",{className:"settings-panel__subtitle",children:"重点放在层级、排序和默认关系,列表尽量轻一点。"})]})}),Nn?a.jsx("div",{className:"settings-inline-status",role:"alert",children:Nn}):null,a.jsx("div",{className:"settings-model-list",role:"list","aria-label":"模型列表",children:Fe.map((W,He)=>{const tt=lt===W.id,Rt=(rt==null?void 0:rt.modelId)===W.id&&rt.position==="before",ct=(rt==null?void 0:rt.modelId)===W.id&&rt.position==="after",Nt=W.value===kt;return a.jsxs("article",{className:`settings-model-card ${tt?"is-dragging":""} ${Rt?"is-drop-before":""} ${ct?"is-drop-after":""}`,draggable:!0,onDragStart:Yn=>vt(Yn,W.id),onDragOver:Yn=>ot(Yn,W.id),onDrop:Yn=>{Yn.preventDefault(),nn(W.id)},onDragEnd:Jt,role:"listitem",children:[a.jsxs("div",{className:"settings-model-card__main",children:[a.jsx("span",{className:"settings-model-card__grip","aria-hidden":"true",children:a.jsx(DM,{})}),a.jsxs("div",{className:"settings-model-card__copy",children:[a.jsxs("div",{className:"settings-model-card__title-row",children:[a.jsx("strong",{children:W.label}),Nt?a.jsx("span",{className:"settings-model-card__badge",children:"默认"}):null]}),a.jsx("code",{className:"settings-model-card__value",children:W.value})]})]}),a.jsxs("div",{className:"settings-model-card__actions",children:[a.jsx("button",{type:"button",className:`settings-mini-button settings-model-card__primary-action ${Nt?"is-active":""}`,onClick:()=>Ue(W.value),children:"设为默认"}),a.jsxs("div",{className:"settings-model-card__icon-actions",children:[a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>Je(W.id,"up"),disabled:He===0,"aria-label":`上移 ${W.label}`,children:a.jsx(UM,{})}),a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>Je(W.id,"down"),disabled:He===Fe.length-1,"aria-label":`下移 ${W.label}`,children:a.jsx(zM,{})}),a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>kn(W),"aria-label":`编辑 ${W.label}`,children:a.jsx(OM,{})}),a.jsx("button",{type:"button",className:"settings-icon-button is-danger",onClick:()=>Ne(W.id),disabled:Fe.length<=1,"aria-label":`删除 ${W.label}`,children:a.jsx(LM,{})})]})]})]},W.id)})}),dt?a.jsxs("div",{className:"settings-model-editor",children:[a.jsx("div",{className:"settings-model-editor__header",children:a.jsx("strong",{children:dt==="new"?"新增模型":"编辑模型"})}),a.jsxs("div",{className:"settings-model-editor__grid",children:[a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"显示名"}),a.jsx("input",{type:"text",value:$t.label,onChange:W=>An(He=>({...He,label:W.target.value})),placeholder:"例如:gpt-5.4"})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"模型 ID"}),a.jsx("input",{type:"text",value:$t.value,onChange:W=>An(He=>({...He,value:W.target.value})),placeholder:"例如:gpt-5.4"})]})]}),a.jsxs("div",{className:"settings-model-editor__actions",children:[a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:pn,children:"取消"}),a.jsx("button",{type:"button",className:"settings-inline-action",onClick:U,children:"保存"})]})]}):null]})]})},ji=()=>{var C,W;return a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"页面缓存"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"适合什么时候用"}),a.jsx("strong",{children:"页面资源或本地缓存异常"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"常见表现"}),a.jsx("strong",{children:"样式没更新、列表卡旧、页面反复异常"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"清理缓存"})})}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void ca(),disabled:d,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:"清理并刷新"}),a.jsx("span",{children:"删除页面资源缓存和本地会话缓存,强制重新加载最新页面。"})]}),a.jsx("span",{className:"settings-action__state",children:d?"处理中…":"→"})]}),y?a.jsx("p",{className:"settings-block__status",children:y}):null]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"移动端诊断"})})}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>Hs("/diagnostics"),children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:"打开安卓诊断页"}),a.jsx("span",{children:"在手机上检查样式能力、资源加载、Service Worker 和缓存状态,并可上传到后端日志。"})]}),a.jsx("span",{className:"settings-action__state",children:"→"})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"命令目录缓存"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 CLI"}),a.jsx("span",{children:((C=Ln.data)==null?void 0:C.cli_version)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近刷新"}),a.jsx("span",{children:((W=Ln.data)==null?void 0:W.loaded_at)??"尚未生成"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"命令数量"}),a.jsx("span",{children:Ln.data?`${Ln.data.commands.length} 条`:"检测中…"})]}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Jn.mutateAsync(),disabled:Jn.isPending,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:"刷新命令目录"}),a.jsx("span",{children:"重新从当前 Codex CLI 对应版本拉取命令并覆盖本地缓存文件。"})]}),a.jsx("span",{className:"settings-action__state",children:Jn.isPending?"刷新中…":"→"})]})]})]})},Qa=()=>{var ct,Nt,Yn,Kn,Ya,Ra,ii,Va,ge,gn,ta,xo,xa,na,sn,ri,yr,So,Dc,jo,ki,wo;const C=Zs.data,W=us.data,He=!!(W!=null&&W.apk_url),tt=PT(C,W),Rt=N3(o.hubUrl);return a.jsxs("div",{className:"settings-content-stack",children:[Le?a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"Hub 连接配置"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前 Hub"}),a.jsx("strong",{children:o.hubUrl||"未配置"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"首启状态"}),a.jsx("strong",{children:o.onboardingCompleted?"已完成":"未完成"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"App 形态"}),a.jsx("strong",{children:"Capacitor Android"})]})]})]}):a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"网页端连接基线"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前网页入口"}),a.jsx("strong",{children:o.hubUrl||"未检测到"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"地址来源"}),a.jsx("strong",{children:"浏览器访问地址"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"缓存策略"}),a.jsx("strong",{children:"同源页面 + 本地查询缓存"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:Le?"重新设置 Hub":"当前访问方式"})})}),Le?a.jsx(Q2,{title:"输入新的 Hub 地址",description:"扫码或手动输入后,保存即可让 APK 用新地址重新建立连接。",currentHubUrl:o.hubUrl,initialHubUrl:o.hubUrl,hint:"保存后会清理旧的查询缓存、会话定位和连接判定缓存,避免继续误连到旧 Hub。",saveLabel:"保存并重连",savingLabel:"正在保存地址",saveDescription:"新的 Hub 地址会持久化到本机,后续重新打开 APK 会继续沿用。",saveSuccessMessage:"Hub 地址已保存,连接缓存和旧会话定位已重置。",onSaveSuccess:async ul=>{await P6({hubUrl:ul.url,onboardingCompleted:!0}),await f3(r),Kt.refetch(),us.refetch(),Zs.refetch()}}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 Hub 地址"}),a.jsx("span",{children:o.hubUrl||"未检测到"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"可修改性"}),a.jsx("span",{children:"网页端跟随浏览器打开的地址,不额外保存本地覆盖配置。"})]})]})]}),o.platform==="android"?a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"App 升级"})}),a.jsx("div",{className:"settings-actions-row",children:a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{Zs.refetch(),us.refetch()},children:"刷新版本"})})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前版本"}),a.jsx("span",{children:(C==null?void 0:C.version)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 build"}),a.jsx("span",{children:(C==null?void 0:C.build)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"应用包名"}),a.jsx("span",{children:(C==null?void 0:C.appId)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"更新清单"}),a.jsx("span",{children:Rt||"等待 Hub 地址"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最新发布"}),a.jsx("span",{children:us.isLoading?"检测中…":W?`${W.version_name} (${W.version_code})`:us.error instanceof Error?us.error.message:"未检测到"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"升级状态"}),a.jsx("span",{className:tt?"is-ok":"is-muted",children:tt?"发现新版本":He?"当前已是最新":"等待发布 APK"})]}),W!=null&&W.published_at?a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"发布时间"}),a.jsx("span",{children:Mu(W.published_at)})]}):null,a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>{W!=null&&W.apk_url&&UT(W.apk_url)},disabled:!(W!=null&&W.apk_url),children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:tt?"下载并覆盖安装新版 APK":"打开最新 APK 下载地址"}),a.jsx("span",{children:"通过同一个 `applicationId` 和固定签名覆盖安装,旧配置和本地数据会保留,不需要卸载重装。"})]}),a.jsx("span",{className:"settings-action__state",children:W!=null&&W.apk_url?"→":"未就绪"})]}),W!=null&&W.release_notes.length?a.jsx("div",{className:"settings-diagnostic-list",children:W.release_notes.map(ul=>a.jsxs("div",{className:"settings-diagnostic-list__item",children:[a.jsx("strong",{children:"发布说明"}),a.jsx("span",{children:ul})]},ul))}):null]}):null,a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"当前设备"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"设备名称"}),a.jsx("strong",{children:(Xe==null?void 0:Xe.name)??"未选择节点"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"连接方式"}),a.jsx("strong",{children:((ct=Kt.data)==null?void 0:ct.modeLabel)??"检测中…"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前链路延迟"}),a.jsx("strong",{className:(Nt=Kt.data)!=null&&Nt.healthOk?"is-ok":"is-muted",children:Kt.isLoading?"检测中…":Hm((Yn=Kt.data)==null?void 0:Yn.latencyMs)})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"当前链路"})}),a.jsx("div",{className:"settings-actions-row",children:a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{Kt.refetch()},children:"刷新延迟"})})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"服务名称"}),a.jsx("span",{children:((Kn=Kt.data)==null?void 0:Kn.backendLabel)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"服务地址"}),a.jsx("span",{children:((Ya=Kt.data)==null?void 0:Ya.backendUrl)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前状态"}),a.jsx("span",{className:(Ra=Kt.data)!=null&&Ra.healthOk?"is-ok":"is-muted",children:Kt.isLoading?"检测中…":(ii=Kt.data)!=null&&ii.healthOk?"在线":((Va=Kt.data)==null?void 0:Va.activeProbe.error)??"无法连接"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前延迟"}),a.jsx("span",{children:Hm((ge=Kt.data)==null?void 0:ge.latencyMs)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近探测"}),a.jsx("span",{children:Mu((gn=Kt.data)==null?void 0:gn.checkedAt)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"设备标识"}),a.jsx("span",{children:(Xe==null?void 0:Xe.id)??"未选择节点"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近会话"}),a.jsx("span",{children:ht??"未选择会话"})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"延迟对比"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"Hub 延迟"}),a.jsx("span",{children:Hm((ta=Kt.data)==null?void 0:ta.hubProbe.latencyMs)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"Hub 状态"}),a.jsx("span",{className:(xo=Kt.data)!=null&&xo.hubProbe.healthOk?"is-ok":"is-muted",children:(xa=Kt.data)!=null&&xa.hubProbe.healthOk?"在线":((na=Kt.data)==null?void 0:na.hubProbe.error)??"无法连接"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"Hub 地址"}),a.jsx("span",{children:((sn=Kt.data)==null?void 0:sn.hubProbe.url)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 Agent 延迟"}),a.jsx("span",{children:Hm((yr=(ri=Kt.data)==null?void 0:ri.agentProbe)==null?void 0:yr.latencyMs)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 Agent 状态"}),a.jsx("span",{className:(Dc=(So=Kt.data)==null?void 0:So.agentProbe)!=null&&Dc.healthOk?"is-ok":"is-muted",children:(jo=Kt.data)!=null&&jo.agentProbe?Kt.data.agentProbe.healthOk?"在线":Kt.data.agentProbe.error??"无法连接":"未选择节点"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 Agent 地址"}),a.jsx("span",{children:((wo=(ki=Kt.data)==null?void 0:ki.agentProbe)==null?void 0:wo.url)||tn||"未配置"})]})]})]})},gr=()=>{const C=Le?"原生 APK":le?"已安装":"未安装",W=k==="granted"?"已允许":k==="denied"?"已拒绝":k==="default"?"待授权":"不支持",He=Le?k==="granted"?"原生通知":"等待授权":Q?G?"同步中":F?"已连接":P.completionNotificationsEnabled&&k==="granted"?"待连接":"未连接":"不支持",tt=Le?k==="granted"?"已开启":"待授权":k==="granted"&&P.completionNotificationsEnabled?F?"后台可达":Q?"前台兜底":"仅前台":"未开启",Rt=Le?"原生系统通知":Q?F?"Hub Web Push + 系统通知":"系统通知,后台通道待建立":"系统通知(仅页面在线)",ct=Le?k==="granted"?"通常可见,细节取决于系统设置":"先授予通知权限":F?le?"已具备条件":"大多可见,安装后更稳":Q?"先建立后台通道":"当前环境很难稳定锁屏提醒",Nt=k==="unsupported"||!Le&&G,Yn=Le?k==="granted"?"系统通知已开启":"申请通知权限":k==="granted"&&P.completionNotificationsEnabled?"关闭完成提醒":G?"正在建立后台提醒":"开启完成提醒",Kn=k==="unsupported"?"当前环境不支持系统通知,需要 HTTPS、Service Worker 和受支持浏览器。":Le?k==="granted"?"首次连接时也会自动申请;这里主要用于补检查权限状态。":"如果首次连接时错过了授权,这里可以补申请一次。":Q?"开启后会向 Hub 注册这台设备,后台或锁屏时也能收到完成提醒。":"当前环境只能在页面在线时提醒,建议安装到桌面并使用支持 Web Push 的浏览器。",Ya=Le?k==="unsupported"?"不可用":k==="granted"?"已开启":"→":k==="unsupported"?"不可用":G?"同步中…":k==="granted"&&P.completionNotificationsEnabled?F?"已连接":Q?"待连接":"已开启":"→",Ra=Le?k==="granted":k==="granted"&&P.completionNotificationsEnabled&&F&&!G,ii=Le?"直接在当前 APK 里发一条本地测试通知,确认系统权限和展示链路正常。":F?"立刻让 Hub 给当前这台设备发一条测试通知,用来确认后台链路是否真的可达。":"只有当前设备已经完成 Web Push 注册后,才能发送测试通知。";return a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"安卓优先提醒"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"桌面安装"}),a.jsx("strong",{children:C})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"系统通知权限"}),a.jsx("strong",{children:W})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"完成提醒"}),a.jsx("strong",{children:tt})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"后台 Web Push"}),a.jsx("strong",{children:He})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:Le?"当前交付形态":"安装到桌面"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"推荐平台"}),a.jsx("span",{children:Le?"当前已经是 Android APK":ye?"Android 当前设备":"Android 效果最佳"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前形态"}),a.jsx("span",{children:Le?"本地前端壳 + 局域网后端":le?"已是桌面应用":"浏览器标签页"})]}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void ua(),disabled:Le||le||R,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:Le?"已经是可安装 APK":le?"已经安装":"安装到桌面"}),a.jsx("span",{children:Le?"当前无需再走 PWA 安装链路,后续升级直接下载新版 APK 覆盖安装即可。":le?"现在可以直接从桌面图标进入 Panda。":"安装后更像应用,系统通知和锁屏提醒也更稳定。"})]}),a.jsx("span",{className:"settings-action__state",children:Le||le?"✓":R?"处理中…":"→"})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"对话完成提醒"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"提醒方式"}),a.jsx("span",{children:Rt})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"锁屏可见"}),a.jsx("span",{children:ct})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"后台通道"}),a.jsx("span",{children:He})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"触发时机"}),a.jsx("span",{children:Le?"App 在线时收到完成事件后,直接发原生系统通知":Q?"Hub 收到对话完成后主动推送":"页面在线时收到完成事件后提醒"})]}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Fs(),disabled:Nt,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:Yn}),a.jsx("span",{children:Kn})]}),a.jsx("span",{className:"settings-action__state",children:Ya})]}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Js(),disabled:!Ra||ae,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:Le?ae?"正在发送测试通知":"发送测试通知":ae?"正在发送测试推送":"发送测试推送"}),a.jsx("span",{children:ii})]}),a.jsx("span",{className:"settings-action__state",children:ae?"发送中…":Ra?"→":"未就绪"})]}),b?a.jsx("p",{className:"settings-block__status",children:b}):null]})]})},wi=()=>{const C=Wn.data,W=C!=null&&C.promptState.installPromptAvailable?"可主动触发":C!=null&&C.promptState.beforeInstallPromptSeen?"本地曾出现":"未出现",He=C!=null&&C.promptState.appInstalledSeen?"记录到过":"未记录到",tt=C!=null&&C.manifest.ok?"正常":C!=null&&C.manifest.present?"读取失败":"缺失",Rt=C!=null&&C.serviceWorker.registrations.length?`${C.serviceWorker.registrations.length} 个注册`:C!=null&&C.serviceWorker.supported?"未注册":"不支持";return a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"安装结果判断"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前研判"}),a.jsx("strong",{children:(C==null?void 0:C.assessment.label)??"检测中…"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"安装事件"}),a.jsx("strong",{children:W})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"appinstalled"}),a.jsx("strong",{children:He})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"当前状态"})}),a.jsxs("div",{className:"settings-actions-row",children:[a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{Wn.refetch()},children:"刷新诊断"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>{dM(),Ot()},children:"清空日志"})]})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前窗口形态"}),a.jsx("span",{children:C?C.environment.standaloneDisplayMode||C.environment.navigatorStandalone?"独立窗口 / 主屏幕入口":"浏览器标签页":"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"系统级安装研判"}),a.jsx("span",{children:(C==null?void 0:C.assessment.label)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"研判置信度"}),a.jsx("span",{children:(C==null?void 0:C.assessment.confidence)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前说明"}),a.jsx("span",{children:(C==null?void 0:C.assessment.detail)??"正在分析…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近抓取时间"}),a.jsx("span",{children:Mu(C==null?void 0:C.capturedAt)})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"PWA 条件与安装信号"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"安全上下文"}),a.jsx("span",{children:C!=null&&C.environment.secureContext?"是":"否"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"manifest"}),a.jsx("span",{children:tt})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"manifest display"}),a.jsx("span",{children:(C==null?void 0:C.manifest.display)??"未声明"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"Service Worker"}),a.jsx("span",{children:Rt})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前可主动触发安装"}),a.jsx("span",{children:C!=null&&C.promptState.installPromptAvailable?"可以":"不可以"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近 beforeinstallprompt"}),a.jsx("span",{children:Mu(C==null?void 0:C.promptState.lastBeforeInstallPromptAt)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近 appinstalled"}),a.jsx("span",{children:Mu(C==null?void 0:C.promptState.lastAppInstalledAt)})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"为什么当前可能安装失败"})})}),Wn.isLoading?a.jsx("p",{className:"settings-block__status",children:"正在收集安装诊断…"}):C!=null&&C.failureReasons.length?a.jsx("div",{className:"settings-diagnostic-list",children:C.failureReasons.map((ct,Nt)=>a.jsxs("div",{className:"settings-diagnostic-list__item",children:[a.jsxs("strong",{children:["原因 ",Nt+1]}),a.jsx("span",{children:ct})]},`${Nt}-${ct}`))}):a.jsx("p",{className:"settings-block__status",children:"当前没有发现明显的前端侧阻断条件;如果仍无法完成系统级安装,更像是浏览器策略、安装链路回退或平台侧判断导致。"})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"成功信号与人工确认"})})}),C!=null&&C.successSignals.length?a.jsx("div",{className:"settings-diagnostic-list",children:C.successSignals.map((ct,Nt)=>a.jsxs("div",{className:"settings-diagnostic-list__item",children:[a.jsxs("strong",{children:["信号 ",Nt+1]}),a.jsx("span",{children:ct})]},`${Nt}-${ct}`))}):null,a.jsx("div",{className:"settings-diagnostic-list",children:(C==null?void 0:C.confirmationChecklist.map((ct,Nt)=>a.jsxs("div",{className:"settings-diagnostic-list__item",children:[a.jsxs("strong",{children:["确认 ",Nt+1]}),a.jsx("span",{children:ct})]},`${Nt}-${ct}`)))??null})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"浏览器安装事件日志"})})}),Wn.isLoading?a.jsx("p",{className:"settings-block__status",children:"正在读取日志…"}):C!=null&&C.logs.length?a.jsx("div",{className:"settings-log-list",children:C.logs.map(ct=>a.jsxs("article",{className:"settings-log-item",children:[a.jsxs("div",{className:"settings-log-item__meta",children:[a.jsx("strong",{children:ct.message}),a.jsx("span",{children:Mu(ct.timestamp)})]}),a.jsx("div",{className:"settings-log-item__kind",children:ct.kind}),ct.detail?a.jsx("pre",{className:"settings-log-item__detail",children:ct.detail}):null]},ct.id))}):a.jsx("p",{className:"settings-block__status",children:"还没有本地安装日志。后续在这个页面触发安装、刷新页面、出现 beforeinstallprompt 或 appinstalled 后,这里会自动积累证据。"})]})]})},Ni=C=>C==="models"?Ma():C==="image"?Wi():C==="cache"?ji():C==="notifications"?gr():C==="installation"?wi():C==="connection"?Qa():C==="dev-manager"?a.jsx(RT,{isActive:v==="dev-manager"||N==="dev-manager",agentId:(Xe==null?void 0:Xe.id)??null}):qi();return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"conversation-page settings-screen settings-screen--workspace",style:Cs,children:a.jsx("div",{className:"conversation-main settings-screen__main settings-screen__workspace-main",children:a.jsx("div",{className:"settings-screen__body",children:a.jsxs("div",{className:"settings-shell",children:[a.jsxs("header",{className:"settings-page-header",children:[a.jsx("button",{type:"button",className:"settings-card__back",onClick:js,"aria-label":"返回会话",children:a.jsx(AM,{})}),a.jsx("div",{className:"settings-page-header__copy",children:a.jsx("h1",{className:"settings-page-header__title",children:"设置"})})]}),T?a.jsxs("div",{className:"settings-workspace",children:[a.jsxs("aside",{className:"settings-sidebar",children:[a.jsx("div",{className:"settings-sidebar__title",children:"设置"}),a.jsx("nav",{className:"settings-sidebar__nav","aria-label":"设置导航",children:Bm.map(C=>{const W=C.id===v;return a.jsxs("button",{type:"button",className:`settings-sidebar__item ${W?"is-active":""}`,onClick:()=>w(C.id),children:[a.jsx(G4,{icon:C.icon}),a.jsx("span",{children:C.title})]},C.id)})})]}),a.jsxs("main",{className:"settings-stage",children:[a.jsx("header",{className:"settings-stage__header",children:a.jsxs("div",{children:[a.jsx("h2",{className:"settings-stage__title",children:is.title}),a.jsx("p",{className:"settings-stage__description",children:is.description})]})}),Ni(v)]})]}):Fi()]})})})}),ea]})},HM=({onClose:e})=>{const t=_.useRef(null);return _.useEffect(()=>{var u;if(typeof document>"u")return;const i=document.documentElement.style.overflow,r=document.body.style.overflow;document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",(u=t.current)==null||u.focus();const o=d=>{d.key==="Escape"&&(d.preventDefault(),e())};return window.addEventListener("keydown",o),()=>{window.removeEventListener("keydown",o),document.documentElement.style.overflow=i,document.body.style.overflow=r}},[e]),a.jsx("div",{ref:t,className:"settings-overlay",role:"dialog","aria-modal":"true","aria-label":"设置",tabIndex:-1,children:a.jsx(J3,{mode:"overlay",onRequestClose:e})})},FM=()=>{const e=Hi();Zp();const t=qa(p=>p.themeSettings),i=qa(p=>p.systemAppearance),r=qa(p=>p.setSystemAppearance),o=qa(p=>p.isSettingsOverlayOpen),u=qa(p=>p.closeSettingsOverlay),d=ai({select:p=>p.location.pathname}),m=_.useRef(null),y=vo(),g=kh(y),b=!!(y&&g);return _.useEffect(()=>{G3(t,i)},[i,t]),_.useEffect(()=>rM(r),[r]),_.useEffect(()=>{Y0().catch(()=>{})},[]),_.useEffect(()=>{let p;return rC(v=>{e({to:v}).catch(()=>{typeof window<"u"&&window.location.assign(v)})}).then(v=>{p=v}),()=>{p==null||p()}},[e]),_.useEffect(()=>{if(!o){m.current=null;return}if(m.current===null){m.current=d;return}d!==m.current&&u()},[u,o,d]),LE()?a.jsx(pC,{}):a.jsxs("div",{className:"app-shell",children:[b?null:a.jsx(xC,{}),a.jsx(zC,{}),a.jsx("div",{className:"app-shell__content","aria-hidden":o,children:a.jsx(F2,{})}),o?a.jsx(HM,{onClose:u}):null]})},Y1=({message:e})=>a.jsx("p",{className:"empty-copy",children:e}),qM=async e=>(await cn()).client.updateAgent({agentId:e.agentId,action:e.action,displayName:e.displayName??null}),WM=(e,t,i)=>e&&{...e,agents:e.agents.map(r=>r.id===t?{...r,...i}:r)},KM=(e,t)=>e&&{...e,agents:e.agents.filter(i=>i.id!==t)},QM=()=>{var R,X;const e=Hi(),t=Ka(),{data:i,isPending:r,isFetching:o,error:u}=oy(),[d,m]=_.useState(!1),[y,g]=_.useState(null),[b,p]=_.useState(""),[v,w]=_.useState(null),[N,j]=_.useState(null),[T,M]=_.useState(null),[P,I]=_.useState(null),[k,O]=_.useState(!1),Q=i??T,J=(Q==null?void 0:Q.agents)??[];_.useEffect(()=>{let le=!1;return cn().then(ue=>{le||m(ue.mode==="hub")}).catch(()=>{le||m(!1)}),()=>{le=!0}},[]),_.useEffect(()=>{i&&(M(i),I(null))},[i]),_.useEffect(()=>{if(i||k)return;let le=!1;const ue=window.setTimeout(()=>{le||(O(!0),I(null),t.removeQueries({queryKey:lr}),y3(t).then(ye=>{le||M(ye)}).catch(ye=>{le||I(ye instanceof Error?ye.message:"节点列表刷新失败")}).finally(()=>{le||O(!1)}))},1200);return()=>{le=!0,window.clearTimeout(ue)}},[t,i,k]);const F=_.useMemo(()=>J.find(le=>le.id===y)??null,[J,y]),B=_.useMemo(()=>J.find(le=>le.id===v)??null,[J,v]),G=Gn({mutationFn:qM,onMutate:async le=>{j(null),await t.cancelQueries({queryKey:lr});const ue=t.getQueryData(lr);return le.action==="rename"&&t.setQueryData(lr,ye=>{var D;return WM(ye,le.agentId,{display_name:((D=le.displayName)==null?void 0:D.trim())||null})}),le.action==="delete"&&t.setQueryData(lr,ye=>KM(ye,le.agentId)),{previousSnapshot:ue}},onSuccess:(le,ue)=>{ue.action==="rename"&&(g(null),p("")),ue.action==="delete"&&w(null)},onError:(le,ue,ye)=>{ye!=null&&ye.previousSnapshot&&t.setQueryData(lr,ye.previousSnapshot),j(le instanceof Error?le.message:"节点操作失败")},onSettled:async()=>{await t.invalidateQueries({queryKey:lr})}}),Z=G.isPending?((R=G.variables)==null?void 0:R.action)??null:null,ae=G.isPending?((X=G.variables)==null?void 0:X.agentId)??null:null,he=le=>{fr(le.id),Ea(null),sl(null),Hu(null),Hf(!1),xE({agentId:le.id,name:le.name,displayName:le.display_name??null,directBaseUrl:le.direct_base_url,wsBaseUrl:le.ws_base_url,createdAt:new Date().toISOString()}),e({to:"/"})},ne=F&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{g(null),p(""),j(null)},"aria-label":"关闭节点备注面板"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered node-sheet",children:[a.jsx("div",{className:"node-sheet__eyebrow",children:"节点备注"}),a.jsx("div",{className:"sheet-panel__title",children:"修改显示名称"}),a.jsx("p",{className:"node-sheet__description",children:"留空后会恢复显示为原始节点名。"}),a.jsxs("div",{className:"node-sheet__meta",children:[a.jsx("span",{children:F.name}),a.jsx("span",{children:z1(F)})]}),a.jsx("input",{className:"sheet-panel__input",value:b,onChange:le=>p(le.target.value),placeholder:F.name,autoFocus:!0}),N?a.jsx("p",{className:"error-text",children:N}):null,a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{g(null),p(""),j(null)},children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:Z==="rename"&&ae===F.id,onClick:()=>{G.mutate({agentId:F.id,action:"rename",displayName:b.trim()||null})},children:Z==="rename"&&ae===F.id?"保存中...":"保存"})]})]})})]}),document.body):null,Ce=B&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{w(null),j(null)},"aria-label":"关闭删除节点面板"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered node-sheet node-sheet--danger",children:[a.jsx("div",{className:"node-sheet__eyebrow is-danger",children:"删除注册"}),a.jsx("div",{className:"sheet-panel__title",children:"确认移除这个节点?"}),a.jsx("p",{className:"node-sheet__description",children:"这只会删除当前 Hub 里的注册记录,不会删除远端机器。agent 重新注册后可以再次加入。"}),a.jsxs("div",{className:"node-sheet__meta",children:[a.jsx("span",{children:Cc(B)}),a.jsx("span",{children:z1(B)})]}),N?a.jsx("p",{className:"error-text",children:N}):null,a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{w(null),j(null)},children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button node-sheet__button-danger",disabled:Z==="delete"&&ae===B.id,onClick:()=>{G.mutate({agentId:B.id,action:"delete"})},children:Z==="delete"&&ae===B.id?"删除中...":"确认删除"})]})]})})]}),document.body):null;return a.jsxs("div",{className:"nodes-screen",children:[a.jsxs("div",{className:"nodes-screen__header",children:[a.jsx("h1",{children:"节点列表"}),a.jsx("p",{children:"查看所有在线节点和局域网地址"})]}),a.jsx("div",{className:"nodes-screen__content node-list",children:!Q&&(r||o||k)?a.jsx(Y1,{message:"正在读取节点列表..."}):!Q&&(u||P)?a.jsx(Y1,{message:u instanceof Error?u.message:P??"节点列表加载失败"}):J.length===0?a.jsx(Y1,{message:"暂无节点"}):J.map(le=>{const ue=fE(le),ye=Cc(le),D=Z==="rename"&&ae===le.id,oe=Z==="delete"&&ae===le.id;return a.jsxs("article",{className:`node-card ${d?"node-card--manageable":""}`,children:[a.jsxs("button",{type:"button",className:"node-card__surface",onClick:()=>he(le),children:[a.jsxs("div",{className:"node-card__title-stack",children:[a.jsx("strong",{children:ye}),ue?a.jsxs("span",{className:"node-card__secondary-name",children:["原名称 · ",ue]}):null]}),a.jsx("div",{className:"node-card__ip",children:z1(le)})]}),a.jsxs("div",{className:"node-card__rail",children:[a.jsx("span",{className:`node-status-dot ${le.status}`,"aria-label":le.status==="online"?"节点在线":"节点离线",title:le.status==="online"?"节点在线":"节点离线"}),d?a.jsxs("div",{className:"node-card__actions",children:[a.jsx("button",{type:"button",className:"node-card__icon-button","aria-label":`修改 ${ye} 的备注名称`,title:"修改备注名称",disabled:oe,onClick:()=>{w(null),j(null),g(le.id),p(le.display_name??"")},children:a.jsx(fh,{size:16,strokeWidth:2})}),a.jsx("button",{type:"button",className:"node-card__icon-button is-danger","aria-label":`删除 ${ye} 节点注册`,title:"删除注册节点",disabled:D,onClick:()=>{g(null),p(""),j(null),w(le.id)},children:a.jsx($p,{size:16,strokeWidth:2})})]}):null]})]},le.id)})}),ne,Ce]})};function GM(e){return cs({queryKey:(e==null?void 0:e.queryKey)??_C,queryFn:async()=>(await cn(e==null?void 0:e.scope)).client.getPhaseOneSnapshot({fallbackToMock:!1}),refetchInterval:3e5,refetchOnWindowFocus:!1,retry:1})}const YM=(e,t)=>{for(const[,i]of e){const r=i==null?void 0:i.sessions.find(o=>o.id===t);if(r!=null&&r.agent_id)return r.agent_id}return null},VM=()=>{var y,g;const{sessionId:e}=Mc({strict:!1}),t=Hi(),i=Ka(),r=W0(e),o=GM({queryKey:["session-route-bridge",e??""]}),u=e?YM(i.getQueriesData({queryKey:hs}),e):null,d=e?((g=(y=o.data)==null?void 0:y.sessions.find(b=>b.id===e))==null?void 0:g.agent_id)??null:null,m=(r==null?void 0:r.agentId)??u??d??vo();return _.useEffect(()=>{if(!e){t({to:"/",replace:!0});return}!m&&(o.isPending||o.isFetching)||(Ea(e),sl(e),m&&fr(m),t({to:"/",replace:!0}))},[t,m,e,o.isFetching,o.isPending]),null},XM=(e,t)=>e==="offline"?"offline":e==="online"&&t==="connected"?"online":e==="online"?"reconnecting":"offline",ZM=e=>{switch(e){case"online":return"节点在线";case"reconnecting":return"节点重连中";case"offline":return"节点离线";default:return"节点状态未知"}},Gr="__chat_only__",Fm=e=>e===Gr;function e5(e){return cs(_3(e))}const JM=24,gh="__projectless__",al={sessions:[],nextCursor:null,totalCount:0,isLoading:!1,error:null,initialized:!1},t5=e=>e.trim(),eR=e=>[...e].sort((t,i)=>Number(i.pinned)-Number(t.pinned)||+new Date(i.last_event_at)-+new Date(t.last_event_at)),tR=(e,t)=>{const i=new Map;for(const r of e)i.set(r.id,r);for(const r of t)i.set(r.id,r);return eR([...i.values()])},qm=(e,t)=>e[t5(t)]??al;function n5(e){var p,v,w;const[t,i]=_.useState({}),[r,o]=_.useState({}),u=_.useCallback(()=>{i({}),o({})},[]);_.useEffect(()=>{u()},[(p=e==null?void 0:e.scope)==null?void 0:p.agentId,(v=e==null?void 0:e.scope)==null?void 0:v.projectId,(w=e==null?void 0:e.scope)==null?void 0:w.sessionId,e==null?void 0:e.selectedSessionId,u]);const d=_.useCallback(async(N,j)=>{var O;const T=((O=j.projectId)==null?void 0:O.trim())??"",M=j.projectless===!0,P=M?gh:t5(T);if(!P)return;const I=N==="history"?i:o,k=qm(N==="history"?t:r,P);if(!k.isLoading&&!(k.initialized&&k.nextCursor===null)){I(Q=>({...Q,[P]:{...qm(Q,P),isLoading:!0,error:null}}));try{const J=await(await cn(e==null?void 0:e.scope)).client.getWorkspaceSessionPage({bucket:N,projectId:M?null:P,projectless:M,cursor:k.initialized?k.nextCursor:null,limit:JM,selectedSessionId:(e==null?void 0:e.selectedSessionId)??null});I(F=>{const B=qm(F,P);return{...F,[P]:{sessions:tR(B.sessions,J.sessions),nextCursor:J.next_cursor,totalCount:J.total_count,isLoading:!1,error:null,initialized:!0}}})}catch(Q){I(J=>({...J,[P]:{...qm(J,P),isLoading:!1,error:Q instanceof Error?Q.message:"加载会话分页失败",initialized:!0}}))}}},[r,t,e==null?void 0:e.scope,e==null?void 0:e.selectedSessionId]),m=_.useCallback(async N=>{await d("history",{projectId:N})},[d]),y=_.useCallback(async()=>{await d("history",{projectless:!0})},[d]),g=_.useCallback(async N=>{await d("archived",{projectId:N})},[d]),b=_.useCallback(async()=>{await d("archived",{projectless:!0})},[d]);return{historyState:t,archivedState:r,loadMoreHistory:m,loadMoreProjectlessHistory:y,loadMoreArchived:g,loadMoreProjectlessArchived:b,reset:u}}const nR=180*1e3,rc=6,s5="panda:completed-session-seen-at",V1=6,sR=220,X1="__chat__",Z1="__image__",Wm=e=>{e.cancelable&&e.preventDefault()},Z4=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.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"})}),J4=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:a.jsx("path",{d:"M12 5v14M5 12h14"})}),aR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{x:"3",y:"4",width:"6",height:"6",rx:"1.5"}),a.jsx("rect",{x:"15",y:"4",width:"6",height:"6",rx:"1.5"}),a.jsx("rect",{x:"3",y:"14",width:"6",height:"6",rx:"1.5"}),a.jsx("rect",{x:"15",y:"14",width:"6",height:"6",rx:"1.5"})]}),ex=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"M5 6.5A2.5 2.5 0 0 1 7.5 4h9A2.5 2.5 0 0 1 19 6.5v6A2.5 2.5 0 0 1 16.5 15H11l-4.5 4v-4H7.5A2.5 2.5 0 0 1 5 12.5z"})}),iR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2.5"}),a.jsx("circle",{cx:"9",cy:"10",r:"1.4"}),a.jsx("path",{d:"m7 16 3.5-3.5 2.5 2.5 2-2 2.5 3"})]}),rR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.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"}),a.jsx("path",{d:"M16.5 10.5v5"}),a.jsx("path",{d:"M14 13h5"})]}),tx=({open:e})=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",className:e?"is-open":"",children:a.jsx("path",{d:"m9 6 6 6-6 6"})}),lR=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})}),oR=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m15 6-6 6 6 6"})}),cR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M10.33 4.32c.6-1.76 2.74-1.76 3.34 0a1.78 1.78 0 0 0 2.66 1l.18-.1c1.6-.92 3.4.88 2.48 2.48l-.1.18a1.78 1.78 0 0 0 1 2.66c1.76.6 1.76 2.74 0 3.34a1.78 1.78 0 0 0-1 2.66l.1.18c.92 1.6-.88 3.4-2.48 2.48l-.18-.1a1.78 1.78 0 0 0-2.66 1c-.6 1.76-2.74 1.76-3.34 0a1.78 1.78 0 0 0-2.66-1l-.18.1c-1.6.92-3.4-.88-2.48-2.48l.1-.18a1.78 1.78 0 0 0-1-2.66c-1.76-.6-1.76-2.74 0-3.34a1.78 1.78 0 0 0 1-2.66l-.1-.18c-.92-1.6.88-3.4 2.48-2.48l.18.1a1.78 1.78 0 0 0 2.66-1Z"}),a.jsx("circle",{cx:"12",cy:"12",r:"3.15"})]}),uR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("circle",{cx:"6",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"12",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"18",cy:"12",r:"1",fill:"currentColor",stroke:"none"})]}),dR=e=>{const t=Date.now(),i=new Date(e).getTime(),r=Math.max(0,t-i),o=60*1e3,u=60*o,d=24*u;return r<u?`${Math.max(1,Math.floor(r/o))}分钟`:r<d?`${Math.max(1,Math.floor(r/u))}小时`:`${Math.max(1,Math.floor(r/d))}天`},J1=e=>e.run_state==="completed"&&e.run_state_changed_at&&Date.now()-new Date(e.run_state_changed_at).getTime()>nR?"idle":e.run_state??"idle",nx=(e,t)=>Number(t.pinned)-Number(e.pinned)||+new Date(t.last_event_at)-+new Date(e.last_event_at),sx=(e,t)=>{if(e.length<=rc)return e;if(!t)return e.slice(0,rc);const i=e.findIndex(r=>r.id===t);return i===-1||i<rc?e.slice(0,rc):[...e.slice(0,rc-1),e[i]]},fR=()=>{if(typeof window>"u")return{};try{const e=window.localStorage.getItem(s5);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},e_=(e,t)=>e.length===t.length&&e.every((i,r)=>i===t[r]),hR=(e,t)=>{if(!t||t.length===0||e.length<=1)return e;const i=new Map(e.map(u=>[u.id,u])),r=new Set,o=[];for(const u of t){const d=i.get(u);!d||r.has(u)||(r.add(u),o.push(d))}for(const u of e)r.has(u.id)||o.push(u);return o},mR=(e,t,i)=>{if(t<0||t>=e.length||i<0||i>=e.length||t===i)return e;const r=[...e],[o]=r.splice(t,1);return o?(r.splice(i,0,o),r):e},pR=(e,t,i)=>{if(t.length===0)return e;const r=new Set(t);let o=0;return e.map(u=>{if(!r.has(u))return u;const d=i[o]??u;return o+=1,d})},Ru=(e,t)=>`${e}:${t}`,a5=_.memo(function({open:t,progress:i=t?1:0,isDragging:r=!1,desktopPinned:o=!1,isDesktopResizing:u=!1,onClose:d,onDesktopResizeStart:m,currentAgent:y,agentIndicatorState:g,projects:b,sessions:p,projectStats:v=[],historySessionsByProject:w={},archivedSessionsByProject:N={},chatHistorySessions:j=[],chatArchivedSessions:T=[],historyPageStateByProject:M={},archivedPageStateByProject:P={},chatHistoryPageState:I=al,chatArchivedPageState:k=al,activeSessionId:O,onCreateSession:Q,onCreateChat:J,onCreateImageSession:F,onCreateDirectoryThread:B,onSelectSession:G,onSessionAction:Z,onThreadAction:ae,onOpenSettings:he,onLoadMoreHistory:ne,onLoadMoreChatHistory:Ce,onLoadMoreArchived:R,onLoadMoreChatArchived:X,pendingSessionActionId:le,pendingThreadActionId:ue}){const ye=Hi(),D=i>.001,oe=!!y,je=oe?g??((y==null?void 0:y.status)==="online"?"online":"offline"):null,z=je?ZM(je):"未选择节点",be=_.useRef({threads:null,archived:null}),De=_.useRef({}),se=_.useRef(null),pe=_.useRef(null),ke=_.useRef(null),Ze=_.useRef(null),zt=_.useRef(null),Fe=_.useRef({}),kt=_.useRef(null),[Bt,Gt]=_.useState({}),[Xt,Ft]=_.useState(null),[qe,dt]=_.useState(null),un=_.useMemo(()=>p.map(U=>{const Ne=Bt[U.id];return Ne?{...U,...Ne.pinned===void 0?null:{pinned:Ne.pinned}}:U}).filter(U=>{var Ne;return!((Ne=Bt[U.id])!=null&&Ne.hidden)}),[Bt,p]),$t=_.useMemo(()=>new Map(v.map(U=>[U.project_id,U])),[v]),An=(qe==null?void 0:qe.nextGlobalProjectIds)??Xt,Nn=_.useMemo(()=>hR(b,An),[b,An]),Tt=_.useMemo(()=>un.filter(U=>!U.subagent),[un]),lt=Tt.find(U=>U.id===O),Et=lt==null?void 0:lt.project_id,rt=lt?lt.project_id||(lt.provider==="image"?Z1:X1):"",[st,Dt]=_.useState(rt?[rt]:[]),[an,re]=_.useState("threads"),[we,Re]=_.useState(null),[te,ve]=_.useState(null),[V,q]=_.useState(null),[de,ce]=_.useState(null),[Ae,Ee]=_.useState([]),[$e,Pe]=_.useState(null),[ht,Xe]=_.useState(""),[tn,Le]=_.useState(()=>fR()),rn=_.useMemo(()=>Tt.filter(U=>!U.archived),[Tt]),hn=_.useMemo(()=>rn.filter(U=>U.pinned).sort((U,Ne)=>+new Date(Ne.last_event_at)-+new Date(U.last_event_at)),[rn]),ns=_.useMemo(()=>rn.filter(U=>!U.pinned&&U.project_id.trim().length>0&&U.provider!=="image"),[rn]),Xs=_.useMemo(()=>rn.filter(U=>!U.pinned&&U.project_id.trim().length===0&&U.provider!=="image"),[rn]),$s=_.useMemo(()=>rn.filter(U=>!U.pinned&&U.project_id.trim().length===0&&U.provider==="image"),[rn]),oa=U=>Nn.map(Ne=>{var St;const Ue=$t.get(Ne.id),Qe=U==="threads"?ns.filter(En=>En.project_id===Ne.id):N[Ne.id]??[],at=U==="threads"?w[Ne.id]??[]:[],Je=[...Qe];for(const En of at)Je.some(gt=>gt.id===En.id)||Je.push(En);const vt=Je.sort((En,gt)=>nx(En,gt)),ot=U==="threads"?M[Ne.id]??al:P[Ne.id]??al,nn=U==="threads"?vt.length+Math.max(0,(Ue==null?void 0:Ue.hidden_history_count)??0):Math.max(vt.length,(Ue==null?void 0:Ue.archived_session_count)??0),Jt=U==="threads"?Math.max(0,((Ue==null?void 0:Ue.hidden_history_count)??0)-ot.sessions.length):Math.max(0,((Ue==null?void 0:Ue.archived_session_count)??0)-ot.sessions.length),qt=((St=vt[0])==null?void 0:St.last_event_at)??new Date(0).toISOString();return{project:Ne,threadSessions:vt,collapsedThreadSessions:sx(vt,O),hiddenSessionCount:Math.max(0,vt.length-rc),totalSessionCount:nn,pageState:ot,remainingPageCount:Jt,latestEventAt:qt}}).filter(({totalSessionCount:Ne})=>Ne>0),On=_.useMemo(()=>oa("threads"),[O,P,N,M,w,Nn,$t,ns]),Ss=_.useMemo(()=>oa("archived"),[O,P,N,M,w,Nn,$t,ns]),Kt=(U,Ne)=>{const Ue=$t.get(""),Qe=U==="threads"?Ne==="image"?$s:Xs:T.filter(qt=>qt.provider===Ne),at=U==="threads"?j.filter(qt=>qt.provider===Ne):[],Je=[...Qe];for(const qt of at)Je.some(St=>St.id===qt.id)||Je.push(qt);const vt=Je.sort((qt,St)=>nx(qt,St)),ot=U==="threads"?I:k,nn=U==="threads"?vt.length+Math.max(0,(Ue==null?void 0:Ue.hidden_history_count)??0):Math.max(vt.length,(Ue==null?void 0:Ue.archived_session_count)??0),Jt=U==="threads"?Math.max(0,((Ue==null?void 0:Ue.hidden_history_count)??0)-ot.sessions.length):Math.max(0,((Ue==null?void 0:Ue.archived_session_count)??0)-ot.sessions.length);return{threadSessions:vt,collapsedThreadSessions:sx(vt,O),hiddenSessionCount:Math.max(0,vt.length-rc),totalSessionCount:nn,pageState:ot,remainingPageCount:Jt}},Zs=_.useMemo(()=>Kt("threads","codex"),[O,k,T,I,j,$t,Xs,$s]),us=_.useMemo(()=>Kt("archived","codex"),[O,k,T,I,j,$t,Xs,$s]),Ln=_.useMemo(()=>Kt("threads","image"),[O,k,T,I,j,$t,Xs,$s]),Ot=_.useMemo(()=>Kt("archived","image"),[O,k,T,I,j,$t,Xs,$s]);_.useEffect(()=>{Gt(U=>{let Ne=!1;const Ue={...U};for(const[Qe,at]of Object.entries(U)){const Je=p.find(ot=>ot.id===Qe);if(!Je){at.hidden&&(delete Ue[Qe],Ne=!0);continue}(at.pinned===void 0||Je.pinned===at.pinned)&&!at.hidden&&(delete Ue[Qe],Ne=!0)}return Ne?Ue:U})},[p]),_.useEffect(()=>{Ft(U=>{if(!U)return U;const Ne=b.map(Qe=>Qe.id),Ue=[...U.filter(Qe=>Ne.includes(Qe)),...Ne.filter(Qe=>!U.includes(Qe))];return e_(Ue,Ne)?null:Ue})},[b]),_.useEffect(()=>{rt&&Dt(U=>U.includes(rt)?U:[...U,rt])},[rt]),_.useEffect(()=>{re(lt!=null&<.archived?"archived":"threads")},[lt==null?void 0:lt.archived,O]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(s5,JSON.stringify(tn))}catch{}},[tn]),_.useEffect(()=>{t||o||(q(null),ce(null),Pe(null),ve(null))},[o,t]),_.useEffect(()=>{if(!o||!V)return;const U=Ne=>{const Ue=Ne.target;if(!(Ue instanceof Element)){q(null);return}Ue.closest(".thread-group__menu-anchor")||Ue.closest(".thread-group__menu")||q(null)};return window.addEventListener("pointerdown",U),()=>{window.removeEventListener("pointerdown",U)}},[o,V]),_.useEffect(()=>{if(!O)return;const U=Tt.find(Ue=>Ue.id===O);if(!U||J1(U)!=="completed"||!U.run_state_changed_at)return;const Ne=U.run_state_changed_at;Le(Ue=>Ue[U.id]===Ne?Ue:{...Ue,[U.id]:Ne})},[O,Tt]),_.useEffect(()=>()=>{se.current!==null&&globalThis.clearTimeout(se.current),Sn(),kt.current!==null&&window.cancelAnimationFrame(kt.current)},[]),_.useEffect(()=>{Ze.current=qe},[qe]),_.useLayoutEffect(()=>{if(typeof window>"u")return;const U={},Ne=[],Ue=qe?Ru(qe.pane,qe.projectId):null;for(const[Qe,at]of Object.entries(De.current)){if(!at)continue;const Je=at.offsetTop;if(U[Qe]=Je,Ue===Qe)continue;const vt=Fe.current[Qe];if(vt===void 0)continue;const ot=vt-Je;Math.abs(ot)<.5||(at.style.transition="none",at.style.transform=`translateY(${ot}px)`,Ne.push(at))}kt.current!==null&&window.cancelAnimationFrame(kt.current),Ne.length>0&&(kt.current=window.requestAnimationFrame(()=>{for(const Qe of Ne)Qe.style.transition="",Qe.style.transform=""})),Fe.current=U},[On,Ss,st,Ae,qe==null?void 0:qe.projectId,An]);const Wn=()=>{se.current!==null&&(globalThis.clearTimeout(se.current),se.current=null)},Sn=()=>{const U=ke.current;U&&(U.removeEventListener("selectstart",Wm),U.removeEventListener("contextmenu",Wm),ke.current=null)},Jn=U=>U==="threads"?On:Ss,js=(U,Ne,Ue,Qe,at)=>{const Je=be.current[Ne],vt=De.current[Ru(Ne,U)];if(!Je||!vt)return!1;const ot=Jn(Ne).map(is=>is.project.id),nn=ot.indexOf(U);if(nn===-1)return!1;const Jt=Nn.map(is=>is.id),qt=Je.getBoundingClientRect(),St=vt.getBoundingClientRect(),En=vt.offsetHeight,gt=vt.offsetWidth,ss=at-St.top,Ns=Je.scrollTop,ks=Math.max(Ns,Je.scrollTop+Je.clientHeight-En),as=Math.max(Ns,Math.min(ks,Je.scrollTop+at-qt.top-ss)),Es={pane:Ne,projectId:U,pointerId:Ue,pointerType:Qe,originIndex:nn,visibleProjectIds:ot,nextVisibleProjectIds:ot,nextGlobalProjectIds:Jt,previewTop:as,itemHeight:En,itemWidth:gt,pointerOffsetY:ss};return Ze.current=Es,dt(Es),zt.current=U,!0},Hs=U=>{dt(Ne=>{if(!Ne)return Ne;Ze.current=Ne;const Ue=be.current[Ne.pane];if(!Ue||!De.current[Ru(Ne.pane,Ne.projectId)])return Ne;const Qe=Ue.getBoundingClientRect(),at=Ue.scrollTop,Je=Math.max(at,Ue.scrollTop+Ue.clientHeight-Ne.itemHeight),vt=Math.max(at,Math.min(Je,Ue.scrollTop+U-Qe.top-Ne.pointerOffsetY)),ot=vt+Ne.itemHeight/2,nn=Ne.nextVisibleProjectIds,Jt=nn.indexOf(Ne.projectId);if(Jt===-1)return Ne;const qt=nn.filter(as=>as!==Ne.projectId);let St=0;const En=qt[0],gt=En?De.current[Ru(Ne.pane,En)]:null;if(gt&&vt<=gt.offsetTop+gt.offsetHeight*.42)St=0;else for(let as=0;as<qt.length;as+=1){const Es=qt[as],is=Es?De.current[Ru(Ne.pane,Es)]:null;if(!is){St=as+1;continue}const Cs=is.offsetTop+is.offsetHeight/2;if(ot<=Cs){St=as;break}St=as+1}const ss=mR(nn,Jt,St),Ns=pR(Ne.nextGlobalProjectIds,Ne.visibleProjectIds,ss);if(vt===Ne.previewTop&&e_(ss,Ne.nextVisibleProjectIds))return Ne;const ks={...Ne,previewTop:vt,nextVisibleProjectIds:ss,nextGlobalProjectIds:Ns};return Ze.current=ks,ks})},ca=U=>{Wn(),Sn(),pe.current=null;const Ne=U??Ze.current;if(Ze.current=null,dt(null),!Ne||!!e_(Ne.visibleProjectIds,Ne.nextVisibleProjectIds)||!ae)return;const Qe=Xt??Nn.map(Je=>Je.id),at=Ne.nextGlobalProjectIds;Ft(at),Promise.resolve(ae(Ne.projectId,"reorder",{orderedProjectIds:at})).catch(()=>{Ft(Qe)})},Fs=()=>{Wn(),Sn(),pe.current=null,Ze.current=null,dt(null)};_.useEffect(()=>{if(typeof window>"u"||!Ze.current)return;const U=Qe=>{const at=Ze.current;!at||at.pointerId!==Qe.pointerId||Hs(Qe.clientY)},Ne=Qe=>{const at=Ze.current;!at||at.pointerId!==Qe.pointerId||ca(at)},Ue=Qe=>{const at=Ze.current;!at||at.pointerId!==Qe.pointerId||Fs()};return window.addEventListener("pointermove",U),window.addEventListener("pointerup",Ne),window.addEventListener("pointercancel",Ue),()=>{window.removeEventListener("pointermove",U),window.removeEventListener("pointerup",Ne),window.removeEventListener("pointercancel",Ue)}},[qe==null?void 0:qe.pointerId]);const Js=U=>{Dt(Ne=>Ne.includes(U)?Ne.filter(Ue=>Ue!==U):[...Ne,U])},ua=U=>{if(zt.current===U){zt.current=null;return}Js(U)},da=(U,Ne,Ue)=>{if(U.pointerType==="mouse"&&U.button!==0)return;Wn();const Qe=U.currentTarget;Sn(),U.pointerType==="touch"&&(ke.current=Qe,Qe.addEventListener("selectstart",Wm),Qe.addEventListener("contextmenu",Wm)),pe.current={pane:Ue,projectId:Ne,pointerId:U.pointerId,pointerType:U.pointerType,startX:U.clientX,startY:U.clientY,currentX:U.clientX,currentY:U.clientY},U.pointerType!=="touch"&&Qe.setPointerCapture(U.pointerId),U.pointerType==="touch"&&(se.current=globalThis.setTimeout(()=>{const at=pe.current;if(!at||at.projectId!==Ne||at.pointerId!==U.pointerId)return;Qe.hasPointerCapture(U.pointerId)||Qe.setPointerCapture(U.pointerId),js(Ne,Ue,U.pointerId,U.pointerType,at.currentY)&&Hs(at.currentY)},sR))},fa=(U,Ne,Ue)=>{const Qe=pe.current;if(!Qe||Qe.projectId!==Ne||Qe.pointerId!==U.pointerId||Qe.pane!==Ue)return;if(Qe.currentX=U.clientX,Qe.currentY=U.clientY,(qe==null?void 0:qe.projectId)===Ne&&qe.pointerId===U.pointerId){U.preventDefault(),Hs(U.clientY);return}const at=U.clientX-Qe.startX,Je=U.clientY-Qe.startY;if(Qe.pointerType==="touch"){(Math.abs(at)>V1||Math.abs(Je)>V1)&&Wn();return}Math.abs(Je)<V1||Math.abs(Je)<Math.abs(at)||!js(Ne,Ue,U.pointerId,U.pointerType,U.clientY)||(U.preventDefault(),Hs(U.clientY))},In=(U,Ne)=>{if(U.currentTarget.hasPointerCapture(U.pointerId)&&U.currentTarget.releasePointerCapture(U.pointerId),(qe==null?void 0:qe.projectId)===Ne&&qe.pointerId===U.pointerId){U.preventDefault(),ca();return}Wn(),Sn(),pe.current=null},ws=(U,Ne)=>{if(U.currentTarget.hasPointerCapture(U.pointerId)&&U.currentTarget.releasePointerCapture(U.pointerId),(qe==null?void 0:qe.projectId)===Ne&&qe.pointerId===U.pointerId){Fs();return}Wn(),Sn(),pe.current=null},Os=U=>{Ee(Ne=>Ne.includes(U)?Ne.filter(Ue=>Ue!==U):[...Ne,U])},ee=U=>{if(J1(U)!=="completed"||!U.run_state_changed_at)return;const Ne=U.run_state_changed_at;Le(Ue=>Ue[U.id]===Ne?Ue:{...Ue,[U.id]:Ne})},Ke=`translateX(-${(an==="threads"?0:1)*50}%)`,Lt=$e&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{Pe(null),Xe("")},"aria-label":"关闭重命名面板"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered",children:[a.jsx("div",{className:"sheet-panel__title",children:"编辑线程名称"}),a.jsx("input",{className:"sheet-panel__input",value:ht,onChange:U=>Xe(U.target.value),placeholder:"输入线程名称",autoFocus:!0}),a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{Pe(null),Xe("")},children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:!ht.trim()||ue===$e,onClick:()=>{Pt()},children:"保存"})]})]})})]}),document.body):null,Zt=U=>{q(null),ce(null),Pe(U.id),Xe(U.display_name??U.name)},Pt=async()=>{!$e||!ht.trim()||!ae||(await ae($e,"rename",{name:ht.trim()}),Pe(null),Xe(""))},At=(U,Ne,Ue)=>{if(!Z)return;const Qe=Bt[U.id];Ne==="pin"||Ne==="unpin"?Gt(Je=>({...Je,[U.id]:{...Je[U.id],pinned:Ne==="pin"}})):Ne==="delete"&&Gt(Je=>({...Je,[U.id]:{...Je[U.id],hidden:!0}}));const at=Z(U.id,Ne,Ue);at&&typeof at.then=="function"&&at.catch(()=>{Gt(Je=>{const vt={...Je};return Qe?vt[U.id]=Qe:delete vt[U.id],vt})})},mn=U=>{const Ne=J1(U),Ue=Ne==="completed"&&U.id!==O&&!!U.run_state_changed_at&&tn[U.id]!==U.run_state_changed_at,Qe=o&&we===U.id,at=!!Z&&Qe,Je=te===U.id,vt=o&&(at||Je);return a.jsxs("div",{className:`thread-session ${U.id===O?"is-active":""}`,onMouseEnter:()=>Re(U.id),onMouseLeave:()=>{Re(ot=>ot===U.id?null:ot),ve(ot=>ot===U.id?null:ot)},children:[a.jsx("button",{type:"button",className:`thread-session__icon-button ${at?"is-visible":""} ${U.pinned?"is-active":""}`,disabled:le===U.id,onClick:ot=>{ot.stopPropagation(),At(U,U.pinned?"unpin":"pin")},"aria-label":U.pinned?"取消置顶会话":"置顶会话",title:U.pinned?"取消置顶":"置顶",children:a.jsx(sT,{strokeWidth:U.pinned?2.1:1.95})}),a.jsxs("div",{className:"thread-session__row",children:[G?a.jsxs("button",{type:"button",className:"thread-session__link thread-session__link--button",title:U.title,onClick:()=>{ee(U),G(U.id),d()},children:[a.jsx("span",{className:`thread-session__status is-${Ue?"completed":Ne} ${Ue?"is-unread":""} ${vt?"is-hidden":""}`,"aria-hidden":"true"}),a.jsx("div",{className:"thread-session__title",children:U.title})]}):a.jsxs(bp,{to:"/session/$sessionId",params:{sessionId:U.id},title:U.title,onClick:()=>{ee(U),d()},className:"thread-session__link",children:[a.jsx("span",{className:`thread-session__status is-${Ue?"completed":Ne} ${Ue?"is-unread":""} ${vt?"is-hidden":""}`,"aria-hidden":"true"}),a.jsx("div",{className:"thread-session__title",children:U.title})]}),a.jsx("div",{className:"thread-session__meta",children:o&&Qe&&Z?Je?a.jsx("button",{type:"button",className:"thread-session__delete-confirm",disabled:le===U.id,onClick:ot=>{ot.stopPropagation(),At(U,"delete")},children:"确认"}):a.jsx("button",{type:"button",className:"thread-session__delete",disabled:le===U.id,onClick:ot=>{ot.stopPropagation(),ve(U.id)},"aria-label":`删除 ${U.title}`,children:a.jsx($p,{strokeWidth:1.95})}):a.jsx("span",{className:"thread-session__time",children:dR(U.last_event_at)})})]})]},U.id)},jn=({project:U,threadSessions:Ne,collapsedThreadSessions:Ue,hiddenSessionCount:Qe,totalSessionCount:at,pageState:Je,remainingPageCount:vt},ot)=>{const nn=Ru(ot,U.id),Jt=st.includes(U.id),qt=Ae.includes(U.id),St=U.display_name??U.name,En=!!ae&&o&&V===U.id,gt=!!ae&&de===U.id,ss=ot==="archived",Ns=qt?Ne:Ue,ks=Qe>0,as=vt>0,Es=ot==="threads"?ne:R,is=(qe==null?void 0:qe.projectId)===U.id&&qe.pane===ot,Cs=gt&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>ce(null),"aria-label":"关闭线程菜单"}),a.jsxs("div",{className:"sheet-panel",children:[a.jsx("div",{className:"sheet-panel__title",children:St}),a.jsx("button",{type:"button",className:"sheet-panel__item",onClick:()=>Zt(U),children:"编辑名称"}),a.jsx("button",{type:"button",className:"sheet-panel__item",disabled:ue===U.id,onClick:()=>{ae==null||ae(U.id,ss?"unarchive":"archive"),ce(null)},children:ss?"取消归档":"归档线程"}),a.jsx("button",{type:"button",className:"sheet-panel__item is-danger",disabled:ue===U.id,onClick:()=>{ae==null||ae(U.id,"remove"),ce(null)},children:"移除"})]})]}),document.body):null;return a.jsxs(_.Fragment,{children:[a.jsx("div",{ref:es=>{De.current[nn]=es},className:`thread-group-shell ${is?"is-drag-placeholder":""}`,children:a.jsxs("section",{className:"thread-group",children:[a.jsxs("div",{className:"thread-group__header",children:[a.jsxs("button",{type:"button",className:"thread-group__title",onClick:()=>ua(U.id),onPointerDown:es=>da(es,U.id,ot),onPointerMove:es=>fa(es,U.id,ot),onPointerUp:es=>In(es,U.id),onPointerCancel:es=>ws(es,U.id),"aria-expanded":Jt,title:St,children:[a.jsx("span",{className:"thread-group__chevron",children:a.jsx(tx,{open:Jt})}),a.jsx("span",{className:"thread-group__icon",children:a.jsx(Z4,{})}),a.jsx("span",{className:"thread-group__title-text",children:St})]}),a.jsxs("div",{className:"thread-group__actions",children:[ae?a.jsxs("div",{className:"thread-group__menu-anchor",children:[a.jsx("button",{type:"button",className:`thread-group__more ${En||gt?"is-open":""}`,onClick:es=>{if(es.stopPropagation(),o){q(qs=>qs===U.id?null:U.id);return}ce(U.id)},"aria-label":`${St} 更多选项`,children:a.jsx(uR,{})}),En?a.jsxs("div",{className:"thread-group__menu",children:[a.jsx("button",{type:"button",className:"thread-group__menu-item",onClick:()=>Zt(U),children:"编辑名称"}),a.jsx("button",{type:"button",className:"thread-group__menu-item",disabled:ue===U.id,onClick:()=>{ae==null||ae(U.id,ss?"unarchive":"archive"),q(null)},children:ss?"取消归档":"归档线程"}),a.jsx("button",{type:"button",className:"thread-group__menu-item is-danger",disabled:ue===U.id,onClick:()=>{ae==null||ae(U.id,"remove"),q(null)},children:"移除"})]}):null]}):null,a.jsx("button",{type:"button",className:"thread-group__add",onClick:es=>{es.stopPropagation(),Q(U.id,U.name)},"aria-label":`在 ${U.name} 下新增会话`,children:a.jsx(J4,{})})]})]}),Jt?at===0?a.jsx("div",{className:"thread-group__empty",children:"这个线程还没有会话"}):a.jsxs(a.Fragment,{children:[Ns.length>0?a.jsx("div",{className:"thread-group__sessions",children:Ns.map(es=>mn(es))}):a.jsx("div",{className:"thread-group__empty",children:ot==="archived"?"这个归档线程还没有已加载的会话":"这个线程还没有已加载的历史会话"}),ks?a.jsx("button",{type:"button",className:"thread-group__session-toggle",onClick:()=>Os(U.id),"aria-expanded":qt,children:qt?"折叠显示":"展开显示"}):null,as&&Es?a.jsx("button",{type:"button",className:"thread-group__session-toggle",disabled:Je.isLoading,onClick:()=>{Es(U.id)},children:Je.isLoading?"加载中...":ot==="archived"?`加载已归档会话 (${vt})`:`加载更早会话 (${vt})`}):null,Je.error?a.jsx("div",{className:"thread-group__empty",children:Je.error}):null]}):null]},U.id)}),Cs]},U.id)},kn=({threadSessions:U,collapsedThreadSessions:Ne,hiddenSessionCount:Ue,totalSessionCount:Qe,pageState:at,remainingPageCount:Je},vt,ot)=>{const nn=st.includes(ot.sectionId),Jt=Ae.includes(ot.sectionId),qt=Jt?U:Ne,St=Ue>0,En=Je>0,gt=vt==="threads"?Ce:X;return a.jsxs("section",{className:"thread-group thread-group--chat",children:[a.jsxs("div",{className:"thread-group__header",children:[a.jsxs("button",{type:"button",className:"thread-group__title",onClick:()=>ua(ot.sectionId),"aria-expanded":nn,title:ot.title,children:[a.jsx("span",{className:"thread-group__icon",children:ot.icon==="image"?a.jsx(iR,{}):a.jsx(ex,{})}),a.jsx("span",{className:"thread-group__title-text",children:ot.title})]}),vt==="threads"&&ot.onCreate?a.jsx("div",{className:"thread-group__actions",children:a.jsx("button",{type:"button",className:"thread-group__add",onClick:ss=>{var Ns;ss.stopPropagation(),d(),(Ns=ot.onCreate)==null||Ns.call(ot)},"aria-label":`新增${ot.title}会话`,children:a.jsx(J4,{})})}):null]}),nn?Qe===0?a.jsx("div",{className:"thread-group__empty",children:vt==="archived"?ot.archivedEmptyText:ot.emptyText}):a.jsxs(a.Fragment,{children:[qt.length>0?a.jsx("div",{className:"thread-group__sessions",children:qt.map(ss=>mn(ss))}):a.jsx("div",{className:"thread-group__empty",children:vt==="archived"?ot.archivedEmptyText:ot.emptyText}),St?a.jsx("button",{type:"button",className:"thread-group__session-toggle",onClick:()=>Os(ot.sectionId),"aria-expanded":Jt,children:Jt?"折叠显示":"展开显示"}):null,En&>?a.jsx("button",{type:"button",className:"thread-group__session-toggle",disabled:at.isLoading,onClick:()=>{gt()},children:at.isLoading?"加载中...":vt==="archived"?`加载已归档会话 (${Je})`:`加载更早会话 (${Je})`}):null,at.error?a.jsx("div",{className:"thread-group__empty",children:at.error}):null]}):null]})},pn=U=>{if(!qe||qe.pane!==U)return null;const Ne=Jn(U).find(at=>at.project.id===qe.projectId);if(!Ne)return null;const Ue={top:qe.previewTop,width:`${qe.itemWidth}px`},Qe=Ne.project.display_name??Ne.project.name;return a.jsx("div",{className:"thread-group-drag-preview",style:Ue,"aria-hidden":"true",children:a.jsxs("div",{className:"thread-group-drag-preview__header",children:[a.jsx("span",{className:"thread-group-drag-preview__chevron",children:a.jsx(tx,{open:!0})}),a.jsx("span",{className:"thread-group-drag-preview__icon",children:a.jsx(Z4,{})}),a.jsx("span",{className:"thread-group-drag-preview__title",children:Qe})]})})};return a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:`sidebar-scrim ${D?"is-visible":""}`,style:{opacity:o?0:i,pointerEvents:o?"none":D?"auto":"none",transition:r?"none":void 0},onClick:d,"aria-label":"关闭侧边栏"}),a.jsxs("aside",{className:`conversation-sidebar ${t?"is-open":""} ${o?"is-desktop-pinned":""} ${u?"is-resizing":""}`,style:{transform:o?"translateX(0)":`translateX(calc(-100% + ${Math.max(0,Math.min(i,1))*100}%))`,transition:r?"none":void 0},children:[o&&m?a.jsx("div",{className:"conversation-sidebar__resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"调整侧边栏宽度",onPointerDown:U=>{U.pointerType!=="touch"&&(U.preventDefault(),U.stopPropagation(),m(U.clientX))}}):null,a.jsxs("div",{className:"conversation-sidebar__header",children:[a.jsxs("div",{className:`conversation-sidebar__brand ${oe&&je?`is-${je}`:"is-empty"}`,"aria-label":z,title:z,children:[oe?a.jsx("span",{className:"conversation-sidebar__status-dot","aria-hidden":"true"}):null,a.jsx("span",{className:"conversation-sidebar__brand-name",children:y?Cc(y):"未选择节点"})]}),o?null:a.jsx("button",{type:"button",className:"conversation-sidebar__close",onClick:d,"aria-label":"关闭",children:"×"})]}),a.jsxs("div",{className:"conversation-sidebar__actions",children:[a.jsxs(bp,{to:"/nodes",className:"sidebar-action",onClick:d,children:[a.jsx("span",{className:"sidebar-action__icon",children:a.jsx(aR,{})}),a.jsx("span",{children:"节点列表"})]}),kn(Zs,"threads",{sectionId:X1,title:"聊天",icon:"chat",onCreate:J,emptyText:"暂时没有聊天会话",archivedEmptyText:"暂时没有已归档的聊天会话"}),kn(Ln,"threads",{sectionId:Z1,title:"绘图",icon:"image",onCreate:F,emptyText:"暂时没有绘图会话",archivedEmptyText:"暂时没有已归档的绘图会话"}),a.jsxs("button",{type:"button",className:"sidebar-action sidebar-action--primary",onClick:()=>{d();const U=b.find(Ne=>Ne.id===Et)??b[0];U?Q(U.id,U.name):ye({to:"/nodes"})},children:[a.jsx("span",{className:"sidebar-action__icon",children:a.jsx(ex,{})}),a.jsx("span",{children:"新会话"})]})]}),a.jsx("div",{className:"conversation-sidebar__threads",children:a.jsxs("div",{className:"sidebar-pane-track",style:{transform:Ke},children:[a.jsxs("div",{ref:U=>{be.current.threads=U},className:`sidebar-pane ${an==="threads"?"is-active":"is-inactive"}`,children:[hn.length>0?a.jsxs("div",{className:"sidebar-pinned",children:[a.jsx("div",{className:"conversation-sidebar__node",children:"置顶会话"}),a.jsx("div",{className:"sidebar-pinned__list",children:hn.map(U=>mn(U))})]}):null,a.jsxs("div",{className:"conversation-sidebar__node-row",children:[a.jsx("div",{className:"conversation-sidebar__node",children:"线程"}),B?a.jsx("button",{type:"button",className:"conversation-sidebar__node-action",onClick:B,"aria-label":"新增目录线程",title:"新增目录线程",children:a.jsx(rR,{})}):null]}),On.map(U=>jn(U,"threads")),pn("threads"),a.jsxs("button",{type:"button",className:"thread-archive__toggle",onClick:()=>re("archived"),children:[a.jsx("span",{children:"已归档"}),a.jsx("span",{className:"thread-archive__icon",children:a.jsx(lR,{})})]})]}),a.jsxs("div",{ref:U=>{be.current.archived=U},className:`sidebar-pane sidebar-pane--archived ${an==="archived"?"is-active":"is-inactive"}`,children:[a.jsx("div",{className:"conversation-sidebar__node",children:"已归档的线程"}),us.totalSessionCount>0?kn(us,"archived",{sectionId:X1,title:"聊天",icon:"chat",emptyText:"还没有已加载的聊天会话",archivedEmptyText:"还没有已加载的归档聊天会话"}):null,Ot.totalSessionCount>0?kn(Ot,"archived",{sectionId:Z1,title:"绘图",icon:"image",emptyText:"还没有已加载的绘图会话",archivedEmptyText:"还没有已加载的归档绘图会话"}):null,Ss.length>0?a.jsx("div",{className:"thread-archive__list",children:Ss.map(U=>jn(U,"archived"))}):a.jsx("div",{className:"thread-archive__empty",children:"暂时没有已归档的线程"}),pn("archived"),a.jsxs("button",{type:"button",className:"thread-archive__back",onClick:()=>re("threads"),"aria-label":"返回线程列表",children:[a.jsx("span",{className:"thread-archive__back-icon",children:a.jsx(oR,{})}),a.jsx("span",{children:"返回"})]})]})]})}),a.jsx("div",{className:"conversation-sidebar__footer",children:a.jsxs("button",{type:"button",className:"sidebar-settings",onClick:()=>{d(),he==null||he()},"aria-label":"打开设置页",children:[a.jsx("span",{className:"sidebar-settings__icon",children:a.jsx(cR,{})}),a.jsx("span",{children:"设置"})]})})]}),Lt]})}),i5="panda:image:model",gR=["gpt-image-2"],_R=(e,t,i)=>{if(typeof window>"u")return i;const r=window.localStorage.getItem(e);return r&&t.includes(r)?r:i},yR=(e,t)=>{typeof window>"u"||window.localStorage.setItem(e,t)},vR=()=>_R(i5,gR,"gpt-image-2"),bR=e=>yR(i5,e),r5="image/",xR=()=>`attachment-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,SR=e=>new Promise((t,i)=>{const r=new FileReader;r.onerror=()=>i(r.error??new Error("无法读取文件")),r.onload=()=>{if(typeof r.result=="string"&&r.result){t(r.result);return}i(new Error("无法读取文件"))},r.readAsDataURL(e)}),cy=async e=>({id:xR(),kind:e.type.startsWith(r5)?"image":"file",name:e.name,mime_type:e.type||null,size_bytes:Number.isFinite(e.size)?Math.max(0,Math.round(e.size)):null,data_url:await SR(e)}),ax=e=>{var t;return e.kind==="image"||!!((t=e.mime_type)!=null&&t.startsWith(r5))},l5=e=>E6((e??[]).map((t,i)=>({id:t.id||`attachment-${i}`,kind:t.kind,name:t.name,mime_type:t.mime_type??null,size_bytes:t.size_bytes??null,content_url:t.data_url}))),qp=e=>typeof e!="number"||!Number.isFinite(e)||e<=0?null:e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,o5=e=>{var t;return["image-session-detail",((t=e==null?void 0:e.scope)==null?void 0:t.agentId)??"",(e==null?void 0:e.sessionId)??""]};function jR(e){return cs({queryKey:o5(e),enabled:!!((e==null?void 0:e.enabled)??!0)&&!!(e!=null&&e.sessionId),queryFn:async()=>e!=null&&e.sessionId?(await cn(e.scope)).client.getImageSessionDetail(e.sessionId):null,refetchOnWindowFocus:!1,retry:1})}const wR=(e,t,i)=>Math.max(t,Math.min(i,e)),ix=(e,t,i,r="source-over")=>{if(t.points.length===0)return;e.save(),e.globalCompositeOperation=r,e.strokeStyle=i,e.lineCap="round",e.lineJoin="round",e.lineWidth=t.size,e.beginPath();const o=t.points[0];if(!o){e.restore();return}e.moveTo(o.x,o.y);for(const u of t.points.slice(1))e.lineTo(u.x,u.y);t.points.length===1&&e.lineTo(o.x+.01,o.y+.01),e.stroke(),e.restore()},NR=({title:e,imageSrc:t,onClose:i,onConfirm:r})=>{const o=_.useRef(null),u=_.useRef(null),[d,m]=_.useState(null),[y,g]=_.useState(null),[b,p]=_.useState(36),[v,w]=_.useState([]),N=_.useRef(null);_.useEffect(()=>{const I=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=I}},[]),_.useEffect(()=>{const I=o.current;if(!I||!d||!y)return;I.width=d.width,I.height=d.height;const k=I.getContext("2d");if(k){k.clearRect(0,0,I.width,I.height);for(const O of v)ix(k,O,"rgba(87, 145, 255, 0.56)")}},[d,y,v]),_.useLayoutEffect(()=>{if(!d||typeof window>"u")return;const I=()=>{const k=u.current;if(!k)return;const O=k.getBoundingClientRect(),Q=Math.min(O.width/d.width,O.height/d.height),J=d.width*Q,F=d.height*Q;g({width:J,height:F})};return I(),window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I)}},[d]);const j=I=>{const k=o.current;if(!k||!d||!y)return;const O=k.getBoundingClientRect(),Q=d.width/O.width,J=d.height/O.height,F={size:b,points:[{x:(I.clientX-O.left)*Q,y:(I.clientY-O.top)*J}]};N.current=F,w(B=>[...B,F]),k.setPointerCapture(I.pointerId)},T=I=>{const k=o.current,O=N.current;if(!k||!O||!d||!y)return;const Q=k.getBoundingClientRect(),J=d.width/Q.width,F=d.height/Q.height;O.points.push({x:(I.clientX-Q.left)*J,y:(I.clientY-Q.top)*F}),w(B=>[...B.slice(0,-1),{...O,points:[...O.points]}])},M=I=>{const k=o.current;k!=null&&k.hasPointerCapture(I.pointerId)&&k.releasePointerCapture(I.pointerId),N.current=null},P=_.useMemo(()=>{if(!d||v.length===0)return null;const I=document.createElement("canvas");I.width=d.width,I.height=d.height;const k=I.getContext("2d");if(!k)return null;k.fillStyle="#ffffff",k.fillRect(0,0,I.width,I.height);for(const O of v)ix(k,O,"#000000","destination-out");return I.toDataURL("image/png")},[d,v]);return typeof document>"u"?null:ra.createPortal(a.jsxs("div",{className:"image-mask-dialog",role:"dialog","aria-modal":"true","aria-label":`${e} 蒙版编辑`,children:[a.jsx("button",{type:"button",className:"image-mask-dialog__scrim",onClick:i,"aria-label":"关闭蒙版编辑器"}),a.jsxs("div",{className:"image-mask-dialog__panel is-stage-fullscreen",children:[a.jsxs("div",{className:"image-mask-dialog__header image-mask-dialog__header--compact",children:[a.jsx("div",{className:"image-mask-dialog__header-actions",children:a.jsxs("label",{className:"image-mask-dialog__range image-mask-dialog__range--toolbar",children:[a.jsx("span",{children:"毛刷大小"}),a.jsx("input",{type:"range",min:8,max:120,step:2,value:b,onChange:I=>p(wR(Number(I.target.value),8,120))}),a.jsxs("strong",{children:[b,"px"]})]})}),a.jsxs("div",{className:"image-mask-dialog__header-actions image-mask-dialog__header-actions--right",children:[a.jsx("button",{type:"button",className:"image-mask-dialog__icon-button",onClick:()=>w(I=>I.slice(0,-1)),disabled:v.length===0,"aria-label":"撤销上一笔",children:a.jsx(cT,{})}),a.jsx("button",{type:"button",className:"image-mask-dialog__confirm-button",onClick:()=>r(P),"aria-label":"确认蒙版",children:a.jsx(Z0,{})}),a.jsx("button",{type:"button",className:"image-mask-dialog__icon-button",onClick:i,"aria-label":"关闭编辑器",children:a.jsx(hh,{})})]})]}),a.jsx("div",{className:"image-mask-dialog__workspace image-mask-dialog__workspace--single",children:a.jsx("div",{className:"image-mask-dialog__stage",children:a.jsx("div",{ref:u,className:"image-mask-dialog__canvas-shell",children:a.jsxs("div",{className:"image-mask-dialog__canvas-stage",style:y?{width:`${y.width}px`,height:`${y.height}px`}:void 0,children:[a.jsx("img",{src:t,alt:e,className:"image-mask-dialog__image",onLoad:I=>{m({width:I.currentTarget.naturalWidth,height:I.currentTarget.naturalHeight})}}),a.jsx("canvas",{ref:o,className:"image-mask-dialog__canvas",onPointerDown:j,onPointerMove:I=>{I.buttons!==1&&I.pointerType!=="touch"||T(I)},onPointerUp:M,onPointerCancel:M})]})})})})]})]}),document.body)},kR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 5v14"}),a.jsx("path",{d:"m7 14 5 5 5-5"})]}),ER=e=>typeof e!="number"||!Number.isFinite(e)||e<=0?null:e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,CR=e=>e.maskDataUrl?"蒙版":e.kind==="session-asset"?"引用":"上传",TR=({isDesktopSidebar:e,sidebarShift:t,isSidebarDragging:i,draft:r,onDraftChange:o,composerError:u,onDismissComposerError:d,pendingSources:m,onUploadImages:y,onRemoveSource:g,onEditSource:b,onSubmit:p,selectedModel:v,onSelectModel:w,modelOptions:N,showJumpToBottom:j,onJumpToBottom:T})=>{const M=_.useId(),P=_.useRef(null),I=_.useRef(null),[k,O]=_.useState(null),Q={transform:`translateX(${t}px)`,transition:i?"none":void 0},J=r.trim().length>0;_.useEffect(()=>{if(!k)return;const B=Z=>{const ae=Z.target;I.current&&ae instanceof Node&&I.current.contains(ae)||O(null)},G=Z=>{Z.key==="Escape"&&O(null)};return window.addEventListener("pointerdown",B),window.addEventListener("keydown",G),()=>{window.removeEventListener("pointerdown",B),window.removeEventListener("keydown",G)}},[k]);const F=B=>{B.key!=="Enter"||B.shiftKey||B.altKey||B.ctrlKey||B.metaKey||B.nativeEvent.isComposing||typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches||(B.preventDefault(),J&&p())};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`composer-wrap ${e?"has-desktop-sidebar":""}`,style:Q,children:[u?a.jsxs("div",{className:"composer-alert",role:"status","aria-live":"polite",children:[a.jsx("span",{className:"composer-alert__text",children:u}),a.jsx("button",{type:"button",className:"composer-alert__close",onClick:d,"aria-label":"关闭错误提示",children:a.jsx(hh,{})})]}):null,a.jsxs("form",{className:"chat-composer image-session-composer",onSubmit:B=>{B.preventDefault(),J&&p()},children:[m.length>0?a.jsx("div",{className:"image-session-composer__source-strip","aria-label":"Current reference images",children:m.map(B=>{const G=ER(B.sizeBytes),Z=CR(B);return a.jsxs("div",{className:"image-session-composer__source-pill",title:`${Z} - ${B.name}${G?` - ${G}`:""}`,children:[a.jsx("img",{src:B.previewUrl,alt:B.name,className:"image-session-composer__source-pill-preview"}),a.jsxs("div",{className:"image-session-composer__source-pill-copy",children:[a.jsx("span",{className:"image-session-composer__source-pill-label",children:Z}),a.jsx("span",{className:"image-session-composer__source-pill-name",children:B.name})]}),a.jsx("button",{type:"button",className:"image-session-composer__source-pill-action",onClick:()=>b(B.id),"aria-label":`编辑 ${B.name}`,children:a.jsx(fh,{})}),a.jsx("button",{type:"button",className:"image-session-composer__source-pill-remove","aria-label":`移除 ${B.name}`,onClick:()=>g(B.id),children:a.jsx(hh,{})})]},B.id)})}):null,a.jsxs("div",{className:"chat-composer__editor",children:[a.jsx("textarea",{className:"chat-composer__input image-session-composer__input",value:r,placeholder:"描述你想生成或修改的图片",onChange:B=>o(B.target.value),onKeyDown:F}),a.jsx("input",{id:M,ref:P,type:"file",accept:"image/*",multiple:!0,className:"chat-composer__file-input",onChange:B=>{B.target.files&&B.target.files.length>0&&y(B.target.files),B.target.value=""}})]}),a.jsxs("div",{className:"chat-composer__toolbar",children:[a.jsxs("div",{ref:I,className:"chat-composer__controls image-session-composer__controls",children:[a.jsxs("div",{className:`composer-utility-menu image-session-composer__utility ${k==="utility"?"is-open":""}`,children:[a.jsx("button",{type:"button",className:"composer-utility-menu__trigger image-session-composer__upload-trigger","aria-label":"打开图片工具","aria-expanded":k==="utility",onClick:()=>O(B=>B==="utility"?null:"utility"),children:a.jsx(T4,{})}),k==="utility"?a.jsx("div",{className:"composer-utility-menu__popover image-session-composer__utility-menu",role:"menu",children:a.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitem",onClick:()=>{var B;O(null),(B=P.current)==null||B.click()},children:[a.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:a.jsx(T4,{})}),a.jsx("span",{className:"composer-utility-menu__item-label",children:"上传图片"})]})}):null]}),a.jsxs("div",{className:`composer-choice image-session-composer__choice ${k==="model"?"is-open":""} is-selected`,children:[a.jsxs("button",{type:"button",className:"composer-control image-session-composer__choice-trigger is-selected","aria-label":"选择模型","aria-expanded":k==="model",onClick:()=>O(B=>B==="model"?null:"model"),children:[a.jsx(pT,{className:"image-session-composer__choice-icon","aria-hidden":"true"}),a.jsx("span",{className:"image-session-composer__choice-value",children:v}),a.jsx(QC,{className:"image-session-composer__choice-arrow","aria-hidden":"true"})]}),k==="model"?a.jsx("div",{className:"composer-choice-menu image-session-composer__choice-menu",role:"menu","aria-label":"选择模型",children:N.map(B=>a.jsxs("button",{type:"button",className:`composer-choice-menu__item ${v===B.id?"is-active":""}`,role:"menuitemradio","aria-checked":v===B.id,onClick:()=>{w(B.id),O(null)},children:[a.jsx("span",{className:"composer-choice-menu__label",children:B.label||B.id}),v===B.id?a.jsx("span",{className:"composer-choice-menu__check","aria-hidden":"true",children:a.jsx(Z0,{})}):null]},B.id))}):null]})]}),a.jsx("div",{className:"chat-composer__actions image-session-composer__actions",children:a.jsx("button",{type:"submit",className:"composer-send",disabled:!J,"aria-label":"Send image request",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:a.jsx("path",{d:"M12 17V7m0 0-4 4m4-4 4 4",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})]})]}),j?a.jsx("button",{type:"button",className:`conversation-jump-bottom ${e?"has-desktop-sidebar":""}`,style:Q,onClick:T,"aria-label":"滚动到底部",children:a.jsx(kR,{})}):null]})},c5=()=>`image-source-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,MR=4200,rx=e=>Math.max(1,Math.min(5,e)),lx={quality:"auto",size:"1024x1024",aspectRatio:"auto",outputFormat:"png",outputCompression:85,background:"auto",moderation:"auto",n:1},RR=[{value:"auto",label:"Auto"},{value:"low",label:"快速"},{value:"medium",label:"均衡"},{value:"high",label:"精细"}],AR=[{value:"auto",label:"Auto"},{value:"1:1",label:"1:1"},{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"},{value:"4:3",label:"4:3"},{value:"3:4",label:"3:4"}],IR=[{value:"1024x1024",label:"1K"},{value:"2048x2048",label:"2K"},{value:"3840x2160",label:"4K"},{value:"auto",label:"Auto"}],DR=[{value:"png",label:"PNG"},{value:"webp",label:"WebP"},{value:"jpeg",label:"JPEG"}],OR=[{value:"auto",label:"Auto"},{value:"opaque",label:"不透明"}],LR=[{value:"auto",label:"Auto"},{value:"low",label:"宽松"}],PR=e=>{switch(e){case"16:9":return{width:28,height:16};case"9:16":return{width:16,height:28};case"4:3":return{width:24,height:18};case"3:4":return{width:18,height:24};case"1:1":return{width:22,height:22};default:return{width:24,height:18}}},UR=({ratio:e})=>{const t=PR(e);return a.jsxs("svg",{viewBox:"0 0 32 32","aria-hidden":"true",className:"image-ratio-icon",children:[a.jsx("rect",{className:"image-ratio-icon__backdrop",x:"4.5",y:"4.5",width:"23",height:"23",rx:"6"}),a.jsx("rect",{className:"image-ratio-icon__shape",x:(32-t.width)/2,y:(32-t.height)/2,width:t.width,height:t.height,rx:"3"})]})},Au=({menuKey:e,activeMenu:t,label:i,selectedValue:r,options:o,onToggle:u,onSelect:d,renderLeading:m})=>{var b;const y=((b=o.find(p=>p.value===r))==null?void 0:b.label)??r,g=typeof m=="function";return a.jsxs("div",{className:"image-option-dropdown",children:[a.jsxs("button",{type:"button",className:`image-option-trigger ${g?"has-leading-visual":""}`,onClick:()=>u(e),"aria-expanded":t===e,children:[m?a.jsx("span",{className:"image-option-trigger__visual","aria-hidden":"true",children:m(r)}):null,a.jsx("span",{children:y})]}),t===e?a.jsx("div",{className:"image-option-menu",role:"listbox","aria-label":i,children:o.map(p=>a.jsxs("button",{type:"button",className:`image-option-menu__item ${r===p.value?"is-active":""} ${g?"has-leading-visual":""}`,onClick:()=>d(p.value),children:[m?a.jsx("span",{className:"image-option-menu__item-visual","aria-hidden":"true",children:m(p.value)}):null,a.jsx("span",{children:p.label})]},p.value))}):null]})},t_=e=>{if(e.length<2)return 0;const t=e.item(0),i=e.item(1);return!t||!i?0:Math.hypot(i.clientX-t.clientX,i.clientY-t.clientY)},zR=(e,t,i)=>t.length===0?null:a.jsx("div",{className:"conversation-entry__attachments",children:a.jsx("div",{className:"conversation-entry__attachment-grid",children:t.map(r=>{const o=qp(r.size_bytes),u=r.name||"图片",d=`图片${o?` · ${o}`:""}`;return a.jsxs("button",{type:"button",className:"conversation-entry__attachment-card is-image",onClick:()=>i(r),"aria-label":`预览 ${u}`,children:[a.jsxs("div",{className:"conversation-entry__attachment-media",children:[a.jsx("img",{src:r.content_url,alt:u,loading:"lazy"}),a.jsx("span",{className:"conversation-entry__attachment-badge",children:"预览"})]}),a.jsxs("div",{className:"conversation-entry__attachment-caption",children:[a.jsx("span",{className:"conversation-entry__attachment-title",children:u}),a.jsx("span",{className:"conversation-entry__attachment-meta",children:d})]})]},`${e}:${r.id}`)})})}),n_=e=>({id:c5(),kind:"session-asset",name:e.name,previewUrl:e.content_url,mimeType:e.mime_type,sizeBytes:e.size_bytes,assetId:e.id,maskDataUrl:null}),BR=(e,t,i,r,o)=>o&&{...o,turns:[...o.turns,{id:`pending-turn-${Date.now()}`,session_id:e,created_at:new Date().toISOString(),completed_at:null,prompt:t,prompt_suffix:null,operation:i.length>0?"edit":"generate",status:"pending",error:null,model:r.model,quality:r.options.quality,size:r.options.size,input_fidelity:null,aspect_ratio:r.options.aspectRatio,output_format:r.options.outputFormat,output_compression:r.options.outputFormat==="png"?null:r.options.outputCompression,background:r.options.background,moderation:r.options.moderation,n:r.options.n,sources:i.map(u=>({id:u.assetId??u.id,session_id:e,turn_id:null,kind:"source",name:u.name,mime_type:u.mimeType,size_bytes:u.sizeBytes,width:null,height:null,content_url:u.previewUrl,created_at:new Date().toISOString()})),outputs:[]}]},$R=({asset:e,onClose:t})=>{const[i,r]=_.useState(1),[o,u]=_.useState({x:0,y:0}),[d,m]=_.useState(!1),y=_.useRef(null),g=_.useRef(null),b=_.useRef(null);_.useEffect(()=>{r(1),u({x:0,y:0}),m(!1),g.current=null,b.current=null},[e.id]),_.useEffect(()=>{const M=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=M}},[]),_.useEffect(()=>{const M=P=>{P.key==="Escape"&&t()};return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[t]),_.useEffect(()=>{i===1&&(o.x!==0||o.y!==0)&&u({x:0,y:0})},[o.x,o.y,i]),_.useEffect(()=>{const M=y.current;if(!M)return;const P=I=>{I.preventDefault(),r(k=>rx(k*Math.exp(-I.deltaY*.0015)))};return M.addEventListener("wheel",P,{passive:!1}),()=>{M.removeEventListener("wheel",P)}},[]);const p=M=>{if(M.touches.length>=2){g.current={distance:t_(M.touches),scale:i},b.current=null,m(!1);return}if(M.touches.length===1&&i>1){const P=M.touches[0];b.current={startX:P.clientX,startY:P.clientY,originX:o.x,originY:o.y},m(!0)}},v=M=>{if(M.touches.length>=2){const P=g.current;if(!P){g.current={distance:t_(M.touches),scale:i};return}const I=t_(M.touches);if(I<=0||P.distance<=0)return;M.preventDefault(),r(rx(I/P.distance*P.scale));return}if(M.touches.length===1&&b.current&&i>1){const P=M.touches[0];M.preventDefault(),u({x:b.current.originX+(P.clientX-b.current.startX),y:b.current.originY+(P.clientY-b.current.startY)})}},w=()=>{g.current&&i<=1&&r(1),i<=1&&u({x:0,y:0}),g.current=null,b.current=null,m(!1)},N=M=>{M.pointerType==="touch"||i<=1||(M.currentTarget.setPointerCapture(M.pointerId),b.current={pointerId:M.pointerId,startX:M.clientX,startY:M.clientY,originX:o.x,originY:o.y},m(!0))},j=M=>{M.pointerType==="touch"||!b.current||i<=1||b.current.pointerId===M.pointerId&&(M.preventDefault(),u({x:b.current.originX+(M.clientX-b.current.startX),y:b.current.originY+(M.clientY-b.current.startY)}))},T=M=>{M.pointerType==="touch"||!b.current||(M.currentTarget.hasPointerCapture(M.pointerId)&&M.currentTarget.releasePointerCapture(M.pointerId),b.current=null,m(!1))};return a.jsxs("div",{className:"attachment-lightbox",role:"dialog","aria-modal":"true","aria-label":`预览 ${e.name||"图片"}`,children:[a.jsx("button",{type:"button",className:"attachment-lightbox__scrim",onClick:t,"aria-label":"关闭图片预览"}),a.jsxs("div",{className:"attachment-lightbox__panel",children:[a.jsx("button",{type:"button",className:"attachment-lightbox__close",onClick:t,"aria-label":"关闭图片预览",children:a.jsx(hh,{})}),a.jsx("div",{className:"attachment-lightbox__frame",children:a.jsx("div",{ref:y,className:`attachment-lightbox__stage ${i>1?"is-zoomed":""} ${d?"is-dragging":""}`,onClick:M=>{M.stopPropagation()},onDoubleClick:()=>{r(M=>M>1?1:2),u({x:0,y:0})},onPointerDown:N,onPointerMove:j,onPointerUp:T,onTouchStart:p,onTouchMove:v,onTouchEnd:w,children:a.jsx("img",{src:e.content_url,alt:e.name,className:"attachment-lightbox__image",style:{transform:`translate(${o.x}px, ${o.y}px) scale(${i})`}})})}),a.jsxs("div",{className:"attachment-lightbox__meta",children:[a.jsx("div",{className:"attachment-lightbox__title",children:e.name}),a.jsx("div",{className:"attachment-lightbox__hint",children:"双指或滚轮缩放,拖动查看细节"})]})]})]})},HR=({sessionId:e,workspaceDirectorySnapshot:t=null,embedded:i=!1,isDesktopSidebar:r=!1,sidebarOffset:o=0,isSidebarDragging:u=!1,onOpenSidebar:d}={})=>{const{sessionId:m}=Mc({strict:!1}),y=e??m??"",g=Ka(),b=(t==null?void 0:t.sessions.find(re=>re.id===y))??null,p=(b==null?void 0:b.agent_id)??vo()??void 0,v=jR({sessionId:y,scope:{sessionId:y,agentId:p},enabled:!!y}),w=v.data??null,[N,j]=_.useState(""),[T,M]=_.useState(null),[P,I]=_.useState([]),k=cs({queryKey:["image-provider-settings",p??""],enabled:!!p,queryFn:async()=>p?(await cn({agentId:p})).client.getImageProviderSettings():null}),O=(()=>{const re=k.data,we=(re==null?void 0:re.channels.find(te=>te.id===re.active_channel_id))??(re==null?void 0:re.channels[0])??null,Re=(we==null?void 0:we.models.filter(te=>te.enabled!==!1))??[];return Re.length?Re:[{id:"gpt-image-2",vendor:"openai",label:"gpt-image-2",enabled:!0}]})(),[Q,J]=_.useState(null),[F,B]=_.useState(null),[G,Z]=_.useState(vR),[ae,he]=_.useState(lx),[ne,Ce]=_.useState(!1),[R,X]=_.useState(!1),[le,ue]=_.useState(""),[ye,D]=_.useState(!1),[oe,je]=_.useState(null),[z,be]=_.useState(()=>new Set),[De,se]=_.useState(null),pe=_.useRef(null),ke=_.useRef(null),Ze=O.find(re=>re.id===G)??O[0]??null,Fe=((Ze==null?void 0:Ze.vendor)??"openai")==="openai";_.useEffect(()=>()=>{pe.current!==null&&window.clearTimeout(pe.current),ke.current!==null&&window.clearTimeout(ke.current)},[]),_.useEffect(()=>{if(ke.current!==null&&(window.clearTimeout(ke.current),ke.current=null),!!T)return ke.current=window.setTimeout(()=>{M(null),ke.current=null},MR),()=>{ke.current!==null&&(window.clearTimeout(ke.current),ke.current=null)}},[T]),_.useEffect(()=>{if(!ye||!oe)return;const re=Re=>{const te=Re.target;if(!(te instanceof Element)){je(null);return}te.closest(".image-option-dropdown")||je(null)},we=Re=>{Re.key==="Escape"&&je(null)};return window.addEventListener("pointerdown",re),window.addEventListener("keydown",we),()=>{window.removeEventListener("pointerdown",re),window.removeEventListener("keydown",we)}},[oe,ye]),_.useEffect(()=>{const re=we=>{const Re=we.target;Re instanceof Element&&Re.closest(".conversation-topbar__title-actions")||Ce(!1)};return window.addEventListener("pointerdown",re),()=>{window.removeEventListener("pointerdown",re)}},[]),_.useEffect(()=>{bR(G)},[G]),_.useEffect(()=>{var we;if(O.some(Re=>Re.id===G))return;const re=((we=O[0])==null?void 0:we.id)??"gpt-image-2";Z(re)},[O,G]),_.useEffect(()=>{Fe||ae.moderation==="auto"||he(re=>({...re,moderation:"auto"}))},[ae.moderation,Fe]);const kt=Gn({mutationFn:async re=>{const we=re.kind==="refresh"?re.turn:null,Re=re.kind==="submit"?re.request:null;return(await cn({sessionId:y,agentId:p})).client.submitImageSessionPrompt({sessionId:y,prompt:(we==null?void 0:we.prompt)??(Re==null?void 0:Re.prompt)??"",append_to_turn_id:(we==null?void 0:we.id)??null,model:(we==null?void 0:we.model)??(Re==null?void 0:Re.model),quality:(we==null?void 0:we.quality)??(Re==null?void 0:Re.options.quality),size:(we==null?void 0:we.size)??(Re==null?void 0:Re.options.size),input_fidelity:(we==null?void 0:we.input_fidelity)??null,aspect_ratio:(we==null?void 0:we.aspect_ratio)??(Re==null?void 0:Re.options.aspectRatio),output_format:(we==null?void 0:we.output_format)??(Re==null?void 0:Re.options.outputFormat),output_compression:we?we.output_compression:(Re==null?void 0:Re.options.outputFormat)==="png"?null:Re==null?void 0:Re.options.outputCompression,background:(we==null?void 0:we.background)??(Re==null?void 0:Re.options.background),moderation:(we==null?void 0:we.moderation)??(Re==null?void 0:Re.options.moderation),n:(we==null?void 0:we.n)??(Re==null?void 0:Re.options.n)??1,sources:(we?we.sources.map(n_):(Re==null?void 0:Re.sources)??[]).map(ve=>({id:ve.id,kind:ve.kind==="session-asset"?"session_asset":"upload",name:ve.name,mime_type:ve.mimeType,size_bytes:ve.sizeBytes,data_url:ve.dataUrl??null,asset_id:ve.assetId??null,mask_data_url:ve.maskDataUrl??null}))})},onMutate:async re=>{M(null),re.kind==="refresh"&&be(te=>new Set(te).add(re.turn.id));const we=o5({sessionId:y,scope:{agentId:p}}),Re=g.getQueryData(we)??null;return g.setQueryData(we,re.kind==="refresh"?Re:BR(y,re.request.prompt,re.request.sources,{model:re.request.model,options:re.request.options},Re)),{previous:Re,queryKey:we,variables:re}},onSuccess:(re,we,Re)=>{g.setQueryData((Re==null?void 0:Re.queryKey)??[],re),g.setQueriesData({queryKey:hs},ve=>ve&&Bp(ve,re.session));const te=Re==null?void 0:Re.variables;(te==null?void 0:te.kind)==="refresh"&&be(ve=>{const V=new Set(ve);return V.delete(te.turn.id),V})},onError:(re,we,Re)=>{Re!=null&&Re.queryKey&&g.setQueryData(Re.queryKey,Re.previous??null);const te=Re==null?void 0:Re.variables;(te==null?void 0:te.kind)==="refresh"&&be(ve=>{const V=new Set(ve);return V.delete(te.turn.id),V}),M(re instanceof Error?re.message:"图片请求失败")}}),Bt=async re=>{var we;try{const te=(await Promise.all([...re].map(ve=>cy(ve)))).map(ve=>({id:c5(),kind:"upload",name:ve.name,previewUrl:ve.data_url,mimeType:ve.mime_type,sizeBytes:ve.size_bytes,dataUrl:ve.data_url,maskDataUrl:null}));I(ve=>[...ve,...te]),B(((we=te[0])==null?void 0:we.id)??null)}catch(Re){M(Re instanceof Error?Re.message:"无法读取图片")}},Gt=re=>{I(we=>[...we,n_(re)])},Xt=()=>{const re=N.trim();if(!re){M("请先输入提示词。");return}const we={id:`pending-image-request-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,prompt:re,sources:P,model:G,options:ae};j(""),I([]),kt.mutate({kind:"submit",request:we})},Ft=async re=>{var te;const we=re.trim();if(!we)return!1;const Re=()=>{const ve=document.createElement("textarea");ve.value=we,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.opacity="0",ve.style.pointerEvents="none",document.body.appendChild(ve),ve.select(),document.execCommand("copy"),document.body.removeChild(ve)};try{return(te=navigator.clipboard)!=null&&te.writeText?await navigator.clipboard.writeText(we):Re(),!0}catch{return!1}},qe=async(re,we)=>{await Ft(we)&&(se(re),pe.current!==null&&window.clearTimeout(pe.current),pe.current=window.setTimeout(()=>{se(te=>te===re?null:te),pe.current=null},1400))},dt=async re=>{try{const we=await fetch(re.content_url);if(!we.ok)throw new Error("download failed");const Re=await we.blob(),te=URL.createObjectURL(Re),ve=document.createElement("a");ve.href=te,ve.download=re.name||"image",document.body.appendChild(ve),ve.click(),document.body.removeChild(ve),URL.revokeObjectURL(te)}catch{M("下载图片失败。")}},un=re=>{const we=n_(re);I(Re=>[...Re,we]),B(we.id)},$t=Gn({mutationFn:async re=>(await cn({sessionId:y,agentId:p})).client.updateSession({sessionId:y,action:re.action,name:re.name}),onSuccess:()=>{g.invalidateQueries({queryKey:hs})},onError:re=>{M(re instanceof Error?re.message:"会话操作失败")}}),An=_.useCallback(()=>{const re=le.trim();re&&($t.mutate({action:"rename",name:re}),X(!1))},[le,$t]),Nn=_.useCallback(()=>{$t.mutate({action:"delete"}),Ce(!1)},[$t]),Tt=P.find(re=>re.id===F)??null,lt=(w==null?void 0:w.session.title)??(b==null?void 0:b.title)??"绘图会话",Et=R&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered image-options-sheet",role:"dialog","aria-modal":"true","aria-label":"重命名绘图会话",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>X(!1),"aria-label":"关闭重命名弹窗"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered image-options-panel image-options-panel--compact",children:[a.jsx("div",{className:"image-options-panel__eyebrow",children:"会话"}),a.jsx("div",{className:"sheet-panel__title",children:"修改会话名称"}),a.jsx("input",{className:"sheet-panel__input",value:le,onChange:re=>ue(re.target.value),placeholder:"输入新的会话名称",autoFocus:!0}),a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>X(!1),children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:!le.trim()||$t.isPending,onClick:An,children:"保存"})]})]})})]}),document.body):null,rt=ye&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered image-options-sheet",role:"dialog","aria-modal":"true","aria-label":"绘图高级选项",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>D(!1),"aria-label":"关闭高级选项"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"image-options-panel",children:[a.jsx("div",{className:"image-options-panel__handle"}),a.jsxs("div",{className:"image-options-panel__header",children:[a.jsxs("div",{className:"image-options-panel__header-copy",children:[a.jsx("h2",{children:"高级绘图选项"}),a.jsx("p",{children:"调整下一次请求的质量、尺寸、格式、背景和安全策略。"})]}),a.jsx("button",{type:"button",className:"image-options-panel__close",onClick:()=>D(!1),"aria-label":"关闭高级选项",children:a.jsx(hh,{})})]}),a.jsxs("div",{className:"image-options-list",children:[a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"质量"}),a.jsx("span",{children:"影响速度、细节和成本"})]}),a.jsx(Au,{menuKey:"quality",activeMenu:oe,label:"选择图片质量",selectedValue:ae.quality,options:RR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,quality:re})),je(null)}})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"Size"}),a.jsx("span",{children:"2K / 4K will be sent to the provider when supported"})]}),a.jsx(Au,{menuKey:"size",activeMenu:oe,label:"Select image size",selectedValue:ae.size,options:IR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,size:re})),je(null)}})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"Ratio"}),a.jsx("span",{children:"Select the output aspect ratio"})]}),a.jsx(Au,{menuKey:"ratio",activeMenu:oe,label:"Select image ratio",selectedValue:ae.aspectRatio,options:AR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,aspectRatio:re})),je(null)},renderLeading:re=>a.jsx(UR,{ratio:re})})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"张数"}),a.jsx("span",{children:"成本会随张数增加"})]}),a.jsx("input",{type:"number",min:1,max:10,value:ae.n,onChange:re=>he(we=>({...we,n:Math.max(1,Math.min(10,Number(re.target.value)||1))}))})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"Format"}),a.jsx("span",{children:ae.outputFormat==="png"?"High fidelity for editing":"Adjustable compression"})]}),a.jsx(Au,{menuKey:"format",activeMenu:oe,label:"Select output format",selectedValue:ae.outputFormat,options:DR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,outputFormat:re})),je(null)}})]}),ae.outputFormat!=="png"?a.jsxs("div",{className:"image-options-row image-options-row--range",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"压缩"}),a.jsxs("span",{children:[ae.outputCompression,"%"]})]}),a.jsx("input",{type:"range",min:0,max:100,value:ae.outputCompression,onChange:re=>he(we=>({...we,outputCompression:Number(re.target.value)}))})]}):null,a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"背景"}),a.jsx("span",{children:"gpt-image-2 暂不支持透明背景"})]}),a.jsx(Au,{menuKey:"background",activeMenu:oe,label:"选择背景模式",selectedValue:ae.background,options:OR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,background:re})),je(null)}})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"安全过滤"}),a.jsx("span",{children:Fe?"推荐保持自动":"当前模型走 provider 固定内容审核,暂不支持手动调节"})]}),Fe?a.jsx(Au,{menuKey:"moderation",activeMenu:oe,label:"选择安全过滤等级",selectedValue:ae.moderation,options:LR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,moderation:re})),je(null)}}):a.jsx("button",{type:"button",className:"image-option-trigger",disabled:!0,"aria-label":"当前模型不支持调节安全过滤",children:a.jsx("span",{children:"不可调"})})]})]}),a.jsxs("div",{className:"image-options-panel__footer",children:[a.jsx("button",{type:"button",onClick:()=>he(lx),children:"恢复默认"}),a.jsx("button",{type:"button",className:"is-primary",onClick:()=>D(!1),children:"完成"})]})]})})]}),document.body):null,st=a.jsxs("div",{className:"conversation-topbar",children:[r?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:d,"aria-label":"Open sidebar",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]}),a.jsx("div",{className:"conversation-topbar__meta",children:a.jsxs("div",{className:"conversation-topbar__title-row",children:[a.jsx("h1",{children:lt}),a.jsxs("div",{className:"conversation-topbar__title-actions",children:[a.jsx("button",{type:"button",className:"conversation-topbar__more",onClick:()=>Ce(re=>!re),"aria-label":"更多绘图会话选项","aria-expanded":ne,children:a.jsx(JC,{})}),ne?a.jsxs("div",{className:"topbar-menu",role:"menu",children:[a.jsx("button",{type:"button",className:"topbar-menu__item",onClick:()=>{ue(lt),X(!0),Ce(!1)},children:"修改会话名称"}),a.jsx("button",{type:"button",className:"topbar-menu__item is-danger",disabled:$t.isPending,onClick:Nn,children:"删除会话"})]}):null]})]})}),a.jsx("div",{className:"conversation-topbar__actions",children:a.jsx("div",{className:"conversation-topbar__run-group",children:a.jsx("button",{type:"button",className:"conversation-topbar__run-button",onClick:()=>{D(!0),Ce(!1)},"aria-label":"编辑高级选项",title:"编辑高级选项",children:a.jsx(hT,{})})})})]}),Dt=v.isPending&&!w?a.jsx("div",{className:"empty-panel empty-panel--loading",children:"Loading image session..."}):w?w.turns.length===0?a.jsxs("div",{className:"image-session-empty-state",children:[a.jsx("h2",{children:"开始新的绘图"}),a.jsx("p",{children:"描述你想生成的画面,或上传参考图继续编辑。"})]}):a.jsx("div",{className:"image-session-thread",children:[...w.turns.flatMap(re=>{const we=a.jsx("section",{className:"conversation-entry is-user is-user",children:a.jsxs("div",{className:"conversation-entry__stack",children:[a.jsxs("div",{className:"conversation-entry__body",children:[a.jsx("p",{className:"image-session-entry__text",children:re.prompt}),zR(`${re.id}:user`,re.sources,te=>J(te))]}),a.jsxs("button",{type:"button",className:`conversation-entry__copy ${De===re.id?"is-copied":""}`,onClick:()=>{qe(re.id,re.prompt)},"aria-label":De===re.id?"Copied message":"Copy message",children:[a.jsx("span",{className:"conversation-entry__copy-icon","aria-hidden":"true",children:De===re.id?a.jsx(Z0,{}):a.jsx(YC,{})}),a.jsx("span",{className:"sr-only",children:De===re.id?"Copied":"Copy"})]})]})},`${re.id}:user`),Re=a.jsx("section",{className:"conversation-entry is-system is-system",children:a.jsxs("div",{className:"conversation-entry__body image-session-entry__result-body",children:[a.jsxs("div",{className:"image-session-entry__meta",children:[a.jsx("span",{children:re.operation==="edit"?"编辑":"生成"}),a.jsx("span",{children:new Date(re.created_at).toLocaleString("zh-CN",{hour12:!1})})]}),re.status==="pending"||z.has(re.id)?a.jsxs("div",{className:"image-result-placeholder",children:[a.jsx("div",{className:"image-result-placeholder__wave"}),a.jsx("span",{children:"Generating image..."})]}):null,re.status==="failed"?a.jsx("div",{className:"image-turn-card__error",children:re.error??"图片生成失败"}):null,re.outputs.length>0?a.jsx("div",{className:"image-result-grid",children:re.outputs.map(te=>a.jsxs("figure",{className:"image-result-card",children:[a.jsx("button",{type:"button",className:"image-result-card__preview",onClick:()=>J(te),children:a.jsx("img",{src:te.content_url,alt:te.name})}),a.jsxs("figcaption",{className:"image-result-card__caption",children:[a.jsx("span",{children:te.name}),a.jsxs("div",{className:"image-result-card__actions",children:[a.jsx("button",{type:"button",onClick:()=>un(te),"aria-label":"编辑图片",title:"编辑",children:a.jsx(fh,{"aria-hidden":"true"})}),a.jsx("button",{type:"button",onClick:()=>Gt(te),"aria-label":"引用图片",title:"引用",children:a.jsx(iT,{"aria-hidden":"true"})}),a.jsx("button",{type:"button",onClick:()=>kt.mutate({kind:"refresh",turn:re}),disabled:z.has(re.id)||re.status!=="completed","aria-label":"Regenerate image",title:"重新生成",children:a.jsx(lT,{"aria-hidden":"true"})}),a.jsx("button",{type:"button",onClick:()=>{dt(te)},"aria-label":"下载图片",title:"下载",children:a.jsx(XC,{"aria-hidden":"true"})})]})]})]},te.id))}):null]})},`${re.id}:system`);return[we,Re]})]}):a.jsx("div",{className:"empty-panel",children:v.error instanceof Error?v.error.message:"Unable to load image session"}),an={transform:`translateX(${o}px)`,transition:u?"none":void 0};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`conversation-main ${r?"has-desktop-sidebar":""} ${i?"is-embedded":""}`,style:an,children:[st,a.jsx("div",{className:"conversation-scroll",children:a.jsx("div",{className:"conversation-thread",children:Dt})})]}),a.jsx(TR,{isDesktopSidebar:r,sidebarShift:o,isSidebarDragging:u,draft:N,onDraftChange:j,composerError:T,onDismissComposerError:()=>M(null),pendingSources:P,onUploadImages:re=>{Bt(re)},onRemoveSource:re=>{I(we=>we.filter(Re=>Re.id!==re))},onEditSource:re=>B(re),onSubmit:()=>{Xt()},selectedModel:G,onSelectModel:Z,modelOptions:O,showJumpToBottom:!1,onJumpToBottom:()=>{}}),Tt?a.jsx(NR,{title:Tt.name,imageSrc:Tt.previewUrl,onClose:()=>B(null),onConfirm:re=>{I(we=>we.map(Re=>Re.id===Tt.id?{...Re,maskDataUrl:re}:{...Re,maskDataUrl:null})),B(null)}}):null,Et,rt,Q&&typeof document<"u"?ra.createPortal(a.jsx($R,{asset:Q,onClose:()=>J(null)},Q.id),document.body):null]})},uy="optimistic-user:",FR="overlay-user:",qR=[uy,FR],WR=5e3,ic=e=>["timeline-optimistic",e],tg=e=>e.kind==="user"&&qR.some(t=>e.id.startsWith(t)),dy=e=>e.kind==="user"&&!tg(e),fy=e=>e.kind==="user"&&e.id.startsWith(uy),KR=e=>e.kind==="user"&&!fy(e),ox=e=>e.body.replace(/\r\n/g,`
|
|
193
|
+
`)}):null]},ae.id)}):a.jsx("p",{className:"settings-block__status",children:"还没有开发版管理任务记录。"})]}),w&&t?a.jsx(NT,{agentId:t,initialPath:r.repo_path,onClose:()=>N(!1),onSelect:ue}):null]})},w3=Ac("App",{web:()=>cl(()=>import("./web-BiBxkdSf.js"),[]).then(e=>new e.AppWeb)}),AT=Ac("Browser",{web:()=>cl(()=>import("./web-Cv1t4xrp.js"),[]).then(e=>new e.BrowserWeb)}),IT=e=>{const t=(e==null?void 0:e.trim())??"";return t?t.replace(/\/+$/,""):""},DT=async()=>{if(!Yp())return{platform:rd(),version:null,build:null,appId:null};const e=await w3.getInfo();return{platform:rd(),version:e.version??null,build:e.build??null,appId:e.id??null}},N3=e=>{const t=IT(e);return t?new URL("/downloads/android/latest.json",t).toString():""},OT=async e=>{const t=N3(e);if(!t)throw new Error("当前还没有配置可用的 Hub 地址。");const i=await fetch(t,{cache:"no-store"});if(!i.ok)throw new Error(`更新清单请求失败(HTTP ${i.status})。`);const r=await i.json(),o=Array.isArray(r.release_notes)?r.release_notes.filter(d=>typeof d=="string"&&d.trim().length>0):[];if(r.platform!=="android"||typeof r.version_name!="string"||typeof r.version_code!="number"||typeof r.published_at!="string"||typeof r.apk_url!="string")throw new Error("Hub 返回的 Android 更新清单格式无效。");const u=new URL(r.apk_url,t).toString();return{platform:"android",version_name:r.version_name,version_code:r.version_code,published_at:r.published_at,apk_url:u,release_notes:o}},LT=e=>{const t=Number(e);return Number.isFinite(t)?t:null},PT=(e,t)=>{if(!e||!t)return!1;const i=LT(e.build);return typeof i=="number"?t.version_code>i:t.version_name!==e.version},UT=async e=>{if(!e.trim())throw new Error("当前没有可用的 APK 下载地址。");await AT.open({url:e})},k3="panda:session-model",E3="panda:command-execution-model",C3="panda:title-generation-model",ey="panda:session-model-options",a0="panda:session-model-options-updated",T3="panda:session-reasoning",M3="panda:session-fast-mode",R3="panda:session-plan-mode",A3="panda:session-yolo-mode",yd=[{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"}],mh=[{label:"低",value:"low"},{label:"中",value:"medium"},{label:"高",value:"high"},{label:"极高",value:"xhigh"}];var u2;const I3=((u2=yd[0])==null?void 0:u2.value)??"gpt-5.4",O4="gpt-5.4-mini",L4="gpt-5.4-mini",zT=mh[2].value,el=e=>typeof e=="string"?e.trim():"",BT=(e,t)=>{if(!e||typeof e!="object")return null;const i=e,r=el(i.value),o=el(i.label)||r,u=el(i.id)||r||`custom-model-${t+1}`;if(!o||!r)return null;const d=el(i.description);return{id:u,label:o,value:r,description:d||null}},$T=e=>{const t=new Set,i=new Set;return e.flatMap(r=>{const o=r.value.toLowerCase();if(i.has(o))return[];i.add(o);let u=r.id,d=2;for(;t.has(u);)u=`${r.id}-${d}`,d+=1;return t.add(u),[{...r,id:u}]})},D3=e=>{if(!Array.isArray(e))return yd;const t=$T(e.flatMap((i,r)=>{const o=BT(i,r);return o?[o]:[]}));return t.length>0?t:yd},Sd=e=>{if(typeof window>"u")return null;try{return window.localStorage.getItem(e)}catch{return null}},HT=()=>{typeof window>"u"||window.dispatchEvent(new Event(a0))},jd=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(e,t)}catch{}},ty=(e,t=!1)=>{const i=Sd(e);return i==="true"?!0:i==="false"?!1:t},ny=(e,t)=>{jd(e,t?"true":"false")},wd=(e,t)=>{const i=t==null?void 0:t.trim();return i?`${e}:${i}`:null},Of=e=>{const t=el(e==null?void 0:e.value)||"",i=el(e==null?void 0:e.label)||t;return{id:el(e==null?void 0:e.id)||el(e==null?void 0:e.value)||`custom-model-${Date.now()}`,label:i,value:t,description:el(e==null?void 0:e.description)||null}},FT=()=>Mh().map(({id:e,...t})=>t),Mh=()=>{const e=Sd(ey);if(!e)return yd;try{return D3(JSON.parse(e))}catch{return yd}},qT=e=>{const t=D3(e);jd(ey,JSON.stringify(t)),HT()},WT=e=>mh.some(t=>t.value===e),sy=()=>{var i;const e=Sd(k3),t=Mh();return t.some(r=>r.value===e)?e:((i=t[0])==null?void 0:i.value)??I3},lp=()=>{const e=Sd(E3),t=Mh();if(t.some(r=>r.value===e))return e;const i=t.find(r=>r.value===O4)??t[0];return(i==null?void 0:i.value)??O4},O3=()=>{const e=Sd(C3),t=Mh();if(t.some(r=>r.value===e))return e;const i=t.find(r=>r.value===L4)??t[0];return(i==null?void 0:i.value)??L4},L3=()=>{const e=Sd(T3);return WT(e)?e:zT},Jf=e=>{jd(k3,e)},F1=e=>{jd(E3,e)},q1=e=>{jd(C3,e)},P3=e=>{jd(T3,e)},P4=e=>{const t=wd(M3,e);return t?ty(t):!1},U4=e=>{const t=wd(R3,e);return t?ty(t):!1},z4=e=>{const t=wd(A3,e);return t?ty(t):!1},U3=(e,t)=>{const i=wd(M3,e);i&&ny(i,t)},z3=(e,t)=>{const i=wd(R3,e);i&&ny(i,t)},B3=(e,t)=>{const i=wd(A3,e);i&&ny(i,t)},KT=(e,t)=>{U3(e,t.isFastModeEnabled),z3(e,t.isPlanModeEnabled),B3(e,t.isYoloModeEnabled)},Fp=(e,t=FT())=>{var i,r;return((i=t.find(o=>o.value===e))==null?void 0:i.label)??(typeof e=="string"&&e.trim()?e.trim():((r=t[0])==null?void 0:r.label)??I3)},QT=e=>{var t;return((t=mh.find(i=>i.value===e))==null?void 0:t.label)??mh[2].label},GT=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"}}]'),YT={themes:GT},$3="panda:theme-settings",VT=13,XT=12,H3="codex",ay="codex",ZT='-apple-system, BlinkMacSystemFont, "Segoe UI Variable", "Segoe UI", sans-serif',JT='ui-monospace, "SFMono-Regular", "SF Mono", "Cascadia Mono", "Cascadia Code", Consolas, monospace',eM=/\b(?:serif|sans-serif|monospace|cursive|fantasy|system-ui|emoji|math|fangsong|ui-serif|ui-sans-serif|ui-monospace|ui-rounded)\b/i,B4=(e,t)=>{const i=e==null?void 0:e.trim();return i?eM.test(i)?i:`${i}, ${t}`:t},tM={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"},Nd=(e,t,i)=>Math.min(i,Math.max(t,e)),ac=(e,t)=>{const r=e.trim().match(/^#?([0-9a-f]{3}|[0-9a-f]{6})$/i);if(!r)return t;const[,o]=r;return`#${(o.length===3?o.split("").map(d=>`${d}${d}`).join(""):o).toUpperCase()}`},Qr=e=>{const t=ac(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)}},nM=(e,t,i)=>`#${[e,t,i].map(r=>Nd(Math.round(r),0,255).toString(16).padStart(2,"0")).join("").toUpperCase()}`,Ct=(e,t,i)=>{const r=Qr(e),o=Qr(t),u=Nd(i,0,1);return nM(r.r+(o.r-r.r)*u,r.g+(o.g-r.g)*u,r.b+(o.b-r.b)*u)},sM=e=>{const{r:t,g:i,b:r}=Qr(e),o=u=>{const d=u/255;return d<=.03928?d/12.92:((d+.055)/1.055)**2.4};return o(t)*.2126+o(i)*.7152+o(r)*.0722},aM=e=>sM(e)>.5?"#0D1117":"#FFFFFF",qr=(e,t)=>{const i=Math.round(Nd(t,0,1)*100);return i>=100?e:`color-mix(in srgb, ${e} ${i}%, transparent)`},F3=YT.themes,q3=(e,t)=>{var r,o;const i=t==="light"?e.light:e.dark;return i?{id:e.id,label:tM[e.id]??e.id,codeThemeId:i.codeThemeId,variant:t,accent:ac(i.theme.accent,"#0169CC"),background:ac(i.theme.surface,"#FFFFFF"),foreground:ac(i.theme.ink,"#0D0D0D"),contrast:Nd(Number(i.theme.contrast),0,100),opaqueWindows:!!i.theme.opaqueWindows,semanticColors:{diffAdded:ac(i.theme.semanticColors.diffAdded,"#00A240"),diffRemoved:ac(i.theme.semanticColors.diffRemoved,"#E02E2A"),skill:ac(i.theme.semanticColors.skill,"#751ED9")},fonts:{ui:((r=i.theme.fonts.ui)==null?void 0:r.trim())||null,code:((o=i.theme.fonts.code)==null?void 0:o.trim())||null}}:null},i0=F3.map(e=>q3(e,"light")).filter(e=>!!e),ph=F3.map(e=>q3(e,"dark")).filter(e=>!!e);ph.find(e=>e.id===ay)??ph[0];const wc={mode:"system",lightThemeId:H3,darkThemeId:ay,uiFontSize:VT,codeFontSize:XT},W3=e=>Nd(Number(e),11,18),K3=e=>Nd(Number(e),10,18),iy=()=>typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",Jp=e=>i0.find(t=>t.id===e)??i0[0],eg=e=>ph.find(t=>t.id===e)??ph[0],$4=(e,t=wc,i="light")=>i==="dark"?{...t,darkThemeId:eg(e).id}:{...t,lightThemeId:Jp(e).id},Zl=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:wc.mode,lightThemeId:Jp((e==null?void 0:e.lightThemeId)??H3).id,darkThemeId:eg((e==null?void 0:e.darkThemeId)??ay).id,uiFontSize:W3((e==null?void 0:e.uiFontSize)??wc.uiFontSize),codeFontSize:K3((e==null?void 0:e.codeFontSize)??wc.codeFontSize)}),Q3=()=>{if(typeof window>"u")return wc;try{const e=window.localStorage.getItem($3);return e?Zl(JSON.parse(e)):wc}catch{return wc}},Lf=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem($3,JSON.stringify(Zl(e)))}catch{}},iM=(e,t)=>e==="system"?t:e,Kr=(e,t=iy())=>{const i=Zl(e),r=iM(i.mode,t),o=Jp(i.lightThemeId),u=eg(i.darkThemeId),d=r==="dark"?u:o;return{...i,appearance:r,lightTheme:o,darkTheme:u,activeTheme:d,uiFontFamily:B4(d.fonts.ui,ZT),codeFontFamily:B4(d.fonts.code,JT)}},rM=e=>{if(typeof window>"u")return()=>{};const t=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>{e(t.matches?"dark":"light")};return i(),t.addEventListener("change",i),()=>{t.removeEventListener("change",i)}},lM=(e,t)=>{const i=Kr(e,t),r=i.activeTheme,o=t==="dark",u=(r.contrast-(o?60:45))/100,d=r.semanticColors.diffAdded,m=r.semanticColors.diffRemoved,y=r.semanticColors.skill,g=Qr(d),b=Qr(m),p=Qr(y),v=Qr(r.accent),w=Qr(r.background),N=Qr(r.foreground),j=r.background,T=o?Ct(r.background,"#FFFFFF",.05+u*.08):Ct(r.background,"#FFFFFF",.42+u*.16),M=o?Ct(r.background,"#FFFFFF",.07+u*.08):Ct(r.background,"#FFFFFF",.78+u*.1),P=o?Ct(r.background,"#FFFFFF",.1+u*.08):Ct(r.background,"#FFFFFF",.56+u*.14),I=o?Ct(r.background,"#FFFFFF",.14+u*.08):Ct(r.background,r.foreground,.1+u*.12),k=o?Ct(r.background,"#000000",.08-u*.06):Ct(r.background,r.foreground,.03+u*.08),O=o?Ct(r.background,"#FFFFFF",.08+u*.06):Ct(r.background,r.foreground,.06+u*.08),Q=o?Ct(r.background,"#FFFFFF",.14+u*.08):Ct(r.background,r.foreground,.14+u*.1),J=o?Ct(r.background,"#FFFFFF",.22+u*.08):Ct(r.background,r.foreground,.22+u*.1),F=o?Ct(r.background,"#FFFFFF",.08+u*.04):Ct(r.background,r.foreground,.1+u*.08),B=r.foreground,G=o?Ct(r.foreground,r.background,.28-u*.1):Ct(r.foreground,r.background,.5-u*.14),Z=o?Ct(r.foreground,r.background,.46-u*.1):Ct(r.foreground,r.background,.64-u*.14),ae=Ct(r.foreground,r.background,o?.58:.74),he=r.accent,ne=o?Ct(r.accent,"#FFFFFF",.18):Ct(r.accent,"#FFFFFF",.24),Ce=o?Ct(r.accent,r.background,.78):Ct(r.accent,r.background,.88),R=o?Ct(r.accent,r.background,.84):Ct(r.accent,r.background,.92),X=aM(he),le=o?Ct(r.background,"#FFFFFF",.1):Ct(r.background,r.foreground,.08),ue=o?Ct(r.background,"#000000",.06):Ct(r.background,r.foreground,.035),ye=o?Ct(r.background,"#FFFFFF",.05):Ct(r.background,r.foreground,.06),D=o?Ct(r.background,"#FFFFFF",.03):Ct(r.background,r.foreground,.085),oe=o?Ct(r.background,"#FFFFFF",.065):Ct(r.background,r.foreground,.05),je=Ct(r.foreground,r.background,o?.42:.68),z=o?Ct(r.background,"#FFFFFF",.08):Ct(r.foreground,r.background,.18),be=o?Ct(r.background,"#FFFFFF",.08):Ct(r.background,r.foreground,.06),De=o?Ct(r.background,"#FFFFFF",.12):Ct(r.background,r.foreground,.1),se=o?Ct(r.background,"#FFFFFF",.14+u*.05):Ct(r.background,r.foreground,.12+u*.08),pe=r.opaqueWindows?1:o?.92:.95,ke=r.opaqueWindows?1:o?.94:.965,Ze=r.opaqueWindows?1:.94;return{"--theme-id":r.id,"--theme-code-theme-id":r.codeThemeId,"--theme-window-opaque":r.opaqueWindows?"1":"0","--theme-accent":he,"--theme-accent-rgb":`${v.r} ${v.g} ${v.b}`,"--theme-background":r.background,"--theme-background-rgb":`${w.r} ${w.g} ${w.b}`,"--theme-foreground":r.foreground,"--theme-foreground-rgb":`${N.r} ${N.g} ${N.b}`,"--theme-shadow-rgb":o?"0 0 0":"39 28 17","--theme-ui-font":i.uiFontFamily,"--theme-code-font":i.codeFontFamily,"--theme-ui-font-size":`${i.uiFontSize}px`,"--theme-code-font-size":`${i.codeFontSize}px`,"--color-surface-base":j,"--color-surface-elevated":T,"--color-surface-panel":M,"--color-surface-raised":P,"--color-surface-panel-strong":I,"--color-surface-sidebar":qr(k,ke),"--color-surface-sidebar-elevated":qr(O,ke),"--color-surface-border":Q,"--color-surface-border-strong":J,"--color-surface-border-soft":F,"--color-surface-overlay":qr(I,pe),"--color-surface-floating":qr(M,pe),"--color-surface-tooltip":qr(z,Ze),"--color-surface-code":ue,"--color-surface-code-muted":ye,"--color-surface-code-gutter":D,"--color-surface-code-meta":oe,"--color-surface-inline-code":le,"--color-surface-hover":be,"--color-surface-pressed":De,"--color-surface-danger-soft":qr(m,o?.14:.08),"--color-surface-success-soft":qr(d,o?.14:.08),"--color-text-primary":B,"--color-text-secondary":G,"--color-text-muted":Z,"--color-text-tertiary":ae,"--color-text-on-accent":X,"--color-text-link":he,"--color-text-link-hover":ne,"--color-text-danger":m,"--color-text-success":d,"--color-accent-primary":he,"--color-accent-primary-soft":Ce,"--color-accent-secondary":ne,"--color-accent-secondary-soft":R,"--color-accent-contrast":X,"--color-accent-primary-rgb":`${v.r} ${v.g} ${v.b}`,"--color-success":d,"--color-warning":Ct(r.accent,d,.35),"--color-danger":m,"--color-status-online":he,"--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":he,"--color-code-string":Ct(d,r.foreground,o?.26:.18),"--color-code-number":Ct(y,he,.36),"--color-code-comment":Ct(r.foreground,r.background,o?.52:.72),"--color-code-meta-text":je,"--color-code-add":d,"--color-code-add-rgb":`${g.r} ${g.g} ${g.b}`,"--color-code-add-bg":qr(d,o?.16:.11),"--color-code-remove":m,"--color-code-remove-rgb":`${b.r} ${b.g} ${b.b}`,"--color-code-remove-bg":qr(m,o?.18:.11),"--color-divider":se,"--color-overlay-scrim":r.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":i.uiFontFamily,"--font-sans":i.uiFontFamily,"--font-mono":i.codeFontFamily,"--font-size-ui-base":`${i.uiFontSize}px`,"--font-size-code-base":`${i.codeFontSize}px`}},G3=(e,t=iy())=>{if(typeof document>"u")return;const i=Kr(e,t),r=lM(i,i.appearance),o=document.documentElement;o.dataset.theme=i.appearance,o.dataset.uiTheme=i.appearance,o.dataset.themeId=i.activeTheme.id,o.dataset.codeThemeId=i.activeTheme.codeThemeId,o.dataset.windowStyle=i.activeTheme.opaqueWindows?"opaque":"soft",o.style.colorScheme=i.appearance;for(const[u,d]of Object.entries(r))o.style.setProperty(u,d)},oM=async()=>{if(await Op().catch(()=>{}),"serviceWorker"in navigator){const t=await navigator.serviceWorker.getRegistrations();await Promise.all(t.map(i=>i.unregister()))}if("caches"in window){const t=await window.caches.keys();await Promise.all(t.map(i=>window.caches.delete(i)))}const e=window.indexedDB;if(typeof e.databases=="function"){const t=await e.databases();await Promise.all(t.map(i=>i.name).filter(i=>!!i).map(i=>new Promise(r=>{const o=e.deleteDatabase(i);o.onsuccess=()=>r(),o.onerror=()=>r(),o.onblocked=()=>r()})))}window.localStorage.clear(),window.sessionStorage.clear()},ry="panda:pwa-install-log",cM=48,Ys=e=>((e==null?void 0:e.trim())??"")||null,Y3=()=>{if(typeof window>"u")return[];try{const e=window.localStorage.getItem(ry);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.map(i=>{if(!i||typeof i!="object")return null;const r=i;return typeof r.id!="string"||typeof r.timestamp!="string"||typeof r.kind!="string"||typeof r.message!="string"?null:{id:r.id,timestamp:r.timestamp,kind:r.kind,message:r.message,detail:Ys(r.detail)}}).filter(i=>!!i).sort((i,r)=>+new Date(r.timestamp)-+new Date(i.timestamp)):[]}catch{return[]}},uM=e=>{if(!(typeof window>"u"))try{window.localStorage.setItem(ry,JSON.stringify(e.slice(0,cM)))}catch{}},dM=()=>{if(!(typeof window>"u"))try{window.localStorage.removeItem(ry)}catch{}},Kl=e=>{const t=Y3(),i={id:`${Date.now()}-${Math.random().toString(36).slice(2,8)}`,timestamp:new Date().toISOString(),kind:e.kind,message:e.message.trim(),detail:Ys(e.detail)};return uM([i,...t]),i},H4=(e,t)=>{var i;return((i=e.find(r=>r.kind===t))==null?void 0:i.timestamp)??null},fM=async e=>{const t=await fetch(e,{cache:"no-store"});if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()},hM=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"}}},mM=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=Ys(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 i=await fM(t),r=Array.isArray(i.icons)?i.icons:[],o=await Promise.all(r.slice(0,8).map(async u=>{const d=u,m=Ys(typeof d.src=="string"?d.src:null);if(!m)return{src:"(missing)",purpose:Ys(typeof d.purpose=="string"?d.purpose:null),sizes:Ys(typeof d.sizes=="string"?d.sizes:null),type:Ys(typeof d.type=="string"?d.type:null),ok:!1,status:null,error:"Icon src is missing."};const y=new URL(m,t).toString(),g=await hM(y);return{src:y,purpose:Ys(typeof d.purpose=="string"?d.purpose:null),sizes:Ys(typeof d.sizes=="string"?d.sizes:null),type:Ys(typeof d.type=="string"?d.type:null),ok:g.ok,status:g.status,error:g.error}}));return{href:t,present:!0,ok:!0,error:null,id:Ys(typeof i.id=="string"?i.id:null),name:Ys(typeof i.name=="string"?i.name:null),shortName:Ys(typeof i.short_name=="string"?i.short_name:null),startUrl:Ys(typeof i.start_url=="string"?i.start_url:null),scope:Ys(typeof i.scope=="string"?i.scope:null),display:Ys(typeof i.display=="string"?i.display:null),displayOverride:Array.isArray(i.display_override)?i.display_override.filter(u=>typeof u=="string"):[],themeColor:Ys(typeof i.theme_color=="string"?i.theme_color:null),backgroundColor:Ys(typeof i.background_color=="string"?i.background_color:null),icons:o}}catch(i){return{href:t,present:!0,ok:!1,error:i instanceof Error?i.message:"Manifest fetch failed.",id:null,name:null,shortName:null,startUrl:null,scope:null,display:null,displayOverride:[],themeColor:null,backgroundColor:null,icons:[]}}},pM=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 i,r,o;return{scope:t.scope,activeScriptUrl:((i=t.active)==null?void 0:i.scriptURL)??null,waitingScriptUrl:((r=t.waiting)==null?void 0:r.scriptURL)??null,installingScriptUrl:((o=t.installing)==null?void 0:o.scriptURL)??null}})}}catch{return{supported:!0,controller:!!navigator.serviceWorker.controller,registrations:[]}}},gM=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:"浏览器当前没有给出可用的安装事件,页面更像普通标签页或只能走“添加到主屏幕”的快捷方式链路。"}},_M=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 r=e.manifest.icons.some(d=>d.ok&&(d.sizes??"").includes("192x192")),o=e.manifest.icons.some(d=>d.ok&&(d.sizes??"").includes("512x512"));(!r||!o)&&t.push("manifest 图标里缺少可访问的 192x192 或 512x512 图标,Android 安装链路可能会退化。");const u=e.manifest.icons.filter(d=>!d.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(r=>{var o;return r.kind==="install-choice"&&((o=r.detail)==null?void 0:o.toLowerCase().includes("accepted"))})&&!e.appInstalledSeen&&t.push("站点记录到用户接受过安装请求,但没有后续 appinstalled 事件,更像是浏览器回退成快捷方式,或系统级安装没有完成。"),e.launchedStandalone&&!e.appInstalledSeen&&t.push("当前虽然是独立窗口形态,但没有观测到 appinstalled,不能把它视为已经完成系统级安装。"),t},yM=async e=>{const t=Y3(),[i,r]=await Promise.all([mM(),pM()]),o=navigator,u=typeof window<"u"&&window.matchMedia("(display-mode: standalone)").matches,d=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,b=u||d,p=[];window.isSecureContext&&p.push("当前是安全上下文。"),i.ok&&p.push("manifest 可读取。"),r.registrations.length>0&&p.push(`检测到 ${r.registrations.length} 个 Service Worker 注册。`),g&&p.push("浏览器已提供可调用的安装事件。"),y&&p.push("站点本地记录到过 appinstalled 事件。");const v=["从桌面图标打开后,确认没有浏览器地址栏或标签栏。","到 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:d},promptState:{installPromptAvailable:g,beforeInstallPromptSeen:m,appInstalledSeen:y,lastBeforeInstallPromptAt:H4(t,"beforeinstallprompt"),lastAppInstalledAt:H4(t,"appinstalled")},manifest:i,serviceWorker:r,assessment:gM({standaloneDisplayMode:u,navigatorStandalone:d,installPromptAvailable:g,beforeInstallPromptSeen:m,appInstalledSeen:y}),failureReasons:_M({secureContext:typeof window<"u"?window.isSecureContext:!1,manifest:i,serviceWorker:r,installPromptAvailable:g,appInstalledSeen:y,launchedStandalone:b,logs:t}),successSignals:p,confirmationChecklist:v,logs:t}},vM=e=>{if(typeof window>"u")return()=>{};const t=r=>{(r.key===null||r.key===ey)&&e()},i=()=>{e()};return window.addEventListener("storage",t),window.addEventListener(a0,i),()=>{window.removeEventListener("storage",t),window.removeEventListener(a0,i)}},bM=()=>Mh(),xM=()=>yd,ly=()=>_.useSyncExternalStore(vM,bM,xM);function oy(e){return cs(g3(e))}const V3=e=>{var t,i,r;return["codex-commands",((t=e==null?void 0:e.agentId)==null?void 0:t.trim())??"",((i=e==null?void 0:e.projectId)==null?void 0:i.trim())??"",((r=e==null?void 0:e.sessionId)==null?void 0:r.trim())??""]},X3=e=>{const t=(e==null?void 0:e.enabled)??!0;return cs({queryKey:V3(e==null?void 0:e.scope),enabled:t,queryFn:async()=>(await cn(e==null?void 0:e.scope)).client.getCodexCommands(),staleTime:0,gcTime:30*6e4,refetchOnWindowFocus:!1,retry:1})},F4=e=>{let t;const i=new Set,r=(g,b)=>{const p=typeof g=="function"?g(t):g;if(!Object.is(p,t)){const v=t;t=b??(typeof p!="object"||p===null)?p:Object.assign({},t,p),i.forEach(w=>w(t,v))}},o=()=>t,m={setState:r,getState:o,getInitialState:()=>y,subscribe:g=>(i.add(g),()=>i.delete(g))},y=t=e(r,o,m);return m},SM=(e=>e?F4(e):F4),jM=e=>e;function wM(e,t=jM){const i=tl.useSyncExternalStore(e.subscribe,tl.useCallback(()=>t(e.getState()),[e,t]),tl.useCallback(()=>t(e.getInitialState()),[e,t]));return tl.useDebugValue(i),i}const q4=e=>{const t=SM(e),i=r=>wM(t,r);return Object.assign(i,t),i},NM=(e=>e?q4(e):q4),W4=Q3(),K4=iy(),qa=NM(e=>({panelTab:"git",composerText:"",activeSessionId:null,bottomNavVisible:!0,isSettingsOverlayOpen:!1,themeSettings:W4,systemAppearance:K4,resolvedTheme:Kr(W4,K4),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(i=>{const r=Zl({...i.themeSettings,mode:t});return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setLightThemeId:t=>e(i=>{const r=Zl($4(Jp(t).id,i.themeSettings,"light"));return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setDarkThemeId:t=>e(i=>{const r=Zl({...$4(eg(t).id,i.themeSettings,"dark")});return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setUiFontSize:t=>e(i=>{const r=Zl({...i.themeSettings,uiFontSize:t});return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setCodeFontSize:t=>e(i=>{const r=Zl({...i.themeSettings,codeFontSize:t});return Lf(r),{themeSettings:r,resolvedTheme:Kr(r,i.systemAppearance)}}),setSystemAppearance:t=>e(i=>({systemAppearance:t,resolvedTheme:Kr(i.themeSettings,t)}))})),Q4=980,$i={id:"gpt-image-2",vendor:"openai",label:"gpt-image-2",enabled:!0},Z3=[{value:"openai",label:"OpenAI"},{value:"xai",label:"xAI"}],kM=["settings-image-provider"],Bm=[{id:"theme",title:"主题",description:"调整界面的颜色风格。",icon:"theme"},{id:"models",title:"模型维护",description:"维护可选模型、默认模型和展示顺序。",icon:"models"},{id:"image",title:"绘图",description:"维护生图渠道、API Key 和可选模型。",icon:"image"},{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"}],EM=[{id:"appearance",label:"外观与模型",sections:["theme","models","image","cache"]},{id:"notifications",label:"提醒与安装",sections:["notifications","installation"]},{id:"connection",label:"连接与设备",sections:["connection","dev-manager"]}],CM=[{value:"light",label:"浅色",icon:"sun"},{value:"dark",label:"深色",icon:"moon"},{value:"system",label:"系统",icon:"system"}],W1=e=>({id:(e==null?void 0:e.id)??(typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`image-channel-${Date.now()}`),remark:(e==null?void 0:e.remark)??"Image Provider",base_url:(e==null?void 0:e.base_url)??"https://api.openai.com/v1",models:e!=null&&e.models.length?e.models:[$i],api_key:""}),K1=e=>({id:(e==null?void 0:e.id)??$i.id,label:(e==null?void 0:e.label)??(e==null?void 0:e.id)??$i.label,vendor:(e==null?void 0:e.vendor)??$i.vendor,enabled:(e==null?void 0:e.enabled)??!0}),TM=(e,t,i)=>({active_channel_id:e,channels:t.map(r=>({id:r.id,remark:r.remark.trim()||"Image Provider",base_url:r.base_url.trim(),models:i.length?i:[$i],api_key:r.api_key.trim()||null,api_key_mode:r.api_key.trim()?"set":"keep"}))}),MM=e=>{var t;return((t=Z3.find(i=>i.value===e))==null?void 0:t.label)??e},RM=(e,t,i,r)=>["const pandaTheme = {",` codeThemeId: "${e}",`,` accent: "${t.toLowerCase()}",`,` contrast: ${i},`,` opaqueWindows: ${r},`,"}"],AM=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m15 6-6 6 6 6"})}),IM=({open:e})=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:e?"m6 9 6 6 6-6":"m9 6 6 6-6 6"})}),DM=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01"})}),Q1=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M12 5v14M5 12h14"})}),OM=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"m13.5 6.5 4 4"})]}),LM=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M4.5 7h15"}),a.jsx("path",{d:"M9.5 4.5h5"}),a.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"}),a.jsx("path",{d:"M10 10.5v5.2"}),a.jsx("path",{d:"M14 10.5v5.2"})]}),PM=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6 18 18"}),a.jsx("path",{d:"M18 6 6 18"})]}),UM=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m12 6-5 5M12 6l5 5M12 6v12"})}),zM=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m12 18-5-5M12 18l5-5M12 18V6"})}),G4=({icon:e})=>e==="cache"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"M5 8.5v7c0 1.93 3.13 3.5 7 3.5s7-1.57 7-3.5v-7"}),a.jsx("path",{d:"M5 12c0 1.93 3.13 3.5 7 3.5s7-1.57 7-3.5"})]}):e==="models"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M5 7.5h14M5 12h14M5 16.5h14"}),a.jsx("path",{d:"M8 5.5h.01M8 10h.01M8 14.5h.01"})]}):e==="image"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2.4"}),a.jsx("path",{d:"m7.5 15 3.2-3.2 2.3 2.3 1.5-1.5 2 2.4"}),a.jsx("circle",{cx:"15.5",cy:"9.2",r:"1.1"})]}):e==="connection"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.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"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 3.75v4.5"}),a.jsx("path",{d:"M12 15.75v4.5"}),a.jsx("path",{d:"M3.75 12h4.5"}),a.jsx("path",{d:"M15.75 12h4.5"}),a.jsx("path",{d:"m6.7 6.7 3.1 3.1"}),a.jsx("path",{d:"m14.2 14.2 3.1 3.1"}),a.jsx("path",{d:"m17.3 6.7-3.1 3.1"}),a.jsx("path",{d:"m9.8 14.2-3.1 3.1"}),a.jsx("circle",{cx:"12",cy:"12",r:"2.9"})]}):e==="notifications"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"M10 18.25a2.1 2.1 0 0 0 4 0"})]}):e==="installation"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 3.75v10.5"}),a.jsx("path",{d:"m8.5 10.75 3.5 3.5 3.5-3.5"}),a.jsx("path",{d:"M5.25 16.75h13.5"}),a.jsx("path",{d:"M6 19.25h12"})]}):a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("circle",{cx:"12",cy:"12",r:"3.85"})]}),BM=({icon:e,active:t})=>{const i=t?2:1.8;return e==="sun"?a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"4.1"}),a.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"?a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.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"})}):a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"3.5",y:"5",width:"17",height:"12",rx:"2.4"}),a.jsx("path",{d:"M8 19h8"})]})},$M=({title:e,caption:t,accent:i,background:r,foreground:o,lines:u})=>a.jsxs("div",{className:"theme-preview-panel",style:{"--preview-accent":i,"--preview-background":r,"--preview-foreground":o},children:[a.jsxs("div",{className:"theme-preview-panel__meta",children:[a.jsx("span",{children:e}),a.jsx("span",{children:t})]}),a.jsx("pre",{className:"theme-preview-panel__code","aria-label":`${e} 主题预览`,children:u.map(d=>a.jsx("code",{children:d},d))})]}),Tu=({label:e,value:t})=>a.jsxs("div",{className:"settings-row settings-row--token",children:[a.jsx("div",{className:"settings-row__copy",children:a.jsx("span",{className:"settings-row__label",children:e})}),a.jsxs("div",{className:"theme-token",children:[a.jsx("span",{className:"theme-token__swatch",style:{"--token-color":t}}),a.jsx("span",{children:t})]})]}),$m=({label:e,value:t})=>a.jsxs("div",{className:"settings-row settings-row--token",children:[a.jsx("div",{className:"settings-row__copy",children:a.jsx("span",{className:"settings-row__label",children:e})}),a.jsx("div",{className:"theme-token",children:t})]}),Y4=({label:e,value:t,mono:i})=>a.jsxs("div",{className:"settings-row settings-row--token",children:[a.jsx("div",{className:"settings-row__copy",children:a.jsx("span",{className:"settings-row__label",children:e})}),a.jsx("div",{className:`theme-token theme-token--font ${i?"is-mono":""}`,children:t})]}),V4=({label:e,value:t,onChange:i,min:r,max:o})=>a.jsxs("div",{className:"settings-row settings-row--size",children:[a.jsx("div",{className:"settings-row__copy",children:a.jsx("span",{className:"settings-row__label",children:e})}),a.jsxs("div",{className:"theme-stepper",children:[a.jsx("button",{type:"button",className:"theme-stepper__button",onClick:()=>i(t-1),"aria-label":`${e} 减小 1px`,children:"-"}),a.jsxs("label",{className:"theme-stepper__input-wrap",children:[a.jsx("input",{className:"theme-stepper__input",type:"number",min:r,max:o,step:1,value:t,onChange:u=>i(Number(u.target.value))}),a.jsx("span",{children:"px"})]}),a.jsx("button",{type:"button",className:"theme-stepper__button",onClick:()=>i(t+1),"aria-label":`${e} 增大 1px`,children:"+"})]})]}),X4=(e,t,i,r)=>{if(t===i)return e;const o=e.findIndex(b=>b.id===t),u=e.findIndex(b=>b.id===i);if(o<0||u<0)return e;const d=[...e],[m]=d.splice(o,1);if(!m)return e;const y=d.findIndex(b=>b.id===i),g=r==="before"?y:y+1;return d.splice(g,0,m),d},Mu=e=>{if(!e)return"未记录";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString("zh-CN",{hour12:!1})},Hm=e=>typeof e!="number"||!Number.isFinite(e)?"未测得":`${Math.max(0,Math.round(e))} ms`,G1=async(e,t)=>{const i=await P_(t);return{label:e,...i}},J3=({mode:e="page",onRequestClose:t}={})=>{var _r,Ga;const i=Hi(),r=Ka(),o=Zp(),{data:u}=oy(),[d,m]=_.useState(!1),[y,g]=_.useState(null),[b,p]=_.useState(null),[v,w]=_.useState("theme"),[N,j]=_.useState(null),[T,M]=_.useState(()=>typeof window<"u"&&window.innerWidth>=Q4),[P,I]=_.useState(()=>Z_()),[k,O]=_.useState(()=>qu()),[Q,J]=_.useState(()=>gd()),[F,B]=_.useState(()=>e0()),[G,Z]=_.useState(!1),[ae,he]=_.useState(!1),[ne,Ce]=_.useState(null),[R,X]=_.useState(!1),[le,ue]=_.useState(()=>$u()),[ye,D]=_.useState(()=>w4()),[oe,je]=_.useState(0),z=qa(C=>C.themeSettings),be=qa(C=>C.resolvedTheme),De=qa(C=>C.systemAppearance),se=qa(C=>C.setThemeMode),pe=qa(C=>C.setLightThemeId),ke=qa(C=>C.setDarkThemeId),Ze=qa(C=>C.setUiFontSize),zt=qa(C=>C.setCodeFontSize),Fe=ly(),[kt,Bt]=_.useState(()=>sy()),[Gt,Xt]=_.useState(()=>lp()),[Ft,qe]=_.useState(()=>O3()),[dt,un]=_.useState(null),[$t,An]=_.useState(()=>Of()),[Nn,Tt]=_.useState(null),[lt,Et]=_.useState(null),[rt,st]=_.useState(null),[Dt,an]=_.useState([]),[re,we]=_.useState(null),[Re,te]=_.useState([K1($i)]),[ve,V]=_.useState(null),[q,de]=_.useState(null),[ce,Ae]=_.useState(null),[Ee,$e]=_.useState(null),Pe=typeof window>"u"?null:vo(),ht=typeof window>"u"?null:Rp(),Xe=(u==null?void 0:u.agents.find(C=>C.id===Pe))??(u==null?void 0:u.agents[0]),tn=((_r=Xe==null?void 0:Xe.direct_base_url)==null?void 0:_r.trim().replace(/\/+$/,""))??"",Le=o.platform!=="web",rn=v==="cache"||N==="cache",hn=Xe!=null&&Xe.id?{agentId:Xe.id}:void 0,ns=Xe!=null&&Xe.id?{agentId:Xe.id}:void 0,Xs=V3(hn),$s=[...kM,(ns==null?void 0:ns.agentId)??""],oa=Dt.find(C=>C.id===re)??Dt[0]??null,On=Re.filter(C=>C.enabled).map(({id:C,label:W,vendor:He})=>({id:C,label:W,vendor:He,enabled:!0})),Ss=cs({queryKey:$s,queryFn:async()=>(await cn(ns)).client.getImageProviderSettings(),enabled:!!ns&&(v==="image"||N==="image")}),Kt=cs({queryKey:["settings-connection",o.hubUrl,(Xe==null?void 0:Xe.id)??"",tn],queryFn:async()=>{const C=await cn(),[W,He,tt]=await Promise.all([G1(C.label,C.baseUrl),G1("Panda Hub",bd()),tn?G1((Xe==null?void 0:Xe.name)??"当前节点",tn):Promise.resolve(null)]);return{modeLabel:C.mode==="hub"?"通过 Panda Hub":"直接连接",backendLabel:C.label,backendUrl:C.baseUrl,healthOk:W.healthOk,latencyMs:W.latencyMs,checkedAt:W.checkedAt,activeProbe:W,hubProbe:He,agentProbe:tt}},enabled:v==="connection"||N==="connection",staleTime:0,refetchOnWindowFocus:!1}),Zs=cs({queryKey:["installed-app-info",o.platform],queryFn:()=>DT(),enabled:Le,staleTime:3e4,refetchOnWindowFocus:!1}),us=cs({queryKey:["android-release-manifest",o.hubUrl],queryFn:()=>OT(o.hubUrl),enabled:o.platform==="android"&&!!o.hubUrl&&(v==="connection"||N==="connection"),staleTime:0,refetchOnWindowFocus:!1}),Ln=X3({enabled:rn&&!!hn,scope:hn}),Ot=()=>{je(C=>C+1)},Wn=cs({queryKey:["pwa-install-diagnostics",oe,!!ne,le],queryFn:async()=>yM({installPromptAvailable:!!ne}),enabled:v==="installation"||N==="installation",staleTime:0,refetchOnWindowFocus:!1}),Sn=Gn({mutationFn:async C=>{if(!ns)throw new Error("当前没有可用节点,暂时无法保存绘图渠道。");return(await cn(ns)).client.saveImageProviderSettings(C)},onSuccess:C=>{var He,tt,Rt;r.setQueryData($s,C),an(C.channels.map(ct=>W1(ct))),we(C.active_channel_id??((He=C.channels[0])==null?void 0:He.id)??null);const W=((tt=C.channels.find(ct=>ct.id===C.active_channel_id))==null?void 0:tt.models)??((Rt=C.channels[0])==null?void 0:Rt.models)??[$i];te((W.length?W:[$i]).map(ct=>K1(ct))),V("绘图设置已保存。")},onError:C=>{V(C instanceof Error?C.message:"保存绘图设置失败。")}}),Jn=Gn({mutationFn:async()=>{if(!hn)throw new Error("当前没有可用节点,无法刷新命令目录。");return(await cn(hn)).client.refreshCodexCommands()},onMutate:()=>{g(null)},onSuccess:C=>{r.setQueryData(Xs,C),g(`命令目录已刷新,共 ${C.commands.length} 条,CLI 版本 ${C.cli_version??"未知"}。`)},onError:C=>{g(C instanceof Error?C.message:"刷新命令目录失败。")}});_.useEffect(()=>{var He,tt,Rt;const C=Ss.data;if(!C)return;an(C.channels.map(ct=>W1(ct))),we(C.active_channel_id??((He=C.channels[0])==null?void 0:He.id)??null);const W=((tt=C.channels.find(ct=>ct.id===C.active_channel_id))==null?void 0:tt.models)??((Rt=C.channels[0])==null?void 0:Rt.models)??[$i];te((W.length?W:[$i]).map(ct=>K1(ct)))},[Ss.data]),_.useEffect(()=>{if(typeof window>"u")return;const C=()=>{const W=window.innerWidth>=Q4;M(W)};return C(),window.addEventListener("resize",C),()=>{window.removeEventListener("resize",C)}},[]),_.useEffect(()=>{g(null)},[(Ga=Kt.data)==null?void 0:Ga.backendUrl]),_.useEffect(()=>{T&&j(v)},[v,T]),_.useEffect(()=>{Tt(null)},[v]),_.useEffect(()=>{if(typeof window>"u")return;const C=tt=>{tt.preventDefault(),Ce(tt),Kl({kind:"beforeinstallprompt",message:"浏览器提供了可调用的安装事件。",detail:window.location.href}),Ot()},W=()=>{Ce(null),ue(!0),p("应用已安装到桌面。"),Kl({kind:"appinstalled",message:"站点收到 appinstalled 事件。",detail:"浏览器报告安装流程已经完成或被接受。"}),Ot()},He=()=>{O(qu()),I(Z_()),ue($u()),D(w4()),Kl({kind:"visibilitychange",message:`页面切换为 ${document.visibilityState}。`,detail:`standalone=${$u()?"yes":"no"}`}),Ot()};return window.addEventListener("beforeinstallprompt",C),window.addEventListener("appinstalled",W),document.addEventListener("visibilitychange",He),()=>{window.removeEventListener("beforeinstallprompt",C),window.removeEventListener("appinstalled",W),document.removeEventListener("visibilitychange",He)}},[]),_.useEffect(()=>{if(Fe.length===0||Fe.some(W=>W.value===kt))return;const C=Fe[0].value;Jf(C),Bt(C)},[Fe,kt]),_.useEffect(()=>{var W;if(Fe.length===0||Fe.some(He=>He.value===Gt))return;const C=((W=Fe.find(He=>He.value==="gpt-5.4-mini"))==null?void 0:W.value)??Fe[0].value;F1(C),Xt(C)},[Gt,Fe]),_.useEffect(()=>{var W;if(Fe.length===0||Fe.some(He=>He.value===Ft))return;const C=((W=Fe.find(He=>He.value==="gpt-5.4-mini"))==null?void 0:W.value)??Fe[0].value;q1(C),qe(C)},[Fe,Ft]),_.useEffect(()=>{const C=()=>{Y0().then(W=>{O(W)}).catch(()=>{O(qu())}),J(gd()),B(e0())};return C(),window.addEventListener("focus",C),document.addEventListener("visibilitychange",C),()=>{window.removeEventListener("focus",C),document.removeEventListener("visibilitychange",C)}},[]),_.useEffect(()=>{if(k!=="granted"||!P.completionNotificationsEnabled||!Q)return;let C=!1;return Z(!0),tC(P).then(W=>{C||B(W.synced)}).catch(()=>{C||B(!1)}).finally(()=>{C||Z(!1)}),()=>{C=!0}},[Q,k,P]);const js=()=>{if(e==="overlay"){t==null||t();return}if(ht){fr((Xe==null?void 0:Xe.id)??null),Ea(ht),i({to:"/"});return}i({to:"/nodes"})},Hs=C=>{e==="overlay"&&(t==null||t()),i({to:C})},ca=async()=>{g(null),m(!0);try{await oM(),g("缓存已清理,正在重新载入…"),window.setTimeout(()=>{window.location.replace(`/settings?cache-reset=${Date.now()}`)},180)}catch{m(!1),g("清理失败,请在浏览器设置中手动清理站点数据。")}},Fs=async()=>{if(p(null),Le){if(k==="granted"){p("当前已经拿到系统通知权限;完成提醒会自动跟随系统权限生效。");return}const C=await J_();if(O(C),C==="granted"){const W={completionNotificationsEnabled:!0};sc(W),I(W),p("系统通知已开启,后续任务完成会直接走原生通知。");return}if(C==="denied"){p("系统通知已被拒绝,请到系统设置里重新开启。");return}p("还没有拿到通知权限,可以稍后再试一次。");return}if(k!=="granted"){const C=await J_();if(O(C),C==="granted"){if(!Q){const W={completionNotificationsEnabled:!0};sc(W),I(W),p(Le?"系统通知已开启,任务完成时会直接走原生通知。":"系统通知已开启,但当前环境不支持后台 Web Push。");return}Z(!0);try{const W={completionNotificationsEnabled:!0};await j4(W),sc(W),I(W),B(!0),p("系统通知和后台 Web Push 都已开启。");return}catch(W){B(!1),p(W instanceof Error?W.message:"通知权限已开启,但 Web Push 订阅失败。");return}finally{Z(!1)}}if(C==="denied"){p("系统通知已被拒绝,请到浏览器或系统设置里重新开启。");return}p("还没有拿到通知权限,可以稍后再试一次。");return}if(P.completionNotificationsEnabled){Z(!0);try{await nC();const C={completionNotificationsEnabled:!1};sc(C),I(C),B(!1),p("完成提醒已关闭,后台推送订阅也已移除。")}catch(C){p(C instanceof Error?C.message:"关闭 Web Push 订阅失败。")}finally{Z(!1)}return}if(!Q){const C={completionNotificationsEnabled:!0};sc(C),I(C),p(Le?"原生通知已开启,后续会沿用当前 App 的在线事件提醒。":"当前环境不支持后台 Web Push,只能在页面在线时提醒。");return}Z(!0);try{const C={completionNotificationsEnabled:!0};await j4(C),sc(C),I(C),B(!0),p("完成提醒已开启,Hub 会在会话完成后推送到这台手机。")}catch(C){B(!1),p(C instanceof Error?C.message:"开启 Web Push 失败。")}finally{Z(!1)}},Js=async()=>{p(null),he(!0);try{if(Le){await l3({sessionId:"settings-test",completedAt:new Date().toISOString(),title:"Panda 测试提醒",body:"这是一条来自 Android 壳的本地通知测试。",url:"/settings"}),p("测试通知已发出,请看当前设备的系统通知栏。");return}await sC(),p("测试推送已发出,请看手机或当前设备的通知栏。")}catch(C){p(C instanceof Error?C.message:"发送测试推送失败。")}finally{he(!1)}},ua=async()=>{if(!ne){Kl({kind:"install-unavailable",message:"当前页面没有可用的安装事件。",detail:ye?"浏览器没有下发 beforeinstallprompt,只能走菜单里的安装应用或添加到主屏幕。":"当前浏览器没有提供可调用的安装对话框。"}),Ot(),p(ye?"请在浏览器菜单里选择“安装应用”或“添加到主屏幕”。":"当前浏览器没有提供安装弹窗,请使用浏览器的“添加到主屏幕”。");return}X(!0),p(null),Kl({kind:"install-button-click",message:"用户点击了设置页里的安装按钮。",detail:"准备调用浏览器安装对话框。"}),Ot();try{Kl({kind:"install-prompt-shown",message:"已调用浏览器安装对话框。",detail:"等待用户在系统安装弹窗里做出选择。"}),await ne.prompt();const C=await ne.userChoice;Kl({kind:"install-choice",message:C.outcome==="accepted"?"用户接受了安装请求。":"用户取消了安装请求。",detail:`outcome=${C.outcome}; platform=${C.platform}`}),Ot(),C.outcome==="accepted"?p("安装请求已提交,请回到桌面查看。"):p("你取消了这次安装。")}catch(C){Kl({kind:"install-error",message:"调用浏览器安装流程时报错。",detail:C instanceof Error?C.message:"Unknown install error"}),Ot(),p("浏览器没有完成安装流程,请查看下方安装诊断。")}finally{Ce(null),X(!1),ue($u()),Ot()}},da=()=>{const C={...W1(),models:On.length?On:[$i]};Ae("create"),$e(C),V(null)},fa=C=>{const W=Dt.find(He=>He.id===C);W&&(Ae("edit"),$e({...W}),V(null))},In=()=>{Ae(null),$e(null)},ws=async(C,W,He=Re)=>{await Sn.mutateAsync(TM(W,C,He))},Os=async()=>{if(!Ee)return;const C={...Ee,remark:Ee.remark.trim(),base_url:Ee.base_url.trim()};if(!C.remark){V("请填写渠道备注名称。");return}const W=ce==="edit"?Dt.map(He=>He.id===C.id?C:He):[...Dt,C];try{await ws(W,re??C.id),In()}catch{return}},ee=async C=>{var tt;const W=Dt.filter(Rt=>Rt.id!==C),He=re===C?((tt=W[0])==null?void 0:tt.id)??null:re;try{await ws(W,He)}catch{return}},Be=()=>{de({originalId:null,vendor:"openai",modelId:""}),V(null)},Ke=C=>{const W=Re.find(He=>He.id===C);W&&(de({originalId:W.id,vendor:W.vendor,modelId:W.id}),V(null))},Lt=async()=>{const C=q,W=(C==null?void 0:C.modelId.trim())??"";if(!C||!W){V("请输入绘图模型 ID。");return}const He={id:W,label:W,vendor:C.vendor,enabled:!0};if(Re.find(ct=>ct.id===He.id&&ct.id!==C.originalId)){V("这个绘图模型已经存在。");return}const Rt=C.originalId===null?[...Re,{...He,enabled:!0}]:Re.map(ct=>ct.id===C.originalId?{...He,enabled:ct.enabled}:ct);try{await ws(Dt,re,Rt.map(({id:ct,label:Nt,vendor:Yn,enabled:Kn})=>({id:ct,label:Nt,vendor:Yn,enabled:Kn}))),de(null)}catch{return}},Zt=async C=>{const W=Re.find(tt=>tt.id===C);if(!W)return;if(W.enabled&&Re.filter(tt=>tt.enabled).length<=1){V("至少保留一个启用中的绘图模型。");return}const He=Re.map(tt=>tt.id===C?{...tt,enabled:!tt.enabled}:tt);try{await ws(Dt,re,He.map(({id:tt,label:Rt,vendor:ct,enabled:Nt})=>({id:tt,label:Rt,vendor:ct,enabled:Nt})))}catch{return}},Pt=async C=>{const W=Re.find(tt=>tt.id===C);if(!W)return;if(W.enabled&&Re.filter(tt=>tt.enabled).length<=1){V("至少保留一个启用中的绘图模型。");return}const He=Re.filter(tt=>tt.id!==C);try{await ws(Dt,re,He.map(({id:tt,label:Rt,vendor:ct,enabled:Nt})=>({id:tt,label:Rt,vendor:ct,enabled:Nt})))}catch{return}},At=async C=>{if(C!==re)try{await ws(Dt,C)}catch{return}},mn=C=>{var W,He,tt,Rt,ct;if(qT(C),!C.some(Nt=>Nt.value===kt)){const Nt=((W=C[0])==null?void 0:W.value)??"";Nt&&(Jf(Nt),Bt(Nt))}if(!C.some(Nt=>Nt.value===Gt)){const Nt=((He=C.find(Yn=>Yn.value==="gpt-5.4-mini"))==null?void 0:He.value)??((tt=C[0])==null?void 0:tt.value)??"";Nt&&(F1(Nt),Xt(Nt))}if(!C.some(Nt=>Nt.value===Ft)){const Nt=((Rt=C.find(Yn=>Yn.value==="gpt-5.4-mini"))==null?void 0:Rt.value)??((ct=C[0])==null?void 0:ct.value)??"";Nt&&(q1(Nt),qe(Nt))}},jn=()=>{un("new"),An(Of()),Tt(null)},kn=C=>{un(C.id),An({...C}),Tt(null)},pn=()=>{un(null),An(Of()),Tt(null)},U=()=>{var ct;const C=$t.label.trim(),W=$t.value.trim();if(!C||!W){Tt("请填写显示名和模型 ID。");return}if(Fe.find(Nt=>Nt.value.toLowerCase()===W.toLowerCase()&&Nt.id!==dt)){Tt(`模型 ID ${W} 已存在。`);return}const tt={...$t,label:C,value:W,description:((ct=$t.description)==null?void 0:ct.trim())||null},Rt=dt==="new"?[...Fe,tt]:Fe.map(Nt=>Nt.id===dt?tt:Nt);mn(Rt),un(null),An(Of()),Tt(dt==="new"?"模型已添加。":"模型已更新。")},Ne=C=>{const W=Fe.filter(He=>He.id!==C);if(W.length===0){Tt("至少保留一个模型。");return}mn(W),dt===C&&(un(null),An(Of())),Tt("模型已删除。")},Ue=C=>{Jf(C),Bt(C),Tt(`默认模型已切换为 ${C}。`)},Qe=C=>{F1(C),Xt(C),Tt(`命令执行模型已切换为 ${C}。`)},at=C=>{q1(C),qe(C),Tt(`标题生成模型已切换为 ${C}。`)},Je=(C,W)=>{const He=Fe.findIndex(ct=>ct.id===C);if(He<0)return;const tt=W==="up"?He-1:He+1;if(tt<0||tt>=Fe.length)return;const Rt=Fe[tt];Rt&&mn(X4(Fe,C,Rt.id,W==="up"?"before":"after"))},vt=(C,W)=>{Et(W),st(null),C.dataTransfer.effectAllowed="move",C.dataTransfer.setData("text/plain",W)},ot=(C,W)=>{if(!lt||lt===W)return;C.preventDefault();const He=C.currentTarget.getBoundingClientRect(),tt=C.clientY<He.top+He.height/2?"before":"after";st(Rt=>(Rt==null?void 0:Rt.modelId)===W&&Rt.position===tt?Rt:{modelId:W,position:tt})},nn=C=>{!lt||!rt||rt.modelId!==C||(mn(X4(Fe,lt,C,rt.position)),Et(null),st(null))},Jt=()=>{Et(null),st(null)},qt=be.appearance,St=qt==="light"?i0:ph,En=qt==="light"?z.lightThemeId:z.darkThemeId,gt=St.find(C=>C.id===En)??St[0],ss=be.activeTheme,Ns=RM(gt.codeThemeId,gt.accent,gt.contrast,gt.opaqueWindows),ks=z.mode==="system"?`当前跟随系统:${De==="dark"?"深色":"浅色"}`:`当前固定为${be.appearance==="dark"?"深色":"浅色"}模式`,as="当前正在显示",Es=gt.opaqueWindows?"不透明窗口":"半透明窗口",is=Bm.find(C=>C.id===v)??Bm[0],Cs={"--settings-mobile-sticky-safe-area":Le?"0px":"var(--app-safe-area-top)"},es=`${gt.label} · ${Es} · 对比度 ${gt.contrast}`,qs=Fe.find(C=>C.value===kt)??Fe[0]??null,Ws=Fe.find(C=>C.value===Gt)??Fe.find(C=>C.value==="gpt-5.4-mini")??Fe[0]??null,Ks=Fe.find(C=>C.value===Ft)??Fe.find(C=>C.value==="gpt-5.4-mini")??Fe[0]??null,pr=C=>{var W;return C==="theme"?be.activeTheme.label:C==="models"?(qs==null?void 0:qs.label)??`${Fe.length} 个模型`:C==="image"?(oa==null?void 0:oa.remark)??`${Dt.length} 个渠道`:C==="cache"?y||(Ln.data?`${Ln.data.commands.length} 条命令`:"站点与命令目录"):C==="notifications"?P.completionNotificationsEnabled?"已开启":"未开启":C==="installation"?le?"已安装":"检查状态":(W=Kt.data)!=null&&W.healthOk?Kt.data.modeLabel:(Xe==null?void 0:Xe.name)??"查看链路"},Fi=()=>a.jsx("div",{className:"settings-mobile-layout",children:a.jsx("div",{className:"settings-mobile-sections",role:"list","aria-label":"设置分组",children:EM.map(C=>a.jsx("section",{className:"settings-mobile-group","aria-label":C.label,children:C.sections.map(W=>{const He=Bm.find(ct=>ct.id===W);if(!He)return null;const tt=N===He.id,Rt=pr(He.id);return a.jsxs(_.Fragment,{children:[a.jsxs("button",{type:"button",className:`settings-mobile-row ${tt?"is-active":""}`,"data-section":He.id,onClick:()=>{w(He.id),j(ct=>ct===He.id?null:He.id)},"aria-expanded":tt,"aria-controls":`settings-mobile-detail-${He.id}`,children:[a.jsx("span",{className:"settings-mobile-row__icon","data-section":He.id,"aria-hidden":"true",children:a.jsx(G4,{icon:He.icon})}),a.jsx("span",{className:"settings-mobile-row__copy",children:a.jsx("span",{className:"settings-mobile-row__title",children:He.title})}),a.jsx("span",{className:"settings-mobile-row__summary",children:Rt}),a.jsx("span",{className:"settings-mobile-row__chevron","aria-hidden":"true",children:a.jsx(IM,{open:!1})})]}),tt?a.jsx("section",{className:"settings-mobile-detail settings-mobile-detail--inline",id:`settings-mobile-detail-${He.id}`,children:Ni(He.id)}):null]},He.id)})},C.id))})}),qi=()=>a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"外观"}),a.jsx("p",{className:"settings-panel__subtitle",children:"先选浅色或深色,再挑一个你喜欢的风格。"})]})}),a.jsx("div",{className:"settings-control-grid",children:a.jsxs("div",{className:"settings-control-block settings-control-block--full",children:[a.jsx("span",{className:"settings-control-block__label",children:"显示方式"}),a.jsx("div",{className:"theme-mode-switch",role:"tablist","aria-label":"主题模式",children:CM.map(C=>{const W=C.value===z.mode;return a.jsxs("button",{type:"button",className:`theme-mode-switch__button ${W?"is-active":""}`,onClick:()=>se(C.value),role:"tab","aria-selected":W,children:[a.jsx(BM,{icon:C.icon,active:W}),a.jsx("span",{children:C.label})]},C.value)})}),a.jsx("p",{className:"settings-control-block__hint",children:ks})]})})]}),a.jsxs("div",{className:"settings-theme-layout",children:[a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:qt==="light"?"浅色风格":"深色风格"})})}),a.jsxs("div",{className:"settings-theme-selector",children:[a.jsx("label",{className:"settings-select settings-select--wide",children:a.jsx("select",{value:gt.id,onChange:C=>{if(qt==="light"){pe(C.target.value);return}ke(C.target.value)},"aria-label":qt==="light"?"选择浅色主题":"选择深色主题",children:St.map(C=>a.jsx("option",{value:C.id,children:C.label},`${C.variant}-${C.id}`))})}),a.jsxs("div",{className:"settings-theme-selector__summary",children:[a.jsxs("div",{className:"settings-theme-selector__swatches","aria-hidden":"true",children:[a.jsx("span",{style:{"--theme-card-color":gt.background}}),a.jsx("span",{style:{"--theme-card-color":gt.foreground}}),a.jsx("span",{style:{"--theme-card-color":gt.accent}}),a.jsx("span",{style:{"--theme-card-color":gt.semanticColors.diffAdded}}),a.jsx("span",{style:{"--theme-card-color":gt.semanticColors.diffRemoved}})]}),a.jsxs("div",{className:"settings-theme-selector__copy",children:[a.jsx("strong",{children:gt.label}),a.jsx("span",{children:es})]}),gt.id===ss.id&>.variant===be.appearance?a.jsx("span",{className:"settings-theme-selector__badge",children:"当前"}):a.jsx("span",{className:"settings-theme-selector__badge is-muted",children:"已选"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"风格细节"})}),a.jsx("div",{className:"theme-status-badge",children:as})]}),a.jsx($M,{title:qt==="light"?"浅色预览":"深色预览",caption:gt.label,accent:gt.accent,background:gt.background,foreground:gt.foreground,lines:Ns}),a.jsxs("div",{className:"settings-list",children:[a.jsx($m,{label:"代码风格",value:gt.codeThemeId}),a.jsx($m,{label:"当前模式",value:gt.variant}),a.jsx($m,{label:"对比度",value:String(gt.contrast)}),a.jsx($m,{label:"面板质感",value:Es}),a.jsx(Tu,{label:"强调色",value:gt.accent}),a.jsx(Tu,{label:"背景色",value:gt.background}),a.jsx(Tu,{label:"文字色",value:gt.foreground}),a.jsx(Tu,{label:"新增颜色",value:gt.semanticColors.diffAdded}),a.jsx(Tu,{label:"删除颜色",value:gt.semanticColors.diffRemoved}),a.jsx(Tu,{label:"特殊强调",value:gt.semanticColors.skill}),a.jsx(Y4,{label:"界面字体",value:gt.fonts.ui??"null"}),a.jsx(Y4,{label:"代码字体",value:gt.fonts.code??"null",mono:!0})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"字号"})})}),a.jsxs("div",{className:"settings-list",children:[a.jsx(V4,{label:"界面字号",value:z.uiFontSize,onChange:C=>Ze(W3(C)),min:11,max:18}),a.jsx(V4,{label:"代码字号",value:z.codeFontSize,onChange:C=>zt(K3(C)),min:10,max:18})]})]})]}),Wi=()=>a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"渠道列表"}),a.jsx("p",{className:"settings-panel__subtitle",children:"列表保持极简:只显示备注名称、编辑、删除和启用开关。"})]}),a.jsx("div",{className:"settings-actions-row",children:a.jsxs("button",{type:"button",className:"settings-inline-action",onClick:da,disabled:Sn.isPending,children:[a.jsx(Q1,{}),"新增渠道"]})})]}),ve?a.jsx("div",{className:"settings-inline-status",role:"alert",children:ve}):null,Dt.length?a.jsx("div",{className:"settings-image-channel-list",role:"list","aria-label":"绘图渠道列表",children:Dt.map(C=>{const W=C.id===re,He=C.remark.trim()||"未命名渠道";return a.jsx("article",{className:`settings-image-channel-card ${W?"is-active":""}`,role:"listitem",children:a.jsxs("div",{className:"settings-image-channel-card__row",children:[a.jsxs("div",{className:"settings-image-channel-card__meta",children:[a.jsx("strong",{children:He}),W?a.jsx("span",{className:"settings-image-channel-card__badge",children:"当前启用"}):null]}),a.jsxs("div",{className:"settings-image-channel-card__actions",children:[a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>fa(C.id),disabled:Sn.isPending,"aria-label":`编辑 ${He}`,title:`编辑 ${He}`,children:a.jsx(fh,{size:16,strokeWidth:1.9})}),a.jsx("button",{type:"button",className:"settings-icon-button is-danger",onClick:()=>void ee(C.id),disabled:Sn.isPending,"aria-label":`删除 ${He}`,title:`删除 ${He}`,children:a.jsx($p,{size:16,strokeWidth:1.9})}),a.jsx("button",{type:"button",className:`settings-switch ${W?"is-on":""}`,role:"switch","aria-checked":W,"aria-label":`启用渠道 ${He}`,onClick:()=>void At(C.id),disabled:Sn.isPending,children:a.jsx("span",{className:"settings-switch__track",children:a.jsx("span",{className:"settings-switch__thumb"})})})]})]})},C.id)})}):a.jsx("p",{className:"settings-block__status",children:"还没有绘图渠道,先新增一个渠道。"})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"共享绘图模型"}),a.jsx("p",{className:"settings-panel__subtitle",children:"当前渠道共用同一组模型,列表结构和渠道一致。"})]}),a.jsx("div",{className:"settings-actions-row",children:a.jsxs("button",{type:"button",className:"settings-inline-action",onClick:Be,children:[a.jsx(Q1,{}),"新增模型"]})})]}),Re.length?a.jsx("div",{className:"settings-image-channel-list",role:"list","aria-label":"绘图模型列表",children:Re.map(C=>a.jsx("article",{className:`settings-image-channel-card ${C.enabled?"is-active":""}`,role:"listitem",children:a.jsxs("div",{className:"settings-image-channel-card__row",children:[a.jsxs("div",{className:"settings-image-model-card__meta",children:[a.jsx("strong",{children:C.label}),a.jsx("span",{className:"settings-image-model-card__vendor",children:MM(C.vendor)})]}),a.jsxs("div",{className:"settings-image-channel-card__actions",children:[a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>Ke(C.id),disabled:Sn.isPending,"aria-label":`编辑 ${C.label}`,title:`编辑 ${C.label}`,children:a.jsx(fh,{size:16,strokeWidth:1.9})}),a.jsx("button",{type:"button",className:"settings-icon-button is-danger",onClick:()=>void Pt(C.id),disabled:Sn.isPending,"aria-label":`删除 ${C.label}`,title:`删除 ${C.label}`,children:a.jsx($p,{size:16,strokeWidth:1.9})}),a.jsx("button",{type:"button",className:`settings-switch ${C.enabled?"is-on":""}`,role:"switch","aria-checked":C.enabled,"aria-label":`${C.enabled?"停用":"启用"}模型 ${C.label}`,onClick:()=>void Zt(C.id),disabled:Sn.isPending,children:a.jsx("span",{className:"settings-switch__track",children:a.jsx("span",{className:"settings-switch__thumb"})})})]})]})},C.id))}):a.jsx("p",{className:"settings-block__status",children:"还没有绘图模型,先新增一个模型。"}),q?a.jsxs("div",{className:"settings-model-editor settings-image-model-picker",children:[a.jsx("div",{className:"settings-model-editor__header",children:a.jsx("strong",{children:q.originalId===null?"新增绘图模型":"编辑绘图模型"})}),a.jsxs("div",{className:"settings-model-editor__grid",children:[a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"模型厂商"}),a.jsx("select",{value:q.vendor,onChange:C=>de(W=>W&&{...W,vendor:C.target.value}),children:Z3.map(C=>a.jsx("option",{value:C.value,children:C.label},C.value))})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"模型 ID"}),a.jsx("input",{type:"text",value:q.modelId,onChange:C=>de(W=>W&&{...W,modelId:C.target.value}),placeholder:"gpt-image-2"})]})]}),a.jsxs("div",{className:"settings-model-editor__actions",children:[a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>de(null),disabled:Sn.isPending,children:"取消"}),a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>void Lt(),disabled:Sn.isPending,children:Sn.isPending?"保存中…":"保存模型"})]})]}):null]})]}),ea=Ee&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered image-options-sheet settings-image-channel-sheet",role:"dialog","aria-modal":"true","aria-label":ce==="create"?"新增绘图渠道":"编辑绘图渠道",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:In,"aria-label":"关闭绘图渠道弹窗"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"image-options-panel image-options-panel--compact settings-image-dialog",children:[a.jsx("div",{className:"image-options-panel__handle"}),a.jsxs("div",{className:"image-options-panel__header",children:[a.jsxs("div",{className:"image-options-panel__header-copy",children:[a.jsx("span",{className:"image-options-panel__eyebrow",children:"绘图渠道"}),a.jsx("h2",{children:ce==="create"?"新增渠道":"编辑渠道"}),a.jsx("p",{children:"保持列表简洁,只在这里维护备注、Base URL 和 API Key。"})]}),a.jsx("button",{type:"button",className:"image-options-panel__close",onClick:In,"aria-label":"关闭绘图渠道弹窗",children:a.jsx(PM,{})})]}),a.jsxs("div",{className:"settings-image-dialog__body",children:[a.jsxs("label",{className:"settings-form-field",children:[a.jsx("span",{className:"settings-form-field__label",children:"备注名称"}),a.jsx("input",{className:"settings-form-field__input",type:"text",value:Ee.remark,placeholder:"例如:OpenAI 官方 / 中转 A",onChange:C=>$e(W=>W&&{...W,remark:C.target.value}),autoFocus:!0})]}),a.jsxs("label",{className:"settings-form-field",children:[a.jsx("span",{className:"settings-form-field__label",children:"Base URL"}),a.jsx("input",{className:"settings-form-field__input",type:"text",value:Ee.base_url,placeholder:"https://api.openai.com/v1",onChange:C=>$e(W=>W&&{...W,base_url:C.target.value})}),a.jsx("span",{className:"settings-form-field__hint",children:"支持兼容 OpenAI Images API 的地址前缀,例如 `xxx/v1`。"})]}),a.jsxs("label",{className:"settings-form-field",children:[a.jsx("span",{className:"settings-form-field__label",children:"API Key"}),a.jsx("input",{className:"settings-form-field__input",type:"password",value:Ee.api_key,onChange:C=>$e(W=>W&&{...W,api_key:C.target.value}),placeholder:"留空则沿用已保存的 Key 或环境变量"}),a.jsx("span",{className:"settings-form-field__hint",children:"填写后会覆盖当前渠道的 Key;留空则保持现状。"})]})]}),a.jsxs("div",{className:"image-options-panel__footer",children:[a.jsx("button",{type:"button",onClick:In,disabled:Sn.isPending,children:"取消"}),a.jsx("button",{type:"button",className:"is-primary",onClick:()=>void Os(),disabled:!Ee.remark.trim()||Sn.isPending,children:Sn.isPending?"保存中…":"确认"})]})]})})]}),document.body):null,Ma=()=>{var C;return a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"模型列表"}),a.jsx("p",{className:"settings-panel__subtitle",children:"保持简洁,但把默认模型、命令执行和标题生成的角色关系看得更清楚。"})]}),a.jsxs("button",{type:"button",className:"settings-inline-action",onClick:jn,children:[a.jsx(Q1,{}),"新增模型"]})]}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"首位模型"}),a.jsx("strong",{children:((C=Fe[0])==null?void 0:C.label)??"未配置"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前默认"}),a.jsx("strong",{children:(qs==null?void 0:qs.label)??"未配置"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"命令执行模型"}),a.jsx("strong",{children:(Ws==null?void 0:Ws.label)??"未配置"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"标题生成模型"}),a.jsx("strong",{children:(Ks==null?void 0:Ks.label)??"未配置"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"模型角色"}),a.jsx("p",{className:"settings-panel__subtitle",children:"三个角色分开配置,避免平时切换时看不出差别。"})]})}),a.jsxs("div",{className:"settings-model-role-grid",children:[a.jsxs("label",{className:"settings-model-role-card",children:[a.jsx("span",{className:"settings-model-role-card__eyebrow",children:"默认模型"}),a.jsx("strong",{className:"settings-model-role-card__value",children:(qs==null?void 0:qs.label)??"未配置"}),a.jsx("select",{value:kt,onChange:W=>Ue(W.target.value),children:Fe.map(W=>a.jsx("option",{value:W.value,children:W.label},W.id))})]}),a.jsxs("label",{className:"settings-model-role-card",children:[a.jsx("span",{className:"settings-model-role-card__eyebrow",children:"命令执行"}),a.jsx("strong",{className:"settings-model-role-card__value",children:(Ws==null?void 0:Ws.label)??"未配置"}),a.jsx("select",{value:Gt,onChange:W=>Qe(W.target.value),children:Fe.map(W=>a.jsx("option",{value:W.value,children:W.label},W.id))})]}),a.jsxs("label",{className:"settings-model-role-card",children:[a.jsx("span",{className:"settings-model-role-card__eyebrow",children:"标题生成"}),a.jsx("strong",{className:"settings-model-role-card__value",children:(Ks==null?void 0:Ks.label)??"未配置"}),a.jsx("select",{value:Ft,onChange:W=>at(W.target.value),children:Fe.map(W=>a.jsx("option",{value:W.value,children:W.label},W.id))})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsxs("div",{children:[a.jsx("h3",{className:"settings-panel__title",children:"维护模型"}),a.jsx("p",{className:"settings-panel__subtitle",children:"重点放在层级、排序和默认关系,列表尽量轻一点。"})]})}),Nn?a.jsx("div",{className:"settings-inline-status",role:"alert",children:Nn}):null,a.jsx("div",{className:"settings-model-list",role:"list","aria-label":"模型列表",children:Fe.map((W,He)=>{const tt=lt===W.id,Rt=(rt==null?void 0:rt.modelId)===W.id&&rt.position==="before",ct=(rt==null?void 0:rt.modelId)===W.id&&rt.position==="after",Nt=W.value===kt;return a.jsxs("article",{className:`settings-model-card ${tt?"is-dragging":""} ${Rt?"is-drop-before":""} ${ct?"is-drop-after":""}`,draggable:!0,onDragStart:Yn=>vt(Yn,W.id),onDragOver:Yn=>ot(Yn,W.id),onDrop:Yn=>{Yn.preventDefault(),nn(W.id)},onDragEnd:Jt,role:"listitem",children:[a.jsxs("div",{className:"settings-model-card__main",children:[a.jsx("span",{className:"settings-model-card__grip","aria-hidden":"true",children:a.jsx(DM,{})}),a.jsxs("div",{className:"settings-model-card__copy",children:[a.jsxs("div",{className:"settings-model-card__title-row",children:[a.jsx("strong",{children:W.label}),Nt?a.jsx("span",{className:"settings-model-card__badge",children:"默认"}):null]}),a.jsx("code",{className:"settings-model-card__value",children:W.value})]})]}),a.jsxs("div",{className:"settings-model-card__actions",children:[a.jsx("button",{type:"button",className:`settings-mini-button settings-model-card__primary-action ${Nt?"is-active":""}`,onClick:()=>Ue(W.value),children:"设为默认"}),a.jsxs("div",{className:"settings-model-card__icon-actions",children:[a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>Je(W.id,"up"),disabled:He===0,"aria-label":`上移 ${W.label}`,children:a.jsx(UM,{})}),a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>Je(W.id,"down"),disabled:He===Fe.length-1,"aria-label":`下移 ${W.label}`,children:a.jsx(zM,{})}),a.jsx("button",{type:"button",className:"settings-icon-button",onClick:()=>kn(W),"aria-label":`编辑 ${W.label}`,children:a.jsx(OM,{})}),a.jsx("button",{type:"button",className:"settings-icon-button is-danger",onClick:()=>Ne(W.id),disabled:Fe.length<=1,"aria-label":`删除 ${W.label}`,children:a.jsx(LM,{})})]})]})]},W.id)})}),dt?a.jsxs("div",{className:"settings-model-editor",children:[a.jsx("div",{className:"settings-model-editor__header",children:a.jsx("strong",{children:dt==="new"?"新增模型":"编辑模型"})}),a.jsxs("div",{className:"settings-model-editor__grid",children:[a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"显示名"}),a.jsx("input",{type:"text",value:$t.label,onChange:W=>An(He=>({...He,label:W.target.value})),placeholder:"例如:gpt-5.4"})]}),a.jsxs("label",{className:"settings-field",children:[a.jsx("span",{children:"模型 ID"}),a.jsx("input",{type:"text",value:$t.value,onChange:W=>An(He=>({...He,value:W.target.value})),placeholder:"例如:gpt-5.4"})]})]}),a.jsxs("div",{className:"settings-model-editor__actions",children:[a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:pn,children:"取消"}),a.jsx("button",{type:"button",className:"settings-inline-action",onClick:U,children:"保存"})]})]}):null]})]})},ji=()=>{var C,W;return a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"页面缓存"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"适合什么时候用"}),a.jsx("strong",{children:"页面资源或本地缓存异常"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"常见表现"}),a.jsx("strong",{children:"样式没更新、列表卡旧、页面反复异常"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"清理缓存"})})}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void ca(),disabled:d,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:"清理并刷新"}),a.jsx("span",{children:"删除页面资源缓存和本地会话缓存,强制重新加载最新页面。"})]}),a.jsx("span",{className:"settings-action__state",children:d?"处理中…":"→"})]}),y?a.jsx("p",{className:"settings-block__status",children:y}):null]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"移动端诊断"})})}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>Hs("/diagnostics"),children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:"打开安卓诊断页"}),a.jsx("span",{children:"在手机上检查样式能力、资源加载、Service Worker 和缓存状态,并可上传到后端日志。"})]}),a.jsx("span",{className:"settings-action__state",children:"→"})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"命令目录缓存"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 CLI"}),a.jsx("span",{children:((C=Ln.data)==null?void 0:C.cli_version)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近刷新"}),a.jsx("span",{children:((W=Ln.data)==null?void 0:W.loaded_at)??"尚未生成"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"命令数量"}),a.jsx("span",{children:Ln.data?`${Ln.data.commands.length} 条`:"检测中…"})]}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Jn.mutateAsync(),disabled:Jn.isPending,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:"刷新命令目录"}),a.jsx("span",{children:"重新从当前 Codex CLI 对应版本拉取命令并覆盖本地缓存文件。"})]}),a.jsx("span",{className:"settings-action__state",children:Jn.isPending?"刷新中…":"→"})]})]})]})},Qa=()=>{var ct,Nt,Yn,Kn,Ya,Ra,ii,Va,ge,gn,ta,xo,xa,na,sn,ri,yr,So,Dc,jo,ki,wo;const C=Zs.data,W=us.data,He=!!(W!=null&&W.apk_url),tt=PT(C,W),Rt=N3(o.hubUrl);return a.jsxs("div",{className:"settings-content-stack",children:[Le?a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"Hub 连接配置"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前 Hub"}),a.jsx("strong",{children:o.hubUrl||"未配置"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"首启状态"}),a.jsx("strong",{children:o.onboardingCompleted?"已完成":"未完成"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"App 形态"}),a.jsx("strong",{children:"Capacitor Android"})]})]})]}):a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"网页端连接基线"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前网页入口"}),a.jsx("strong",{children:o.hubUrl||"未检测到"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"地址来源"}),a.jsx("strong",{children:"浏览器访问地址"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"缓存策略"}),a.jsx("strong",{children:"同源页面 + 本地查询缓存"})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:Le?"重新设置 Hub":"当前访问方式"})})}),Le?a.jsx(Q2,{title:"输入新的 Hub 地址",description:"扫码或手动输入后,保存即可让 APK 用新地址重新建立连接。",currentHubUrl:o.hubUrl,initialHubUrl:o.hubUrl,hint:"保存后会清理旧的查询缓存、会话定位和连接判定缓存,避免继续误连到旧 Hub。",saveLabel:"保存并重连",savingLabel:"正在保存地址",saveDescription:"新的 Hub 地址会持久化到本机,后续重新打开 APK 会继续沿用。",saveSuccessMessage:"Hub 地址已保存,连接缓存和旧会话定位已重置。",onSaveSuccess:async ul=>{await P6({hubUrl:ul.url,onboardingCompleted:!0}),await f3(r),Kt.refetch(),us.refetch(),Zs.refetch()}}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 Hub 地址"}),a.jsx("span",{children:o.hubUrl||"未检测到"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"可修改性"}),a.jsx("span",{children:"网页端跟随浏览器打开的地址,不额外保存本地覆盖配置。"})]})]})]}),o.platform==="android"?a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"App 升级"})}),a.jsx("div",{className:"settings-actions-row",children:a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{Zs.refetch(),us.refetch()},children:"刷新版本"})})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前版本"}),a.jsx("span",{children:(C==null?void 0:C.version)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 build"}),a.jsx("span",{children:(C==null?void 0:C.build)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"应用包名"}),a.jsx("span",{children:(C==null?void 0:C.appId)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"更新清单"}),a.jsx("span",{children:Rt||"等待 Hub 地址"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最新发布"}),a.jsx("span",{children:us.isLoading?"检测中…":W?`${W.version_name} (${W.version_code})`:us.error instanceof Error?us.error.message:"未检测到"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"升级状态"}),a.jsx("span",{className:tt?"is-ok":"is-muted",children:tt?"发现新版本":He?"当前已是最新":"等待发布 APK"})]}),W!=null&&W.published_at?a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"发布时间"}),a.jsx("span",{children:Mu(W.published_at)})]}):null,a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>{W!=null&&W.apk_url&&UT(W.apk_url)},disabled:!(W!=null&&W.apk_url),children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:tt?"下载并覆盖安装新版 APK":"打开最新 APK 下载地址"}),a.jsx("span",{children:"通过同一个 `applicationId` 和固定签名覆盖安装,旧配置和本地数据会保留,不需要卸载重装。"})]}),a.jsx("span",{className:"settings-action__state",children:W!=null&&W.apk_url?"→":"未就绪"})]}),W!=null&&W.release_notes.length?a.jsx("div",{className:"settings-diagnostic-list",children:W.release_notes.map(ul=>a.jsxs("div",{className:"settings-diagnostic-list__item",children:[a.jsx("strong",{children:"发布说明"}),a.jsx("span",{children:ul})]},ul))}):null]}):null,a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"当前设备"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"设备名称"}),a.jsx("strong",{children:(Xe==null?void 0:Xe.name)??"未选择节点"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"连接方式"}),a.jsx("strong",{children:((ct=Kt.data)==null?void 0:ct.modeLabel)??"检测中…"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前链路延迟"}),a.jsx("strong",{className:(Nt=Kt.data)!=null&&Nt.healthOk?"is-ok":"is-muted",children:Kt.isLoading?"检测中…":Hm((Yn=Kt.data)==null?void 0:Yn.latencyMs)})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"当前链路"})}),a.jsx("div",{className:"settings-actions-row",children:a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{Kt.refetch()},children:"刷新延迟"})})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"服务名称"}),a.jsx("span",{children:((Kn=Kt.data)==null?void 0:Kn.backendLabel)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"服务地址"}),a.jsx("span",{children:((Ya=Kt.data)==null?void 0:Ya.backendUrl)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前状态"}),a.jsx("span",{className:(Ra=Kt.data)!=null&&Ra.healthOk?"is-ok":"is-muted",children:Kt.isLoading?"检测中…":(ii=Kt.data)!=null&&ii.healthOk?"在线":((Va=Kt.data)==null?void 0:Va.activeProbe.error)??"无法连接"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前延迟"}),a.jsx("span",{children:Hm((ge=Kt.data)==null?void 0:ge.latencyMs)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近探测"}),a.jsx("span",{children:Mu((gn=Kt.data)==null?void 0:gn.checkedAt)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"设备标识"}),a.jsx("span",{children:(Xe==null?void 0:Xe.id)??"未选择节点"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近会话"}),a.jsx("span",{children:ht??"未选择会话"})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"延迟对比"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"Hub 延迟"}),a.jsx("span",{children:Hm((ta=Kt.data)==null?void 0:ta.hubProbe.latencyMs)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"Hub 状态"}),a.jsx("span",{className:(xo=Kt.data)!=null&&xo.hubProbe.healthOk?"is-ok":"is-muted",children:(xa=Kt.data)!=null&&xa.hubProbe.healthOk?"在线":((na=Kt.data)==null?void 0:na.hubProbe.error)??"无法连接"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"Hub 地址"}),a.jsx("span",{children:((sn=Kt.data)==null?void 0:sn.hubProbe.url)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 Agent 延迟"}),a.jsx("span",{children:Hm((yr=(ri=Kt.data)==null?void 0:ri.agentProbe)==null?void 0:yr.latencyMs)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 Agent 状态"}),a.jsx("span",{className:(Dc=(So=Kt.data)==null?void 0:So.agentProbe)!=null&&Dc.healthOk?"is-ok":"is-muted",children:(jo=Kt.data)!=null&&jo.agentProbe?Kt.data.agentProbe.healthOk?"在线":Kt.data.agentProbe.error??"无法连接":"未选择节点"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前 Agent 地址"}),a.jsx("span",{children:((wo=(ki=Kt.data)==null?void 0:ki.agentProbe)==null?void 0:wo.url)||tn||"未配置"})]})]})]})},gr=()=>{const C=Le?"原生 APK":le?"已安装":"未安装",W=k==="granted"?"已允许":k==="denied"?"已拒绝":k==="default"?"待授权":"不支持",He=Le?k==="granted"?"原生通知":"等待授权":Q?G?"同步中":F?"已连接":P.completionNotificationsEnabled&&k==="granted"?"待连接":"未连接":"不支持",tt=Le?k==="granted"?"已开启":"待授权":k==="granted"&&P.completionNotificationsEnabled?F?"后台可达":Q?"前台兜底":"仅前台":"未开启",Rt=Le?"原生系统通知":Q?F?"Hub Web Push + 系统通知":"系统通知,后台通道待建立":"系统通知(仅页面在线)",ct=Le?k==="granted"?"通常可见,细节取决于系统设置":"先授予通知权限":F?le?"已具备条件":"大多可见,安装后更稳":Q?"先建立后台通道":"当前环境很难稳定锁屏提醒",Nt=k==="unsupported"||!Le&&G,Yn=Le?k==="granted"?"系统通知已开启":"申请通知权限":k==="granted"&&P.completionNotificationsEnabled?"关闭完成提醒":G?"正在建立后台提醒":"开启完成提醒",Kn=k==="unsupported"?"当前环境不支持系统通知,需要 HTTPS、Service Worker 和受支持浏览器。":Le?k==="granted"?"首次连接时也会自动申请;这里主要用于补检查权限状态。":"如果首次连接时错过了授权,这里可以补申请一次。":Q?"开启后会向 Hub 注册这台设备,后台或锁屏时也能收到完成提醒。":"当前环境只能在页面在线时提醒,建议安装到桌面并使用支持 Web Push 的浏览器。",Ya=Le?k==="unsupported"?"不可用":k==="granted"?"已开启":"→":k==="unsupported"?"不可用":G?"同步中…":k==="granted"&&P.completionNotificationsEnabled?F?"已连接":Q?"待连接":"已开启":"→",Ra=Le?k==="granted":k==="granted"&&P.completionNotificationsEnabled&&F&&!G,ii=Le?"直接在当前 APK 里发一条本地测试通知,确认系统权限和展示链路正常。":F?"立刻让 Hub 给当前这台设备发一条测试通知,用来确认后台链路是否真的可达。":"只有当前设备已经完成 Web Push 注册后,才能发送测试通知。";return a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"安卓优先提醒"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"桌面安装"}),a.jsx("strong",{children:C})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"系统通知权限"}),a.jsx("strong",{children:W})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"完成提醒"}),a.jsx("strong",{children:tt})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"后台 Web Push"}),a.jsx("strong",{children:He})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:Le?"当前交付形态":"安装到桌面"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"推荐平台"}),a.jsx("span",{children:Le?"当前已经是 Android APK":ye?"Android 当前设备":"Android 效果最佳"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前形态"}),a.jsx("span",{children:Le?"本地前端壳 + 局域网后端":le?"已是桌面应用":"浏览器标签页"})]}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void ua(),disabled:Le||le||R,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:Le?"已经是可安装 APK":le?"已经安装":"安装到桌面"}),a.jsx("span",{children:Le?"当前无需再走 PWA 安装链路,后续升级直接下载新版 APK 覆盖安装即可。":le?"现在可以直接从桌面图标进入 Panda。":"安装后更像应用,系统通知和锁屏提醒也更稳定。"})]}),a.jsx("span",{className:"settings-action__state",children:Le||le?"✓":R?"处理中…":"→"})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"对话完成提醒"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"提醒方式"}),a.jsx("span",{children:Rt})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"锁屏可见"}),a.jsx("span",{children:ct})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"后台通道"}),a.jsx("span",{children:He})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"触发时机"}),a.jsx("span",{children:Le?"App 在线时收到完成事件后,直接发原生系统通知":Q?"Hub 收到对话完成后主动推送":"页面在线时收到完成事件后提醒"})]}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Fs(),disabled:Nt,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:Yn}),a.jsx("span",{children:Kn})]}),a.jsx("span",{className:"settings-action__state",children:Ya})]}),a.jsxs("button",{type:"button",className:"settings-action",onClick:()=>void Js(),disabled:!Ra||ae,children:[a.jsxs("div",{className:"settings-action__copy",children:[a.jsx("strong",{children:Le?ae?"正在发送测试通知":"发送测试通知":ae?"正在发送测试推送":"发送测试推送"}),a.jsx("span",{children:ii})]}),a.jsx("span",{className:"settings-action__state",children:ae?"发送中…":Ra?"→":"未就绪"})]}),b?a.jsx("p",{className:"settings-block__status",children:b}):null]})]})},wi=()=>{const C=Wn.data,W=C!=null&&C.promptState.installPromptAvailable?"可主动触发":C!=null&&C.promptState.beforeInstallPromptSeen?"本地曾出现":"未出现",He=C!=null&&C.promptState.appInstalledSeen?"记录到过":"未记录到",tt=C!=null&&C.manifest.ok?"正常":C!=null&&C.manifest.present?"读取失败":"缺失",Rt=C!=null&&C.serviceWorker.registrations.length?`${C.serviceWorker.registrations.length} 个注册`:C!=null&&C.serviceWorker.supported?"未注册":"不支持";return a.jsxs("div",{className:"settings-content-stack",children:[a.jsxs("section",{className:"settings-panel settings-panel--hero",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"安装结果判断"})})}),a.jsxs("div",{className:"settings-summary-strip",children:[a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"当前研判"}),a.jsx("strong",{children:(C==null?void 0:C.assessment.label)??"检测中…"})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"安装事件"}),a.jsx("strong",{children:W})]}),a.jsxs("div",{className:"settings-summary-strip__item",children:[a.jsx("span",{children:"appinstalled"}),a.jsx("strong",{children:He})]})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsxs("div",{className:"settings-panel__header",children:[a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"当前状态"})}),a.jsxs("div",{className:"settings-actions-row",children:[a.jsx("button",{type:"button",className:"settings-inline-action",onClick:()=>{Wn.refetch()},children:"刷新诊断"}),a.jsx("button",{type:"button",className:"settings-ghost-button",onClick:()=>{dM(),Ot()},children:"清空日志"})]})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前窗口形态"}),a.jsx("span",{children:C?C.environment.standaloneDisplayMode||C.environment.navigatorStandalone?"独立窗口 / 主屏幕入口":"浏览器标签页":"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"系统级安装研判"}),a.jsx("span",{children:(C==null?void 0:C.assessment.label)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"研判置信度"}),a.jsx("span",{children:(C==null?void 0:C.assessment.confidence)??"检测中…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前说明"}),a.jsx("span",{children:(C==null?void 0:C.assessment.detail)??"正在分析…"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近抓取时间"}),a.jsx("span",{children:Mu(C==null?void 0:C.capturedAt)})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"PWA 条件与安装信号"})})}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"安全上下文"}),a.jsx("span",{children:C!=null&&C.environment.secureContext?"是":"否"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"manifest"}),a.jsx("span",{children:tt})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"manifest display"}),a.jsx("span",{children:(C==null?void 0:C.manifest.display)??"未声明"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"Service Worker"}),a.jsx("span",{children:Rt})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"当前可主动触发安装"}),a.jsx("span",{children:C!=null&&C.promptState.installPromptAvailable?"可以":"不可以"})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近 beforeinstallprompt"}),a.jsx("span",{children:Mu(C==null?void 0:C.promptState.lastBeforeInstallPromptAt)})]}),a.jsxs("div",{className:"settings-meta",children:[a.jsx("span",{children:"最近 appinstalled"}),a.jsx("span",{children:Mu(C==null?void 0:C.promptState.lastAppInstalledAt)})]})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"为什么当前可能安装失败"})})}),Wn.isLoading?a.jsx("p",{className:"settings-block__status",children:"正在收集安装诊断…"}):C!=null&&C.failureReasons.length?a.jsx("div",{className:"settings-diagnostic-list",children:C.failureReasons.map((ct,Nt)=>a.jsxs("div",{className:"settings-diagnostic-list__item",children:[a.jsxs("strong",{children:["原因 ",Nt+1]}),a.jsx("span",{children:ct})]},`${Nt}-${ct}`))}):a.jsx("p",{className:"settings-block__status",children:"当前没有发现明显的前端侧阻断条件;如果仍无法完成系统级安装,更像是浏览器策略、安装链路回退或平台侧判断导致。"})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"成功信号与人工确认"})})}),C!=null&&C.successSignals.length?a.jsx("div",{className:"settings-diagnostic-list",children:C.successSignals.map((ct,Nt)=>a.jsxs("div",{className:"settings-diagnostic-list__item",children:[a.jsxs("strong",{children:["信号 ",Nt+1]}),a.jsx("span",{children:ct})]},`${Nt}-${ct}`))}):null,a.jsx("div",{className:"settings-diagnostic-list",children:(C==null?void 0:C.confirmationChecklist.map((ct,Nt)=>a.jsxs("div",{className:"settings-diagnostic-list__item",children:[a.jsxs("strong",{children:["确认 ",Nt+1]}),a.jsx("span",{children:ct})]},`${Nt}-${ct}`)))??null})]}),a.jsxs("section",{className:"settings-panel",children:[a.jsx("div",{className:"settings-panel__header",children:a.jsx("div",{children:a.jsx("h3",{className:"settings-panel__title",children:"浏览器安装事件日志"})})}),Wn.isLoading?a.jsx("p",{className:"settings-block__status",children:"正在读取日志…"}):C!=null&&C.logs.length?a.jsx("div",{className:"settings-log-list",children:C.logs.map(ct=>a.jsxs("article",{className:"settings-log-item",children:[a.jsxs("div",{className:"settings-log-item__meta",children:[a.jsx("strong",{children:ct.message}),a.jsx("span",{children:Mu(ct.timestamp)})]}),a.jsx("div",{className:"settings-log-item__kind",children:ct.kind}),ct.detail?a.jsx("pre",{className:"settings-log-item__detail",children:ct.detail}):null]},ct.id))}):a.jsx("p",{className:"settings-block__status",children:"还没有本地安装日志。后续在这个页面触发安装、刷新页面、出现 beforeinstallprompt 或 appinstalled 后,这里会自动积累证据。"})]})]})},Ni=C=>C==="models"?Ma():C==="image"?Wi():C==="cache"?ji():C==="notifications"?gr():C==="installation"?wi():C==="connection"?Qa():C==="dev-manager"?a.jsx(RT,{isActive:v==="dev-manager"||N==="dev-manager",agentId:(Xe==null?void 0:Xe.id)??null}):qi();return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"conversation-page settings-screen settings-screen--workspace",style:Cs,children:a.jsx("div",{className:"conversation-main settings-screen__main settings-screen__workspace-main",children:a.jsx("div",{className:"settings-screen__body",children:a.jsxs("div",{className:"settings-shell",children:[a.jsxs("header",{className:"settings-page-header",children:[a.jsx("button",{type:"button",className:"settings-card__back",onClick:js,"aria-label":"返回会话",children:a.jsx(AM,{})}),a.jsx("div",{className:"settings-page-header__copy",children:a.jsx("h1",{className:"settings-page-header__title",children:"设置"})})]}),T?a.jsxs("div",{className:"settings-workspace",children:[a.jsxs("aside",{className:"settings-sidebar",children:[a.jsx("div",{className:"settings-sidebar__title",children:"设置"}),a.jsx("nav",{className:"settings-sidebar__nav","aria-label":"设置导航",children:Bm.map(C=>{const W=C.id===v;return a.jsxs("button",{type:"button",className:`settings-sidebar__item ${W?"is-active":""}`,onClick:()=>w(C.id),children:[a.jsx(G4,{icon:C.icon}),a.jsx("span",{children:C.title})]},C.id)})})]}),a.jsxs("main",{className:"settings-stage",children:[a.jsx("header",{className:"settings-stage__header",children:a.jsxs("div",{children:[a.jsx("h2",{className:"settings-stage__title",children:is.title}),a.jsx("p",{className:"settings-stage__description",children:is.description})]})}),Ni(v)]})]}):Fi()]})})})}),ea]})},HM=({onClose:e})=>{const t=_.useRef(null);return _.useEffect(()=>{var u;if(typeof document>"u")return;const i=document.documentElement.style.overflow,r=document.body.style.overflow;document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",(u=t.current)==null||u.focus();const o=d=>{d.key==="Escape"&&(d.preventDefault(),e())};return window.addEventListener("keydown",o),()=>{window.removeEventListener("keydown",o),document.documentElement.style.overflow=i,document.body.style.overflow=r}},[e]),a.jsx("div",{ref:t,className:"settings-overlay",role:"dialog","aria-modal":"true","aria-label":"设置",tabIndex:-1,children:a.jsx(J3,{mode:"overlay",onRequestClose:e})})},FM=()=>{const e=Hi();Zp();const t=qa(p=>p.themeSettings),i=qa(p=>p.systemAppearance),r=qa(p=>p.setSystemAppearance),o=qa(p=>p.isSettingsOverlayOpen),u=qa(p=>p.closeSettingsOverlay),d=ai({select:p=>p.location.pathname}),m=_.useRef(null),y=vo(),g=kh(y),b=!!(y&&g);return _.useEffect(()=>{G3(t,i)},[i,t]),_.useEffect(()=>rM(r),[r]),_.useEffect(()=>{Y0().catch(()=>{})},[]),_.useEffect(()=>{let p;return rC(v=>{e({to:v}).catch(()=>{typeof window<"u"&&window.location.assign(v)})}).then(v=>{p=v}),()=>{p==null||p()}},[e]),_.useEffect(()=>{if(!o){m.current=null;return}if(m.current===null){m.current=d;return}d!==m.current&&u()},[u,o,d]),LE()?a.jsx(pC,{}):a.jsxs("div",{className:"app-shell",children:[b?null:a.jsx(xC,{}),a.jsx(zC,{}),a.jsx("div",{className:"app-shell__content","aria-hidden":o,children:a.jsx(F2,{})}),o?a.jsx(HM,{onClose:u}):null]})},Y1=({message:e})=>a.jsx("p",{className:"empty-copy",children:e}),qM=async e=>(await cn()).client.updateAgent({agentId:e.agentId,action:e.action,displayName:e.displayName??null}),WM=(e,t,i)=>e&&{...e,agents:e.agents.map(r=>r.id===t?{...r,...i}:r)},KM=(e,t)=>e&&{...e,agents:e.agents.filter(i=>i.id!==t)},QM=()=>{var R,X;const e=Hi(),t=Ka(),{data:i,isPending:r,isFetching:o,error:u}=oy(),[d,m]=_.useState(!1),[y,g]=_.useState(null),[b,p]=_.useState(""),[v,w]=_.useState(null),[N,j]=_.useState(null),[T,M]=_.useState(null),[P,I]=_.useState(null),[k,O]=_.useState(!1),Q=i??T,J=(Q==null?void 0:Q.agents)??[];_.useEffect(()=>{let le=!1;return cn().then(ue=>{le||m(ue.mode==="hub")}).catch(()=>{le||m(!1)}),()=>{le=!0}},[]),_.useEffect(()=>{i&&(M(i),I(null))},[i]),_.useEffect(()=>{if(i||k)return;let le=!1;const ue=window.setTimeout(()=>{le||(O(!0),I(null),t.removeQueries({queryKey:lr}),y3(t).then(ye=>{le||M(ye)}).catch(ye=>{le||I(ye instanceof Error?ye.message:"节点列表刷新失败")}).finally(()=>{le||O(!1)}))},1200);return()=>{le=!0,window.clearTimeout(ue)}},[t,i,k]);const F=_.useMemo(()=>J.find(le=>le.id===y)??null,[J,y]),B=_.useMemo(()=>J.find(le=>le.id===v)??null,[J,v]),G=Gn({mutationFn:qM,onMutate:async le=>{j(null),await t.cancelQueries({queryKey:lr});const ue=t.getQueryData(lr);return le.action==="rename"&&t.setQueryData(lr,ye=>{var D;return WM(ye,le.agentId,{display_name:((D=le.displayName)==null?void 0:D.trim())||null})}),le.action==="delete"&&t.setQueryData(lr,ye=>KM(ye,le.agentId)),{previousSnapshot:ue}},onSuccess:(le,ue)=>{ue.action==="rename"&&(g(null),p("")),ue.action==="delete"&&w(null)},onError:(le,ue,ye)=>{ye!=null&&ye.previousSnapshot&&t.setQueryData(lr,ye.previousSnapshot),j(le instanceof Error?le.message:"节点操作失败")},onSettled:async()=>{await t.invalidateQueries({queryKey:lr})}}),Z=G.isPending?((R=G.variables)==null?void 0:R.action)??null:null,ae=G.isPending?((X=G.variables)==null?void 0:X.agentId)??null:null,he=le=>{fr(le.id),Ea(null),sl(null),Hu(null),Hf(!1),xE({agentId:le.id,name:le.name,displayName:le.display_name??null,directBaseUrl:le.direct_base_url,wsBaseUrl:le.ws_base_url,createdAt:new Date().toISOString()}),e({to:"/"})},ne=F&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{g(null),p(""),j(null)},"aria-label":"关闭节点备注面板"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered node-sheet",children:[a.jsx("div",{className:"node-sheet__eyebrow",children:"节点备注"}),a.jsx("div",{className:"sheet-panel__title",children:"修改显示名称"}),a.jsx("p",{className:"node-sheet__description",children:"留空后会恢复显示为原始节点名。"}),a.jsxs("div",{className:"node-sheet__meta",children:[a.jsx("span",{children:F.name}),a.jsx("span",{children:z1(F)})]}),a.jsx("input",{className:"sheet-panel__input",value:b,onChange:le=>p(le.target.value),placeholder:F.name,autoFocus:!0}),N?a.jsx("p",{className:"error-text",children:N}):null,a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{g(null),p(""),j(null)},children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:Z==="rename"&&ae===F.id,onClick:()=>{G.mutate({agentId:F.id,action:"rename",displayName:b.trim()||null})},children:Z==="rename"&&ae===F.id?"保存中...":"保存"})]})]})})]}),document.body):null,Ce=B&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{w(null),j(null)},"aria-label":"关闭删除节点面板"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered node-sheet node-sheet--danger",children:[a.jsx("div",{className:"node-sheet__eyebrow is-danger",children:"删除注册"}),a.jsx("div",{className:"sheet-panel__title",children:"确认移除这个节点?"}),a.jsx("p",{className:"node-sheet__description",children:"这只会删除当前 Hub 里的注册记录,不会删除远端机器。agent 重新注册后可以再次加入。"}),a.jsxs("div",{className:"node-sheet__meta",children:[a.jsx("span",{children:Cc(B)}),a.jsx("span",{children:z1(B)})]}),N?a.jsx("p",{className:"error-text",children:N}):null,a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{w(null),j(null)},children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button node-sheet__button-danger",disabled:Z==="delete"&&ae===B.id,onClick:()=>{G.mutate({agentId:B.id,action:"delete"})},children:Z==="delete"&&ae===B.id?"删除中...":"确认删除"})]})]})})]}),document.body):null;return a.jsxs("div",{className:"nodes-screen",children:[a.jsxs("div",{className:"nodes-screen__header",children:[a.jsx("h1",{children:"节点列表"}),a.jsx("p",{children:"查看所有在线节点和局域网地址"})]}),a.jsx("div",{className:"nodes-screen__content node-list",children:!Q&&(r||o||k)?a.jsx(Y1,{message:"正在读取节点列表..."}):!Q&&(u||P)?a.jsx(Y1,{message:u instanceof Error?u.message:P??"节点列表加载失败"}):J.length===0?a.jsx(Y1,{message:"暂无节点"}):J.map(le=>{const ue=fE(le),ye=Cc(le),D=Z==="rename"&&ae===le.id,oe=Z==="delete"&&ae===le.id;return a.jsxs("article",{className:`node-card ${d?"node-card--manageable":""}`,children:[a.jsxs("button",{type:"button",className:"node-card__surface",onClick:()=>he(le),children:[a.jsxs("div",{className:"node-card__title-stack",children:[a.jsx("strong",{children:ye}),ue?a.jsxs("span",{className:"node-card__secondary-name",children:["原名称 · ",ue]}):null]}),a.jsx("div",{className:"node-card__ip",children:z1(le)})]}),a.jsxs("div",{className:"node-card__rail",children:[a.jsx("span",{className:`node-status-dot ${le.status}`,"aria-label":le.status==="online"?"节点在线":"节点离线",title:le.status==="online"?"节点在线":"节点离线"}),d?a.jsxs("div",{className:"node-card__actions",children:[a.jsx("button",{type:"button",className:"node-card__icon-button","aria-label":`修改 ${ye} 的备注名称`,title:"修改备注名称",disabled:oe,onClick:()=>{w(null),j(null),g(le.id),p(le.display_name??"")},children:a.jsx(fh,{size:16,strokeWidth:2})}),a.jsx("button",{type:"button",className:"node-card__icon-button is-danger","aria-label":`删除 ${ye} 节点注册`,title:"删除注册节点",disabled:D,onClick:()=>{g(null),p(""),j(null),w(le.id)},children:a.jsx($p,{size:16,strokeWidth:2})})]}):null]})]},le.id)})}),ne,Ce]})};function GM(e){return cs({queryKey:(e==null?void 0:e.queryKey)??_C,queryFn:async()=>(await cn(e==null?void 0:e.scope)).client.getPhaseOneSnapshot({fallbackToMock:!1}),refetchInterval:3e5,refetchOnWindowFocus:!1,retry:1})}const YM=(e,t)=>{for(const[,i]of e){const r=i==null?void 0:i.sessions.find(o=>o.id===t);if(r!=null&&r.agent_id)return r.agent_id}return null},VM=()=>{var y,g;const{sessionId:e}=Mc({strict:!1}),t=Hi(),i=Ka(),r=W0(e),o=GM({queryKey:["session-route-bridge",e??""]}),u=e?YM(i.getQueriesData({queryKey:hs}),e):null,d=e?((g=(y=o.data)==null?void 0:y.sessions.find(b=>b.id===e))==null?void 0:g.agent_id)??null:null,m=(r==null?void 0:r.agentId)??u??d??vo();return _.useEffect(()=>{if(!e){t({to:"/",replace:!0});return}!m&&(o.isPending||o.isFetching)||(Ea(e),sl(e),m&&fr(m),t({to:"/",replace:!0}))},[t,m,e,o.isFetching,o.isPending]),null},XM=(e,t)=>e==="offline"?"offline":e==="online"&&t==="connected"?"online":e==="online"?"reconnecting":"offline",ZM=e=>{switch(e){case"online":return"节点在线";case"reconnecting":return"节点重连中";case"offline":return"节点离线";default:return"节点状态未知"}},Gr="__chat_only__",Fm=e=>e===Gr;function e5(e){return cs(_3(e))}const JM=24,gh="__projectless__",al={sessions:[],nextCursor:null,totalCount:0,isLoading:!1,error:null,initialized:!1},t5=e=>e.trim(),eR=e=>[...e].sort((t,i)=>Number(i.pinned)-Number(t.pinned)||+new Date(i.last_event_at)-+new Date(t.last_event_at)),tR=(e,t)=>{const i=new Map;for(const r of e)i.set(r.id,r);for(const r of t)i.set(r.id,r);return eR([...i.values()])},qm=(e,t)=>e[t5(t)]??al;function n5(e){var p,v,w;const[t,i]=_.useState({}),[r,o]=_.useState({}),u=_.useCallback(()=>{i({}),o({})},[]);_.useEffect(()=>{u()},[(p=e==null?void 0:e.scope)==null?void 0:p.agentId,(v=e==null?void 0:e.scope)==null?void 0:v.projectId,(w=e==null?void 0:e.scope)==null?void 0:w.sessionId,e==null?void 0:e.selectedSessionId,u]);const d=_.useCallback(async(N,j)=>{var O;const T=((O=j.projectId)==null?void 0:O.trim())??"",M=j.projectless===!0,P=M?gh:t5(T);if(!P)return;const I=N==="history"?i:o,k=qm(N==="history"?t:r,P);if(!k.isLoading&&!(k.initialized&&k.nextCursor===null)){I(Q=>({...Q,[P]:{...qm(Q,P),isLoading:!0,error:null}}));try{const J=await(await cn(e==null?void 0:e.scope)).client.getWorkspaceSessionPage({bucket:N,projectId:M?null:P,projectless:M,cursor:k.initialized?k.nextCursor:null,limit:JM,selectedSessionId:(e==null?void 0:e.selectedSessionId)??null});I(F=>{const B=qm(F,P);return{...F,[P]:{sessions:tR(B.sessions,J.sessions),nextCursor:J.next_cursor,totalCount:J.total_count,isLoading:!1,error:null,initialized:!0}}})}catch(Q){I(J=>({...J,[P]:{...qm(J,P),isLoading:!1,error:Q instanceof Error?Q.message:"加载会话分页失败",initialized:!0}}))}}},[r,t,e==null?void 0:e.scope,e==null?void 0:e.selectedSessionId]),m=_.useCallback(async N=>{await d("history",{projectId:N})},[d]),y=_.useCallback(async()=>{await d("history",{projectless:!0})},[d]),g=_.useCallback(async N=>{await d("archived",{projectId:N})},[d]),b=_.useCallback(async()=>{await d("archived",{projectless:!0})},[d]);return{historyState:t,archivedState:r,loadMoreHistory:m,loadMoreProjectlessHistory:y,loadMoreArchived:g,loadMoreProjectlessArchived:b,reset:u}}const nR=180*1e3,rc=6,s5="panda:completed-session-seen-at",V1=6,sR=220,X1="__chat__",Z1="__image__",Wm=e=>{e.cancelable&&e.preventDefault()},Z4=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.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"})}),J4=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:a.jsx("path",{d:"M12 5v14M5 12h14"})}),aR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{x:"3",y:"4",width:"6",height:"6",rx:"1.5"}),a.jsx("rect",{x:"15",y:"4",width:"6",height:"6",rx:"1.5"}),a.jsx("rect",{x:"3",y:"14",width:"6",height:"6",rx:"1.5"}),a.jsx("rect",{x:"15",y:"14",width:"6",height:"6",rx:"1.5"})]}),ex=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"M5 6.5A2.5 2.5 0 0 1 7.5 4h9A2.5 2.5 0 0 1 19 6.5v6A2.5 2.5 0 0 1 16.5 15H11l-4.5 4v-4H7.5A2.5 2.5 0 0 1 5 12.5z"})}),iR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{x:"4",y:"5",width:"16",height:"14",rx:"2.5"}),a.jsx("circle",{cx:"9",cy:"10",r:"1.4"}),a.jsx("path",{d:"m7 16 3.5-3.5 2.5 2.5 2-2 2.5 3"})]}),rR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.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"}),a.jsx("path",{d:"M16.5 10.5v5"}),a.jsx("path",{d:"M14 13h5"})]}),tx=({open:e})=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",className:e?"is-open":"",children:a.jsx("path",{d:"m9 6 6 6-6 6"})}),lR=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})}),oR=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m15 6-6 6 6 6"})}),cR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M10.33 4.32c.6-1.76 2.74-1.76 3.34 0a1.78 1.78 0 0 0 2.66 1l.18-.1c1.6-.92 3.4.88 2.48 2.48l-.1.18a1.78 1.78 0 0 0 1 2.66c1.76.6 1.76 2.74 0 3.34a1.78 1.78 0 0 0-1 2.66l.1.18c.92 1.6-.88 3.4-2.48 2.48l-.18-.1a1.78 1.78 0 0 0-2.66 1c-.6 1.76-2.74 1.76-3.34 0a1.78 1.78 0 0 0-2.66-1l-.18.1c-1.6.92-3.4-.88-2.48-2.48l.1-.18a1.78 1.78 0 0 0-1-2.66c-1.76-.6-1.76-2.74 0-3.34a1.78 1.78 0 0 0 1-2.66l-.1-.18c-.92-1.6.88-3.4 2.48-2.48l.18.1a1.78 1.78 0 0 0 2.66-1Z"}),a.jsx("circle",{cx:"12",cy:"12",r:"3.15"})]}),uR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("circle",{cx:"6",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"12",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"18",cy:"12",r:"1",fill:"currentColor",stroke:"none"})]}),dR=e=>{const t=Date.now(),i=new Date(e).getTime(),r=Math.max(0,t-i),o=60*1e3,u=60*o,d=24*u;return r<u?`${Math.max(1,Math.floor(r/o))}分钟`:r<d?`${Math.max(1,Math.floor(r/u))}小时`:`${Math.max(1,Math.floor(r/d))}天`},J1=e=>e.run_state==="completed"&&e.run_state_changed_at&&Date.now()-new Date(e.run_state_changed_at).getTime()>nR?"idle":e.run_state??"idle",nx=(e,t)=>Number(t.pinned)-Number(e.pinned)||+new Date(t.last_event_at)-+new Date(e.last_event_at),sx=(e,t)=>{if(e.length<=rc)return e;if(!t)return e.slice(0,rc);const i=e.findIndex(r=>r.id===t);return i===-1||i<rc?e.slice(0,rc):[...e.slice(0,rc-1),e[i]]},fR=()=>{if(typeof window>"u")return{};try{const e=window.localStorage.getItem(s5);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},e_=(e,t)=>e.length===t.length&&e.every((i,r)=>i===t[r]),hR=(e,t)=>{if(!t||t.length===0||e.length<=1)return e;const i=new Map(e.map(u=>[u.id,u])),r=new Set,o=[];for(const u of t){const d=i.get(u);!d||r.has(u)||(r.add(u),o.push(d))}for(const u of e)r.has(u.id)||o.push(u);return o},mR=(e,t,i)=>{if(t<0||t>=e.length||i<0||i>=e.length||t===i)return e;const r=[...e],[o]=r.splice(t,1);return o?(r.splice(i,0,o),r):e},pR=(e,t,i)=>{if(t.length===0)return e;const r=new Set(t);let o=0;return e.map(u=>{if(!r.has(u))return u;const d=i[o]??u;return o+=1,d})},Ru=(e,t)=>`${e}:${t}`,a5=_.memo(function({open:t,progress:i=t?1:0,isDragging:r=!1,desktopPinned:o=!1,isDesktopResizing:u=!1,onClose:d,onDesktopResizeStart:m,currentAgent:y,agentIndicatorState:g,projects:b,sessions:p,projectStats:v=[],historySessionsByProject:w={},archivedSessionsByProject:N={},chatHistorySessions:j=[],chatArchivedSessions:T=[],historyPageStateByProject:M={},archivedPageStateByProject:P={},chatHistoryPageState:I=al,chatArchivedPageState:k=al,activeSessionId:O,onCreateSession:Q,onCreateChat:J,onCreateImageSession:F,onCreateDirectoryThread:B,onSelectSession:G,onSessionAction:Z,onThreadAction:ae,onOpenSettings:he,onLoadMoreHistory:ne,onLoadMoreChatHistory:Ce,onLoadMoreArchived:R,onLoadMoreChatArchived:X,pendingSessionActionId:le,pendingThreadActionId:ue}){const ye=Hi(),D=i>.001,oe=!!y,je=oe?g??((y==null?void 0:y.status)==="online"?"online":"offline"):null,z=je?ZM(je):"未选择节点",be=_.useRef({threads:null,archived:null}),De=_.useRef({}),se=_.useRef(null),pe=_.useRef(null),ke=_.useRef(null),Ze=_.useRef(null),zt=_.useRef(null),Fe=_.useRef({}),kt=_.useRef(null),[Bt,Gt]=_.useState({}),[Xt,Ft]=_.useState(null),[qe,dt]=_.useState(null),un=_.useMemo(()=>p.map(U=>{const Ne=Bt[U.id];return Ne?{...U,...Ne.pinned===void 0?null:{pinned:Ne.pinned}}:U}).filter(U=>{var Ne;return!((Ne=Bt[U.id])!=null&&Ne.hidden)}),[Bt,p]),$t=_.useMemo(()=>new Map(v.map(U=>[U.project_id,U])),[v]),An=(qe==null?void 0:qe.nextGlobalProjectIds)??Xt,Nn=_.useMemo(()=>hR(b,An),[b,An]),Tt=_.useMemo(()=>un.filter(U=>!U.subagent),[un]),lt=Tt.find(U=>U.id===O),Et=lt==null?void 0:lt.project_id,rt=lt?lt.project_id||(lt.provider==="image"?Z1:X1):"",[st,Dt]=_.useState(rt?[rt]:[]),[an,re]=_.useState("threads"),[we,Re]=_.useState(null),[te,ve]=_.useState(null),[V,q]=_.useState(null),[de,ce]=_.useState(null),[Ae,Ee]=_.useState([]),[$e,Pe]=_.useState(null),[ht,Xe]=_.useState(""),[tn,Le]=_.useState(()=>fR()),rn=_.useMemo(()=>Tt.filter(U=>!U.archived),[Tt]),hn=_.useMemo(()=>rn.filter(U=>U.pinned).sort((U,Ne)=>+new Date(Ne.last_event_at)-+new Date(U.last_event_at)),[rn]),ns=_.useMemo(()=>rn.filter(U=>!U.pinned&&U.project_id.trim().length>0&&U.provider!=="image"),[rn]),Xs=_.useMemo(()=>rn.filter(U=>!U.pinned&&U.project_id.trim().length===0&&U.provider!=="image"),[rn]),$s=_.useMemo(()=>rn.filter(U=>!U.pinned&&U.project_id.trim().length===0&&U.provider==="image"),[rn]),oa=U=>Nn.map(Ne=>{var St;const Ue=$t.get(Ne.id),Qe=U==="threads"?ns.filter(En=>En.project_id===Ne.id):N[Ne.id]??[],at=U==="threads"?w[Ne.id]??[]:[],Je=[...Qe];for(const En of at)Je.some(gt=>gt.id===En.id)||Je.push(En);const vt=Je.sort((En,gt)=>nx(En,gt)),ot=U==="threads"?M[Ne.id]??al:P[Ne.id]??al,nn=U==="threads"?vt.length+Math.max(0,(Ue==null?void 0:Ue.hidden_history_count)??0):Math.max(vt.length,(Ue==null?void 0:Ue.archived_session_count)??0),Jt=U==="threads"?Math.max(0,((Ue==null?void 0:Ue.hidden_history_count)??0)-ot.sessions.length):Math.max(0,((Ue==null?void 0:Ue.archived_session_count)??0)-ot.sessions.length),qt=((St=vt[0])==null?void 0:St.last_event_at)??new Date(0).toISOString();return{project:Ne,threadSessions:vt,collapsedThreadSessions:sx(vt,O),hiddenSessionCount:Math.max(0,vt.length-rc),totalSessionCount:nn,pageState:ot,remainingPageCount:Jt,latestEventAt:qt}}).filter(({totalSessionCount:Ne})=>Ne>0),On=_.useMemo(()=>oa("threads"),[O,P,N,M,w,Nn,$t,ns]),Ss=_.useMemo(()=>oa("archived"),[O,P,N,M,w,Nn,$t,ns]),Kt=(U,Ne)=>{const Ue=$t.get(""),Qe=U==="threads"?Ne==="image"?$s:Xs:T.filter(qt=>qt.provider===Ne),at=U==="threads"?j.filter(qt=>qt.provider===Ne):[],Je=[...Qe];for(const qt of at)Je.some(St=>St.id===qt.id)||Je.push(qt);const vt=Je.sort((qt,St)=>nx(qt,St)),ot=U==="threads"?I:k,nn=U==="threads"?vt.length+Math.max(0,(Ue==null?void 0:Ue.hidden_history_count)??0):Math.max(vt.length,(Ue==null?void 0:Ue.archived_session_count)??0),Jt=U==="threads"?Math.max(0,((Ue==null?void 0:Ue.hidden_history_count)??0)-ot.sessions.length):Math.max(0,((Ue==null?void 0:Ue.archived_session_count)??0)-ot.sessions.length);return{threadSessions:vt,collapsedThreadSessions:sx(vt,O),hiddenSessionCount:Math.max(0,vt.length-rc),totalSessionCount:nn,pageState:ot,remainingPageCount:Jt}},Zs=_.useMemo(()=>Kt("threads","codex"),[O,k,T,I,j,$t,Xs,$s]),us=_.useMemo(()=>Kt("archived","codex"),[O,k,T,I,j,$t,Xs,$s]),Ln=_.useMemo(()=>Kt("threads","image"),[O,k,T,I,j,$t,Xs,$s]),Ot=_.useMemo(()=>Kt("archived","image"),[O,k,T,I,j,$t,Xs,$s]);_.useEffect(()=>{Gt(U=>{let Ne=!1;const Ue={...U};for(const[Qe,at]of Object.entries(U)){const Je=p.find(ot=>ot.id===Qe);if(!Je){at.hidden&&(delete Ue[Qe],Ne=!0);continue}(at.pinned===void 0||Je.pinned===at.pinned)&&!at.hidden&&(delete Ue[Qe],Ne=!0)}return Ne?Ue:U})},[p]),_.useEffect(()=>{Ft(U=>{if(!U)return U;const Ne=b.map(Qe=>Qe.id),Ue=[...U.filter(Qe=>Ne.includes(Qe)),...Ne.filter(Qe=>!U.includes(Qe))];return e_(Ue,Ne)?null:Ue})},[b]),_.useEffect(()=>{rt&&Dt(U=>U.includes(rt)?U:[...U,rt])},[rt]),_.useEffect(()=>{re(lt!=null&<.archived?"archived":"threads")},[lt==null?void 0:lt.archived,O]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(s5,JSON.stringify(tn))}catch{}},[tn]),_.useEffect(()=>{t||o||(q(null),ce(null),Pe(null),ve(null))},[o,t]),_.useEffect(()=>{if(!o||!V)return;const U=Ne=>{const Ue=Ne.target;if(!(Ue instanceof Element)){q(null);return}Ue.closest(".thread-group__menu-anchor")||Ue.closest(".thread-group__menu")||q(null)};return window.addEventListener("pointerdown",U),()=>{window.removeEventListener("pointerdown",U)}},[o,V]),_.useEffect(()=>{if(!O)return;const U=Tt.find(Ue=>Ue.id===O);if(!U||J1(U)!=="completed"||!U.run_state_changed_at)return;const Ne=U.run_state_changed_at;Le(Ue=>Ue[U.id]===Ne?Ue:{...Ue,[U.id]:Ne})},[O,Tt]),_.useEffect(()=>()=>{se.current!==null&&globalThis.clearTimeout(se.current),Sn(),kt.current!==null&&window.cancelAnimationFrame(kt.current)},[]),_.useEffect(()=>{Ze.current=qe},[qe]),_.useLayoutEffect(()=>{if(typeof window>"u")return;const U={},Ne=[],Ue=qe?Ru(qe.pane,qe.projectId):null;for(const[Qe,at]of Object.entries(De.current)){if(!at)continue;const Je=at.offsetTop;if(U[Qe]=Je,Ue===Qe)continue;const vt=Fe.current[Qe];if(vt===void 0)continue;const ot=vt-Je;Math.abs(ot)<.5||(at.style.transition="none",at.style.transform=`translateY(${ot}px)`,Ne.push(at))}kt.current!==null&&window.cancelAnimationFrame(kt.current),Ne.length>0&&(kt.current=window.requestAnimationFrame(()=>{for(const Qe of Ne)Qe.style.transition="",Qe.style.transform=""})),Fe.current=U},[On,Ss,st,Ae,qe==null?void 0:qe.projectId,An]);const Wn=()=>{se.current!==null&&(globalThis.clearTimeout(se.current),se.current=null)},Sn=()=>{const U=ke.current;U&&(U.removeEventListener("selectstart",Wm),U.removeEventListener("contextmenu",Wm),ke.current=null)},Jn=U=>U==="threads"?On:Ss,js=(U,Ne,Ue,Qe,at)=>{const Je=be.current[Ne],vt=De.current[Ru(Ne,U)];if(!Je||!vt)return!1;const ot=Jn(Ne).map(is=>is.project.id),nn=ot.indexOf(U);if(nn===-1)return!1;const Jt=Nn.map(is=>is.id),qt=Je.getBoundingClientRect(),St=vt.getBoundingClientRect(),En=vt.offsetHeight,gt=vt.offsetWidth,ss=at-St.top,Ns=Je.scrollTop,ks=Math.max(Ns,Je.scrollTop+Je.clientHeight-En),as=Math.max(Ns,Math.min(ks,Je.scrollTop+at-qt.top-ss)),Es={pane:Ne,projectId:U,pointerId:Ue,pointerType:Qe,originIndex:nn,visibleProjectIds:ot,nextVisibleProjectIds:ot,nextGlobalProjectIds:Jt,previewTop:as,itemHeight:En,itemWidth:gt,pointerOffsetY:ss};return Ze.current=Es,dt(Es),zt.current=U,!0},Hs=U=>{dt(Ne=>{if(!Ne)return Ne;Ze.current=Ne;const Ue=be.current[Ne.pane];if(!Ue||!De.current[Ru(Ne.pane,Ne.projectId)])return Ne;const Qe=Ue.getBoundingClientRect(),at=Ue.scrollTop,Je=Math.max(at,Ue.scrollTop+Ue.clientHeight-Ne.itemHeight),vt=Math.max(at,Math.min(Je,Ue.scrollTop+U-Qe.top-Ne.pointerOffsetY)),ot=vt+Ne.itemHeight/2,nn=Ne.nextVisibleProjectIds,Jt=nn.indexOf(Ne.projectId);if(Jt===-1)return Ne;const qt=nn.filter(as=>as!==Ne.projectId);let St=0;const En=qt[0],gt=En?De.current[Ru(Ne.pane,En)]:null;if(gt&&vt<=gt.offsetTop+gt.offsetHeight*.42)St=0;else for(let as=0;as<qt.length;as+=1){const Es=qt[as],is=Es?De.current[Ru(Ne.pane,Es)]:null;if(!is){St=as+1;continue}const Cs=is.offsetTop+is.offsetHeight/2;if(ot<=Cs){St=as;break}St=as+1}const ss=mR(nn,Jt,St),Ns=pR(Ne.nextGlobalProjectIds,Ne.visibleProjectIds,ss);if(vt===Ne.previewTop&&e_(ss,Ne.nextVisibleProjectIds))return Ne;const ks={...Ne,previewTop:vt,nextVisibleProjectIds:ss,nextGlobalProjectIds:Ns};return Ze.current=ks,ks})},ca=U=>{Wn(),Sn(),pe.current=null;const Ne=U??Ze.current;if(Ze.current=null,dt(null),!Ne||!!e_(Ne.visibleProjectIds,Ne.nextVisibleProjectIds)||!ae)return;const Qe=Xt??Nn.map(Je=>Je.id),at=Ne.nextGlobalProjectIds;Ft(at),Promise.resolve(ae(Ne.projectId,"reorder",{orderedProjectIds:at})).catch(()=>{Ft(Qe)})},Fs=()=>{Wn(),Sn(),pe.current=null,Ze.current=null,dt(null)};_.useEffect(()=>{if(typeof window>"u"||!Ze.current)return;const U=Qe=>{const at=Ze.current;!at||at.pointerId!==Qe.pointerId||Hs(Qe.clientY)},Ne=Qe=>{const at=Ze.current;!at||at.pointerId!==Qe.pointerId||ca(at)},Ue=Qe=>{const at=Ze.current;!at||at.pointerId!==Qe.pointerId||Fs()};return window.addEventListener("pointermove",U),window.addEventListener("pointerup",Ne),window.addEventListener("pointercancel",Ue),()=>{window.removeEventListener("pointermove",U),window.removeEventListener("pointerup",Ne),window.removeEventListener("pointercancel",Ue)}},[qe==null?void 0:qe.pointerId]);const Js=U=>{Dt(Ne=>Ne.includes(U)?Ne.filter(Ue=>Ue!==U):[...Ne,U])},ua=U=>{if(zt.current===U){zt.current=null;return}Js(U)},da=(U,Ne,Ue)=>{if(U.pointerType==="mouse"&&U.button!==0)return;Wn();const Qe=U.currentTarget;Sn(),U.pointerType==="touch"&&(ke.current=Qe,Qe.addEventListener("selectstart",Wm),Qe.addEventListener("contextmenu",Wm)),pe.current={pane:Ue,projectId:Ne,pointerId:U.pointerId,pointerType:U.pointerType,startX:U.clientX,startY:U.clientY,currentX:U.clientX,currentY:U.clientY},U.pointerType!=="touch"&&Qe.setPointerCapture(U.pointerId),U.pointerType==="touch"&&(se.current=globalThis.setTimeout(()=>{const at=pe.current;if(!at||at.projectId!==Ne||at.pointerId!==U.pointerId)return;Qe.hasPointerCapture(U.pointerId)||Qe.setPointerCapture(U.pointerId),js(Ne,Ue,U.pointerId,U.pointerType,at.currentY)&&Hs(at.currentY)},sR))},fa=(U,Ne,Ue)=>{const Qe=pe.current;if(!Qe||Qe.projectId!==Ne||Qe.pointerId!==U.pointerId||Qe.pane!==Ue)return;if(Qe.currentX=U.clientX,Qe.currentY=U.clientY,(qe==null?void 0:qe.projectId)===Ne&&qe.pointerId===U.pointerId){U.preventDefault(),Hs(U.clientY);return}const at=U.clientX-Qe.startX,Je=U.clientY-Qe.startY;if(Qe.pointerType==="touch"){(Math.abs(at)>V1||Math.abs(Je)>V1)&&Wn();return}Math.abs(Je)<V1||Math.abs(Je)<Math.abs(at)||!js(Ne,Ue,U.pointerId,U.pointerType,U.clientY)||(U.preventDefault(),Hs(U.clientY))},In=(U,Ne)=>{if(U.currentTarget.hasPointerCapture(U.pointerId)&&U.currentTarget.releasePointerCapture(U.pointerId),(qe==null?void 0:qe.projectId)===Ne&&qe.pointerId===U.pointerId){U.preventDefault(),ca();return}Wn(),Sn(),pe.current=null},ws=(U,Ne)=>{if(U.currentTarget.hasPointerCapture(U.pointerId)&&U.currentTarget.releasePointerCapture(U.pointerId),(qe==null?void 0:qe.projectId)===Ne&&qe.pointerId===U.pointerId){Fs();return}Wn(),Sn(),pe.current=null},Os=U=>{Ee(Ne=>Ne.includes(U)?Ne.filter(Ue=>Ue!==U):[...Ne,U])},ee=U=>{if(J1(U)!=="completed"||!U.run_state_changed_at)return;const Ne=U.run_state_changed_at;Le(Ue=>Ue[U.id]===Ne?Ue:{...Ue,[U.id]:Ne})},Ke=`translateX(-${(an==="threads"?0:1)*50}%)`,Lt=$e&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{Pe(null),Xe("")},"aria-label":"关闭重命名面板"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered",children:[a.jsx("div",{className:"sheet-panel__title",children:"编辑线程名称"}),a.jsx("input",{className:"sheet-panel__input",value:ht,onChange:U=>Xe(U.target.value),placeholder:"输入线程名称",autoFocus:!0}),a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{Pe(null),Xe("")},children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:!ht.trim()||ue===$e,onClick:()=>{Pt()},children:"保存"})]})]})})]}),document.body):null,Zt=U=>{q(null),ce(null),Pe(U.id),Xe(U.display_name??U.name)},Pt=async()=>{!$e||!ht.trim()||!ae||(await ae($e,"rename",{name:ht.trim()}),Pe(null),Xe(""))},At=(U,Ne,Ue)=>{if(!Z)return;const Qe=Bt[U.id];Ne==="pin"||Ne==="unpin"?Gt(Je=>({...Je,[U.id]:{...Je[U.id],pinned:Ne==="pin"}})):Ne==="delete"&&Gt(Je=>({...Je,[U.id]:{...Je[U.id],hidden:!0}}));const at=Z(U.id,Ne,Ue);at&&typeof at.then=="function"&&at.catch(()=>{Gt(Je=>{const vt={...Je};return Qe?vt[U.id]=Qe:delete vt[U.id],vt})})},mn=U=>{const Ne=J1(U),Ue=Ne==="completed"&&U.id!==O&&!!U.run_state_changed_at&&tn[U.id]!==U.run_state_changed_at,Qe=o&&we===U.id,at=!!Z&&Qe,Je=te===U.id,vt=o&&(at||Je);return a.jsxs("div",{className:`thread-session ${U.id===O?"is-active":""}`,onMouseEnter:()=>Re(U.id),onMouseLeave:()=>{Re(ot=>ot===U.id?null:ot),ve(ot=>ot===U.id?null:ot)},children:[a.jsx("button",{type:"button",className:`thread-session__icon-button ${at?"is-visible":""} ${U.pinned?"is-active":""}`,disabled:le===U.id,onClick:ot=>{ot.stopPropagation(),At(U,U.pinned?"unpin":"pin")},"aria-label":U.pinned?"取消置顶会话":"置顶会话",title:U.pinned?"取消置顶":"置顶",children:a.jsx(sT,{strokeWidth:U.pinned?2.1:1.95})}),a.jsxs("div",{className:"thread-session__row",children:[G?a.jsxs("button",{type:"button",className:"thread-session__link thread-session__link--button",title:U.title,onClick:()=>{ee(U),G(U.id),d()},children:[a.jsx("span",{className:`thread-session__status is-${Ue?"completed":Ne} ${Ue?"is-unread":""} ${vt?"is-hidden":""}`,"aria-hidden":"true"}),a.jsx("div",{className:"thread-session__title",children:U.title})]}):a.jsxs(bp,{to:"/session/$sessionId",params:{sessionId:U.id},title:U.title,onClick:()=>{ee(U),d()},className:"thread-session__link",children:[a.jsx("span",{className:`thread-session__status is-${Ue?"completed":Ne} ${Ue?"is-unread":""} ${vt?"is-hidden":""}`,"aria-hidden":"true"}),a.jsx("div",{className:"thread-session__title",children:U.title})]}),a.jsx("div",{className:"thread-session__meta",children:o&&Qe&&Z?Je?a.jsx("button",{type:"button",className:"thread-session__delete-confirm",disabled:le===U.id,onClick:ot=>{ot.stopPropagation(),At(U,"delete")},children:"确认"}):a.jsx("button",{type:"button",className:"thread-session__delete",disabled:le===U.id,onClick:ot=>{ot.stopPropagation(),ve(U.id)},"aria-label":`删除 ${U.title}`,children:a.jsx($p,{strokeWidth:1.95})}):a.jsx("span",{className:"thread-session__time",children:dR(U.last_event_at)})})]})]},U.id)},jn=({project:U,threadSessions:Ne,collapsedThreadSessions:Ue,hiddenSessionCount:Qe,totalSessionCount:at,pageState:Je,remainingPageCount:vt},ot)=>{const nn=Ru(ot,U.id),Jt=st.includes(U.id),qt=Ae.includes(U.id),St=U.display_name??U.name,En=!!ae&&o&&V===U.id,gt=!!ae&&de===U.id,ss=ot==="archived",Ns=qt?Ne:Ue,ks=Qe>0,as=vt>0,Es=ot==="threads"?ne:R,is=(qe==null?void 0:qe.projectId)===U.id&&qe.pane===ot,Cs=gt&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>ce(null),"aria-label":"关闭线程菜单"}),a.jsxs("div",{className:"sheet-panel",children:[a.jsx("div",{className:"sheet-panel__title",children:St}),a.jsx("button",{type:"button",className:"sheet-panel__item",onClick:()=>Zt(U),children:"编辑名称"}),a.jsx("button",{type:"button",className:"sheet-panel__item",disabled:ue===U.id,onClick:()=>{ae==null||ae(U.id,ss?"unarchive":"archive"),ce(null)},children:ss?"取消归档":"归档线程"}),a.jsx("button",{type:"button",className:"sheet-panel__item is-danger",disabled:ue===U.id,onClick:()=>{ae==null||ae(U.id,"remove"),ce(null)},children:"移除"})]})]}),document.body):null;return a.jsxs(_.Fragment,{children:[a.jsx("div",{ref:es=>{De.current[nn]=es},className:`thread-group-shell ${is?"is-drag-placeholder":""}`,children:a.jsxs("section",{className:"thread-group",children:[a.jsxs("div",{className:"thread-group__header",children:[a.jsxs("button",{type:"button",className:"thread-group__title",onClick:()=>ua(U.id),onPointerDown:es=>da(es,U.id,ot),onPointerMove:es=>fa(es,U.id,ot),onPointerUp:es=>In(es,U.id),onPointerCancel:es=>ws(es,U.id),"aria-expanded":Jt,title:St,children:[a.jsx("span",{className:"thread-group__chevron",children:a.jsx(tx,{open:Jt})}),a.jsx("span",{className:"thread-group__icon",children:a.jsx(Z4,{})}),a.jsx("span",{className:"thread-group__title-text",children:St})]}),a.jsxs("div",{className:"thread-group__actions",children:[ae?a.jsxs("div",{className:"thread-group__menu-anchor",children:[a.jsx("button",{type:"button",className:`thread-group__more ${En||gt?"is-open":""}`,onClick:es=>{if(es.stopPropagation(),o){q(qs=>qs===U.id?null:U.id);return}ce(U.id)},"aria-label":`${St} 更多选项`,children:a.jsx(uR,{})}),En?a.jsxs("div",{className:"thread-group__menu",children:[a.jsx("button",{type:"button",className:"thread-group__menu-item",onClick:()=>Zt(U),children:"编辑名称"}),a.jsx("button",{type:"button",className:"thread-group__menu-item",disabled:ue===U.id,onClick:()=>{ae==null||ae(U.id,ss?"unarchive":"archive"),q(null)},children:ss?"取消归档":"归档线程"}),a.jsx("button",{type:"button",className:"thread-group__menu-item is-danger",disabled:ue===U.id,onClick:()=>{ae==null||ae(U.id,"remove"),q(null)},children:"移除"})]}):null]}):null,a.jsx("button",{type:"button",className:"thread-group__add",onClick:es=>{es.stopPropagation(),Q(U.id,U.name)},"aria-label":`在 ${U.name} 下新增会话`,children:a.jsx(J4,{})})]})]}),Jt?at===0?a.jsx("div",{className:"thread-group__empty",children:"这个线程还没有会话"}):a.jsxs(a.Fragment,{children:[Ns.length>0?a.jsx("div",{className:"thread-group__sessions",children:Ns.map(es=>mn(es))}):a.jsx("div",{className:"thread-group__empty",children:ot==="archived"?"这个归档线程还没有已加载的会话":"这个线程还没有已加载的历史会话"}),ks?a.jsx("button",{type:"button",className:"thread-group__session-toggle",onClick:()=>Os(U.id),"aria-expanded":qt,children:qt?"折叠显示":"展开显示"}):null,as&&Es?a.jsx("button",{type:"button",className:"thread-group__session-toggle",disabled:Je.isLoading,onClick:()=>{Es(U.id)},children:Je.isLoading?"加载中...":ot==="archived"?`加载已归档会话 (${vt})`:`加载更早会话 (${vt})`}):null,Je.error?a.jsx("div",{className:"thread-group__empty",children:Je.error}):null]}):null]},U.id)}),Cs]},U.id)},kn=({threadSessions:U,collapsedThreadSessions:Ne,hiddenSessionCount:Ue,totalSessionCount:Qe,pageState:at,remainingPageCount:Je},vt,ot)=>{const nn=st.includes(ot.sectionId),Jt=Ae.includes(ot.sectionId),qt=Jt?U:Ne,St=Ue>0,En=Je>0,gt=vt==="threads"?Ce:X;return a.jsxs("section",{className:"thread-group thread-group--chat",children:[a.jsxs("div",{className:"thread-group__header",children:[a.jsxs("button",{type:"button",className:"thread-group__title",onClick:()=>ua(ot.sectionId),"aria-expanded":nn,title:ot.title,children:[a.jsx("span",{className:"thread-group__icon",children:ot.icon==="image"?a.jsx(iR,{}):a.jsx(ex,{})}),a.jsx("span",{className:"thread-group__title-text",children:ot.title})]}),vt==="threads"&&ot.onCreate?a.jsx("div",{className:"thread-group__actions",children:a.jsx("button",{type:"button",className:"thread-group__add",onClick:ss=>{var Ns;ss.stopPropagation(),d(),(Ns=ot.onCreate)==null||Ns.call(ot)},"aria-label":`新增${ot.title}会话`,children:a.jsx(J4,{})})}):null]}),nn?Qe===0?a.jsx("div",{className:"thread-group__empty",children:vt==="archived"?ot.archivedEmptyText:ot.emptyText}):a.jsxs(a.Fragment,{children:[qt.length>0?a.jsx("div",{className:"thread-group__sessions",children:qt.map(ss=>mn(ss))}):a.jsx("div",{className:"thread-group__empty",children:vt==="archived"?ot.archivedEmptyText:ot.emptyText}),St?a.jsx("button",{type:"button",className:"thread-group__session-toggle",onClick:()=>Os(ot.sectionId),"aria-expanded":Jt,children:Jt?"折叠显示":"展开显示"}):null,En&>?a.jsx("button",{type:"button",className:"thread-group__session-toggle",disabled:at.isLoading,onClick:()=>{gt()},children:at.isLoading?"加载中...":vt==="archived"?`加载已归档会话 (${Je})`:`加载更早会话 (${Je})`}):null,at.error?a.jsx("div",{className:"thread-group__empty",children:at.error}):null]}):null]})},pn=U=>{if(!qe||qe.pane!==U)return null;const Ne=Jn(U).find(at=>at.project.id===qe.projectId);if(!Ne)return null;const Ue={top:qe.previewTop,width:`${qe.itemWidth}px`},Qe=Ne.project.display_name??Ne.project.name;return a.jsx("div",{className:"thread-group-drag-preview",style:Ue,"aria-hidden":"true",children:a.jsxs("div",{className:"thread-group-drag-preview__header",children:[a.jsx("span",{className:"thread-group-drag-preview__chevron",children:a.jsx(tx,{open:!0})}),a.jsx("span",{className:"thread-group-drag-preview__icon",children:a.jsx(Z4,{})}),a.jsx("span",{className:"thread-group-drag-preview__title",children:Qe})]})})};return a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:`sidebar-scrim ${D?"is-visible":""}`,style:{opacity:o?0:i,pointerEvents:o?"none":D?"auto":"none",transition:r?"none":void 0},onClick:d,"aria-label":"关闭侧边栏"}),a.jsxs("aside",{className:`conversation-sidebar ${t?"is-open":""} ${o?"is-desktop-pinned":""} ${u?"is-resizing":""}`,style:{transform:o?"translateX(0)":`translateX(calc(-100% + ${Math.max(0,Math.min(i,1))*100}%))`,transition:r?"none":void 0},children:[o&&m?a.jsx("div",{className:"conversation-sidebar__resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"调整侧边栏宽度",onPointerDown:U=>{U.pointerType!=="touch"&&(U.preventDefault(),U.stopPropagation(),m(U.clientX))}}):null,a.jsxs("div",{className:"conversation-sidebar__header",children:[a.jsxs("div",{className:`conversation-sidebar__brand ${oe&&je?`is-${je}`:"is-empty"}`,"aria-label":z,title:z,children:[oe?a.jsx("span",{className:"conversation-sidebar__status-dot","aria-hidden":"true"}):null,a.jsx("span",{className:"conversation-sidebar__brand-name",children:y?Cc(y):"未选择节点"})]}),o?null:a.jsx("button",{type:"button",className:"conversation-sidebar__close",onClick:d,"aria-label":"关闭",children:"×"})]}),a.jsxs("div",{className:"conversation-sidebar__actions",children:[a.jsxs(bp,{to:"/nodes",className:"sidebar-action",onClick:d,children:[a.jsx("span",{className:"sidebar-action__icon",children:a.jsx(aR,{})}),a.jsx("span",{children:"节点列表"})]}),kn(Zs,"threads",{sectionId:X1,title:"聊天",icon:"chat",onCreate:J,emptyText:"暂时没有聊天会话",archivedEmptyText:"暂时没有已归档的聊天会话"}),kn(Ln,"threads",{sectionId:Z1,title:"绘图",icon:"image",onCreate:F,emptyText:"暂时没有绘图会话",archivedEmptyText:"暂时没有已归档的绘图会话"}),a.jsxs("button",{type:"button",className:"sidebar-action sidebar-action--primary",onClick:()=>{d();const U=b.find(Ne=>Ne.id===Et)??b[0];U?Q(U.id,U.name):ye({to:"/nodes"})},children:[a.jsx("span",{className:"sidebar-action__icon",children:a.jsx(ex,{})}),a.jsx("span",{children:"新会话"})]})]}),a.jsx("div",{className:"conversation-sidebar__threads",children:a.jsxs("div",{className:"sidebar-pane-track",style:{transform:Ke},children:[a.jsxs("div",{ref:U=>{be.current.threads=U},className:`sidebar-pane ${an==="threads"?"is-active":"is-inactive"}`,children:[hn.length>0?a.jsxs("div",{className:"sidebar-pinned",children:[a.jsx("div",{className:"conversation-sidebar__node",children:"置顶会话"}),a.jsx("div",{className:"sidebar-pinned__list",children:hn.map(U=>mn(U))})]}):null,a.jsxs("div",{className:"conversation-sidebar__node-row",children:[a.jsx("div",{className:"conversation-sidebar__node",children:"线程"}),B?a.jsx("button",{type:"button",className:"conversation-sidebar__node-action",onClick:B,"aria-label":"新增目录线程",title:"新增目录线程",children:a.jsx(rR,{})}):null]}),On.map(U=>jn(U,"threads")),pn("threads"),a.jsxs("button",{type:"button",className:"thread-archive__toggle",onClick:()=>re("archived"),children:[a.jsx("span",{children:"已归档"}),a.jsx("span",{className:"thread-archive__icon",children:a.jsx(lR,{})})]})]}),a.jsxs("div",{ref:U=>{be.current.archived=U},className:`sidebar-pane sidebar-pane--archived ${an==="archived"?"is-active":"is-inactive"}`,children:[a.jsx("div",{className:"conversation-sidebar__node",children:"已归档的线程"}),us.totalSessionCount>0?kn(us,"archived",{sectionId:X1,title:"聊天",icon:"chat",emptyText:"还没有已加载的聊天会话",archivedEmptyText:"还没有已加载的归档聊天会话"}):null,Ot.totalSessionCount>0?kn(Ot,"archived",{sectionId:Z1,title:"绘图",icon:"image",emptyText:"还没有已加载的绘图会话",archivedEmptyText:"还没有已加载的归档绘图会话"}):null,Ss.length>0?a.jsx("div",{className:"thread-archive__list",children:Ss.map(U=>jn(U,"archived"))}):a.jsx("div",{className:"thread-archive__empty",children:"暂时没有已归档的线程"}),pn("archived"),a.jsxs("button",{type:"button",className:"thread-archive__back",onClick:()=>re("threads"),"aria-label":"返回线程列表",children:[a.jsx("span",{className:"thread-archive__back-icon",children:a.jsx(oR,{})}),a.jsx("span",{children:"返回"})]})]})]})}),a.jsx("div",{className:"conversation-sidebar__footer",children:a.jsxs("button",{type:"button",className:"sidebar-settings",onClick:()=>{d(),he==null||he()},"aria-label":"打开设置页",children:[a.jsx("span",{className:"sidebar-settings__icon",children:a.jsx(cR,{})}),a.jsx("span",{children:"设置"})]})})]}),Lt]})}),i5="panda:image:model",gR=["gpt-image-2"],_R=(e,t,i)=>{if(typeof window>"u")return i;const r=window.localStorage.getItem(e);return r&&t.includes(r)?r:i},yR=(e,t)=>{typeof window>"u"||window.localStorage.setItem(e,t)},vR=()=>_R(i5,gR,"gpt-image-2"),bR=e=>yR(i5,e),r5="image/",xR=()=>`attachment-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,SR=e=>new Promise((t,i)=>{const r=new FileReader;r.onerror=()=>i(r.error??new Error("无法读取文件")),r.onload=()=>{if(typeof r.result=="string"&&r.result){t(r.result);return}i(new Error("无法读取文件"))},r.readAsDataURL(e)}),cy=async e=>({id:xR(),kind:e.type.startsWith(r5)?"image":"file",name:e.name,mime_type:e.type||null,size_bytes:Number.isFinite(e.size)?Math.max(0,Math.round(e.size)):null,data_url:await SR(e)}),ax=e=>{var t;return e.kind==="image"||!!((t=e.mime_type)!=null&&t.startsWith(r5))},l5=e=>E6((e??[]).map((t,i)=>({id:t.id||`attachment-${i}`,kind:t.kind,name:t.name,mime_type:t.mime_type??null,size_bytes:t.size_bytes??null,content_url:t.data_url}))),qp=e=>typeof e!="number"||!Number.isFinite(e)||e<=0?null:e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,o5=e=>{var t;return["image-session-detail",((t=e==null?void 0:e.scope)==null?void 0:t.agentId)??"",(e==null?void 0:e.sessionId)??""]};function jR(e){return cs({queryKey:o5(e),enabled:!!((e==null?void 0:e.enabled)??!0)&&!!(e!=null&&e.sessionId),queryFn:async()=>e!=null&&e.sessionId?(await cn(e.scope)).client.getImageSessionDetail(e.sessionId):null,refetchOnWindowFocus:!1,retry:1})}const wR=(e,t,i)=>Math.max(t,Math.min(i,e)),ix=(e,t,i,r="source-over")=>{if(t.points.length===0)return;e.save(),e.globalCompositeOperation=r,e.strokeStyle=i,e.lineCap="round",e.lineJoin="round",e.lineWidth=t.size,e.beginPath();const o=t.points[0];if(!o){e.restore();return}e.moveTo(o.x,o.y);for(const u of t.points.slice(1))e.lineTo(u.x,u.y);t.points.length===1&&e.lineTo(o.x+.01,o.y+.01),e.stroke(),e.restore()},NR=({title:e,imageSrc:t,onClose:i,onConfirm:r})=>{const o=_.useRef(null),u=_.useRef(null),[d,m]=_.useState(null),[y,g]=_.useState(null),[b,p]=_.useState(36),[v,w]=_.useState([]),N=_.useRef(null);_.useEffect(()=>{const I=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=I}},[]),_.useEffect(()=>{const I=o.current;if(!I||!d||!y)return;I.width=d.width,I.height=d.height;const k=I.getContext("2d");if(k){k.clearRect(0,0,I.width,I.height);for(const O of v)ix(k,O,"rgba(87, 145, 255, 0.56)")}},[d,y,v]),_.useLayoutEffect(()=>{if(!d||typeof window>"u")return;const I=()=>{const k=u.current;if(!k)return;const O=k.getBoundingClientRect(),Q=Math.min(O.width/d.width,O.height/d.height),J=d.width*Q,F=d.height*Q;g({width:J,height:F})};return I(),window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I)}},[d]);const j=I=>{const k=o.current;if(!k||!d||!y)return;const O=k.getBoundingClientRect(),Q=d.width/O.width,J=d.height/O.height,F={size:b,points:[{x:(I.clientX-O.left)*Q,y:(I.clientY-O.top)*J}]};N.current=F,w(B=>[...B,F]),k.setPointerCapture(I.pointerId)},T=I=>{const k=o.current,O=N.current;if(!k||!O||!d||!y)return;const Q=k.getBoundingClientRect(),J=d.width/Q.width,F=d.height/Q.height;O.points.push({x:(I.clientX-Q.left)*J,y:(I.clientY-Q.top)*F}),w(B=>[...B.slice(0,-1),{...O,points:[...O.points]}])},M=I=>{const k=o.current;k!=null&&k.hasPointerCapture(I.pointerId)&&k.releasePointerCapture(I.pointerId),N.current=null},P=_.useMemo(()=>{if(!d||v.length===0)return null;const I=document.createElement("canvas");I.width=d.width,I.height=d.height;const k=I.getContext("2d");if(!k)return null;k.fillStyle="#ffffff",k.fillRect(0,0,I.width,I.height);for(const O of v)ix(k,O,"#000000","destination-out");return I.toDataURL("image/png")},[d,v]);return typeof document>"u"?null:ra.createPortal(a.jsxs("div",{className:"image-mask-dialog",role:"dialog","aria-modal":"true","aria-label":`${e} 蒙版编辑`,children:[a.jsx("button",{type:"button",className:"image-mask-dialog__scrim",onClick:i,"aria-label":"关闭蒙版编辑器"}),a.jsxs("div",{className:"image-mask-dialog__panel is-stage-fullscreen",children:[a.jsxs("div",{className:"image-mask-dialog__header image-mask-dialog__header--compact",children:[a.jsx("div",{className:"image-mask-dialog__header-actions",children:a.jsxs("label",{className:"image-mask-dialog__range image-mask-dialog__range--toolbar",children:[a.jsx("span",{children:"毛刷大小"}),a.jsx("input",{type:"range",min:8,max:120,step:2,value:b,onChange:I=>p(wR(Number(I.target.value),8,120))}),a.jsxs("strong",{children:[b,"px"]})]})}),a.jsxs("div",{className:"image-mask-dialog__header-actions image-mask-dialog__header-actions--right",children:[a.jsx("button",{type:"button",className:"image-mask-dialog__icon-button",onClick:()=>w(I=>I.slice(0,-1)),disabled:v.length===0,"aria-label":"撤销上一笔",children:a.jsx(cT,{})}),a.jsx("button",{type:"button",className:"image-mask-dialog__confirm-button",onClick:()=>r(P),"aria-label":"确认蒙版",children:a.jsx(Z0,{})}),a.jsx("button",{type:"button",className:"image-mask-dialog__icon-button",onClick:i,"aria-label":"关闭编辑器",children:a.jsx(hh,{})})]})]}),a.jsx("div",{className:"image-mask-dialog__workspace image-mask-dialog__workspace--single",children:a.jsx("div",{className:"image-mask-dialog__stage",children:a.jsx("div",{ref:u,className:"image-mask-dialog__canvas-shell",children:a.jsxs("div",{className:"image-mask-dialog__canvas-stage",style:y?{width:`${y.width}px`,height:`${y.height}px`}:void 0,children:[a.jsx("img",{src:t,alt:e,className:"image-mask-dialog__image",onLoad:I=>{m({width:I.currentTarget.naturalWidth,height:I.currentTarget.naturalHeight})}}),a.jsx("canvas",{ref:o,className:"image-mask-dialog__canvas",onPointerDown:j,onPointerMove:I=>{I.buttons!==1&&I.pointerType!=="touch"||T(I)},onPointerUp:M,onPointerCancel:M})]})})})})]})]}),document.body)},kR=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 5v14"}),a.jsx("path",{d:"m7 14 5 5 5-5"})]}),ER=e=>typeof e!="number"||!Number.isFinite(e)||e<=0?null:e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`,CR=e=>e.maskDataUrl?"蒙版":e.kind==="session-asset"?"引用":"上传",TR=({isDesktopSidebar:e,sidebarShift:t,isSidebarDragging:i,draft:r,onDraftChange:o,composerError:u,onDismissComposerError:d,pendingSources:m,onUploadImages:y,onRemoveSource:g,onEditSource:b,onSubmit:p,selectedModel:v,onSelectModel:w,modelOptions:N,showJumpToBottom:j,onJumpToBottom:T})=>{const M=_.useId(),P=_.useRef(null),I=_.useRef(null),[k,O]=_.useState(null),Q={transform:`translateX(${t}px)`,transition:i?"none":void 0},J=r.trim().length>0;_.useEffect(()=>{if(!k)return;const B=Z=>{const ae=Z.target;I.current&&ae instanceof Node&&I.current.contains(ae)||O(null)},G=Z=>{Z.key==="Escape"&&O(null)};return window.addEventListener("pointerdown",B),window.addEventListener("keydown",G),()=>{window.removeEventListener("pointerdown",B),window.removeEventListener("keydown",G)}},[k]);const F=B=>{B.key!=="Enter"||B.shiftKey||B.altKey||B.ctrlKey||B.metaKey||B.nativeEvent.isComposing||typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches||(B.preventDefault(),J&&p())};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`composer-wrap ${e?"has-desktop-sidebar":""}`,style:Q,children:[u?a.jsxs("div",{className:"composer-alert",role:"status","aria-live":"polite",children:[a.jsx("span",{className:"composer-alert__text",children:u}),a.jsx("button",{type:"button",className:"composer-alert__close",onClick:d,"aria-label":"关闭错误提示",children:a.jsx(hh,{})})]}):null,a.jsxs("form",{className:"chat-composer image-session-composer",onSubmit:B=>{B.preventDefault(),J&&p()},children:[m.length>0?a.jsx("div",{className:"image-session-composer__source-strip","aria-label":"Current reference images",children:m.map(B=>{const G=ER(B.sizeBytes),Z=CR(B);return a.jsxs("div",{className:"image-session-composer__source-pill",title:`${Z} - ${B.name}${G?` - ${G}`:""}`,children:[a.jsx("img",{src:B.previewUrl,alt:B.name,className:"image-session-composer__source-pill-preview"}),a.jsxs("div",{className:"image-session-composer__source-pill-copy",children:[a.jsx("span",{className:"image-session-composer__source-pill-label",children:Z}),a.jsx("span",{className:"image-session-composer__source-pill-name",children:B.name})]}),a.jsx("button",{type:"button",className:"image-session-composer__source-pill-action",onClick:()=>b(B.id),"aria-label":`编辑 ${B.name}`,children:a.jsx(fh,{})}),a.jsx("button",{type:"button",className:"image-session-composer__source-pill-remove","aria-label":`移除 ${B.name}`,onClick:()=>g(B.id),children:a.jsx(hh,{})})]},B.id)})}):null,a.jsxs("div",{className:"chat-composer__editor",children:[a.jsx("textarea",{className:"chat-composer__input image-session-composer__input",value:r,placeholder:"描述你想生成或修改的图片",onChange:B=>o(B.target.value),onKeyDown:F}),a.jsx("input",{id:M,ref:P,type:"file",accept:"image/*",multiple:!0,className:"chat-composer__file-input",onChange:B=>{B.target.files&&B.target.files.length>0&&y(B.target.files),B.target.value=""}})]}),a.jsxs("div",{className:"chat-composer__toolbar",children:[a.jsxs("div",{ref:I,className:"chat-composer__controls image-session-composer__controls",children:[a.jsxs("div",{className:`composer-utility-menu image-session-composer__utility ${k==="utility"?"is-open":""}`,children:[a.jsx("button",{type:"button",className:"composer-utility-menu__trigger image-session-composer__upload-trigger","aria-label":"打开图片工具","aria-expanded":k==="utility",onClick:()=>O(B=>B==="utility"?null:"utility"),children:a.jsx(T4,{})}),k==="utility"?a.jsx("div",{className:"composer-utility-menu__popover image-session-composer__utility-menu",role:"menu",children:a.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitem",onClick:()=>{var B;O(null),(B=P.current)==null||B.click()},children:[a.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:a.jsx(T4,{})}),a.jsx("span",{className:"composer-utility-menu__item-label",children:"上传图片"})]})}):null]}),a.jsxs("div",{className:`composer-choice image-session-composer__choice ${k==="model"?"is-open":""} is-selected`,children:[a.jsxs("button",{type:"button",className:"composer-control image-session-composer__choice-trigger is-selected","aria-label":"选择模型","aria-expanded":k==="model",onClick:()=>O(B=>B==="model"?null:"model"),children:[a.jsx(pT,{className:"image-session-composer__choice-icon","aria-hidden":"true"}),a.jsx("span",{className:"image-session-composer__choice-value",children:v}),a.jsx(QC,{className:"image-session-composer__choice-arrow","aria-hidden":"true"})]}),k==="model"?a.jsx("div",{className:"composer-choice-menu image-session-composer__choice-menu",role:"menu","aria-label":"选择模型",children:N.map(B=>a.jsxs("button",{type:"button",className:`composer-choice-menu__item ${v===B.id?"is-active":""}`,role:"menuitemradio","aria-checked":v===B.id,onClick:()=>{w(B.id),O(null)},children:[a.jsx("span",{className:"composer-choice-menu__label",children:B.label||B.id}),v===B.id?a.jsx("span",{className:"composer-choice-menu__check","aria-hidden":"true",children:a.jsx(Z0,{})}):null]},B.id))}):null]})]}),a.jsx("div",{className:"chat-composer__actions image-session-composer__actions",children:a.jsx("button",{type:"submit",className:"composer-send",disabled:!J,"aria-label":"Send image request",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:a.jsx("path",{d:"M12 17V7m0 0-4 4m4-4 4 4",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})})]})]})]}),j?a.jsx("button",{type:"button",className:`conversation-jump-bottom ${e?"has-desktop-sidebar":""}`,style:Q,onClick:T,"aria-label":"滚动到底部",children:a.jsx(kR,{})}):null]})},c5=()=>`image-source-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,MR=4200,rx=e=>Math.max(1,Math.min(5,e)),lx={quality:"auto",size:"1024x1024",aspectRatio:"auto",outputFormat:"png",outputCompression:85,background:"auto",moderation:"auto",n:1},RR=[{value:"auto",label:"Auto"},{value:"low",label:"快速"},{value:"medium",label:"均衡"},{value:"high",label:"精细"}],AR=[{value:"auto",label:"Auto"},{value:"1:1",label:"1:1"},{value:"16:9",label:"16:9"},{value:"9:16",label:"9:16"},{value:"4:3",label:"4:3"},{value:"3:4",label:"3:4"}],IR=[{value:"1024x1024",label:"1K"},{value:"2048x2048",label:"2K"},{value:"3840x2160",label:"4K"},{value:"auto",label:"Auto"}],DR=[{value:"png",label:"PNG"},{value:"webp",label:"WebP"},{value:"jpeg",label:"JPEG"}],OR=[{value:"auto",label:"Auto"},{value:"opaque",label:"不透明"}],LR=[{value:"auto",label:"Auto"},{value:"low",label:"宽松"}],PR=e=>{switch(e){case"16:9":return{width:28,height:16};case"9:16":return{width:16,height:28};case"4:3":return{width:24,height:18};case"3:4":return{width:18,height:24};case"1:1":return{width:22,height:22};default:return{width:24,height:18}}},UR=({ratio:e})=>{const t=PR(e);return a.jsxs("svg",{viewBox:"0 0 32 32","aria-hidden":"true",className:"image-ratio-icon",children:[a.jsx("rect",{className:"image-ratio-icon__backdrop",x:"4.5",y:"4.5",width:"23",height:"23",rx:"6"}),a.jsx("rect",{className:"image-ratio-icon__shape",x:(32-t.width)/2,y:(32-t.height)/2,width:t.width,height:t.height,rx:"3"})]})},Au=({menuKey:e,activeMenu:t,label:i,selectedValue:r,options:o,onToggle:u,onSelect:d,renderLeading:m})=>{var b;const y=((b=o.find(p=>p.value===r))==null?void 0:b.label)??r,g=typeof m=="function";return a.jsxs("div",{className:"image-option-dropdown",children:[a.jsxs("button",{type:"button",className:`image-option-trigger ${g?"has-leading-visual":""}`,onClick:()=>u(e),"aria-expanded":t===e,children:[m?a.jsx("span",{className:"image-option-trigger__visual","aria-hidden":"true",children:m(r)}):null,a.jsx("span",{children:y})]}),t===e?a.jsx("div",{className:"image-option-menu",role:"listbox","aria-label":i,children:o.map(p=>a.jsxs("button",{type:"button",className:`image-option-menu__item ${r===p.value?"is-active":""} ${g?"has-leading-visual":""}`,onClick:()=>d(p.value),children:[m?a.jsx("span",{className:"image-option-menu__item-visual","aria-hidden":"true",children:m(p.value)}):null,a.jsx("span",{children:p.label})]},p.value))}):null]})},t_=e=>{if(e.length<2)return 0;const t=e.item(0),i=e.item(1);return!t||!i?0:Math.hypot(i.clientX-t.clientX,i.clientY-t.clientY)},zR=(e,t,i)=>t.length===0?null:a.jsx("div",{className:"conversation-entry__attachments",children:a.jsx("div",{className:"conversation-entry__attachment-grid",children:t.map(r=>{const o=qp(r.size_bytes),u=r.name||"图片",d=`图片${o?` · ${o}`:""}`;return a.jsxs("button",{type:"button",className:"conversation-entry__attachment-card is-image",onClick:()=>i(r),"aria-label":`预览 ${u}`,children:[a.jsxs("div",{className:"conversation-entry__attachment-media",children:[a.jsx("img",{src:r.content_url,alt:u,loading:"lazy"}),a.jsx("span",{className:"conversation-entry__attachment-badge",children:"预览"})]}),a.jsxs("div",{className:"conversation-entry__attachment-caption",children:[a.jsx("span",{className:"conversation-entry__attachment-title",children:u}),a.jsx("span",{className:"conversation-entry__attachment-meta",children:d})]})]},`${e}:${r.id}`)})})}),n_=e=>({id:c5(),kind:"session-asset",name:e.name,previewUrl:e.content_url,mimeType:e.mime_type,sizeBytes:e.size_bytes,assetId:e.id,maskDataUrl:null}),BR=(e,t,i,r,o)=>o&&{...o,turns:[...o.turns,{id:`pending-turn-${Date.now()}`,session_id:e,created_at:new Date().toISOString(),completed_at:null,prompt:t,prompt_suffix:null,operation:i.length>0?"edit":"generate",status:"pending",error:null,model:r.model,quality:r.options.quality,size:r.options.size,input_fidelity:null,aspect_ratio:r.options.aspectRatio,output_format:r.options.outputFormat,output_compression:r.options.outputFormat==="png"?null:r.options.outputCompression,background:r.options.background,moderation:r.options.moderation,n:r.options.n,sources:i.map(u=>({id:u.assetId??u.id,session_id:e,turn_id:null,kind:"source",name:u.name,mime_type:u.mimeType,size_bytes:u.sizeBytes,width:null,height:null,content_url:u.previewUrl,created_at:new Date().toISOString()})),outputs:[]}]},$R=({asset:e,onClose:t})=>{const[i,r]=_.useState(1),[o,u]=_.useState({x:0,y:0}),[d,m]=_.useState(!1),y=_.useRef(null),g=_.useRef(null),b=_.useRef(null);_.useEffect(()=>{r(1),u({x:0,y:0}),m(!1),g.current=null,b.current=null},[e.id]),_.useEffect(()=>{const M=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=M}},[]),_.useEffect(()=>{const M=P=>{P.key==="Escape"&&t()};return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[t]),_.useEffect(()=>{i===1&&(o.x!==0||o.y!==0)&&u({x:0,y:0})},[o.x,o.y,i]),_.useEffect(()=>{const M=y.current;if(!M)return;const P=I=>{I.preventDefault(),r(k=>rx(k*Math.exp(-I.deltaY*.0015)))};return M.addEventListener("wheel",P,{passive:!1}),()=>{M.removeEventListener("wheel",P)}},[]);const p=M=>{if(M.touches.length>=2){g.current={distance:t_(M.touches),scale:i},b.current=null,m(!1);return}if(M.touches.length===1&&i>1){const P=M.touches[0];b.current={startX:P.clientX,startY:P.clientY,originX:o.x,originY:o.y},m(!0)}},v=M=>{if(M.touches.length>=2){const P=g.current;if(!P){g.current={distance:t_(M.touches),scale:i};return}const I=t_(M.touches);if(I<=0||P.distance<=0)return;M.preventDefault(),r(rx(I/P.distance*P.scale));return}if(M.touches.length===1&&b.current&&i>1){const P=M.touches[0];M.preventDefault(),u({x:b.current.originX+(P.clientX-b.current.startX),y:b.current.originY+(P.clientY-b.current.startY)})}},w=()=>{g.current&&i<=1&&r(1),i<=1&&u({x:0,y:0}),g.current=null,b.current=null,m(!1)},N=M=>{M.pointerType==="touch"||i<=1||(M.currentTarget.setPointerCapture(M.pointerId),b.current={pointerId:M.pointerId,startX:M.clientX,startY:M.clientY,originX:o.x,originY:o.y},m(!0))},j=M=>{M.pointerType==="touch"||!b.current||i<=1||b.current.pointerId===M.pointerId&&(M.preventDefault(),u({x:b.current.originX+(M.clientX-b.current.startX),y:b.current.originY+(M.clientY-b.current.startY)}))},T=M=>{M.pointerType==="touch"||!b.current||(M.currentTarget.hasPointerCapture(M.pointerId)&&M.currentTarget.releasePointerCapture(M.pointerId),b.current=null,m(!1))};return a.jsxs("div",{className:"attachment-lightbox",role:"dialog","aria-modal":"true","aria-label":`预览 ${e.name||"图片"}`,children:[a.jsx("button",{type:"button",className:"attachment-lightbox__scrim",onClick:t,"aria-label":"关闭图片预览"}),a.jsxs("div",{className:"attachment-lightbox__panel",children:[a.jsx("button",{type:"button",className:"attachment-lightbox__close",onClick:t,"aria-label":"关闭图片预览",children:a.jsx(hh,{})}),a.jsx("div",{className:"attachment-lightbox__frame",children:a.jsx("div",{ref:y,className:`attachment-lightbox__stage ${i>1?"is-zoomed":""} ${d?"is-dragging":""}`,onClick:M=>{M.stopPropagation()},onDoubleClick:()=>{r(M=>M>1?1:2),u({x:0,y:0})},onPointerDown:N,onPointerMove:j,onPointerUp:T,onTouchStart:p,onTouchMove:v,onTouchEnd:w,children:a.jsx("img",{src:e.content_url,alt:e.name,className:"attachment-lightbox__image",style:{transform:`translate(${o.x}px, ${o.y}px) scale(${i})`}})})}),a.jsxs("div",{className:"attachment-lightbox__meta",children:[a.jsx("div",{className:"attachment-lightbox__title",children:e.name}),a.jsx("div",{className:"attachment-lightbox__hint",children:"双指或滚轮缩放,拖动查看细节"})]})]})]})},HR=({sessionId:e,workspaceDirectorySnapshot:t=null,embedded:i=!1,isDesktopSidebar:r=!1,sidebarOffset:o=0,isSidebarDragging:u=!1,onOpenSidebar:d}={})=>{const{sessionId:m}=Mc({strict:!1}),y=e??m??"",g=Ka(),b=(t==null?void 0:t.sessions.find(re=>re.id===y))??null,p=(b==null?void 0:b.agent_id)??vo()??void 0,v=jR({sessionId:y,scope:{sessionId:y,agentId:p},enabled:!!y}),w=v.data??null,[N,j]=_.useState(""),[T,M]=_.useState(null),[P,I]=_.useState([]),k=cs({queryKey:["image-provider-settings",p??""],enabled:!!p,queryFn:async()=>p?(await cn({agentId:p})).client.getImageProviderSettings():null}),O=(()=>{const re=k.data,we=(re==null?void 0:re.channels.find(te=>te.id===re.active_channel_id))??(re==null?void 0:re.channels[0])??null,Re=(we==null?void 0:we.models.filter(te=>te.enabled!==!1))??[];return Re.length?Re:[{id:"gpt-image-2",vendor:"openai",label:"gpt-image-2",enabled:!0}]})(),[Q,J]=_.useState(null),[F,B]=_.useState(null),[G,Z]=_.useState(vR),[ae,he]=_.useState(lx),[ne,Ce]=_.useState(!1),[R,X]=_.useState(!1),[le,ue]=_.useState(""),[ye,D]=_.useState(!1),[oe,je]=_.useState(null),[z,be]=_.useState(()=>new Set),[De,se]=_.useState(null),pe=_.useRef(null),ke=_.useRef(null),Ze=O.find(re=>re.id===G)??O[0]??null,Fe=((Ze==null?void 0:Ze.vendor)??"openai")==="openai";_.useEffect(()=>()=>{pe.current!==null&&window.clearTimeout(pe.current),ke.current!==null&&window.clearTimeout(ke.current)},[]),_.useEffect(()=>{if(ke.current!==null&&(window.clearTimeout(ke.current),ke.current=null),!!T)return ke.current=window.setTimeout(()=>{M(null),ke.current=null},MR),()=>{ke.current!==null&&(window.clearTimeout(ke.current),ke.current=null)}},[T]),_.useEffect(()=>{if(!ye||!oe)return;const re=Re=>{const te=Re.target;if(!(te instanceof Element)){je(null);return}te.closest(".image-option-dropdown")||je(null)},we=Re=>{Re.key==="Escape"&&je(null)};return window.addEventListener("pointerdown",re),window.addEventListener("keydown",we),()=>{window.removeEventListener("pointerdown",re),window.removeEventListener("keydown",we)}},[oe,ye]),_.useEffect(()=>{const re=we=>{const Re=we.target;Re instanceof Element&&Re.closest(".conversation-topbar__title-actions")||Ce(!1)};return window.addEventListener("pointerdown",re),()=>{window.removeEventListener("pointerdown",re)}},[]),_.useEffect(()=>{bR(G)},[G]),_.useEffect(()=>{var we;if(O.some(Re=>Re.id===G))return;const re=((we=O[0])==null?void 0:we.id)??"gpt-image-2";Z(re)},[O,G]),_.useEffect(()=>{Fe||ae.moderation==="auto"||he(re=>({...re,moderation:"auto"}))},[ae.moderation,Fe]);const kt=Gn({mutationFn:async re=>{const we=re.kind==="refresh"?re.turn:null,Re=re.kind==="submit"?re.request:null;return(await cn({sessionId:y,agentId:p})).client.submitImageSessionPrompt({sessionId:y,prompt:(we==null?void 0:we.prompt)??(Re==null?void 0:Re.prompt)??"",append_to_turn_id:(we==null?void 0:we.id)??null,model:(we==null?void 0:we.model)??(Re==null?void 0:Re.model),quality:(we==null?void 0:we.quality)??(Re==null?void 0:Re.options.quality),size:(we==null?void 0:we.size)??(Re==null?void 0:Re.options.size),input_fidelity:(we==null?void 0:we.input_fidelity)??null,aspect_ratio:(we==null?void 0:we.aspect_ratio)??(Re==null?void 0:Re.options.aspectRatio),output_format:(we==null?void 0:we.output_format)??(Re==null?void 0:Re.options.outputFormat),output_compression:we?we.output_compression:(Re==null?void 0:Re.options.outputFormat)==="png"?null:Re==null?void 0:Re.options.outputCompression,background:(we==null?void 0:we.background)??(Re==null?void 0:Re.options.background),moderation:(we==null?void 0:we.moderation)??(Re==null?void 0:Re.options.moderation),n:(we==null?void 0:we.n)??(Re==null?void 0:Re.options.n)??1,sources:(we?we.sources.map(n_):(Re==null?void 0:Re.sources)??[]).map(ve=>({id:ve.id,kind:ve.kind==="session-asset"?"session_asset":"upload",name:ve.name,mime_type:ve.mimeType,size_bytes:ve.sizeBytes,data_url:ve.dataUrl??null,asset_id:ve.assetId??null,mask_data_url:ve.maskDataUrl??null}))})},onMutate:async re=>{M(null),re.kind==="refresh"&&be(te=>new Set(te).add(re.turn.id));const we=o5({sessionId:y,scope:{agentId:p}}),Re=g.getQueryData(we)??null;return g.setQueryData(we,re.kind==="refresh"?Re:BR(y,re.request.prompt,re.request.sources,{model:re.request.model,options:re.request.options},Re)),{previous:Re,queryKey:we,variables:re}},onSuccess:(re,we,Re)=>{g.setQueryData((Re==null?void 0:Re.queryKey)??[],re),g.setQueriesData({queryKey:hs},ve=>ve&&Bp(ve,re.session));const te=Re==null?void 0:Re.variables;(te==null?void 0:te.kind)==="refresh"&&be(ve=>{const V=new Set(ve);return V.delete(te.turn.id),V})},onError:(re,we,Re)=>{Re!=null&&Re.queryKey&&g.setQueryData(Re.queryKey,Re.previous??null);const te=Re==null?void 0:Re.variables;(te==null?void 0:te.kind)==="refresh"&&be(ve=>{const V=new Set(ve);return V.delete(te.turn.id),V}),M(re instanceof Error?re.message:"图片请求失败")}}),Bt=async re=>{var we;try{const te=(await Promise.all([...re].map(ve=>cy(ve)))).map(ve=>({id:c5(),kind:"upload",name:ve.name,previewUrl:ve.data_url,mimeType:ve.mime_type,sizeBytes:ve.size_bytes,dataUrl:ve.data_url,maskDataUrl:null}));I(ve=>[...ve,...te]),B(((we=te[0])==null?void 0:we.id)??null)}catch(Re){M(Re instanceof Error?Re.message:"无法读取图片")}},Gt=re=>{I(we=>[...we,n_(re)])},Xt=()=>{const re=N.trim();if(!re){M("请先输入提示词。");return}const we={id:`pending-image-request-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,prompt:re,sources:P,model:G,options:ae};j(""),I([]),kt.mutate({kind:"submit",request:we})},Ft=async re=>{var te;const we=re.trim();if(!we)return!1;const Re=()=>{const ve=document.createElement("textarea");ve.value=we,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.opacity="0",ve.style.pointerEvents="none",document.body.appendChild(ve),ve.select(),document.execCommand("copy"),document.body.removeChild(ve)};try{return(te=navigator.clipboard)!=null&&te.writeText?await navigator.clipboard.writeText(we):Re(),!0}catch{return!1}},qe=async(re,we)=>{await Ft(we)&&(se(re),pe.current!==null&&window.clearTimeout(pe.current),pe.current=window.setTimeout(()=>{se(te=>te===re?null:te),pe.current=null},1400))},dt=async re=>{try{const we=await fetch(re.content_url);if(!we.ok)throw new Error("download failed");const Re=await we.blob(),te=URL.createObjectURL(Re),ve=document.createElement("a");ve.href=te,ve.download=re.name||"image",document.body.appendChild(ve),ve.click(),document.body.removeChild(ve),URL.revokeObjectURL(te)}catch{M("下载图片失败。")}},un=re=>{const we=n_(re);I(Re=>[...Re,we]),B(we.id)},$t=Gn({mutationFn:async re=>(await cn({sessionId:y,agentId:p})).client.updateSession({sessionId:y,action:re.action,name:re.name}),onSuccess:()=>{g.invalidateQueries({queryKey:hs})},onError:re=>{M(re instanceof Error?re.message:"会话操作失败")}}),An=_.useCallback(()=>{const re=le.trim();re&&($t.mutate({action:"rename",name:re}),X(!1))},[le,$t]),Nn=_.useCallback(()=>{$t.mutate({action:"delete"}),Ce(!1)},[$t]),Tt=P.find(re=>re.id===F)??null,lt=(w==null?void 0:w.session.title)??(b==null?void 0:b.title)??"绘图会话",Et=R&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered image-options-sheet",role:"dialog","aria-modal":"true","aria-label":"重命名绘图会话",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>X(!1),"aria-label":"关闭重命名弹窗"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered image-options-panel image-options-panel--compact",children:[a.jsx("div",{className:"image-options-panel__eyebrow",children:"会话"}),a.jsx("div",{className:"sheet-panel__title",children:"修改会话名称"}),a.jsx("input",{className:"sheet-panel__input",value:le,onChange:re=>ue(re.target.value),placeholder:"输入新的会话名称",autoFocus:!0}),a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>X(!1),children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:!le.trim()||$t.isPending,onClick:An,children:"保存"})]})]})})]}),document.body):null,rt=ye&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered image-options-sheet",role:"dialog","aria-modal":"true","aria-label":"绘图高级选项",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>D(!1),"aria-label":"关闭高级选项"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"image-options-panel",children:[a.jsx("div",{className:"image-options-panel__handle"}),a.jsxs("div",{className:"image-options-panel__header",children:[a.jsxs("div",{className:"image-options-panel__header-copy",children:[a.jsx("h2",{children:"高级绘图选项"}),a.jsx("p",{children:"调整下一次请求的质量、尺寸、格式、背景和安全策略。"})]}),a.jsx("button",{type:"button",className:"image-options-panel__close",onClick:()=>D(!1),"aria-label":"关闭高级选项",children:a.jsx(hh,{})})]}),a.jsxs("div",{className:"image-options-list",children:[a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"质量"}),a.jsx("span",{children:"影响速度、细节和成本"})]}),a.jsx(Au,{menuKey:"quality",activeMenu:oe,label:"选择图片质量",selectedValue:ae.quality,options:RR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,quality:re})),je(null)}})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"Size"}),a.jsx("span",{children:"2K / 4K will be sent to the provider when supported"})]}),a.jsx(Au,{menuKey:"size",activeMenu:oe,label:"Select image size",selectedValue:ae.size,options:IR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,size:re})),je(null)}})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"Ratio"}),a.jsx("span",{children:"Select the output aspect ratio"})]}),a.jsx(Au,{menuKey:"ratio",activeMenu:oe,label:"Select image ratio",selectedValue:ae.aspectRatio,options:AR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,aspectRatio:re})),je(null)},renderLeading:re=>a.jsx(UR,{ratio:re})})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"张数"}),a.jsx("span",{children:"成本会随张数增加"})]}),a.jsx("input",{type:"number",min:1,max:10,value:ae.n,onChange:re=>he(we=>({...we,n:Math.max(1,Math.min(10,Number(re.target.value)||1))}))})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"Format"}),a.jsx("span",{children:ae.outputFormat==="png"?"High fidelity for editing":"Adjustable compression"})]}),a.jsx(Au,{menuKey:"format",activeMenu:oe,label:"Select output format",selectedValue:ae.outputFormat,options:DR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,outputFormat:re})),je(null)}})]}),ae.outputFormat!=="png"?a.jsxs("div",{className:"image-options-row image-options-row--range",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"压缩"}),a.jsxs("span",{children:[ae.outputCompression,"%"]})]}),a.jsx("input",{type:"range",min:0,max:100,value:ae.outputCompression,onChange:re=>he(we=>({...we,outputCompression:Number(re.target.value)}))})]}):null,a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"背景"}),a.jsx("span",{children:"gpt-image-2 暂不支持透明背景"})]}),a.jsx(Au,{menuKey:"background",activeMenu:oe,label:"选择背景模式",selectedValue:ae.background,options:OR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,background:re})),je(null)}})]}),a.jsxs("div",{className:"image-options-row",children:[a.jsxs("div",{children:[a.jsx("strong",{children:"安全过滤"}),a.jsx("span",{children:Fe?"推荐保持自动":"当前模型走 provider 固定内容审核,暂不支持手动调节"})]}),Fe?a.jsx(Au,{menuKey:"moderation",activeMenu:oe,label:"选择安全过滤等级",selectedValue:ae.moderation,options:LR,onToggle:re=>je(we=>we===re?null:re),onSelect:re=>{he(we=>({...we,moderation:re})),je(null)}}):a.jsx("button",{type:"button",className:"image-option-trigger",disabled:!0,"aria-label":"当前模型不支持调节安全过滤",children:a.jsx("span",{children:"不可调"})})]})]}),a.jsxs("div",{className:"image-options-panel__footer",children:[a.jsx("button",{type:"button",onClick:()=>he(lx),children:"恢复默认"}),a.jsx("button",{type:"button",className:"is-primary",onClick:()=>D(!1),children:"完成"})]})]})})]}),document.body):null,st=a.jsxs("div",{className:"conversation-topbar",children:[r?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:d,"aria-label":"Open sidebar",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]}),a.jsx("div",{className:"conversation-topbar__meta",children:a.jsxs("div",{className:"conversation-topbar__title-row",children:[a.jsx("h1",{children:lt}),a.jsxs("div",{className:"conversation-topbar__title-actions",children:[a.jsx("button",{type:"button",className:"conversation-topbar__more",onClick:()=>Ce(re=>!re),"aria-label":"更多绘图会话选项","aria-expanded":ne,children:a.jsx(JC,{})}),ne?a.jsxs("div",{className:"topbar-menu",role:"menu",children:[a.jsx("button",{type:"button",className:"topbar-menu__item",onClick:()=>{ue(lt),X(!0),Ce(!1)},children:"修改会话名称"}),a.jsx("button",{type:"button",className:"topbar-menu__item is-danger",disabled:$t.isPending,onClick:Nn,children:"删除会话"})]}):null]})]})}),a.jsx("div",{className:"conversation-topbar__actions",children:a.jsx("div",{className:"conversation-topbar__run-group",children:a.jsx("button",{type:"button",className:"conversation-topbar__run-button",onClick:()=>{D(!0),Ce(!1)},"aria-label":"编辑高级选项",title:"编辑高级选项",children:a.jsx(hT,{})})})})]}),Dt=v.isPending&&!w?a.jsx("div",{className:"empty-panel empty-panel--loading",children:"Loading image session..."}):w?w.turns.length===0?a.jsxs("div",{className:"image-session-empty-state",children:[a.jsx("h2",{children:"开始新的绘图"}),a.jsx("p",{children:"描述你想生成的画面,或上传参考图继续编辑。"})]}):a.jsx("div",{className:"image-session-thread",children:[...w.turns.flatMap(re=>{const we=a.jsx("section",{className:"conversation-entry is-user is-user",children:a.jsxs("div",{className:"conversation-entry__stack",children:[a.jsxs("div",{className:"conversation-entry__body",children:[a.jsx("p",{className:"image-session-entry__text",children:re.prompt}),zR(`${re.id}:user`,re.sources,te=>J(te))]}),a.jsxs("button",{type:"button",className:`conversation-entry__copy ${De===re.id?"is-copied":""}`,onClick:()=>{qe(re.id,re.prompt)},"aria-label":De===re.id?"Copied message":"Copy message",children:[a.jsx("span",{className:"conversation-entry__copy-icon","aria-hidden":"true",children:De===re.id?a.jsx(Z0,{}):a.jsx(YC,{})}),a.jsx("span",{className:"sr-only",children:De===re.id?"Copied":"Copy"})]})]})},`${re.id}:user`),Re=a.jsx("section",{className:"conversation-entry is-system is-system",children:a.jsxs("div",{className:"conversation-entry__body image-session-entry__result-body",children:[a.jsxs("div",{className:"image-session-entry__meta",children:[a.jsx("span",{children:re.operation==="edit"?"编辑":"生成"}),a.jsx("span",{children:new Date(re.created_at).toLocaleString("zh-CN",{hour12:!1})})]}),re.status==="pending"||z.has(re.id)?a.jsxs("div",{className:"image-result-placeholder",children:[a.jsx("div",{className:"image-result-placeholder__wave"}),a.jsx("span",{children:"Generating image..."})]}):null,re.status==="failed"?a.jsx("div",{className:"image-turn-card__error",children:re.error??"图片生成失败"}):null,re.outputs.length>0?a.jsx("div",{className:"image-result-grid",children:re.outputs.map(te=>a.jsxs("figure",{className:"image-result-card",children:[a.jsx("button",{type:"button",className:"image-result-card__preview",onClick:()=>J(te),children:a.jsx("img",{src:te.content_url,alt:te.name})}),a.jsxs("figcaption",{className:"image-result-card__caption",children:[a.jsx("span",{children:te.name}),a.jsxs("div",{className:"image-result-card__actions",children:[a.jsx("button",{type:"button",onClick:()=>un(te),"aria-label":"编辑图片",title:"编辑",children:a.jsx(fh,{"aria-hidden":"true"})}),a.jsx("button",{type:"button",onClick:()=>Gt(te),"aria-label":"引用图片",title:"引用",children:a.jsx(iT,{"aria-hidden":"true"})}),a.jsx("button",{type:"button",onClick:()=>kt.mutate({kind:"refresh",turn:re}),disabled:z.has(re.id)||re.status!=="completed","aria-label":"Regenerate image",title:"重新生成",children:a.jsx(lT,{"aria-hidden":"true"})}),a.jsx("button",{type:"button",onClick:()=>{dt(te)},"aria-label":"下载图片",title:"下载",children:a.jsx(XC,{"aria-hidden":"true"})})]})]})]},te.id))}):null]})},`${re.id}:system`);return[we,Re]})]}):a.jsx("div",{className:"empty-panel",children:v.error instanceof Error?v.error.message:"Unable to load image session"}),an={transform:`translateX(${o}px)`,transition:u?"none":void 0};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`conversation-main ${r?"has-desktop-sidebar":""} ${i?"is-embedded":""}`,style:an,children:[st,a.jsx("div",{className:"conversation-scroll",children:a.jsx("div",{className:"conversation-thread",children:Dt})})]}),a.jsx(TR,{isDesktopSidebar:r,sidebarShift:o,isSidebarDragging:u,draft:N,onDraftChange:j,composerError:T,onDismissComposerError:()=>M(null),pendingSources:P,onUploadImages:re=>{Bt(re)},onRemoveSource:re=>{I(we=>we.filter(Re=>Re.id!==re))},onEditSource:re=>B(re),onSubmit:()=>{Xt()},selectedModel:G,onSelectModel:Z,modelOptions:O,showJumpToBottom:!1,onJumpToBottom:()=>{}}),Tt?a.jsx(NR,{title:Tt.name,imageSrc:Tt.previewUrl,onClose:()=>B(null),onConfirm:re=>{I(we=>we.map(Re=>Re.id===Tt.id?{...Re,maskDataUrl:re}:{...Re,maskDataUrl:null})),B(null)}}):null,Et,rt,Q&&typeof document<"u"?ra.createPortal(a.jsx($R,{asset:Q,onClose:()=>J(null)},Q.id),document.body):null]})},uy="optimistic-user:",FR="overlay-user:",qR=[uy,FR],WR=5e3,ic=e=>["timeline-optimistic",e],tg=e=>e.kind==="user"&&qR.some(t=>e.id.startsWith(t)),dy=e=>e.kind==="user"&&!tg(e),fy=e=>e.kind==="user"&&e.id.startsWith(uy),KR=e=>e.kind==="user"&&!fy(e),ox=e=>e.body.replace(/\r\n/g,`
|
|
194
194
|
`).trim(),cx=e=>new Date(e).getTime(),ng=(e,t)=>{if(ox(e)!==ox(t))return!1;const i=cx(e.timestamp),r=cx(t.timestamp);return!Number.isFinite(i)||!Number.isFinite(r)?!0:r>=i-WR},QR=(e,t)=>{const i=t.filter(dy);if(i.length===0)return new Set;const r=new Set,o=new Set;for(const u of e??[]){if(!tg(u))continue;const d=i.findIndex((m,y)=>!r.has(y)&&ng(u,m));d<0||(r.add(d),o.add(u.id))}return o},GR=(e,t)=>{const i=t.map((u,d)=>({entry:u,index:d})).filter(({entry:u})=>dy(u));if(i.length===0)return new Map;const r=new Set,o=new Map;for(const u of e??[]){if(!tg(u))continue;const d=i.find(({entry:m,index:y})=>!r.has(y)&&ng(u,m));d&&(r.add(d.index),(u.attachments??[]).length!==0&&o.set(d.index,C6(d.entry.attachments,u.attachments)))}return o},YR=(e,t)=>{const i=t.filter(KR);if(i.length===0)return new Set;const r=new Set,o=new Set;for(const u of e??[]){if(!fy(u))continue;const d=i.findIndex((m,y)=>!r.has(y)&&ng(u,m));d<0||(r.add(d),o.add(u.id))}return o},VR=e=>{const t=[...e??[]],i=t.map((u,d)=>({entry:u,index:d})).filter(({entry:u})=>dy(u));if(i.length===0)return t;const r=new Set,o=new Set;for(const u of t){if(!tg(u))continue;const d=i.find(({entry:m,index:y})=>!r.has(y)&&ng(u,m));d&&(r.add(d.index),o.add(u.id))}return o.size===0?t:t.filter(u=>!o.has(u.id))},r0=(e,t)=>[...e??[],t],u5=(e,t)=>{const i=GR(e,t),r=QR(e,t),o=[...e??[]].filter(d=>!r.has(d.id)),u=new Set(o.map(d=>d.id));for(const[d,m]of t.entries())u.has(m.id)||(u.add(m.id),o.push(i.has(d)?{...m,attachments:i.get(d)??m.attachments}:m));return o},l0=(e,t)=>[...u5(e,t)].sort((i,r)=>{const o=new Date(i.timestamp).getTime(),u=new Date(r.timestamp).getTime();return!Number.isFinite(o)||!Number.isFinite(u)?0:o-u}),d5=(e,t)=>(e??[]).filter(i=>fy(i)&&!YR([i],t).has(i.id)),XR=(e,t)=>{const i=VR(e),r=d5(t,i);return l0(r,i)},ZR=(e,t)=>{if(!e||e.session_id!==t.session_id)return{...t,entries:l0(void 0,t.entries)};const i=e.view==="full_compact"&&t.view==="tail",r=l0(e.entries,t.entries);return{session_id:t.session_id,generated_at:t.generated_at,view:i?e.view:t.view,anchor_entry_id:i?e.anchor_entry_id??t.anchor_entry_id:t.anchor_entry_id,has_earlier_entries:i?!1:t.has_earlier_entries,entries:r}},JR=(e,t)=>(e??[]).filter(i=>i.id!==t),eA=/\[[^\]]+\]\([^)]+\)|`[^`\n]+`|\*\*.+?\*\*|~~[^~\n][^~\n]*~~|\*[^*\n][^*\n]*\*|\$[A-Za-z0-9._-]+|\/[A-Za-z][A-Za-z0-9._-]*/g,tA=/^[A-Za-z0-9._-]$/,nA=/^[A-Za-z0-9._-]$/,o0=e=>/\s/.test(e),ux=e=>tA.test(e),sA=e=>nA.test(e),si=e=>e.trim().toLowerCase(),aA=e=>si(e).split(/[^a-z0-9]+/i).filter(Boolean),dx=e=>e==="repo"?0:e==="user"?1:2,iA=e=>e==="repo"?"项目":e==="user"?"个人":"系统",f5=e=>{const t=[];let i=0;for(const r of e.matchAll(eA)){const o=r[0],u=r.index??0;if(o.startsWith("$")){const d=u>0?e[u-1]??"":"";if(u>0&&!o0(d))continue}if(o.startsWith("/")){const d=u>0?e[u-1]??"":"";if(u>0&&!o0(d))continue}if(u>i&&t.push({kind:"text",value:e.slice(i,u)}),o.startsWith("`")&&o.endsWith("`"))t.push({kind:"code",value:o.slice(1,-1)});else if(o.startsWith("**")&&o.endsWith("**"))t.push({kind:"strong",value:o.slice(2,-2)});else if(o.startsWith("~~")&&o.endsWith("~~"))t.push({kind:"strikethrough",value:o.slice(2,-2)});else if(o.startsWith("*")&&o.endsWith("*"))t.push({kind:"emphasis",value:o.slice(1,-1)});else if(o.startsWith("[")){const d=/^\[([^\]]+)\]\(([^)]+)\)$/.exec(o);d?t.push({kind:"path-link",label:d[1]??"",path:d[2]??""}):t.push({kind:"text",value:o})}else o.startsWith("/")?t.push({kind:"command",raw:o,name:o.slice(1)}):t.push({kind:"skill",raw:o,name:o.slice(1)});i=u+o.length}return i<e.length&&t.push({kind:"text",value:e.slice(i)}),t},h5=(e,t,i=t)=>{if(t!==i)return null;let r=t;for(;r>0&&ux(e[r-1]??"");)r-=1;const o=r-1;if(o<0||e[o]!=="$")return null;const u=o>0?e[o-1]??"":"";if(o>0&&!o0(u))return null;let d=t;for(;d<e.length&&ux(e[d]??"");)d+=1;return{start:o,end:d,query:e.slice(o+1,t)}},rA=(e,t,i,r)=>{const o=h5(e,t,i);if(!o)return null;const m=(e[o.end]??"").length===0?`$${r} `:`$${r}`,y=`${e.slice(0,o.start)}${m}${e.slice(o.end)}`,g=o.start+m.length;return{value:y,selectionStart:g,selectionEnd:g}},hy=e=>e.startsWith("/"),m5=(e,t,i=t)=>{if(!hy(e)||t!==i)return null;const r=e.search(/\s/),o=r<0?e.length:r;if(t>o)return null;let u=1;for(;u<e.length&&sA(e[u]??"");)u+=1;return t>u?null:{start:0,end:u,query:e.slice(1,t)}},lA=(e,t,i,r)=>{const o=m5(e,t,i);if(!o)return null;const m=(e[o.end]??"").length===0?`/${r} `:`/${r}`,y=`${e.slice(0,o.start)}${m}${e.slice(o.end)}`,g=o.start+m.length;return{value:y,selectionStart:g,selectionEnd:g}},oA=(e,t)=>{const i=si(t),r=e.filter(u=>{if(!u.enabled)return!1;if(!i)return!0;const d=si(u.name),m=si(u.description);return d.includes(i)||m.includes(i)}),o=u=>{if(!i)return 0;const d=si(u.name),m=si(u.description),y=aA(u.name);return d===i?0:y.some(g=>g===i)?1:d.startsWith(i)?2:y.some(g=>g.startsWith(i))?3:d.includes(i)?4:m.startsWith(i)?5:6};return[...r].sort((u,d)=>{const m=o(u),y=o(d);if(m!==y)return m-y;const g=dx(u.scope)-dx(d.scope);if(g!==0)return g;const b=si(u.name),p=si(d.name);return b.localeCompare(p)})},cA=(e,t)=>{const i=si(t);return[...e.filter(o=>{if(!i)return!0;const u=si(o.name),d=si(o.description);return u.includes(i)||d.includes(i)})].sort((o,u)=>{const d=si(o.name),m=si(u.name),y=d===i?0:d.startsWith(i)?1:2,g=m===i?0:m.startsWith(i)?1:2;return y!==g?y-g:o.availability!==u.availability?o.availability==="supported"?-1:1:d.localeCompare(m)})},s_=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.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"})}),uA=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m9 6 6 6-6 6"})}),fx=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m5 12 4.5 4.5L19 7"})}),dA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6l12 12"}),a.jsx("path",{d:"M18 6 6 18"})]}),hx=e=>!!(e&&/^[A-Za-z]:[\\/]?$/.test(e.trim())),fA=({agentId:e,projects:t,initialPath:i=null,title:r="选择目录",subtitle:o="线程名会使用目录最后一级名称",confirmLabel:u="选择此目录",cancelLabel:d="返回上级",onProjectCreated:m})=>{const y=Ka(),[g,b]=_.useState(i),[p,v]=_.useState(i),[w,N]=_.useState([]),[j,T]=_.useState(!0),[M,P]=_.useState(null),[I,k]=_.useState(0),[O,Q]=_.useState(!1),[J,F]=_.useState(""),[B,G]=_.useState(null),Z=_.useRef(null);_.useEffect(()=>{b(i),v(i)},[i]),_.useEffect(()=>{Q(!1),F(""),G(null),he.reset()},[g]),_.useEffect(()=>{let pe=!1;return T(!0),P(null),S3({agentId:e,path:g}).then(ke=>{pe||N(ke)}).catch(ke=>{pe||(P(ke instanceof Error?ke.message:"目录列表加载失败"),N([]))}).finally(()=>{pe||T(!1)}),()=>{pe=!0}},[e,g,I]),_.useEffect(()=>{var pe,ke;O&&((pe=Z.current)==null||pe.focus(),(ke=Z.current)==null||ke.select())},[O]);const ae=Gn({mutationFn:async pe=>ST({agentId:e,path:pe,projects:t,queryClient:y,bootstrapQueryKey:yC}),onSuccess:pe=>{m(pe)}}),he=Gn({mutationFn:async pe=>xT({agentId:e,parentPath:pe.parentPath,name:pe.name}),onSuccess:({directory:pe})=>{Q(!1),F(""),G(null),v(pe.path),k(ke=>ke+1)}}),ne=_.useMemo(()=>{const pe=new Map;for(const ke of t)pe.set(Hp(ke.path),ke);return pe},[t]),Ce=_.useMemo(()=>p?ne.get(Hp(p))??null:null,[ne,p]),R=u!=="选择此目录"?u:Ce?"在线程中继续":"创建新线程",X=x3(g),le=X!==null||hx(g),ue=!!g,ye=J.trim(),D=B??(he.error instanceof Error?he.error.message:null),oe=ae.error instanceof Error?ae.error.message:ae.error?"创建线程失败":null,je=()=>{if(X!==null){b(X),v(X);return}hx(g)&&(b(null),v(null))},z=pe=>{b(pe),v(pe)},be=()=>{Q(!1),F(""),G(null),he.reset()},De=()=>{g&&(he.reset(),G(null),F(""),Q(!0))},se=()=>{if(g){if(!ye){G("目录名称不能为空");return}G(null),he.mutate({parentPath:g,name:ye})}};return a.jsx("section",{className:"directory-picker",children:a.jsxs("div",{className:"directory-picker__panel",children:[a.jsx("header",{className:"directory-picker__header",children:a.jsxs("div",{className:"directory-picker__heading",children:[a.jsx("h2",{children:r}),o?a.jsx("p",{children:o}):null]})}),a.jsxs("div",{className:"directory-picker__field",children:[a.jsx("span",{className:"directory-picker__field-label",children:"当前路径"}),a.jsxs("button",{type:"button",className:`directory-picker__path ${p===g?"is-selected":""}`,onClick:()=>{g&&v(g)},disabled:!g,"aria-pressed":p===g,children:[a.jsx("span",{className:"directory-picker__path-icon",children:a.jsx(s_,{})}),a.jsx("span",{className:"directory-picker__path-value",children:g??"根目录"})]})]}),a.jsxs("div",{className:"directory-picker__field",children:[a.jsx("span",{className:"directory-picker__field-label",children:"目录"}),a.jsx("div",{className:"directory-picker__list",role:"listbox","aria-label":"目录列表",children:j?a.jsx("div",{className:"directory-picker__state",children:"正在读取目录…"}):M?a.jsx("div",{className:"directory-picker__state is-error",children:M}):a.jsxs(a.Fragment,{children:[w.length===0&&!O?a.jsx("div",{className:"directory-picker__state",children:"当前目录下没有可用子目录"}):null,w.map(pe=>{const ke=p===pe.path;return a.jsxs("div",{className:`directory-picker__row ${ke?"is-selected":""}`,children:[a.jsxs("button",{type:"button",className:"directory-picker__row-main",onClick:Ze=>{if(pe.has_children&&Ze.detail>=2){z(pe.path);return}v(pe.path)},"aria-selected":ke,children:[a.jsx("span",{className:"directory-picker__row-icon",children:a.jsx(s_,{})}),a.jsx("span",{className:"directory-picker__row-name",children:pe.name}),!pe.has_children&&ke?a.jsx("span",{className:"directory-picker__row-check",children:a.jsx(fx,{})}):null]}),pe.has_children?a.jsx("button",{type:"button",className:"directory-picker__row-enter-button","aria-label":`进入 ${pe.name}`,onClick:()=>z(pe.path),children:a.jsx("span",{className:"directory-picker__row-enter","aria-hidden":"true",children:a.jsx(uA,{})})}):null]},pe.path)}),O?a.jsx("div",{className:"directory-picker__row is-creating",children:a.jsxs("div",{className:"directory-picker__row-editor",children:[a.jsx("span",{className:"directory-picker__row-icon",children:a.jsx(s_,{})}),a.jsx("input",{ref:Z,type:"text",className:"directory-picker__row-input",value:J,onChange:pe=>{F(pe.target.value),B&&G(null),he.error&&he.reset()},onKeyDown:pe=>{pe.key==="Enter"&&(pe.preventDefault(),se()),pe.key==="Escape"&&(pe.preventDefault(),be())},placeholder:"输入目录名称","aria-label":"新目录名称",disabled:he.isPending}),a.jsxs("div",{className:"directory-picker__row-actions",children:[a.jsx("button",{type:"button",className:"directory-picker__row-action",onClick:se,"aria-label":"确认创建目录",disabled:!ye||he.isPending,children:a.jsx(fx,{})}),a.jsx("button",{type:"button",className:"directory-picker__row-action",onClick:be,"aria-label":"取消创建目录",disabled:he.isPending,children:a.jsx(dA,{})})]})]})}):null]})})]}),D?a.jsx("div",{className:"directory-picker__feedback is-error",role:"status","aria-live":"polite",children:D}):null,oe?a.jsx("div",{className:"directory-picker__feedback is-error",role:"status","aria-live":"polite",children:oe}):null,a.jsx("footer",{className:"directory-picker__footer",children:a.jsxs("div",{className:"directory-picker__footer-actions",children:[le?a.jsx("button",{type:"button",className:"directory-picker__secondary",onClick:je,children:a.jsx("span",{children:d})}):null,ue?a.jsx("button",{type:"button",className:"directory-picker__secondary",onClick:De,disabled:O||he.isPending,children:a.jsx("span",{children:"新建目录"})}):null,a.jsx("button",{type:"button",className:"directory-picker__primary",disabled:!p||ae.isPending,onClick:()=>{p&&ae.mutate(p)},children:ae.isPending?"创建中…":R})]})})]})})},hA=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 281.999849615234 85.965369875" width="281.999849615234" height="85.965369875" role="img" aria-label="Panda wordmark">\r
|
|
195
195
|
<path fill="#d97757" fill-rule="nonzero" d="M539.0830078125,114.554069519043C537.650695800781,114.554061889648 536.2041015625,114.826202392578 534.7431640625,115.370460510254 533.2822265625,115.914741516113 531.892883300781,116.616561889648 530.5751953125,117.475936889648 529.257507324219,118.335311889648 528.054382324219,119.280624389648 526.9658203125,120.311874389648 525.877258300781,121.343124389648 524.9892578125,122.345733642578 524.3017578125,123.319686889648 522.9267578125,125.153022766113 521.480163574219,127.244171142578 519.9619140625,129.593124389648 518.443664550781,131.942077636719 516.925476074219,134.405624389648 515.4072265625,136.983749389648 513.888977050781,139.561874389648 512.4423828125,142.197296142578 511.0673828125,144.889999389648 509.6923828125,147.582702636719 508.474945068359,150.203796386719 507.4150390625,152.753280639648 506.355133056641,155.302764892578 505.510101318359,157.737655639648 504.8798828125,160.057968139648 504.249664306641,162.378280639648 503.9345703125,164.455108642578 503.9345703125,166.288436889648 503.9345703125,168.981140136719 504.4501953125,171.143905639648 505.4814453125,172.776718139648 506.5126953125,174.409530639648 508.460601806641,175.225936889648 511.3251953125,175.225936889648 512.299133300781,175.225936889648 513.7314453125,174.610046386719 515.6220703125,173.378280639648 517.5126953125,172.146514892578 519.5322265625,170.585311889648 521.6806640625,168.694686889648 523.8291015625,166.804061889648 525.9345703125,164.755889892578 527.9970703125,162.550155639648 530.0595703125,160.344421386719 531.749694824219,158.238952636719 533.0673828125,156.233749389648 534.499694824219,154.113952636719 535.9462890625,151.793640136719 537.4072265625,149.272811889648 538.8681640625,146.751983642578 540.2001953125,144.173858642578 541.4033203125,141.538436889648 542.6064453125,138.903015136719 543.580383300781,136.310577392578 544.3251953125,133.761093139648 545.070007324219,131.211608886719 545.4423828125,128.848327636719 545.4423828125,126.671249389648 545.4423828125,122.374374389648 544.7978515625,119.280624389648 543.5087890625,117.389999389648 542.2197265625,115.499374389648 540.744445800781,114.554061889648 539.0830078125,114.554069519043z M416.966674804688,110.343124389648C413.930206298828,110.343124389648 409.805206298828,113.522811889648 404.591674804688,119.882186889648 401.956268310547,123.147811889648 399.535675048828,126.270210266113 397.329956054688,129.249374389648 395.124237060547,132.228546142578 393.104705810547,135.179061889648 391.271362304688,138.100936889648 389.266143798828,141.251983642578 387.561737060547,144.145202636719 386.158081054688,146.780624389648 384.754425048828,149.416046142578 383.565643310547,151.764999389648 382.591674804688,153.827499389648 379.211456298828,161.103546142578 377.521362304688,166.832702636719 377.521362304688,171.014999389648 377.521362304688,176.343124389648 379.326049804688,179.007186889648 382.935424804688,179.007186889648 386.143768310547,179.007186889648 390.555206298828,177.145202636719 396.169799804688,173.421249389648 401.956268310547,169.468124389648 406.425018310547,165.916046142578 409.576049804688,162.764999389648 412.841674804688,159.327499389648 415.563018798828,156.434265136719 417.740112304688,154.085311889648 419.917205810547,151.736358642578 421.635955810547,149.845733642578 422.896362304688,148.413436889648 424.156768798828,146.981140136719 425.316925048828,145.376983642578 426.376831054688,143.600936889648 427.436706542969,141.824890136719 428.453643798828,139.876983642578 429.427612304688,137.757186889648 427.938018798828,137.413436889648 426.806518554688,136.668640136719 426.033081054688,135.522811889648 425.259643554688,134.376983642578 424.872924804688,133.087921142578 424.872924804688,131.655624389648 424.872924804688,130.509796142578 425.044799804688,128.819686889648 425.388549804688,126.585311889648 425.732299804688,124.350936889648 425.904174804688,122.632186889648 425.904174804688,121.429061889648 425.904174804688,120.397811889648 425.632019042969,119.237655639648 425.087768554688,117.948593139648 424.543487548828,116.659530639648 423.841674804688,115.456405639648 422.982299804688,114.339218139648 422.122924804688,113.222030639648 421.163299560547,112.276718139648 420.103393554688,111.503280639648 419.043487548828,110.729843139648 417.997924804688,110.343124389648 416.966674804688,110.343124389648z M181.0703125,108.538436889648C178.95051574707,108.767608642578 176.6875,109.469429016113 174.28125,110.643905639648 171.875,111.818389892578 169.32551574707,113.623077392578 166.6328125,116.057968139648 163.940093994141,118.492866516113 161.104156494141,121.629585266113 158.125,125.468124389648 155.14582824707,129.306671142578 152.05207824707,133.975936889648 148.84375,139.475936889648 147.869781494141,141.137390136719 146.795562744141,142.956405639648 145.62109375,144.932968139648 144.44660949707,146.909530639648 143.32942199707,149.086608886719 142.26953125,151.464218139648 141.20964050293,153.841827392578 140.32160949707,156.376983642578 139.60546875,159.069686889648 138.88932800293,161.762390136719 138.53125,164.598327636719 138.53125,167.577499389648 138.53125,169.353546142578 139.17578125,170.699890136719 140.46484375,171.616561889648 141.75390625,172.533233642578 143.0859375,172.991561889648 144.4609375,172.991561889648 145.893218994141,172.991561889648 147.75520324707,172.203796386719 150.046875,170.628280639648 152.338531494141,169.052764892578 154.81640625,166.961608886719 157.48046875,164.354843139648 160.14453125,161.748077392578 162.865875244141,158.768905639648 165.64453125,155.417343139648 168.42317199707,152.065780639648 171.00129699707,148.613952636719 173.37890625,145.061874389648 175.756500244141,141.509796142578 177.819000244141,138.014999389648 179.56640625,134.577499389648 181.31379699707,131.139999389648 182.502593994141,128.017608642578 183.1328125,125.210311889648 183.3046875,124.350936889648 183.50520324707,123.334014892578 183.734375,122.159530639648 183.963531494141,120.985054016113 184.178375244141,119.810577392578 184.37890625,118.636093139648 184.57942199707,117.461616516113 184.75129699707,116.373077392578 184.89453125,115.370460510254 185.037750244141,114.367866516113 185.109375,113.637397766113 185.109375,113.179061889648 185.109375,113.064483642578 185.0234375,112.749374389648 184.8515625,112.233749389648 184.6796875,111.718124389648 184.421875,111.188179016113 184.078125,110.643905639648 183.734375,110.099639892578 183.319000244141,109.612655639648 182.83203125,109.182968139648 182.34504699707,108.753280639648 181.815093994141,108.538436889648 181.2421875,108.538436889648L181.0703125,108.538436889648z M453.576049804688,56.2884368896484C455.294799804688,56.2884368896484 456.984893798828,56.6608428955078 458.646362304688,57.4056243896484 460.422393798828,58.0931243896484 461.310424804688,59.0670928955078 461.310424804688,60.3274993896484 461.310424804688,61.0149993896484 461.181518554688,62.1321868896484 460.923706054688,63.6790618896484 460.665893554688,65.2259368896484 460.307800292969,67.2311477661133 459.849487304688,69.6946868896484 459.391143798828,72.1582336425781 458.775268554688,75.2090148925781 458.001831054688,78.8470306396484 457.228393554688,82.4850540161133 456.383331298828,86.8248977661133 455.466674804688,91.8665618896484 455.409362792969,92.4394836425781 455.237487792969,93.5853118896484 454.951049804688,95.3040618896484 454.664581298828,97.0228118896484 454.349487304688,98.8418273925781 454.005737304688,100.761093139648 453.661987304688,102.680366516113 453.346862792969,104.456405639648 453.060424804688,106.089218139648 452.773956298828,107.722030639648 452.602081298828,108.738960266113 452.544799804688,109.139999389648 451.799987792969,113.780624389648 451.198425292969,118.134796142578 450.740112304688,122.202499389648 450.281768798828,126.270210266113 450.052612304688,130.395202636719 450.052612304688,134.577499389648 450.052612304688,137.900421142578 450.138549804688,141.824890136719 450.310424804688,146.350936889648 450.482299804688,150.934265136719 450.911987304688,155.374374389648 451.599487304688,159.671249389648 452.286987304688,163.968124389648 453.289581298828,166.116561889648 454.607299804688,166.116561889648 459.305206298828,166.116561889648 464.977081298828,163.968124389648 471.622924804688,159.671249389648 478.211456298828,155.317077636719 484.570831298828,150.332702636719 490.701049804688,144.718124389648 493.766143798828,141.910827636719 496.659362792969,139.167999267578 499.380737304688,136.489608764648L504.336578369141,131.408462524414 505.0302734375,130.205429077148C506.390960693359,128.092803955078 507.859069824219,126.041038513184 509.4345703125,124.050155639648 512.585632324219,120.068389892578 515.7939453125,116.573593139648 519.0595703125,113.565780639648 522.3251953125,110.557968139648 525.433288574219,108.180366516113 528.3837890625,106.432968139648 531.334289550781,104.685577392578 533.726257324219,103.811874389648 535.5595703125,103.811874389648 536.0751953125,103.811874389648 536.662414550781,103.926460266113 537.3212890625,104.155616760254 537.980163574219,104.384796142578 538.667663574219,104.628280639648 539.3837890625,104.886093139648 540.099914550781,105.143905639648 540.787414550781,105.373077392578 541.4462890625,105.573593139648 542.105163574219,105.774116516113 542.663757324219,105.874374389648 543.1220703125,105.874374389648 543.580383300781,105.874374389648 544.038757324219,105.774116516113 544.4970703125,105.573593139648 544.955383300781,105.373077392578 545.413757324219,105.143905639648 545.8720703125,104.886093139648 546.330383300781,104.628280639648 546.788757324219,104.384796142578 547.2470703125,104.155616760254 547.705383300781,103.926460266113 548.163757324219,103.811874389648 548.6220703125,103.811874389648 549.3095703125,103.811874389648 550.054382324219,104.041046142578 550.8564453125,104.499374389648 551.658508300781,104.957710266113 552.431945800781,105.544952392578 553.1767578125,106.261093139648 553.921569824219,106.977241516113 554.580383300781,107.793647766113 555.1533203125,108.710311889648 555.726257324219,109.626983642578 556.127258300781,110.514999389648 556.3564453125,111.374374389648 556.585632324219,112.405624389648 556.886413574219,113.164741516113 557.2587890625,113.651718139648 557.631164550781,114.138702392578 558.003601074219,114.582710266113 558.3759765625,114.983749389648 558.748352050781,115.384796142578 559.0634765625,115.857452392578 559.3212890625,116.401718139648 559.5791015625,116.945991516113 559.7080078125,117.791046142578 559.7080078125,118.936874389648 559.7080078125,119.509796142578 559.507507324219,120.712921142578 559.1064453125,122.546249389648 558.705383300781,124.379585266113 558.261413574219,126.513702392578 557.7744140625,128.948593139648 557.287414550781,131.383483886719 556.843444824219,133.918640136719 556.4423828125,136.554061889648 556.041320800781,139.189483642578 555.8408203125,141.595733642578 555.8408203125,143.772811889648 555.8408203125,149.903015136719 556.1845703125,154.916046142578 556.8720703125,158.811874389648 557.5595703125,162.707702636719 558.5048828125,165.787139892578 559.7080078125,168.050155639648 560.9111328125,170.313171386719 562.3291015625,171.874374389648 563.9619140625,172.733749389648 565.5947265625,173.593124389648 567.327819824219,174.022811889648 569.1611328125,174.022811889648 573.515319824219,174.022811889648 577.081726074219,173.278015136719 579.8603515625,171.788436889648 582.638977050781,170.298858642578 585.116882324219,168.093124389648 587.2939453125,165.171249389648 587.924133300781,164.369171142578 588.468444824219,163.653015136719 588.9267578125,163.022811889648 589.385070800781,162.392608642578 589.843383789063,162.077499389648 590.3017578125,162.077499389648 591.103820800781,162.077499389648 591.834289550781,162.392608642578 592.4931640625,163.022811889648 593.151977539063,163.653015136719 593.4814453125,164.311874389648 593.4814453125,164.999374389648 593.4814453125,165.916046142578 593.295227050781,166.961608886719 592.9228515625,168.136093139648 592.550476074219,169.310577392578 591.963195800781,170.499374389648 591.1611328125,171.702499389648 590.1298828125,173.478546142578 588.769165039063,175.297546386719 587.0791015625,177.159530639648 585.388977050781,179.021514892578 583.498352050781,180.711608886719 581.4072265625,182.229843139648 579.316101074219,183.748077392578 577.038757324219,184.994171142578 574.5751953125,185.968124389648 572.111633300781,186.942077636719 569.562194824219,187.429061889648 566.9267578125,187.429061889648 563.4892578125,187.429061889648 560.5244140625,186.655624389648 558.0322265625,185.108749389648 555.5400390625,183.561874389648 553.3916015625,181.456405639648 551.5869140625,178.792343139648 549.7822265625,176.128280639648 548.292663574219,173.020202636719 547.1181640625,169.468124389648 545.943664550781,165.916046142578 544.984069824219,162.163436889648 544.2392578125,158.210311889648 541.718444824219,161.876983642578 538.724914550781,165.514999389648 535.2587890625,169.124374389648 531.792663574219,172.733749389648 528.2119140625,175.985046386719 524.5166015625,178.878280639648 520.8212890625,181.771514892578 517.183288574219,184.120468139648 513.6025390625,185.925155639648 510.021820068359,187.729843139648 506.8564453125,188.632186889648 504.1064453125,188.632186889648 502.273101806641,188.632186889648 500.511383056641,188.173858642578 498.8212890625,187.257186889648 497.131195068359,186.340515136719 495.6416015625,185.108749389648 494.3525390625,183.561874389648 493.0634765625,182.014999389648 492.046539306641,180.238952636719 491.3017578125,178.233749389648 490.556976318359,176.228546142578 490.1845703125,174.108749389648 490.1845703125,171.874374389648 490.1845703125,169.639999389648 490.370758056641,167.291046142578 490.7431640625,164.827499389648 491.115570068359,162.363952636719 491.745758056641,159.714218139648 492.6337890625,156.878280639648L493.119232177734,155.466354370117 492.849487304688,155.761093139648C490.385925292969,158.253280639648 487.779174804688,160.788436889648 485.029174804688,163.366561889648 482.279174804688,165.944686889648 479.615112304688,168.264999389648 477.036987304688,170.327499389648 474.458862304688,172.389999389648 471.938018798828,174.251983642578 469.474487304688,175.913436889648 464.604675292969,179.236358642578 460.708862304688,180.897811889648 457.786987304688,180.897811889648 456.641143798828,180.897811889648 455.180206298828,180.496765136719 453.404174804688,179.694686889648 449.794799804688,178.033233642578 446.930206298828,174.996765136719 444.810424804688,170.585311889648 442.747924804688,166.173858642578 441.286987304688,161.561874389648 440.427612304688,156.749374389648 439.568237304688,151.936874389648 438.852081298828,146.551452636719 438.279174804688,140.593124389648 431.117706298828,153.942077636719 421.836456298828,165.801452636719 410.435424804688,176.171249389648 398.977081298828,186.598327636719 387.117706298828,191.811874389648 374.857299804688,191.811874389648 371.477081298828,191.811874389648 368.898956298828,190.007186889648 367.122924804688,186.397811889648 365.346893310547,182.845733642578 364.458862304688,179.150421142578 364.458862304688,175.311874389648 364.458862304688,170.155624389648 364.888549804688,166.317077636719 365.747924804688,163.796249389648L366.740081787109,161.069854736328 361.366027832031,165.944686889648C358.67333984375,168.179061889648 356.037902832031,170.155624389648 353.459777832031,171.874374389648 351.397277832031,173.249374389648 349.43505859375,174.538436889648 347.573059082031,175.741561889648 345.711090087891,176.944686889648 343.834777832031,177.975936889648 341.944152832031,178.835311889648 340.053527832031,179.694686889648 338.076965332031,180.382186889648 336.014465332031,180.897811889648 333.951965332031,181.413436889648 331.68896484375,181.671249389648 329.225402832031,181.671249389648 324.47021484375,181.671249389648 320.60302734375,180.468124389648 317.623840332031,178.061874389648 316.13427734375,176.858749389648 314.830871582031,175.297546386719 313.713684082031,173.378280639648 312.596496582031,171.459014892578 311.62255859375,169.324890136719 310.791809082031,166.975936889648 309.961090087891,164.626983642578 309.244934082031,162.134796142578 308.643371582031,159.499374389648 308.041809082031,156.863952636719 307.54052734375,154.257186889648 307.139465332031,151.679061889648 306.623840332031,148.470733642578 306.136871337891,145.591827392578 305.678527832031,143.042343139648 305.22021484375,140.492858886719 304.690246582031,138.344421386719 304.088684082031,136.597030639648 303.487121582031,134.849639892578 302.756652832031,133.503280639648 301.897277832031,132.557968139648 301.037902832031,131.612655639648 299.920715332031,131.139999389648 298.545715332031,131.139999389648 297.457183837891,131.139999389648 296.425933837891,131.254577636719 295.451965332031,131.483749389648 294.47802734375,131.712921142578 293.461090087891,132.171249389648 292.401184082031,132.858749389648 291.34130859375,133.546249389648 290.18115234375,134.520202636719 288.920715332031,135.780624389648 287.660308837891,137.041046142578 286.18505859375,138.702499389648 284.494934082031,140.764999389648 282.804840087891,142.827499389648 280.871246337891,145.348327636719 278.694152832031,148.327499389648 276.51708984375,151.306671142578 273.967590332031,154.858749389648 271.045715332031,158.983749389648 269.613433837891,160.988952636719 267.92333984375,163.194686889648 265.975402832031,165.600936889648 264.027496337891,168.007186889648 262.03662109375,170.298858642578 260.002746582031,172.475936889648 257.968902587891,174.653015136719 255.97802734375,176.572296142578 254.03010559082,178.233749389648 252.082183837891,179.895202636719 250.363433837891,180.955108642578 248.87385559082,181.413436889648 243.832183837891,180.324890136719 241.31135559082,174.051452636719 241.31135559082,162.593124389648 241.31135559082,159.556671142578 241.65510559082,154.944686889648 242.34260559082,148.757186889648 242.68635559082,145.949890136719 243.08740234375,143.013702392578 243.54573059082,139.948593139648L243.633743286133,139.477767944336 241.3662109375,142.344100952148C239.48274230957,144.571319580078 237.55989074707,146.694686889648 235.59765625,148.714218139648 231.67317199707,152.753280639648 227.705718994141,156.577499389648 223.6953125,160.186874389648 219.51301574707,163.968124389648 215.34504699707,166.918640136719 211.19140625,169.038436889648 207.037750244141,171.158233642578 203.299468994141,172.218124389648 199.9765625,172.218124389648 198.54426574707,172.218124389648 197.12629699707,171.874374389648 195.72265625,171.186874389648 194.319000244141,170.499374389648 193.00129699707,169.597030639648 191.76953125,168.479843139648 190.537750244141,167.362655639648 189.44921875,166.059265136719 188.50390625,164.569686889648 187.55859375,163.080108642578 186.828125,161.533233642578 186.3125,159.929061889648 186.026031494141,159.069686889648 185.768218994141,158.081405639648 185.5390625,156.964218139648 185.30989074707,155.847030639648 185.080718994141,154.815780639648 184.8515625,153.870468139648 184.62239074707,152.925155639648 184.36457824707,152.123077392578 184.078125,151.464218139648 183.791656494141,150.805358886719 183.4765625,150.475936889648 183.1328125,150.475936889648 182.90364074707,150.475936889648 182.416656494141,150.848327636719 181.671875,151.593124389648 180.92707824707,152.337921142578 180.053375244141,153.297546386719 179.05078125,154.472030639648 178.04817199707,155.646514892578 176.97395324707,156.964218139648 175.828125,158.425155639648 174.682281494141,159.886093139648 173.55078125,161.304061889648 172.43359375,162.679061889648 171.31640625,164.054061889648 170.31379699707,165.314483642578 169.42578125,166.460311889648 168.537750244141,167.606140136719 167.8359375,168.465515136719 167.3203125,169.038436889648 165.54426574707,171.043640136719 163.43879699707,173.091827392578 161.00390625,175.182968139648 158.569000244141,177.274108886719 156.13410949707,179.179061889648 153.69921875,180.897811889648 151.264312744141,182.616561889648 149.02995300293,184.020202636719 146.99609375,185.108749389648 144.96223449707,186.197296142578 143.45832824707,186.741561889648 142.484375,186.741561889648 140.30729675293,186.741561889648 138.20182800293,186.383483886719 136.16796875,185.667343139648 134.13410949707,184.951202392578 132.34375,183.905624389648 130.796875,182.530624389648 129.25,181.155624389648 128.00390625,179.465515136719 127.05859375,177.460311889648 126.11328125,175.455108642578 125.640625,173.163436889648 125.640625,170.585311889648 125.640625,166.345733642578 126.485679626465,161.504577636719 128.17578125,156.061874389648 129.020843505859,153.340515136719 130.001953125,150.597686767578 131.119140625,147.833358764648L132.791915893555,144.115005493164 132.34375,144.417343139648C129.36457824707,146.336608886719 126.05598449707,148.370468139648 122.41796875,150.518905639648 118.779945373535,152.667343139648 114.92707824707,154.844421386719 110.859375,157.050155639648 106.791664123535,159.255889892578 102.72395324707,161.418640136719 98.65625,163.538436889648 94.5885391235352,165.658233642578 90.6354141235352,167.663436889648 86.796875,169.554061889648 82.9583282470703,171.444686889648 79.4635391235352,173.106140136719 76.3125,174.538436889648 74.0208282470703,175.569686889648 71.84375,176.729843139648 69.78125,178.018905639648 67.71875,179.307968139648 65.69921875,180.511093139648 63.7226600646973,181.628280639648 61.74609375,182.745468139648 59.7552070617676,183.676452636719 57.7499961853027,184.421249389648 55.7447891235352,185.166046142578 53.625,185.538436889648 51.390625,185.538436889648 50.0729141235352,185.538436889648 48.7981758117676,185.380889892578 47.5664100646973,185.065780639648 46.3346328735352,184.750671386719 45.2317695617676,184.249374389648 44.2578163146973,183.561874389648 43.2838516235352,182.874374389648 42.49609375,182.000671386719 41.8945274353027,180.940780639648 41.29296875,179.880889892578 40.9921875,178.606140136719 40.9921875,177.116561889648 40.9921875,176.314483642578 41.2643203735352,175.569686889648 41.80859375,174.882186889648 42.3528633117676,174.194686889648 43.0546875,173.578796386719 43.9140625,173.034530639648 44.7734375,172.490264892578 45.71875,171.988952636719 46.75,171.530624389648 47.78125,171.072296142578 48.7838516235352,170.671249389648 49.7578086853027,170.327499389648 50.7890586853027,169.926452636719 52.0065078735352,169.511093139648 53.41015625,169.081405639648 54.8138008117676,168.651718139648 56.2317695617676,168.222030639648 57.6640625,167.792343139648 59.0963516235352,167.362655639648 60.4856719970703,166.918640136719 61.83203125,166.460311889648 63.1783828735352,166.001983642578 64.3385391235352,165.543640136719 65.3125,165.085311889648 67.1458282470703,164.111358642578 68.8645782470703,162.879577636719 70.46875,161.389999389648 72.0729141235352,159.900421142578 73.5625,158.267608642578 74.9375,156.491561889648 76.3125,154.715515136719 77.6015625,152.867858886719 78.8046875,150.948593139648 80.0078125,149.029327392578 81.125,147.181671142578 82.1562576293945,145.405624389648 82.84375,144.202499389648 83.5026016235352,142.856140136719 84.1328125,141.366561889648 84.7630157470703,139.876983642578 85.3216094970703,138.387390136719 85.80859375,136.897811889648 86.2955703735352,135.408233642578 86.66796875,133.990264892578 86.92578125,132.643905639648 87.18359375,131.297546386719 87.3125,130.166046142578 87.3125,129.249374389648 87.3125,125.296249389648 86.453125,122.145210266113 84.734375,119.796249389648 83.015625,117.447296142578 80.8671875,116.272811889648 78.2890548706055,116.272811889648 76.6848907470703,116.272811889648 74.8372344970703,116.802764892578 72.74609375,117.862655639648 70.6549453735352,118.922554016113 68.5637969970703,120.197296142578 66.47265625,121.686874389648 64.3815078735352,123.176460266113 62.43359375,124.737655639648 60.62890625,126.370468139648 58.82421875,128.003280639648 57.3776016235352,129.392608642578 56.2890586853027,130.538436889648 53.6536407470703,133.345733642578 51.1757774353027,136.396514892578 48.85546875,139.690780639648 46.53515625,142.985046386719 44.34375,146.365264892578 42.2812461853027,149.831405639648 40.21875,153.297546386719 38.2708320617676,156.778015136719 36.4375,160.272811889648 34.6041641235352,163.767608642578 32.9140625,167.119171142578 31.3671855926514,170.327499389648 30.6796875,173.020202636719 30.0065097808838,175.999374389648 29.3476543426514,179.264999389648 28.6888008117676,182.530624389648 28.1874980926514,186.111358642578 27.8437538146973,190.007186889648 27.2135410308838,197.741561889648 26.7408847808838,204.645202636719 26.4257793426514,210.718124389648 26.1106758117676,216.791046142578 25.4661445617676,222.348327636719 24.4921913146973,227.389999389648 24.1484375,229.223327636719 23.3177070617676,230.841827392578 22.0000057220459,232.245468139648 20.6822910308838,233.649108886719 18.9635410308838,234.350936889648 16.84375,234.350936889648 16.2135410308838,234.350936889648 15.46875,234.193389892578 14.6093778610229,233.878280639648 13.75,233.563171386719 12.93359375,233.119171142578 12.1601552963257,232.546249389648 11.38671875,231.973327636719 10.7278642654419,231.328796386719 10.1835947036743,230.612655639648 9.63932228088379,229.896514892578 9.3671875,229.108749389648 9.3671875,228.249374389648 9.3671875,226.358749389648 9.49609375,224.024108886719 9.75390529632568,221.245468139648 10.01171875,218.466827392578 10.3125,215.673858642578 10.6562471389771,212.866561889648 11,210.059265136719 11.3294267654419,207.509796142578 11.6445322036743,205.218124389648 11.9596347808838,202.926452636719 12.1744785308838,201.322296142578 12.2890615463257,200.405624389648 13.0911455154419,194.504577636719 13.8072910308838,188.130889892578 14.4375,181.284530639648 15.0677080154419,174.438171386719 15.5833330154419,166.975936889648 15.9843711853027,158.897811889648 16.0416660308838,157.179061889648 16.11328125,154.901718139648 16.1992206573486,152.065780639648 16.28515625,149.229843139648 16.37109375,146.365264892578 16.4570331573486,143.472030639648 16.54296875,140.578796386719 16.62890625,137.886093139648 16.71484375,135.393905639648 16.80078125,132.901718139648 16.9010410308838,131.139999389648 17.0156269073486,130.108749389648 17.8177070617676,119.166046142578 20.6822929382324,113.694686889648 25.6093730926514,113.694686889648 26.5833320617676,113.694686889648 27.5143203735352,113.938179016113 28.4023399353027,114.425163269043 29.2903633117676,114.912139892578 30.078125,115.542343139648 30.7656288146973,116.315780639648 31.453125,117.089218139648 31.9973945617676,117.962921142578 32.3984336853027,118.936874389648 32.7994766235352,119.910835266113 33,120.856147766113 33,121.772804260254 33,123.778022766113 32.78515625,125.940780639648 32.3554725646973,128.261093139648 31.9257793426514,130.581405639648 31.4531230926514,132.959014892578 30.9374961853027,135.393905639648 30.4218730926514,137.828796386719 29.9492168426514,140.220733642578 29.51953125,142.569686889648 29.0898418426514,144.918640136719 28.8749980926514,147.067077636719 28.8750019073486,149.014999389648 28.8749980926514,150.676452636719 29.0468730926514,151.507186889648 29.390625,151.507186889648 33.4010391235352,144.288436889648 37.3255195617676,137.943389892578 41.1640663146973,132.472030639648 45.0026016235352,127.000679016113 48.8411445617676,122.460311889648 52.6796836853027,118.850936889648 55.1432266235352,116.559272766113 57.578125,114.453804016113 59.9843788146973,112.534530639648 62.390625,110.615264892578 64.8111953735352,108.953804016113 67.24609375,107.550155639648 69.6809844970703,106.146514892578 72.2018203735352,105.057968139648 74.80859375,104.284538269043 77.4153594970703,103.511093139648 80.1796875,103.095733642578 83.1015625,103.038436889648 85.1067657470703,102.981147766113 87.18359375,103.468124389648 89.33203125,104.499374389648 91.48046875,105.530624389648 93.4140625,107.077499389648 95.1328125,109.139999389648 96.8515548706055,111.202499389648 98.2695236206055,113.709014892578 99.38671875,116.659530639648 100.503898620605,119.610054016113 101.033843994141,122.947296142578 100.976554870605,126.671249389648 101.033843994141,129.535827636719 100.589836120605,132.400421142578 99.6445236206055,135.264999389648 98.6992111206055,138.129577636719 97.4387969970703,140.951202392578 95.86328125,143.729843139648 94.2877578735352,146.508483886719 92.46875,149.186874389648 90.40625,151.764999389648 88.34375,154.343124389648 86.1953125,156.720733642578 83.9609375,158.897811889648 88.6588516235352,157.121765136719 93.4856719970703,154.944686889648 98.4413986206055,152.366561889648 103.397132873535,149.788436889648 108.35285949707,147.009796142578 113.30859375,144.030624389648 118.264320373535,141.051452636719 123.13410949707,137.957702636719 127.91796875,134.749374389648 132.701812744141,131.541046142578 137.27082824707,128.418640136719 141.625,125.382186889648 142.283843994141,124.923858642578 142.87825012207,124.501327514648 143.408203125,124.114616394043L144.405715942383,123.362648010254 144.4609375,123.276718139648C148.0703125,118.091827392578 151.822906494141,113.637397766113 155.71875,109.913436889648 160.244781494141,105.616561889648 164.98567199707,102.451202392578 169.94140625,100.417350769043 174.897125244141,98.3834915161133 179.98176574707,97.3665618896484 185.1953125,97.3665618896484 186.16926574707,97.3665618896484 187.014312744141,97.5670852661133 187.73046875,97.9681243896484 188.44660949707,98.3691711425781 189.0625,98.8847961425781 189.578125,99.5149993896484 190.09375,100.145210266113 190.55207824707,100.847030639648 190.953125,101.620460510254 191.354156494141,102.393905639648 191.75520324707,103.181671142578 192.15625,103.983749389648 192.385406494141,104.499374389648 192.87239074707,105.072296142578 193.6171875,105.702499389648 194.361968994141,106.332710266113 195.135406494141,106.977241516113 195.9375,107.636093139648 196.73957824707,108.294952392578 197.44140625,108.939483642578 198.04296875,109.569686889648 198.64453125,110.199897766113 198.9453125,110.801460266113 198.9453125,111.374374389648 198.9453125,112.577499389648 198.701812744141,113.909530639648 198.21484375,115.370460510254 197.72785949707,116.831405639648 197.197906494141,118.521514892578 196.625,120.440773010254 196.05207824707,122.360054016113 195.522125244141,124.537139892578 195.03515625,126.972023010254 194.54817199707,129.406921386719 194.3046875,132.199890136719 194.3046875,135.350936889648 194.3046875,137.413436889648 194.490875244141,139.762390136719 194.86328125,142.397811889648 195.23567199707,145.033233642578 195.80859375,147.539733886719 196.58203125,149.917343139648 197.35546875,152.294952392578 198.34375,154.285827636719 199.546875,155.889999389648 200.75,157.494171142578 202.15364074707,158.296249389648 203.7578125,158.296249389648 205.705718994141,158.296249389648 207.65364074707,157.737655639648 209.6015625,156.620468139648 211.549468994141,155.503280639648 213.783843994141,153.942077636719 216.3046875,151.936874389648 221.91926574707,147.468124389648 227.24739074707,142.569686889648 232.2890625,137.241561889648 237.330718994141,131.913436889648 242.486968994141,126.613960266113 247.7578125,121.343124389648L247.835861206055,121.282699584961 250.76448059082,113.780624389648C251.33740234375,112.634796142578 251.93896484375,111.732452392578 252.56916809082,111.073593139648 253.199371337891,110.414741516113 253.843902587891,109.927764892578 254.50276184082,109.612655639648 255.16162109375,109.297554016113 255.84912109375,109.097030639648 256.565246582031,109.011093139648 257.281402587891,108.925155639648 258.011871337891,108.882186889648 258.756652832031,108.882186889648 259.67333984375,108.882186889648 260.48974609375,109.512397766113 261.205871582031,110.772811889648 261.922027587891,112.033233642578 262.280090332031,113.780624389648 262.280090332031,116.014999389648 262.280090332031,117.389999389648 262.16552734375,118.679061889648 261.936340332031,119.882186889648 261.707183837891,121.085311889648 261.39208984375,122.317085266113 260.991027832031,123.577499389648 260.589996337891,124.837921142578 260.160308837891,126.198593139648 259.701965332031,127.659530639648 259.24365234375,129.120468139648 258.785308837891,130.796249389648 258.326965332031,132.686874389648 257.983215332031,134.233749389648 257.596496582031,135.952499389648 257.166809082031,137.843124389648 256.737121582031,139.733749389648 256.336090087891,141.653015136719 255.96369934082,143.600936889648 255.59130859375,145.548858642578 255.27619934082,147.453796386719 255.01838684082,149.315780639648 254.76057434082,151.177764892578 254.63166809082,152.853546142578 254.63166809082,154.343124389648 254.63166809082,155.374374389648 254.80354309082,156.434265136719 255.14729309082,157.522811889648 256.75146484375,157.350936889648 259.386871337891,154.944686889648 263.053527832031,150.304061889648 264.944152832031,147.955108642578 267.02099609375,145.376983642578 269.283996582031,142.569686889648 271.547027587891,139.762390136719 273.996246337891,136.668640136719 276.631652832031,133.288436889648 278.57958984375,130.767608642578 280.51318359375,128.418640136719 282.432434082031,126.241561889648 284.351715087891,124.064483642578 286.342590332031,122.159530639648 288.405090332031,120.526718139648 290.467590332031,118.893905639648 292.658996582031,117.604843139648 294.979309082031,116.659530639648 297.299621582031,115.714218139648 299.863433837891,115.241561889648 302.670715332031,115.241561889648 305.64990234375,115.241561889648 308.127746582031,115.886093139648 310.104309082031,117.175155639648 312.080871582031,118.464218139648 313.670715332031,120.240264892578 314.873840332031,122.503280639648 316.076965332031,124.766304016113 317.007965087891,127.473335266113 317.666809082031,130.624374389648 318.32568359375,133.775421142578 318.855621337891,137.241561889648 319.256652832031,141.022811889648 319.600402832031,144.231140136719 319.929840087891,147.410827636719 320.244934082031,150.561874389648 320.56005859375,153.712921142578 321.175933837891,156.534530639648 322.092590332031,159.026718139648 323.00927734375,161.518905639648 324.326965332031,163.538436889648 326.045715332031,165.085311889648 327.764465332031,166.632186889648 330.22802734375,167.405624389648 333.436340332031,167.405624389648 335.89990234375,167.405624389648 338.47802734375,166.832702636719 341.170715332031,165.686874389648 343.863433837891,164.541046142578 346.699371337891,162.951202392578 349.678527832031,160.917343139648 352.65771484375,158.883483886719 355.737121582031,156.491561889648 358.916809082031,153.741561889648 362.096496582031,150.991561889648 365.37646484375,147.983749389648 368.756652832031,144.718124389648 370.074371337891,143.457702636719 371.52099609375,141.867858886719 373.096496582031,139.948593139648 374.672027587891,138.029327392578 376.218902587891,136.181671142578 377.737121582031,134.405624389648 378.496246337891,133.517608642578 379.230285644531,132.694030761719 379.939300537109,131.934921264648L381.199279785156,130.655120849609 385.427612304688,124.264999389648C388.349487304688,120.254585266113 391.672393798828,116.244171142578 395.396362304688,112.233749389648 399.177612304688,108.223335266113 402.729705810547,105.358749389648 406.052612304688,103.639999389648 410.177612304688,101.405624389648 416.107299804688,100.288436889648 423.841674804688,100.288429260254 426.534362792969,100.288436889648 428.826049804688,101.778022766113 430.716674804688,104.757186889648 432.607299804688,107.736358642578 434.039581298828,111.202499389648 435.013549804688,115.155624389648 435.987487792969,119.337921142578 436.474487304688,122.603546142578 436.474487304688,124.952499389648 437.333862304688,122.145210266113 438.107299804688,119.294952392578 438.794799804688,116.401718139648 439.482299804688,113.508491516113 440.083862304688,110.514999389648 440.599487304688,107.421249389648 441.115112304688,104.327499389648 441.587768554688,101.076202392578 442.017456054688,97.6673431396484 442.447143554688,94.2584915161133 442.833862304688,90.6061477661133 443.177612304688,86.7103118896484 443.292175292969,85.679069519043 443.406768798828,84.3613586425781 443.521362304688,82.7571868896484 443.635925292969,81.1530227661133 443.779174804688,79.2623977661133 443.951049804688,77.0853118896484 444.294799804688,72.6165618896484 444.638549804688,68.8496398925781 444.982299804688,65.7845306396484 445.326049804688,62.7194366455078 445.784362792969,60.7285461425781 446.357299804688,59.8118743896484 447.732299804688,57.4629211425781 450.138549804688,56.2884368896484 453.576049804688,56.2884368896484z" transform="translate(-4.522309515625 -27.1750441384583) scale(0.482782)" />\r
|
|
196
196
|
</svg>\r
|
|
@@ -198,11 +198,11 @@ Error generating stack: `+c.message+`
|
|
|
198
198
|
\r
|
|
199
199
|
\r
|
|
200
200
|
`,mA=()=>a.jsx("span",{"aria-hidden":"true",className:"new-thread-hero__logo",dangerouslySetInnerHTML:{__html:hA}}),pA=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m15 18-6-6 6-6"})}),gA=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m9 18 6-6-6-6"})}),mx=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"8.5"}),a.jsx("path",{d:"M12 10.4v4.2"}),a.jsx("path",{d:"M12 7.9h.01"})]}),_A=(e,t)=>{var i;return((i=e[t])==null?void 0:i.trim())??""},px=()=>typeof window<"u"&&!window.matchMedia("(max-width: 768px)").matches,yA=_.memo(function({requests:t,hasStripBelow:i,pendingRequestId:r,onRespond:o}){const u=t[0]??null,[d,m]=_.useState(null),[y,g]=_.useState(""),[b,p]=_.useState({}),[v,w]=_.useState(0),[N,j]=_.useState(null),[T,M]=_.useState(null);_.useEffect(()=>{m(null),g(""),p({}),w(0),j(null),M(null)},[u==null?void 0:u.id]);const P=u?r===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(v,u.questions.length-1))]??null:null,O=k?_A(b,k.id):"",Q=k?k.options.some(ne=>ne.label===O):!1,J=!!(k&&O&&(!Q||N===k.id));_.useEffect(()=>{if(!k){j(null);return}if(Q){j(null);return}O&&j(k.id)},[Q,k,O]);const F=_.useMemo(()=>!u||P?!1:u.kind==="user_input"?k?!!O:!1:d?!0:u.allow_freeform?!!y.trim():!1,[k,O,u,y,P,d]);if(!u)return null;const B=u.questions.reduce((ne,Ce)=>ne+Ce.options.length,u.options.length),G=ne=>{P||o({requestId:u.id,optionId:(ne==null?void 0:ne.optionId)??d,text:(ne==null?void 0:ne.text)??y,answers:(ne==null?void 0:ne.answers)??b})},Z=()=>{if(!(!u||u.kind!=="user_input"||!k)){if(v<u.questions.length-1){w(ne=>Math.min(ne+1,u.questions.length-1));return}G()}},ae=()=>{if(!u||u.kind!=="user_input"||!k)return;const ne={...b,[k.id]:"忽略"};if(p(ne),j(null),v<u.questions.length-1){w(Ce=>Math.min(Ce+1,u.questions.length-1));return}G({answers:ne})},he=ne=>{if(!(!u||u.kind!=="user_input"||!k||P)){if(O===ne){Z();return}p(Ce=>({...Ce,[k.id]:ne})),j(null)}};return a.jsx("section",{className:`session-interaction-strip ${i?"has-strip-below":""} ${I?"is-user-input-flow":""}`,children:u.kind==="user_input"&&k?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"session-interaction-flow__header",children:[a.jsx("div",{className:"session-interaction-flow__prompt",children:k.question}),a.jsxs("div",{className:"session-interaction-flow__progress",children:[a.jsx("button",{type:"button",className:"session-interaction-flow__nav","aria-label":"上一题",disabled:v===0||P,onClick:()=>w(ne=>Math.max(0,ne-1)),children:a.jsx(pA,{})}),a.jsxs("span",{className:"session-interaction-flow__counter",children:[v+1," / ",u.questions.length]}),a.jsx("button",{type:"button",className:"session-interaction-flow__nav","aria-label":v===u.questions.length-1?"提交回复":"下一题",disabled:P||!F,onClick:Z,children:a.jsx(gA,{})})]})]}),a.jsx("div",{className:"session-interaction-flow__body",children:a.jsxs("div",{className:"session-interaction-flow__list",children:[k.options.map((ne,Ce)=>a.jsxs("div",{className:`session-interaction-flow__item is-${ne.emphasis} ${O===ne.label?"is-active":""}`,role:"button",tabIndex:P?-1:0,"aria-pressed":O===ne.label,onClick:()=>he(ne.label),onKeyDown:R=>{R.key==="Enter"&&px()&&(R.preventDefault(),he(ne.label))},children:[a.jsxs("span",{className:"session-interaction-flow__item-index",children:[Ce+1,"."]}),a.jsxs("span",{className:"session-interaction-flow__item-choice",children:[a.jsx("span",{className:"session-interaction-flow__item-label",children:ne.label}),ne.description?a.jsxs("span",{className:"session-interaction-flow__tooltip-wrap",children:[a.jsx("button",{type:"button",className:"session-interaction-flow__tooltip-trigger","aria-label":`查看 ${ne.label} 的说明`,"aria-expanded":T===ne.id,onMouseEnter:()=>M(ne.id),onMouseLeave:()=>M(R=>R===ne.id?null:R),onBlur:()=>M(R=>R===ne.id?null:R),onClick:R=>{R.stopPropagation(),M(X=>X===ne.id?null:ne.id)},children:a.jsx(mx,{})}),a.jsx("div",{className:`session-interaction-flow__tooltip ${T===ne.id?"is-visible":""}`,role:"tooltip",children:ne.description})]}):null]})]},ne.id)),a.jsx("div",{className:`session-interaction-flow__item is-custom ${J?"is-active":""}`,children:a.jsxs("div",{className:"session-interaction-flow__custom-input-wrap",children:[a.jsx("input",{type:"text",className:"session-interaction-flow__custom-input",value:Q?"":O,disabled:P,placeholder:k.is_secret?"输入敏感信息":"否,请告知如何调整",onFocus:()=>{j(k.id),Q&&p(ne=>({...ne,[k.id]:""}))},onKeyDown:ne=>{ne.key==="Enter"&&F&&!P&&px()&&(ne.preventDefault(),Z())},onChange:ne=>{j(k.id),p(Ce=>({...Ce,[k.id]:ne.target.value}))}}),a.jsxs("div",{className:"session-interaction-flow__inline-actions",children:[a.jsx("button",{type:"button",className:"session-interaction-flow__ghost",disabled:P,onClick:ae,children:"忽略"}),a.jsx("button",{type:"button",className:"session-interaction-flow__primary",disabled:!F,onClick:Z,children:P?"提交中...":v===u.questions.length-1?u.submit_label??"提交回复":"继续"})]})]})})]})})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"session-interaction-strip__header",children:[a.jsx("span",{className:"session-interaction-strip__icon","aria-hidden":"true",children:a.jsx(mx,{})}),a.jsxs("div",{className:"session-interaction-strip__copy",children:[a.jsxs("div",{className:"session-interaction-strip__title",children:[u.title,t.length>1?a.jsxs("span",{className:"session-interaction-strip__count",children:["还有 ",t.length-1," 个待处理"]}):null]}),u.description?a.jsx("div",{className:"session-interaction-strip__description",children:u.description}):null]})]}),u.options.length>0?a.jsx("div",{className:"session-interaction-strip__options",children:u.options.map(ne=>a.jsxs("button",{type:"button",className:`session-interaction-option is-${ne.emphasis} ${d===ne.id?"is-active":""}`,disabled:P,onClick:()=>{m(ne.id),!u.allow_freeform&&B<=3&&G({optionId:ne.id})},children:[a.jsx("span",{className:"session-interaction-option__label",children:ne.label}),ne.description?a.jsx("span",{className:"session-interaction-option__description",children:ne.description}):null]},ne.id))}):null,u.allow_freeform?a.jsxs("label",{className:"session-interaction-strip__freeform",children:[a.jsx("span",{className:"session-interaction-strip__freeform-label",children:"自定义回复"}),a.jsx("textarea",{value:y,disabled:P,placeholder:u.freeform_placeholder??"输入回复内容",onChange:ne=>g(ne.target.value)})]}):null,u.allow_freeform||u.options.length>3?a.jsx("div",{className:"session-interaction-strip__footer",children:a.jsx("button",{type:"button",className:"session-interaction-strip__submit",disabled:!F,onClick:()=>G(),children:P?"提交中...":u.submit_label??"继续"})}):null]})})}),vA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6l12 12"}),a.jsx("path",{d:"M18 6 6 18"})]}),bA=({panel:e,isPending:t,onDismiss:i,onSelectOption:r,onSubmitText:o})=>{const[u,d]=_.useState("");return _.useEffect(()=>{d("")},[e.panel_id,e.status]),a.jsxs("section",{className:`session-command-panel is-${e.status}`,children:[a.jsxs("div",{className:"session-command-panel__header",children:[a.jsxs("div",{className:"session-command-panel__command",children:["/",e.command_name]}),a.jsx("button",{type:"button",className:"session-command-panel__close","aria-label":"关闭命令面板",onClick:i,children:a.jsx(vA,{})})]}),a.jsx("div",{className:"session-command-panel__title",children:e.title}),e.description?a.jsx("div",{className:"session-command-panel__description",children:e.description}):null,a.jsx("pre",{className:"session-command-panel__body",children:e.body}),e.input_type==="choice"&&e.options.length>0?a.jsx("div",{className:"session-command-panel__options",children:e.options.map(m=>a.jsxs("button",{type:"button",className:"session-command-panel__option",disabled:t,onClick:()=>r(m.id),children:[a.jsx("span",{className:"session-command-panel__option-label",children:m.label}),m.description?a.jsx("span",{className:"session-command-panel__option-description",children:m.description}):null]},m.id))}):null,e.input_type==="text"?a.jsxs("form",{className:"session-command-panel__form",onSubmit:m=>{m.preventDefault(),!(!u.trim()||t)&&o(u.trim())},children:[a.jsx("input",{className:"session-command-panel__input",value:u,disabled:t,placeholder:e.input_placeholder??"继续输入",onChange:m=>d(m.target.value)}),a.jsx("button",{type:"submit",className:"session-command-panel__submit",disabled:t||!u.trim(),children:e.submit_label??"提交"})]}):null]})},xA=_.memo(function({planSnapshot:t,hasStripAbove:i,hasStripBelow:r}){const[o,u]=_.useState(!0);return t.steps.length?a.jsxs("section",{className:`session-plan-strip ${o?"is-collapsed":""} ${i?"has-strip-above":""} ${r?"has-strip-below":""}`,children:[a.jsxs("button",{type:"button",className:"session-plan-strip__toggle",onClick:()=>u(d=>!d),"aria-expanded":!o,children:[a.jsxs("div",{className:"session-plan-strip__summary",children:[a.jsx("span",{className:"session-plan-strip__summary-mark","aria-hidden":"true",children:a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{x:"4.5",y:"5",width:"15",height:"14",rx:"2.5"}),a.jsx("path",{d:"M8 9h8"}),a.jsx("path",{d:"M8 13h5.5"}),a.jsx("path",{d:"m15.5 14.5 1.5 1.5 2.5-3"})]})}),a.jsx("span",{className:"session-plan-strip__summary-text",children:a.jsxs("span",{children:["共 ",t.total_count," 个任务,已完成 ",t.completed_count," 个"]})})]}),a.jsx("span",{className:"session-plan-strip__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m8 10 4 4 4-4"})})})]}),o?null:a.jsx(a.Fragment,{children:a.jsx("div",{className:"session-plan-strip__steps",children:t.steps.map((d,m)=>a.jsxs("div",{className:`session-plan-step is-${d.status}`,children:[a.jsx("span",{className:"session-plan-step__dot","aria-hidden":"true",children:d.status==="in_progress"?a.jsx("span",{className:"session-plan-step__spinner"}):null}),a.jsxs("span",{className:"session-plan-step__index",children:[m+1,"."]}),a.jsx("span",{className:"session-plan-step__label",children:d.step})]},d.id))})})]}):null}),SA=(e,t,i)=>{const r=((i==null?void 0:i.enabled)??!0)&&!!e;return cs({queryKey:["project-skills",t??"",e],enabled:r,queryFn:async()=>e?(await cn({projectId:e,agentId:t??null})).client.getProjectSkills(e):[],staleTime:6e4,gcTime:10*6e4,refetchOnWindowFocus:!1,retry:1})},gx=24,jA=e=>{const t=f5(e);return t.length===0?a.jsx("span",{children:" "}):t.map((i,r)=>{const o=`skill-aware-token-${r}`;return i.kind==="skill"?a.jsx("span",{className:"skill-aware-textarea__token is-skill",children:i.raw},o):i.kind==="command"?a.jsx("span",{className:"skill-aware-textarea__token is-command",children:i.raw},o):i.kind==="code"?a.jsx("span",{className:"skill-aware-textarea__token is-code",children:i.value},o):i.kind==="path-link"?a.jsx("span",{className:"skill-aware-textarea__token is-link",children:i.label},o):a.jsx("span",{children:i.value},o)})},_x=({value:e,onChange:t,onKeyDown:i,placeholder:r,disabled:o=!1,className:u,projectId:d,agentId:m,autoFocus:y=!1})=>{var le;const g=u.includes("composer-fullscreen-sheet__input"),b=_.useRef(null),p=_.useRef(null),[v,w]=_.useState({start:0,end:0}),[N,j]=_.useState(!1),[T,M]=_.useState(!1),[P,I]=_.useState(0),k=_.useMemo(()=>h5(e,v.start,v.end),[v.end,v.start,e]),O=_.useMemo(()=>m5(e,v.start,v.end),[v.end,v.start,e]),Q=N&&!o&&!!k&&!T,J=N&&!o&&!!O&&!T,F=J?"command":Q?"skill":null,B=SA(d,m,{enabled:Q}),G=X3({enabled:J,scope:m?{agentId:m,projectId:d}:void 0}),Z=_.useMemo(()=>oA(B.data??[],(k==null?void 0:k.query)??"").slice(0,gx),[k==null?void 0:k.query,B.data]),ae=_.useMemo(()=>{var ue;return cA(((ue=G.data)==null?void 0:ue.commands)??[],(O==null?void 0:O.query)??"").slice(0,gx)},[O==null?void 0:O.query,(le=G.data)==null?void 0:le.commands]);_.useEffect(()=>{I(0)},[k==null?void 0:k.query,k==null?void 0:k.start,O==null?void 0:O.query,e,d]),_.useEffect(()=>{M(!1)},[k==null?void 0:k.query,k==null?void 0:k.start,k==null?void 0:k.end,O==null?void 0:O.query,O==null?void 0:O.start,O==null?void 0:O.end]);const he=()=>{if(!b.current||!p.current)return;const ue=b.current,ye=p.current;ye.scrollTop=ue.scrollTop,ye.scrollLeft=ue.scrollLeft;const D=Math.max(0,ue.offsetWidth-ue.clientWidth);ye.style.setProperty("--skill-aware-textarea-scrollbar-width",`${D}px`),ye.style.setProperty("--skill-aware-textarea-padding-inline-end",window.getComputedStyle(ue).paddingInlineEnd)};_.useEffect(()=>{he()},[e]),_.useEffect(()=>{if(typeof window>"u"||typeof ResizeObserver>"u")return;const ue=b.current;if(!ue)return;const ye=new ResizeObserver(()=>{he()});return ye.observe(ue),he(),()=>{ye.disconnect()}},[]);const ne=()=>{b.current&&w({start:b.current.selectionStart??0,end:b.current.selectionEnd??0})},Ce=ue=>{if(!b.current)return;const ye=rA(e,b.current.selectionStart??v.start,b.current.selectionEnd??v.end,ue.name);ye&&(t(ye.value),typeof window<"u"&&window.requestAnimationFrame(()=>{b.current&&(b.current.focus(),b.current.setSelectionRange(ye.selectionStart,ye.selectionEnd),w({start:ye.selectionStart,end:ye.selectionEnd}))}))},R=ue=>{if(!b.current)return;const ye=lA(e,b.current.selectionStart??v.start,b.current.selectionEnd??v.end,ue.name);ye&&(t(ye.value),typeof window<"u"&&window.requestAnimationFrame(()=>{b.current&&(b.current.focus(),b.current.setSelectionRange(ye.selectionStart,ye.selectionEnd),w({start:ye.selectionStart,end:ye.selectionEnd}))}))},X=ue=>{const ye=F==="skill"&&Z.length>0||F==="command"&&ae.length>0;if(F&&ye){if(ue.key==="ArrowDown"){ue.preventDefault();const D=F==="command"?ae.length:Z.length;I(oe=>(oe+1)%D);return}if(ue.key==="ArrowUp"){ue.preventDefault();const D=F==="command"?ae.length:Z.length;I(oe=>oe-1<0?D-1:oe-1);return}if((ue.key==="Enter"||ue.key==="Tab")&&!ue.shiftKey&&!ue.altKey&&!ue.ctrlKey&&!ue.metaKey){if(ue.preventDefault(),F==="command"){const oe=ae[P]??ae[0];if(!oe)return;R(oe);return}const D=Z[P]??Z[0];if(!D)return;Ce(D);return}}if(F&&ue.key==="Escape"){ue.preventDefault(),M(!0);return}i==null||i(ue)};return a.jsxs("div",{className:`skill-aware-textarea ${F?"is-picker-open":""} ${g?"is-fullscreen":""}`,children:[J?a.jsx("div",{className:"skill-mention-picker",role:"listbox","aria-label":"命令建议",children:G.isLoading?a.jsx("div",{className:"skill-mention-picker__empty",children:"正在加载命令…"}):G.isError?a.jsx("div",{className:"skill-mention-picker__empty",children:"命令列表加载失败"}):ae.length===0?a.jsx("div",{className:"skill-mention-picker__empty",children:"未找到匹配命令"}):ae.map((ue,ye)=>{const D=ye===P;return a.jsx("button",{type:"button",className:`skill-mention-picker__item ${D?"is-active":""}`,role:"option","aria-selected":D,onMouseDown:oe=>{oe.preventDefault(),R(ue)},onMouseEnter:()=>I(ye),children:a.jsxs("span",{className:"skill-mention-picker__main",children:[a.jsxs("span",{className:"skill-mention-picker__name",children:["/",ue.name]}),a.jsx("span",{className:"skill-mention-picker__description",children:ue.description})]})},ue.name)})}):Q?a.jsx("div",{className:"skill-mention-picker",role:"listbox","aria-label":"技能建议",children:B.isLoading?a.jsx("div",{className:"skill-mention-picker__empty",children:"正在加载技能…"}):B.isError?a.jsx("div",{className:"skill-mention-picker__empty",children:"技能列表加载失败"}):Z.length===0?a.jsx("div",{className:"skill-mention-picker__empty",children:"未找到匹配技能"}):Z.map((ue,ye)=>{const D=ye===P;return a.jsx("button",{type:"button",className:`skill-mention-picker__item ${D?"is-active":""}`,role:"option","aria-selected":D,onMouseDown:oe=>{oe.preventDefault(),Ce(ue)},onMouseEnter:()=>I(ye),children:a.jsxs("span",{className:"skill-mention-picker__main",children:[a.jsxs("span",{className:"skill-mention-picker__name",children:["$",ue.name]}),a.jsx("span",{className:"skill-mention-picker__description",children:ue.description}),a.jsx("span",{className:"skill-mention-picker__scope",children:iA(ue.scope)})]})},`${ue.scope}:${ue.name}:${ue.path}`)})}):null,a.jsxs("div",{className:"skill-aware-textarea__surface",children:[a.jsx("div",{ref:p,className:`${u} skill-aware-textarea__overlay`,"aria-hidden":"true",children:e?jA(e):a.jsx("span",{children:" "})}),a.jsx("textarea",{ref:b,className:`${u} skill-aware-textarea__input`,value:e,disabled:o,placeholder:r,autoFocus:y,onChange:ue=>{t(ue.target.value),M(!1),w({start:ue.target.selectionStart??0,end:ue.target.selectionEnd??0})},onKeyDown:X,onClick:ne,onSelect:ne,onKeyUp:ne,onFocus:()=>{j(!0),M(!1),ne()},onBlur:()=>{j(!1)},onScroll:he})]})]})},a_=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6l12 12"}),a.jsx("path",{d:"M18 6 6 18"})]}),wA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 5v14"}),a.jsx("path",{d:"m7 14 5 5 5-5"})]}),NA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M8 3H4v4"}),a.jsx("path",{d:"M16 3h4v4"}),a.jsx("path",{d:"M8 21H4v-4"}),a.jsx("path",{d:"M16 21h4v-4"}),a.jsx("path",{d:"M9 9 4 4"}),a.jsx("path",{d:"m15 9 5-5"}),a.jsx("path",{d:"m9 15-5 5"}),a.jsx("path",{d:"m15 15 5 5"})]}),kA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 5v14"}),a.jsx("path",{d:"M5 12h14"})]}),yx=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M13 2 5.5 13h5L9 22l9.5-13h-5L13 2Z"})}),vx=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M9 6h10"}),a.jsx("path",{d:"M9 12h10"}),a.jsx("path",{d:"M9 18h10"}),a.jsx("path",{d:"m4 6 1.5 1.5L7.5 5"}),a.jsx("path",{d:"m4 12 1.5 1.5L7.5 11"}),a.jsx("path",{d:"m4 18 1.5 1.5L7.5 17"})]}),bx=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M7 10V7.8A5 5 0 0 1 12 3a5 5 0 0 1 5 4.8V10"}),a.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"}),a.jsx("path",{d:"M12 14v2.6"})]}),EA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 16V5"}),a.jsx("path",{d:"m8 9 4-4 4 4"}),a.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"})]}),p5=_.memo(function({isDesktopSidebar:t,sidebarShift:i,isSidebarDragging:r,composerError:o,onDismissComposerError:u,interactionRequests:d,pendingInteractionRequestId:m,onRespondInteraction:y,parentSession:g,backgroundAgentSessions:b,isBackgroundAgentsOpen:p,planSnapshot:v,onToggleBackgroundAgents:w,onOpenSession:N,getBackgroundAgentStatusLabel:j,getBackgroundAgentAccent:T,formatBackgroundAgentsLabel:M,hasBackgroundAgentStrip:P,commandPanel:I,isCommandPanelPending:k,onDismissCommandPanel:O,onCommandPanelOptionSelect:Q,onCommandPanelTextSubmit:J,projectId:F=null,agentId:B=null,draft:G,pendingAttachments:Z,canSendInput:ae,canSubmitInput:he=!0,isInputLocked:ne=!1,inputPlaceholder:Ce,readOnlyPlaceholder:R,onDraftChange:X,onUploadFiles:le,onRemoveAttachment:ue,onSubmit:ye,showStopIcon:D,isSendPending:oe,onInterrupt:je,isFastModeEnabled:z,isPlanModeEnabled:be,isYoloModeEnabled:De,onToggleFastMode:se,onTogglePlanMode:pe,onToggleYoloMode:ke,showModeBadges:Ze=!1,selectedModel:zt,modelOptions:Fe=[],selectedReasoning:kt,onSelectModel:Bt,onSelectReasoning:Gt,contextUsage:Xt,isContextUsageOpen:Ft,onToggleContextUsage:qe,contextUsageRingStyle:dt,usedPercent:un,remainingPercent:$t,usedTokensLabel:An,totalTokensLabel:Nn,showJumpToBottom:Tt,onJumpToBottom:lt}){const Et=_.useId(),[rt,st]=_.useState(!1),[Dt,an]=_.useState(null),re=_.useRef(null),we=_.useRef(null),Re=d[0]??null,te=(Re==null?void 0:Re.kind)==="user_input",ve=d.length>0,V=!!v&&!te,q=!te&&P,de=V||q,ce=ve||V||q,Ae={transform:`translateX(${i}px)`,transition:r?"none":void 0},Ee=(!!G.trim()||Z.length>0)&&ae&&he&&!ne&&!oe&&!D,$e=ae&&!ne,Pe=Ze&&(z||be||De),ht=()=>{Ee&&(an(null),ye())},Xe=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(),ht())};_.useEffect(()=>{if(!rt)return;const Le=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=Le}},[rt]),_.useEffect(()=>{if(!rt||typeof window>"u")return;const Le=window.matchMedia("(min-width: 769px)"),rn=()=>{Le.matches&&st(!1)};return rn(),typeof Le.addEventListener=="function"?(Le.addEventListener("change",rn),()=>{Le.removeEventListener("change",rn)}):(Le.addListener(rn),()=>{Le.removeListener(rn)})},[rt]),_.useEffect(()=>{if(!Dt)return;const Le=hn=>{const ns=hn.target;re.current&&ns instanceof Node&&re.current.contains(ns)||an(null)},rn=hn=>{hn.key==="Escape"&&an(null)};return window.addEventListener("pointerdown",Le),window.addEventListener("keydown",rn),()=>{window.removeEventListener("pointerdown",Le),window.removeEventListener("keydown",rn)}},[Dt]);const tn=Le=>Pe?a.jsxs("div",{className:Le,"aria-label":"当前已启用的会话模式",children:[z?a.jsxs("button",{type:"button",className:"composer-mode-badge is-fast",onClick:()=>{an(null),se()},"aria-label":"关闭 Fast 模式",children:[a.jsx("span",{className:"composer-mode-badge__icon","aria-hidden":"true",children:a.jsx(yx,{})}),a.jsx("span",{className:"composer-mode-badge__label",children:"Fast"})]}):null,be?a.jsxs("button",{type:"button",className:"composer-mode-badge is-plan",onClick:()=>{an(null),pe()},"aria-label":"关闭计划模式",children:[a.jsx("span",{className:"composer-mode-badge__icon","aria-hidden":"true",children:a.jsx(vx,{})}),a.jsx("span",{className:"composer-mode-badge__label",children:"计划"})]}):null,De?a.jsxs("button",{type:"button",className:"composer-mode-badge is-yolo",onClick:()=>{an(null),ke()},"aria-label":"关闭 Yolo 模式",children:[a.jsx("span",{className:"composer-mode-badge__icon","aria-hidden":"true",children:a.jsx(bx,{})}),a.jsx("span",{className:"composer-mode-badge__label",children:"Yolo"})]}):null]}):null;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`composer-wrap ${t?"has-desktop-sidebar":""}`,style:Ae,children:[o?a.jsxs("div",{className:"composer-alert",role:"status","aria-live":"polite",children:[a.jsx("span",{className:"composer-alert__text",children:o}),a.jsx("button",{type:"button",className:"composer-alert__close",onClick:u,"aria-label":"关闭错误提示",children:a.jsx(a_,{})})]}):null,ve?a.jsx(yA,{requests:d,hasStripBelow:de,pendingRequestId:m,onRespond:y}):null,V&&v?a.jsx(xA,{planSnapshot:v,hasStripAbove:ve,hasStripBelow:q}):null,q&&g?a.jsxs("button",{type:"button",className:`background-agents-exit ${ve||V?"has-strip-above":""}`,onClick:()=>{N(g.id)},children:[a.jsx("span",{className:"background-agents-exit__icon","aria-hidden":"true",children:a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.85",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M6 12h12"}),a.jsx("path",{d:"m13 7 5 5-5 5"})]})}),a.jsx("span",{children:"返回主会话"})]}):q&&b.length>0?a.jsxs("section",{className:`background-agents-card ${p?"is-open":""} ${ve||V?"has-strip-above":""}`,children:[a.jsxs("button",{type:"button",className:"background-agents-card__toggle",onClick:w,"aria-expanded":p,children:[a.jsx("span",{className:"background-agents-card__icon","aria-hidden":"true",children:a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("rect",{x:"7",y:"4",width:"10",height:"7",rx:"2.5"}),a.jsx("path",{d:"M12 11v3"}),a.jsx("circle",{cx:"10",cy:"7.5",r:"0.8",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"14",cy:"7.5",r:"0.8",fill:"currentColor",stroke:"none"}),a.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"})]})}),a.jsxs("span",{className:"background-agents-card__summary",children:[a.jsx("span",{className:"background-agents-card__title",children:M(b.length)}),p?a.jsx("span",{className:"background-agents-card__hint",children:"(@ to tag agents)"}):null]}),a.jsx("span",{className:"background-agents-card__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m8 10 4 4 4-4"})})})]}),p?a.jsx("div",{className:"background-agents-card__list",children:b.map(Le=>{var rn,hn;return a.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:[a.jsx("span",{className:"background-agent-row__accent","aria-hidden":"true"}),a.jsxs("span",{className:"background-agent-row__meta",children:[a.jsxs("span",{className:"background-agent-row__title",children:[a.jsx("span",{className:"background-agent-row__name",children:((rn=Le.subagent)==null?void 0:rn.nickname)??Le.title}),a.jsxs("span",{className:"background-agent-row__role",children:["(",((hn=Le.subagent)==null?void 0:hn.role)??"agent",")"]})]}),a.jsx("span",{className:"background-agent-row__status",children:j(Le)})]}),a.jsx("span",{className:"background-agent-row__open",children:"Open"})]},Le.id)})}):null]}):null,I?a.jsx(bA,{panel:I,isPending:k,onDismiss:O,onSelectOption:Q,onSubmitText:J}):null,te?null:a.jsxs("form",{className:`chat-composer ${ce?"is-attached-to-agent-strip":""}`,onSubmit:Le=>{Le.preventDefault(),ht()},children:[a.jsxs("div",{className:"chat-composer__editor",children:[Z.length>0?a.jsx("div",{className:"chat-composer__attachments",children:Z.map(Le=>{const rn=qp(Le.size_bytes);return a.jsxs("div",{className:"chat-composer__attachment-chip",children:[a.jsxs("div",{className:"chat-composer__attachment-copy",children:[a.jsx("span",{className:"chat-composer__attachment-name",children:Le.name}),a.jsxs("span",{className:"chat-composer__attachment-meta",children:[Le.kind==="image"?"图片":"文件",rn?` · ${rn}`:""]})]}),a.jsx("button",{type:"button",className:"chat-composer__attachment-remove","aria-label":`移除 ${Le.name}`,onClick:()=>ue(Le.id),children:a.jsx(a_,{})})]},Le.id)})}):null,a.jsx(_x,{className:"chat-composer__input",value:G,disabled:!$e,projectId:F,agentId:B,placeholder:$e?Ce??"要求后续变更":R??"当前会话为只读模式",onChange:X,onKeyDown:Xe}),a.jsx("button",{type:"button",className:"composer-fullscreen-toggle","aria-label":"全屏编辑",onClick:()=>st(!0),children:a.jsx(NA,{})}),a.jsx("input",{id:Et,ref:we,type:"file",className:"chat-composer__file-input",multiple:!0,onChange:Le=>{Le.target.files&&Le.target.files.length>0&&le(Le.target.files),Le.target.value=""}})]}),tn("composer-mode-badges composer-mode-badges--mobile"),a.jsxs("div",{className:"chat-composer__toolbar",children:[a.jsxs("div",{ref:re,className:"chat-composer__controls",children:[a.jsxs("div",{className:`composer-utility-menu ${Dt==="utility"?"is-open":""}`,children:[a.jsx("button",{type:"button",className:"composer-utility-menu__trigger","aria-label":"打开额外功能","aria-expanded":Dt==="utility",onClick:()=>an(Le=>Le==="utility"?null:"utility"),children:a.jsx(kA,{})}),Dt==="utility"?a.jsxs("div",{className:"composer-utility-menu__popover",role:"menu",children:[a.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitem",onClick:()=>{var Le;an(null),(Le=we.current)==null||Le.click()},children:[a.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:a.jsx(EA,{})}),a.jsx("span",{className:"composer-utility-menu__item-label",children:"上传文件"})]}),a.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitemcheckbox","aria-checked":z,onClick:se,children:[a.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:a.jsx(yx,{})}),a.jsx("span",{className:"composer-utility-menu__item-label",children:"Fast 模式"}),a.jsx("span",{className:`composer-utility-menu__switch ${z?"is-on":""}`,"aria-hidden":"true",children:a.jsx("span",{className:"composer-utility-menu__switch-thumb"})})]}),a.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitemcheckbox","aria-checked":be,onClick:pe,children:[a.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:a.jsx(vx,{})}),a.jsx("span",{className:"composer-utility-menu__item-label",children:"计划模式"}),a.jsx("span",{className:`composer-utility-menu__switch ${be?"is-on":""}`,"aria-hidden":"true",children:a.jsx("span",{className:"composer-utility-menu__switch-thumb"})})]}),a.jsxs("button",{type:"button",className:"composer-utility-menu__item",role:"menuitemcheckbox","aria-checked":De,onClick:ke,children:[a.jsx("span",{className:"composer-utility-menu__item-icon","aria-hidden":"true",children:a.jsx(bx,{})}),a.jsx("span",{className:"composer-utility-menu__item-label",children:"Yolo 模式"}),a.jsx("span",{className:`composer-utility-menu__switch ${De?"is-on":""}`,"aria-hidden":"true",children:a.jsx("span",{className:"composer-utility-menu__switch-thumb"})})]})]}):null]}),a.jsxs("div",{className:`composer-choice ${Dt==="model"?"is-open":""}`,children:[a.jsxs("button",{type:"button",className:"composer-control","aria-label":"选择模型","aria-expanded":Dt==="model",onClick:()=>an(Le=>Le==="model"?null:"model"),children:[a.jsx("span",{className:"composer-icon",children:a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M12 3 4 7v10l8 4 8-4V7z"}),a.jsx("path",{d:"m4 7 8 4 8-4"}),a.jsx("path",{d:"M12 11v10"})]})}),a.jsx("span",{className:"composer-control__value",children:Fp(zt,Fe)})]}),Dt==="model"?a.jsx("div",{className:"composer-choice-menu",role:"menu","aria-label":"选择模型",children:Fe.map(Le=>a.jsxs("button",{type:"button",className:`composer-choice-menu__item ${zt===Le.value?"is-active":""}`,role:"menuitemradio","aria-checked":zt===Le.value,onClick:()=>{Bt(Le.value),an(null)},children:[a.jsx("span",{className:"composer-choice-menu__text",children:a.jsx("span",{className:"composer-choice-menu__label",children:Le.label})}),zt===Le.value?a.jsx("span",{className:"composer-choice-menu__check",children:"✓"}):null]},Le.value))}):null]}),a.jsxs("div",{className:`composer-choice ${Dt==="reasoning"?"is-open":""}`,children:[a.jsxs("button",{type:"button",className:"composer-control","aria-label":"选择推理强度","aria-expanded":Dt==="reasoning",onClick:()=>an(Le=>Le==="reasoning"?null:"reasoning"),children:[a.jsx("span",{className:"composer-icon",children:a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[a.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"}),a.jsx("path",{d:"M10 21h4"}),a.jsx("path",{d:"M9 18h6"})]})}),a.jsx("span",{className:"composer-control__value",children:QT(kt)})]}),Dt==="reasoning"?a.jsx("div",{className:"composer-choice-menu",role:"menu","aria-label":"选择推理强度",children:mh.map(Le=>a.jsxs("button",{type:"button",className:`composer-choice-menu__item ${kt===Le.value?"is-active":""}`,role:"menuitemradio","aria-checked":kt===Le.value,onClick:()=>{Gt(Le.value),an(null)},children:[a.jsx("span",{className:"composer-choice-menu__label",children:Le.label}),kt===Le.value?a.jsx("span",{className:"composer-choice-menu__check",children:"✓"}):null]},Le.value))}):null]}),tn("composer-mode-badges composer-mode-badges--inline")]}),a.jsxs("div",{className:"chat-composer__actions",children:[Xt?a.jsxs("div",{className:`composer-context ${Ft?"is-open":""}`,children:[a.jsx("button",{type:"button",className:"composer-context__trigger","aria-label":"查看背景信息窗口使用情况",onClick:Le=>{Le.stopPropagation(),qe()},children:a.jsx("span",{className:"composer-context__ring",style:dt,children:a.jsx("span",{className:"composer-context__ring-core"})})}),Ft?a.jsxs("div",{className:"composer-context__popover",role:"tooltip",children:[a.jsx("div",{className:"composer-context__title",children:"背景信息窗口:"}),a.jsxs("div",{children:[un,"% 已用(剩余 ",$t,"%)"]}),a.jsxs("div",{children:["已用 ",An,",共 ",Nn]})]}):null]}):null,a.jsx("button",{type:D?"button":"submit",className:"composer-send",disabled:D?!ae:!Ee,"aria-label":D?"中断":"发送",onClick:()=>{D&&je()},children:D?a.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:a.jsx("rect",{x:"7",y:"7",width:"10",height:"10",rx:"2.5"})}):a.jsx("svg",{viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:a.jsx("path",{d:"M12 17V7m0 0-4 4m4-4 4 4",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})})]})]})]})]}),rt?a.jsx("div",{className:"composer-fullscreen-sheet",role:"dialog","aria-modal":"true","aria-label":"全屏编辑",children:a.jsxs("div",{className:"composer-fullscreen-sheet__panel",children:[a.jsxs("div",{className:"composer-fullscreen-sheet__header",children:[a.jsx("div",{className:"composer-fullscreen-sheet__title",children:"全屏编辑"}),a.jsx("button",{type:"button",className:"composer-fullscreen-sheet__close","aria-label":"退出全屏编辑",onClick:()=>st(!1),children:a.jsx(a_,{})})]}),a.jsx(_x,{className:"composer-fullscreen-sheet__input",value:G,disabled:!$e,projectId:F,agentId:B,placeholder:$e?Ce??"要求后续变更":R??"当前会话为只读模式",onChange:X,onKeyDown:Xe,autoFocus:!0}),a.jsxs("div",{className:"composer-fullscreen-sheet__footer",children:[a.jsxs("div",{className:"composer-fullscreen-sheet__meta",children:[a.jsx("span",{children:zt}),a.jsx("span",{children:kt}),De?a.jsx("span",{children:"Yolo"}):null,Z.length>0?a.jsxs("span",{children:[Z.length," 个附件"]}):null]}),a.jsxs("div",{className:"composer-fullscreen-sheet__actions",children:[a.jsx("button",{type:"button",className:"composer-fullscreen-sheet__button",onClick:()=>st(!1),children:"关闭"}),D?a.jsx("button",{type:"button",className:"composer-fullscreen-sheet__button is-primary",disabled:!ae,onClick:je,children:"中断"}):a.jsx("button",{type:"button",className:"composer-fullscreen-sheet__button is-primary",disabled:!Ee,onClick:()=>{ht(),st(!1)},children:"发送"})]})]})]})}):null,Tt?a.jsx("button",{type:"button",className:`conversation-jump-bottom ${t?"has-desktop-sidebar":""}`,style:Ae,onClick:lt,"aria-label":"滚动到最下面",children:a.jsx(wA,{})}):null]})}),xx=10,CA=e=>{const t=e.replace(/\s+/g," ").trim();return t.length<=xx?t:t.slice(0,xx).trimEnd()},TA=(e,t)=>{var r,o;const i=CA(e);return i||((o=(r=t[0])==null?void 0:r.name)==null?void 0:o.trim())||"附件"},MA=e=>{var i;const t=/^\/([A-Za-z][A-Za-z0-9._-]*)/.exec(e.trim());return((i=t==null?void 0:t[1])==null?void 0:i.toLowerCase())??""},RA=({currentAgent:e,projects:t,sessions:i,initialProjectId:r=null,entryView:o,isDesktopSidebar:u,sidebarOffset:d,isSidebarDragging:m,onOpenSidebar:y,onProjectSelected:g,onSessionCreated:b})=>{const p=Ka(),[v,w]=_.useState(""),[N,j]=_.useState(r),[T,M]=_.useState(null),[P,I]=_.useState(null),[k,O]=_.useState(()=>sy()),[Q,J]=_.useState(()=>L3()),[F,B]=_.useState([]),[G,Z]=_.useState(!1),[ae,he]=_.useState(!1),[ne,Ce]=_.useState(!1),[R,X]=_.useState(o),le=ly(),ue=_.useMemo(()=>le.map(({id:se,...pe})=>pe),[le]),ye=Fm(N),D=_.useMemo(()=>Fm(N)?null:t.find(se=>se.id===N)??null,[t,N]);_.useEffect(()=>{Jf(k)},[k]),_.useEffect(()=>{P3(Q)},[Q]),_.useEffect(()=>{ue.length!==0&&(ue.some(se=>se.value===k)||O(ue[0].value))},[ue,k]),_.useEffect(()=>{X(o)},[o]),_.useEffect(()=>{I(null)},[N]),_.useEffect(()=>{var pe,ke;if(Fm(N)||N&&t.some(Ze=>Ze.id===N))return;const se=(Fm(r)?Gr:null)??(r&&t.some(Ze=>Ze.id===r)?r:null)??((pe=i.find(Ze=>!Ze.archived&&Ze.project_id))==null?void 0:pe.project_id)??((ke=t[0])==null?void 0:ke.id)??null;j(se)},[r,t,N,i]);const oe=Gn({mutationFn:async se=>{if(!se.chatOnly&&!D||!se.input.trim()&&se.attachments.length===0)throw new Error("请先选择线程,再输入第一条消息");const pe=await cn({projectId:se.projectId,agentId:e.id});return(se.chatOnly?await pe.client.createChat({agentId:e.id,title:se.title,input:se.input,attachments:se.attachments,model:se.model,titleGenerationModel:se.titleGenerationModel,reasoningEffort:se.reasoningEffort,serviceTier:se.serviceTier,planMode:se.planMode,yoloMode:se.yoloMode}):await pe.client.createSession({agentId:e.id,projectId:se.projectId,title:se.title,input:se.input,attachments:se.attachments,model:se.model,titleGenerationModel:se.titleGenerationModel,reasoningEffort:se.reasoningEffort,serviceTier:se.serviceTier,planMode:se.planMode,yoloMode:se.yoloMode})).session},onMutate:()=>M(null),onSuccess:async(se,pe)=>{const ke=new Date().toISOString(),Ze={id:`optimistic-user:${se.id}:create`,kind:"user",title:"你",body:pe.input,body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:se.last_event_at||ke,accent:"primary",attachments:l5(pe.attachments)};fr(e.id),Ea(se.id),KT(se.id,{isFastModeEnabled:pe.serviceTier==="fast",isPlanModeEnabled:pe.planMode,isYoloModeEnabled:pe.yoloMode}),sl(se.id),Hu(null),vE({sessionId:se.id,agentId:se.agent_id,projectId:se.project_id,createdAt:ke,session:se,project:D?{id:D.id,agent_id:D.agent_id,name:D.name,display_name:D.display_name,pinned:D.pinned,path:D.path}:null,optimisticEntry:Ze}),p.setQueriesData({queryKey:hs},zt=>Bp(zt,se)),p.setQueryData(ic(se.id),zt=>r0(zt,Ze)),Z(!1),he(!1),Ce(!1),b(se.id),p.invalidateQueries({queryKey:["plan",se.id]}),p.invalidateQueries({queryKey:["change-sets",se.id]})},onError:se=>{M(se instanceof Error?se.message:"创建会话失败")}}),je=(D==null?void 0:D.path)??null,z=R==="directory-picker",be={transform:`translateX(${d}px)`,transition:m?"none":void 0},De=()=>{const se=v.trim();if(!(!se&&F.length===0||oe.isPending||!D&&!ye)){if(hy(se)){if(F.length>0){M("命令暂不支持附件,请先移除附件后再执行。");return}const pe=MA(se);if(pe==="model"){if(w(""),ue.length>0){I({panel_id:`new-thread-command-${Date.now()}`,session_id:`new-thread:${(D==null?void 0:D.id)??Gr}`,command_name:pe,command_text:se,title:"为新会话选择模型",description:"选择后会更新新会话的默认模型,再继续输入真正的首条消息。",status:"awaiting_input",body:"在下面选择一个模型。",submitted_at:new Date().toISOString(),updated_at:new Date().toISOString(),input_type:"choice",options:ue.map(ke=>({id:ke.value,label:ke.label,description:ke.description??null})),input_placeholder:null,submit_label:null,effect:null});return}I({panel_id:`new-thread-command-${Date.now()}`,session_id:`new-thread:${(D==null?void 0:D.id)??Gr}`,command_name:pe,command_text:se,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(pe==="status"){w(""),I({panel_id:`new-thread-command-${Date.now()}`,session_id:`new-thread:${(D==null?void 0:D.id)??Gr}`,command_name:pe,command_text:se,title:"新会话当前设置",description:"这里展示的是创建下一条会话时会使用的本地设置。",status:"completed",body:[`线程:${ye?"仅聊天":(D==null?void 0:D.display_name)??(D==null?void 0:D.name)??"未选择"}`,`模型:${k}`,`推理强度:${Q}`,`Fast 模式:${G?"开启":"关闭"}`,`计划模式:${ae?"开启":"关闭"}`,`Yolo 模式:${ne?"开启":"关闭"}`].join(`
|
|
201
|
-
`),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:${(D==null?void 0:D.id)??Gr}`,command_name:pe||"unknown",command_text:se,title:`/${pe||"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}oe.mutate({projectId:ye?null:D.id,chatOnly:ye,input:se,title:TA(se,F),attachments:F,model:k,titleGenerationModel:O3(),reasoningEffort:Q,serviceTier:G?"fast":void 0,planMode:ae,yoloMode:ne})}};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`conversation-main conversation-main--new-thread ${u?"has-desktop-sidebar":""}`,style:be,children:[a.jsxs("div",{className:"conversation-topbar",children:[u?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:y,"aria-label":"打开侧边栏",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]}),a.jsx("div",{className:"conversation-topbar__meta",children:a.jsx("div",{className:"conversation-topbar__title-row",children:a.jsx("h1",{"aria-label":"未命名会话",children:" "})})})]}),a.jsx("div",{className:"conversation-scroll conversation-scroll--empty",children:a.jsx("div",{className:"conversation-thread conversation-thread--empty",children:z?a.jsx(fA,{agentId:e.id,projects:t,title:"选择目录",subtitle:"",onProjectCreated:se=>{p.setQueriesData({queryKey:hs},pe=>wC(pe,se)),j(se.id),g(se.id),X("composer")}}):a.jsx("section",{className:"new-thread-hero",children:a.jsxs("div",{className:"new-thread-hero__stack",children:[a.jsx(mA,{}),a.jsxs("label",{className:"new-thread-hero__selector",children:[a.jsx("span",{className:"new-thread-hero__selector-label",children:"在线程中发起会话"}),a.jsxs("select",{className:"new-thread-hero__select",value:N??"",onChange:se=>{const pe=se.target.value||null;j(pe),g(pe)},children:[t.map(se=>a.jsx("option",{value:se.id,children:se.display_name??se.name},se.id)),a.jsx("option",{value:Gr,children:"仅聊天"})]})]}),je?a.jsx("div",{className:"new-thread-hero__path",children:je}):ye?a.jsx("div",{className:"new-thread-hero__hint",children:"当前会话不会绑定项目,只保留聊天上下文。"}):a.jsx("div",{className:"new-thread-hero__hint",children:"选择一个线程后,直接输入第一条消息即可开始。"}),u?null:a.jsx("button",{type:"button",className:"new-thread-hero__directory-trigger",onClick:()=>X("directory-picker"),children:"新增目录线程"})]})})})})]}),z?null:a.jsx(p5,{isDesktopSidebar:u,sidebarShift:d,isSidebarDragging:m,composerError:T,onDismissComposerError:()=>M(null),interactionRequests:[],pendingInteractionRequestId:null,onRespondInteraction:()=>{},parentSession:null,backgroundAgentSessions:[],isBackgroundAgentsOpen:!1,planSnapshot:null,onToggleBackgroundAgents:()=>{},onOpenSession:()=>{},getBackgroundAgentStatusLabel:()=>"",getBackgroundAgentAccent:()=>"var(--color-accent-primary)",formatBackgroundAgentsLabel:se=>`${se} background agents`,hasBackgroundAgentStrip:!1,commandPanel:P,isCommandPanelPending:!1,onDismissCommandPanel:()=>I(null),onCommandPanelOptionSelect:se=>{O(se),I(pe=>pe&&{...pe,status:"completed",body:`新会话默认模型已切换为 ${Fp(se,ue)}。现在可以继续输入真正的首条消息。`,updated_at:new Date().toISOString(),input_type:"none",options:[]})},onCommandPanelTextSubmit:()=>{},projectId:(D==null?void 0:D.id)??null,agentId:e.id,draft:v,pendingAttachments:F,canSendInput:!!D||ye,inputPlaceholder:ye?"发起仅聊天会话…":D?`向 ${D.display_name??D.name} 发起第一条任务…`:"先选择线程,再输入第一条任务",readOnlyPlaceholder:"先选择线程,再输入第一条任务",onDraftChange:w,onUploadFiles:se=>{const pe=[...se];pe.length!==0&&(M(null),Promise.all(pe.map(ke=>cy(ke))).then(ke=>{B(Ze=>[...Ze,...ke])}).catch(ke=>{M(ke instanceof Error?ke.message:"无法读取附件")}))},onRemoveAttachment:se=>{B(pe=>pe.filter(ke=>ke.id!==se))},onSubmit:De,showStopIcon:!1,isSendPending:oe.isPending,onInterrupt:()=>{},isFastModeEnabled:G,isPlanModeEnabled:ae,isYoloModeEnabled:ne,onToggleFastMode:()=>Z(se=>!se),onTogglePlanMode:()=>he(se=>!se),onToggleYoloMode:()=>Ce(se=>!se),showModeBadges:!0,selectedModel:k,modelOptions:ue,selectedReasoning:Q,onSelectModel:O,onSelectReasoning:se=>J(se),contextUsage:null,isContextUsageOpen:!1,onToggleContextUsage:()=>{},usedPercent:0,remainingPercent:0,usedTokensLabel:"0",totalTokensLabel:"0",showJumpToBottom:!1,onJumpToBottom:()=>{}})]})},g5="panda:session-timeline-snapshots",op=1,AA=1440*60*1e3,_5=12,IA=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},DA=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}},y5=()=>{const e=IA(g5);if(!e||e.version!==op||!Array.isArray(e.items))return{version:op,items:[]};const t=Date.now(),i=e.items.filter(r=>!!(r&&typeof r.sessionId=="string"&&typeof r.storedAt=="number"&&r.snapshot&&typeof r.snapshot=="object")).filter(r=>t-r.storedAt<=AA).sort((r,o)=>o.storedAt-r.storedAt).slice(0,_5);return{version:op,items:i}},OA=e=>{const i=y5().items.find(r=>r.sessionId===e);return i?i.snapshot:null},LA=e=>{if(!e||e.view!=="full_compact")return;const t=Date.now(),i=y5(),r=[{sessionId:e.session_id,storedAt:t,snapshot:e},...i.items.filter(o=>o.sessionId!==e.session_id)].slice(0,_5);DA(g5,{version:op,items:r})},PA=e=>{var t,i,r;return["session-tool-detail",((t=e==null?void 0:e.scope)==null?void 0:t.sessionId)??"",(i=e==null?void 0:e.scope)!=null&&i.sessionId?"":((r=e==null?void 0:e.scope)==null?void 0:r.agentId)??"",(e==null?void 0:e.sessionId)??"",(e==null?void 0:e.entryId)??""]};function UA(e){return cs({queryKey:PA(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 cn(e.scope)).client.getSessionToolCallDetail(e.sessionId,e.entryId),refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1})}const v5=e=>{var t,i,r;return["workspace-session-detail",((t=e==null?void 0:e.scope)==null?void 0:t.sessionId)??"",(i=e==null?void 0:e.scope)!=null&&i.sessionId?"":((r=e==null?void 0:e.scope)==null?void 0:r.agentId)??"",(e==null?void 0:e.sessionId)??""]};function zA(e){return cs({queryKey:v5(e),enabled:!!((e==null?void 0:e.enabled)??!0)&&!!(e!=null&&e.sessionId),queryFn:async()=>e!=null&&e.sessionId?(await cn(e.scope)).client.getWorkspaceSessionDetail(e.sessionId):null,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1})}const BA={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},$A=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:e.provider,mode:"managed",health:"active",branch:"",worktree:"",summary:"",latest_assistant_message:null,context_usage:null,capability:BA}),HA=(e,t)=>e?!t||t.id!==e.id?$A(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,provider:e.provider}:t??null,Sx=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},FA=(e,t,i)=>{if(!e||e.session.id!==t)return e;const{last_event_at:r,...o}=i;let u={...e.session,...o};if(typeof r=="string"&&r.trim()){const d=new Date(r).getTime(),m=new Date(e.session.last_event_at).getTime();Number.isFinite(d)&&(!Number.isFinite(m)||d>m)&&(u={...u,last_event_at:r})}return{...e,session:u}},jx=_.lazy(async()=>({default:(await cl(()=>import("./session-diff-preview-kDHdPa6S.js"),__vite__mapDeps([0,1]))).SessionDiffPreview})),i_=["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)"],b5=14,x5=10,Ql=24,Iu=48,r_=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m9 6 6 6-6 6"})}),qA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M20 11a8 8 0 1 0 2.2 5.5"}),a.jsx("path",{d:"M20 4v7h-7"})]}),WA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M3 12a9 9 0 1 0 2.64-6.36"}),a.jsx("path",{d:"M3 4v5h5"}),a.jsx("path",{d:"M12 7v5l3 2"})]}),wx=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M9 14 4 9l5-5"}),a.jsx("path",{d:"M4 9h8a8 8 0 1 1 0 16h-1"})]}),Nx=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M7.5 12.5 10.5 15.5 16.5 8.5"}),a.jsx("circle",{cx:"12",cy:"12",r:"8.5"})]}),KA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 16V5"}),a.jsx("path",{d:"m7.5 9.5 4.5-4.5 4.5 4.5"}),a.jsx("path",{d:"M5 19h14"})]}),QA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6 18 18"}),a.jsx("path",{d:"M18 6 6 18"})]}),GA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M7 4v10"}),a.jsx("path",{d:"M7 14a4 4 0 0 0 4 4h6"}),a.jsx("path",{d:"M17 6a4 4 0 0 0-4 4H7"}),a.jsx("circle",{cx:"7",cy:"4",r:"2"}),a.jsx("circle",{cx:"17",cy:"6",r:"2"}),a.jsx("circle",{cx:"17",cy:"18",r:"2"})]}),YA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"4",y:"5",width:"16",height:"11",rx:"2"}),a.jsx("path",{d:"M8 19h8"}),a.jsx("path",{d:"M10 16v3"}),a.jsx("path",{d:"M14 16v3"})]}),VA=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.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"})}),XA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M7 4v10"}),a.jsx("path",{d:"M7 14a4 4 0 0 0 4 4h6"}),a.jsx("path",{d:"M7 10a4 4 0 0 1 4-4h6"}),a.jsx("circle",{cx:"7",cy:"4",r:"2"}),a.jsx("circle",{cx:"17",cy:"6",r:"2"}),a.jsx("circle",{cx:"17",cy:"18",r:"2"})]}),Gl=({label:e,icon:t,onClick:i,disabled:r=!1,variant:o="default",pending:u=!1,className:d})=>a.jsx("button",{type:"button",className:`session-git-panel__icon-button is-${o} ${u?"is-pending":""} ${d??""}`.trim(),onClick:i,disabled:r,"aria-label":e,title:e,children:a.jsx("span",{className:"session-git-panel__icon-button-glyph","aria-hidden":"true",children:t})}),kx=e=>{switch(e){case"added":return"A";case"deleted":return"D";case"renamed":return"R";case"untracked":return"U";default:return"M"}},ZA=e=>e.status==="renamed"&&e.previous_path?`该变更仅包含重命名:${e.previous_path} -> ${e.path}`:e.status==="deleted"?"该文件已删除,没有可展示的补丁内容。":e.status==="untracked"?"该文件还没有可展示的补丁内容。":"此变更没有可展示的补丁内容。",JA=(e,t)=>t&&t.diff.trim()?"此变更没有可展示的补丁内容。":e.status==="renamed"&&e.previous_path?`该提交仅包含重命名:${e.previous_path} -> ${e.path}`:e.status==="deleted"?"该文件在这次提交中已删除,没有可展示的补丁内容。":"该文件在这次提交中没有可展示的补丁内容。",Pf=e=>i_[e%i_.length]??i_[0],tc=e=>x5+e*b5,Km=(e,t)=>`${e}\0${t}`,my=e=>Array.isArray(e.parent_oids)?e.parent_oids.filter(Boolean):[],eI=e=>Array.isArray(e.refs)?e.refs.filter(Boolean):[],tI=e=>{var u;const t={};let i=[],r=0;const o=()=>{const d=r;return r+=1,d};for(const d of e){let m=i.findIndex(w=>w.oid===d.oid);m<0&&(i=[...i,{oid:d.oid,colorIndex:o()}],m=i.length-1);const y=i.map(w=>({...w})),g=((u=y[m])==null?void 0:u.colorIndex)??o(),b=[...new Set(my(d))],p=y.map(w=>({...w}));b.length>0?p[m]={oid:b[0],colorIndex:g}:p.splice(m,1);const v=[];if(b.length>0){const w=p.findIndex(N=>N.oid===b[0]);v.push(w>=0?w:m)}b.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()})),v.push(j)}),t[d.oid]={beforeLanes:y,afterLanes:p,laneIndex:m,nodeColorIndex:g,parentLaneIndexes:v},i=p.filter((w,N,j)=>j.findIndex(T=>T.oid===w.oid)===N)}return t},nI=({commit:e,row:t,isLocalHead:i,isRemoteHead:r,isFirstRow:o,maxLaneCount:u})=>{const d=my(e).length,m=Math.max(u,t.beforeLanes.length,t.afterLanes.length,1),y=Math.max(40,x5*2+(m-1)*b5),g=tc(t.laneIndex),b=d>1?4.7:3.9,p=Math.max(0,Ql-b-1.1),v={"--session-git-graph-width":`${Math.max(48,Math.ceil(y*(56/Iu)))}px`};return a.jsx("span",{className:"session-git-history__graph",style:v,children:a.jsxs("svg",{className:`session-git-history__graph-svg ${d>1?"is-merge":""}`,viewBox:`0 0 ${y} ${Iu}`,preserveAspectRatio:"xMinYMid meet","aria-hidden":"true",children:[t.beforeLanes.map((w,N)=>a.jsx("path",{d:`M ${tc(N)} ${o?p:0} L ${tc(N)} ${p}`,stroke:Pf(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?tc(j):tc(N),M=tc(N),P=T===M?`M ${M} ${Ql} L ${M} ${Iu}`:`M ${T} ${Ql} C ${T} 27 ${M} 31 ${M} ${Iu}`;return a.jsx("path",{d:P,stroke:Pf(w.colorIndex),strokeWidth:"2",strokeLinecap:"round",fill:"none"},`after:${w.oid}:${N}`)}),t.parentLaneIndexes.map((w,N)=>{var P;const j=tc(w),T=Pf(((P=t.afterLanes[w])==null?void 0:P.colorIndex)??t.nodeColorIndex),M=j===g?`M ${g} ${Ql} L ${j} ${Iu}`:`M ${g} ${Ql} C ${g} 27 ${j} 31 ${j} ${Iu}`;return a.jsx("path",{d:M,stroke:T,strokeWidth:N>0||d>1?"2.2":"2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",opacity:N>0||d>1?.96:.88},`parent:${e.oid}:${N}`)}),a.jsx("circle",{cx:g,cy:Ql,r:b,fill:"var(--color-surface-panel)",stroke:Pf(t.nodeColorIndex),strokeWidth:d>1?"1.8":"1.55"}),a.jsx("circle",{cx:g,cy:Ql,r:i||r?1.6:1.05,fill:Pf(t.nodeColorIndex)}),i&&r?a.jsx("circle",{cx:g,cy:Ql,r:"6.4",fill:"none",stroke:"color-mix(in oklab, var(--color-accent-primary) 22%, transparent)",strokeWidth:"1",strokeDasharray:"1.5 3"}):null]})})},sI=({workspace:e,history:t,isLoading:i,isHistoryLoading:r,error:o,historyError:u,onRefresh:d,onRefreshHistory:m,onRequestHistory:y,onDiscardFile:g,onDiscardAll:b,onCommitAll:p,onSwitchBranch:v,onPush:w,onLoadWorkspaceFileDiff:N,onLoadHistoryFileDiff:j,pendingAction:T,compact:M=!1})=>{const[P,I]=_.useState("changes"),[k,O]=_.useState({}),[Q,J]=_.useState({}),[F,B]=_.useState({}),[G,Z]=_.useState({}),[ae,he]=_.useState({}),[ne,Ce]=_.useState({}),[R,X]=_.useState({}),[le,ue]=_.useState({}),[ye,D]=_.useState({}),[oe,je]=_.useState(!1),[z,be]=_.useState(null),[De,se]=_.useState(""),[pe,ke]=_.useState(null),Ze=_.useRef(null);_.useEffect(()=>{O(ve=>{if(!(e!=null&&e.files.length))return{};const V=new Set(e.files.map(ce=>ce.path));let q=!1;const de={};for(const[ce,Ae]of Object.entries(ve)){if(!V.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:ve});const te=new Set((e==null?void 0:e.files.map(ve=>ve.path))??[]);J(ve=>{let V=!1;const q={};for(const[de,ce]of Object.entries(ve)){if(!te.has(de)){V=!0;continue}q[de]=ce}return V?q:ve}),B(ve=>{let V=!1;const q={};for(const[de,ce]of Object.entries(ve)){if(!te.has(de)){V=!0;continue}q[de]=ce}return V?q:ve}),Z(ve=>{let V=!1;const q={};for(const[de,ce]of Object.entries(ve)){if(!te.has(de)){V=!0;continue}q[de]=ce}return V?q:ve})},[e==null?void 0:e.files]),_.useEffect(()=>{const te=new Set((t==null?void 0:t.commits.map(V=>V.oid))??[]),ve=new Set((t==null?void 0:t.commits.flatMap(V=>V.files.map(q=>Km(V.oid,q.path))))??[]);he(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!te.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:V}),Ce(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!te.has(ce)){q=!0;continue}if(Ae&&!ve.has(Km(ce,Ae))){q=!0,de[ce]=null;continue}de[ce]=Ae}return q?de:V}),X(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!ve.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:V}),ue(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!ve.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:V}),D(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!ve.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:V})},[t==null?void 0:t.commits]),_.useEffect(()=>{if(!oe)return;const te=ve=>{var V;(V=Ze.current)!=null&&V.contains(ve.target)||je(!1)};return window.addEventListener("pointerdown",te),()=>{window.removeEventListener("pointerdown",te)}},[oe]),_.useEffect(()=>{e&&(z==="commit"&&(T==null?void 0:T.action)!=="commit-all"&&e.files.length===0&&(be(null),se("")),pe&&e.branch===pe&&(ke(null),be(null),se(""),je(!1)))},[z,T==null?void 0:T.action,pe,e]),_.useEffect(()=>{e!=null&&e.branches.length||je(!1)},[e==null?void 0:e.branches]),_.useEffect(()=>{J({}),B({}),Z({})},[e==null?void 0:e.updated_at]);const zt=(e==null?void 0:e.files)??[],Fe=(t==null?void 0:t.commits)??[],kt=zt.length>0,Bt=Fe.length>0,Gt=(T==null?void 0:T.action)==="discard-all",Xt=(T==null?void 0:T.action)==="commit-all",Ft=(T==null?void 0:T.action)==="switch-branch",qe=(T==null?void 0:T.action)==="push",dt=P==="changes",un=z==="switch-branch"&&pe?`提交后切换到 ${pe}`:"提交全部改动",$t=_.useMemo(()=>{if(!e)return null;const te=[];return e.upstream_branch&&te.push(e.upstream_branch),e.ahead_count>0&&te.push(`ahead ${e.ahead_count}`),e.behind_count>0&&te.push(`behind ${e.behind_count}`),te.join(" · ")},[e]),An=_.useMemo(()=>{if(!t)return null;const te=[t.branch];return t.upstream_branch&&te.push(t.upstream_branch),te.join(" · ")},[t]),Nn=_.useMemo(()=>P==="history"?tI(Fe):{},[P,Fe]),Tt=_.useMemo(()=>P!=="history"?1:Math.max(1,...Object.values(Nn).map(te=>Math.max(te.beforeLanes.length,te.afterLanes.length,te.laneIndex+1))),[P,Nn]),lt=(te,ve)=>{Q[te]||F[te]||(B(V=>({...V,[te]:!0})),Z(V=>{const q={...V};return delete q[te],q}),N(te,ve).then(V=>{J(q=>({...q,[te]:V}))}).catch(V=>{Z(q=>({...q,[te]:V instanceof Error?V.message:"无法读取该文件的差异。"}))}).finally(()=>{B(V=>{const q={...V};return delete q[te],q})}))};_.useEffect(()=>{if(!(P!=="changes"||zt.length===0))for(const te of zt)k[te.path]&<(te.path,te.previous_path)},[P,k,zt,N,Q,F]);const Et=()=>{be(null),se(""),ke(null)},rt=()=>{ke(null),be(te=>te==="commit"?(se(""),null):"commit")},st=()=>{const te=De.trim();if(te){if(z==="switch-branch"&&pe){Promise.resolve(v(pe,te)).catch(()=>{});return}p(te)}},Dt=te=>{if(!(!e||te===e.branch||T)){if(je(!1),e.files.length>0){ke(te),be("switch-branch");return}Promise.resolve(v(te)).catch(()=>{})}},an=()=>{if(dt){d();return}m()},re=()=>{I(te=>{const ve=te==="changes"?"history":"changes";return ve==="history"&&y(),ve})},we=(te,ve)=>{const V=Km(te.oid,ve.path),q=ne[te.oid]===ve.path;Ce(de=>({...de,[te.oid]:q?null:ve.path})),!(q||R[V]||le[V])&&(ue(de=>({...de,[V]:!0})),D(de=>{const ce={...de};return delete ce[V],ce}),j(te.oid,ve.path,ve.previous_path).then(de=>{X(ce=>({...ce,[V]:de}))}).catch(de=>{D(ce=>({...ce,[V]:de instanceof Error?de.message:"无法读取该文件的提交差异。"}))}).finally(()=>{ue(de=>{const ce={...de};return delete ce[V],ce})}))},Re=te=>{const ve=new Date(te);return Number.isNaN(ve.getTime())?te:new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(ve)};return a.jsxs("section",{className:`session-git-panel ${M?"is-compact":""}`,children:[a.jsxs("div",{className:"session-git-panel__header",children:[a.jsxs("div",{className:"session-git-panel__heading",ref:Ze,children:[a.jsxs("button",{type:"button",className:"session-git-panel__branch-button",onClick:()=>je(te=>!te),disabled:!e||!!T,"aria-haspopup":"menu","aria-expanded":oe,title:e?`切换分支:${e.branch}`:"分支加载中",children:[a.jsx("span",{className:"session-git-panel__branch-icon","aria-hidden":"true",children:a.jsx(GA,{})}),a.jsx("span",{className:"session-git-panel__branch",children:(e==null?void 0:e.branch)??"加载中"}),a.jsx("span",{className:`session-git-panel__branch-chevron ${oe?"is-open":""}`,"aria-hidden":"true",children:a.jsx(r_,{})})]}),oe&&e?a.jsx("div",{className:"session-git-panel__branch-menu",role:"menu","aria-label":"分支列表",children:e.branches.map(te=>{const ve=te===e.branch,V=(T==null?void 0:T.action)==="switch-branch"&&T.branch===te;return a.jsxs("button",{type:"button",className:`session-git-panel__branch-option ${ve?"is-current":""}`,onClick:()=>Dt(te),disabled:ve||!!T,role:"menuitemradio","aria-checked":ve,title:ve?`${te}(当前)`:`切换到 ${te}`,children:[a.jsx("span",{className:"session-git-panel__branch-option-name",children:te}),ve?a.jsx("span",{className:"session-git-panel__branch-option-meta",children:"当前"}):null,V?a.jsx("span",{className:"session-git-panel__branch-option-meta",children:"切换中"}):null]},te)})}):null]}),a.jsxs("div",{className:"session-git-panel__toolbar",children:[a.jsx(Gl,{label:dt?"切换到提交历史":"返回修改列表",icon:a.jsx(WA,{}),onClick:re,disabled:!!T,variant:dt?"default":"primary",className:dt?void 0:"is-active"}),a.jsx(Gl,{label:dt?i?"正在刷新":"刷新":r?"正在刷新历史":"刷新历史",icon:a.jsx(qA,{}),onClick:an,disabled:dt?i||!!T:r,pending:dt?i:r}),dt&&kt?a.jsxs(a.Fragment,{children:[a.jsx(Gl,{label:Gt?"正在撤回全部修改":"撤回全部修改",icon:a.jsx(wx,{}),onClick:b,disabled:!!T,variant:"danger",pending:Gt}),a.jsx(Gl,{label:Xt?"正在提交全部修改":z==="commit"?"收起提交编辑器":"提交全部修改",icon:a.jsx(Nx,{}),onClick:rt,disabled:!!T,variant:"primary",pending:Xt})]}):null,dt&&!kt?a.jsx(Gl,{label:qe?"正在推送当前分支":"推送当前分支",icon:a.jsx(KA,{}),onClick:w,disabled:!!T,variant:"primary",pending:qe}):null]})]}),dt&&e?a.jsxs("div",{className:"session-git-panel__summary",children:[a.jsx("span",{className:"session-git-panel__summary-text",children:kt?`${zt.length} 个文件待处理`:"当前工作区没有待提交改动"}),$t?a.jsx("span",{className:"session-git-panel__summary-meta",children:$t}):null]}):null,!dt&&t?a.jsxs("div",{className:"session-git-panel__summary",children:[a.jsx("span",{className:"session-git-panel__summary-text",children:Bt?`${Fe.length} 条最近提交`:"当前分支还没有提交历史"}),An?a.jsx("span",{className:"session-git-panel__summary-meta",children:An}):null]}):null,dt&&z&&kt?a.jsxs("div",{className:"session-git-panel__composer",children:[a.jsx("div",{className:"session-git-panel__composer-title",children:un}),a.jsxs("div",{className:"session-git-panel__composer-row",children:[a.jsx("input",{value:De,onChange:te=>se(te.target.value),placeholder:"输入 commit message",className:"session-git-panel__input",disabled:!!T}),a.jsx(Gl,{label:z==="switch-branch"?"提交并切换分支":"确认提交",icon:a.jsx(Nx,{}),onClick:st,disabled:!De.trim()||!!T,variant:"primary",pending:Xt||Ft}),a.jsx(Gl,{label:"取消提交",icon:a.jsx(QA,{}),onClick:Et,disabled:!!T})]})]}):null,dt&&o?a.jsx("div",{className:"session-git-panel__notice is-error",children:o}):null,!dt&&u?a.jsx("div",{className:"session-git-panel__notice is-error",children:u}):null,dt&&i&&!e?a.jsx("div",{className:"session-git-panel__empty",children:"正在读取当前工作区改动…"}):null,!dt&&r&&!t?a.jsx("div",{className:"session-git-panel__empty",children:"正在读取当前分支提交历史…"}):null,dt&&!i&&e&&!kt?a.jsx("div",{className:"session-git-panel__empty",children:"当前分支没有待提交改动。你现在可以直接推送当前分支。"}):null,!dt&&!r&&t&&!Bt?a.jsx("div",{className:"session-git-panel__empty",children:"当前分支还没有提交历史。"}):null,dt&&kt?a.jsx("div",{className:"session-git-panel__list",children:zt.map(te=>{const ve=!!k[te.path],V=(T==null?void 0:T.action)==="discard-file"&&T.path===te.path,q=Q[te.path],de=!!F[te.path],ce=G[te.path]??null;return a.jsxs("article",{className:`session-git-file ${ve?"is-expanded":""}`,children:[a.jsxs("div",{className:"session-git-file__head",children:[a.jsxs("button",{type:"button",className:"session-git-file__toggle",onClick:()=>{const Ae=!ve;O(Ee=>({...Ee,[te.path]:Ae})),Ae&<(te.path,te.previous_path)},"aria-expanded":ve,children:[a.jsxs("span",{className:"session-git-file__main",children:[a.jsx("span",{className:"session-git-file__path",children:te.path}),te.previous_path?a.jsxs("span",{className:"session-git-file__rename",children:["来自 ",te.previous_path]}):null]}),a.jsxs("span",{className:"session-git-file__meta",children:[a.jsx("span",{className:`session-git-file__status is-${te.status}`,children:kx(te.status)}),a.jsxs("span",{className:"session-git-file__counts",children:[a.jsxs("span",{className:"is-add",children:["+",te.additions]}),a.jsxs("span",{className:"is-remove",children:["-",te.deletions]})]}),a.jsx("span",{className:"session-git-file__chevron","aria-hidden":"true",children:a.jsx(r_,{})})]})]}),a.jsx(Gl,{label:V?`正在撤回 ${te.path}`:`撤回 ${te.path}`,icon:a.jsx(wx,{}),onClick:()=>g(te.path),disabled:!!T,variant:"danger",pending:V,className:"session-git-file__action"})]}),ve?a.jsx("div",{className:"session-git-file__detail",children:ce?a.jsx("div",{className:"session-git-panel__notice is-error",children:ce}):de?a.jsx("div",{className:"patch-file-card__empty",children:"正在读取该文件的差异…"}):a.jsx(_.Suspense,{fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),children:a.jsx(jx,{diffText:(q==null?void 0:q.diff)??"",filePath:te.path,emptyMessage:ZA(te)})})}):null]},te.path)})}):null,!dt&&Bt?a.jsx("div",{className:"session-git-history",children:Fe.map((te,ve)=>{const V=!!ae[te.oid],q=my(te),de=ne[te.oid]??null,ce=Nn[te.oid],Ae=(t==null?void 0:t.head_oid)===te.oid,Ee=(t==null?void 0:t.upstream_head_oid)===te.oid,$e=eI(te).filter(Pe=>!Pe||Pe===(t==null?void 0:t.branch)||Pe===(t==null?void 0:t.upstream_branch)||Pe===`HEAD -> ${t==null?void 0:t.branch}`?!1:Pe!=="HEAD");return a.jsxs("article",{className:`session-git-history__item ${V?"is-expanded":""} ${q.length>1?"is-merge":""} ${Ae?"is-local-head":""} ${Ee?"is-remote-head":""}`.trim(),children:[a.jsxs("button",{type:"button",className:"session-git-history__toggle",onClick:()=>he(Pe=>({...Pe,[te.oid]:!Pe[te.oid]})),"aria-expanded":V,children:[ce?a.jsx(nI,{commit:te,row:ce,isLocalHead:Ae,isRemoteHead:Ee,isFirstRow:ve===0,maxLaneCount:Tt}):null,a.jsxs("span",{className:"session-git-history__content",children:[a.jsx("span",{className:"session-git-history__subject",children:te.subject}),a.jsxs("span",{className:"session-git-history__meta",children:[a.jsx("span",{children:te.short_oid}),a.jsx("span",{children:te.author_name}),a.jsx("span",{children:Re(te.committed_at)})]})]}),a.jsxs("span",{className:"session-git-history__refs",children:[Ae?a.jsx("span",{className:"session-git-history__ref is-local",title:"本地当前 HEAD",children:a.jsx(YA,{})}):null,Ee?a.jsx("span",{className:"session-git-history__ref is-remote",title:t!=null&&t.upstream_branch?`云端位置:${t.upstream_branch}`:"云端位置",children:a.jsx(VA,{})}):null,q.length>1?a.jsx("span",{className:"session-git-history__ref is-merge",title:"合并提交",children:a.jsx(XA,{})}):null,$e.slice(0,2).map(Pe=>a.jsx("span",{className:"session-git-history__ref is-label",title:Pe,children:Pe},`${te.oid}:${Pe}`))]}),a.jsx("span",{className:"session-git-history__chevron","aria-hidden":"true",children:a.jsx(r_,{})})]}),V?a.jsx("div",{className:"session-git-history__files",children:a.jsx("div",{className:"session-git-history__files-list",children:te.files.map(Pe=>{const ht=de===Pe.path,Xe=Km(te.oid,Pe.path),tn=R[Xe],Le=!!le[Xe],rn=ye[Xe]??null;return a.jsxs("div",{className:`session-git-history-file-row ${ht?"is-selected":""}`,children:[a.jsxs("button",{type:"button",className:`session-git-history-file ${ht?"is-selected":""}`,onClick:()=>we(te,Pe),"aria-pressed":ht,children:[a.jsx("span",{className:`session-git-file__status is-${Pe.status}`,children:kx(Pe.status)}),a.jsx("span",{className:"session-git-history-file__path",children:Pe.path}),Pe.previous_path?a.jsxs("span",{className:"session-git-history-file__rename",children:["来自 ",Pe.previous_path]}):null,a.jsx("span",{className:"session-git-history-file__meta",children:tn?a.jsxs("span",{className:"session-git-history-file__counts",children:[a.jsxs("span",{className:"is-add",children:["+",tn.additions]}),a.jsxs("span",{className:"is-remove",children:["-",tn.deletions]})]}):Le?a.jsx("span",{className:"session-git-history-file__loading",children:"读取中…"}):a.jsx("span",{className:"session-git-history-file__hint",children:"点击查看"})})]}),ht?a.jsxs("div",{className:"session-git-history__diff is-inline",children:[a.jsxs("div",{className:"session-git-history__diff-header",children:[a.jsx("span",{className:"session-git-history__diff-path",children:Pe.path}),Pe.previous_path?a.jsxs("span",{className:"session-git-history__diff-rename",children:["来自 ",Pe.previous_path]}):null]}),rn?a.jsx("div",{className:"session-git-panel__notice is-error",children:rn}):Le?a.jsx("div",{className:"patch-file-card__empty",children:"正在读取该文件的提交差异…"}):a.jsx(_.Suspense,{fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),children:a.jsx(jx,{diffText:(tn==null?void 0:tn.diff)??"",filePath:Pe.path,emptyMessage:JA(Pe,tn??null)})})]}):null]},`${te.oid}:${Pe.path}`)})})}):null]},te.oid)})}):null]})},Ex={name:"",description:null,command:"",kill_command:null,cwd:null,shell:"auto",node_version:null,port:null},Cx=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m8 6 9 6-9 6z"})}),Tx=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("rect",{x:"6.5",y:"6.5",width:"11",height:"11",rx:"1.8"})}),aI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"m12 3 1.4 4.6L18 9l-4.6 1.4L12 15l-1.4-4.6L6 9l4.6-1.4Z"}),a.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"})]}),iI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"m13.5 6.5 4 4"})]}),rI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M4.5 7h15"}),a.jsx("path",{d:"M9.5 4.5h5"}),a.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"}),a.jsx("path",{d:"M10 10.5v5.2"}),a.jsx("path",{d:"M14 10.5v5.2"})]}),lI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 5v14"}),a.jsx("path",{d:"M5 12h14"})]}),Mx={auto:"自动",powershell:"PowerShell",cmd:"CMD",bash:"Bash"},oI=({commands:e,nodeRuntime:t,error:i,pendingRunCommandId:r,pendingKillCommandId:o,pendingDeleteCommandId:u,isSaving:d,isGenerating:m,isStartingAll:y,isStoppingAll:g,generationReason:b,executionModelLabel:p,onRun:v,onRunAll:w,onRunAllKill:N,onRunKill:j,onSave:T,onDelete:M,onGenerate:P})=>{var Ce;const[I,k]=_.useState("list"),[O,Q]=_.useState(null),[J,F]=_.useState(Ex),B=_.useMemo(()=>e.find(R=>R.id===O)??null,[e,O]),G=_.useMemo(()=>{const R=[...(t==null?void 0:t.versions)??[]];return J.node_version&&!R.includes(J.node_version)&&R.unshift(J.node_version),R},[J.node_version,t==null?void 0:t.versions]),Z=_.useMemo(()=>e.filter(R=>!!R.kill_command).length,[e]),ae=()=>{F(Ex),Q(null),k("edit")},he=R=>{F({name:R.name,description:R.description,command:R.command,kill_command:R.kill_command,cwd:R.cwd,shell:R.shell,node_version:R.node_version,port:R.port}),Q(R.id),k("edit")},ne=()=>{T({commandId:B==null?void 0:B.id,draft:J}),d||(k("list"),Q(null))};return a.jsxs("div",{className:"session-run-panel",children:[a.jsxs("div",{className:"session-run-panel__header",children:[a.jsxs("div",{className:"session-run-panel__header-copy",children:[a.jsxs("div",{className:"session-run-panel__title-row",children:[a.jsx("h2",{className:"session-run-panel__title",children:"项目命令"}),a.jsxs("span",{className:"session-run-panel__count",children:[e.length," 条"]})]}),a.jsxs("div",{className:"session-run-panel__hint",children:["一键生成使用模型:",p]})]}),a.jsxs("div",{className:"session-run-panel__header-actions",children:[a.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:a.jsx(Cx,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-warning","aria-label":g?"正在一键停止项目命令":"一键停止项目命令",title:g?"正在一键停止项目命令":"一键停止项目命令",disabled:Z===0||y||g,onClick:N,children:a.jsx(Tx,{})}),a.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:P,children:a.jsx(aI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":"新增项目命令",title:"新增项目命令",onClick:ae,children:a.jsx(lI,{})})]})]}),i?a.jsx("div",{className:"session-run-panel__notice is-error",children:i}):null,m?a.jsx("div",{className:"session-run-panel__notice is-loading",role:"status","aria-live":"polite",children:"正在分析项目并生成推荐命令…"}):null,b?a.jsx("div",{className:"session-run-panel__hint",children:b}):null,I==="edit"?a.jsxs("div",{className:"session-run-panel__card",children:[a.jsx("h3",{className:"session-run-panel__section-title",children:B?"编辑命令":"新增命令"}),a.jsxs("div",{className:"session-run-panel__form-grid",children:[a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"名称"}),a.jsx("input",{value:J.name,onChange:R=>F(X=>({...X,name:R.target.value})),className:"session-run-panel__input",placeholder:"例如:启动前端"})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"说明"}),a.jsx("input",{value:J.description??"",onChange:R=>F(X=>({...X,description:R.target.value||null})),className:"session-run-panel__input",placeholder:"给自己留一个短说明"})]}),a.jsxs("label",{className:"session-run-panel__field is-full",children:[a.jsx("span",{children:"命令"}),a.jsx("textarea",{value:J.command,onChange:R=>F(X=>({...X,command:R.target.value})),className:"session-run-panel__textarea",placeholder:"pnpm dev",rows:4})]}),a.jsxs("label",{className:"session-run-panel__field is-full",children:[a.jsx("span",{children:"停止命令"}),a.jsx("textarea",{value:J.kill_command??"",onChange:R=>F(X=>({...X,kill_command:R.target.value||null})),className:"session-run-panel__textarea",placeholder:"留空表示不需要单独停止",rows:3})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"工作目录"}),a.jsx("input",{value:J.cwd??"",onChange:R=>F(X=>({...X,cwd:R.target.value||null})),className:"session-run-panel__input",placeholder:"留空表示项目根目录"})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"端口"}),a.jsx("input",{value:J.port??"",onChange:R=>{const X=Number.parseInt(R.target.value,10);F(le=>({...le,port:Number.isFinite(X)&&X>0?X:null}))},className:"session-run-panel__input",placeholder:"例如:5173",inputMode:"numeric"})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"Shell"}),a.jsx("select",{value:J.shell,onChange:R=>F(X=>({...X,shell:R.target.value})),className:"session-run-panel__select",children:Object.entries(Mx).map(([R,X])=>a.jsx("option",{value:R,children:X},R))})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"Node 环境"}),a.jsxs("select",{value:J.node_version??"",onChange:R=>F(X=>({...X,node_version:R.target.value||null})),className:"session-run-panel__select",children:[a.jsx("option",{value:"",children:"默认环境"}),G.map(R=>a.jsxs("option",{value:R,children:["Node ",R,t!=null&&t.versions.includes(R)?"":"(未检测到)"]},R))]})]})]}),a.jsx("div",{className:"session-run-panel__hint",children:t!=null&&t.versions.length?"Node 版本只会临时注入当前命令,不会修改系统全局环境。":((Ce=t==null?void 0:t.error)==null?void 0:Ce.trim())||"未检测到可用的 nvm Node 版本,将按默认环境运行。"}),a.jsxs("div",{className:"session-run-panel__form-actions",children:[a.jsx("button",{type:"button",className:"session-run-panel__ghost-button",onClick:()=>k("list"),children:"取消"}),a.jsx("button",{type:"button",className:"session-run-panel__primary-button",disabled:!J.name.trim()||!J.command.trim()||d,onClick:ne,children:d?"保存中...":B?"保存修改":"保存命令"})]})]}):null,a.jsx("div",{className:"session-run-panel__list",children:e.length>0?e.map(R=>a.jsxs("article",{className:"session-run-panel__command-card",children:[a.jsxs("div",{className:"session-run-panel__command-head",children:[a.jsxs("button",{type:"button",className:"session-run-panel__command-main",onClick:()=>he(R),children:[a.jsxs("div",{className:"session-run-panel__command-heading",children:[a.jsx("span",{className:"session-run-panel__command-name",children:R.name}),R.description?a.jsx("span",{className:"session-run-panel__command-description",children:R.description}):null]}),a.jsx("div",{className:"session-run-panel__command-line",children:R.command})]}),a.jsxs("div",{className:"session-run-panel__command-actions",children:[R.kill_command?a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-warning","aria-label":`执行 ${R.name} 的停止命令`,title:`执行 ${R.name} 的停止命令`,disabled:o===R.id,onClick:()=>j(R.id),children:a.jsx(Tx,{})}):null,a.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":`编辑 ${R.name}`,title:`编辑 ${R.name}`,onClick:()=>he(R),children:a.jsx(iI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-danger","aria-label":`删除 ${R.name}`,title:`删除 ${R.name}`,disabled:u===R.id,onClick:()=>M(R.id),children:a.jsx(rI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-primary","aria-label":`运行 ${R.name}`,title:`运行 ${R.name}`,disabled:r===R.id,onClick:()=>v(R.id),children:a.jsx(Cx,{})})]})]}),a.jsx("div",{className:"session-run-panel__command-footer",children:a.jsxs("div",{className:"session-run-panel__command-meta",children:[a.jsx("span",{className:"session-run-panel__command-pill",children:Mx[R.shell]}),R.node_version?a.jsxs("span",{className:"session-run-panel__command-pill is-node",children:["Node ",R.node_version]}):null,R.port?a.jsxs("span",{className:"session-run-panel__command-pill",children:[":",R.port]}):null,R.kill_command?a.jsx("span",{className:"session-run-panel__command-pill is-kill",children:"可停止"}):null,a.jsx("span",{className:"session-run-panel__command-pill",children:R.cwd?R.cwd:"项目根目录"})]})})]},R.id)):a.jsxs("div",{className:"session-run-panel__empty",children:[a.jsx("div",{className:"session-run-panel__empty-title",children:"还没有项目命令"}),a.jsx("div",{className:"session-run-panel__empty-copy",children:"可以手动新增,或直接点击一键生成。"})]})})]})},Rx={name:"",description:null,url:""},cI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"m12 3 1.4 4.6L18 9l-4.6 1.4L12 15l-1.4-4.6L6 9l4.6-1.4Z"}),a.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"})]}),uI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"8.5"}),a.jsx("path",{d:"M3.8 12h16.4"}),a.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"})]}),dI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"m13.5 6.5 4 4"})]}),fI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M4.5 7h15"}),a.jsx("path",{d:"M9.5 4.5h5"}),a.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"}),a.jsx("path",{d:"M10 10.5v5.2"}),a.jsx("path",{d:"M14 10.5v5.2"})]}),hI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 5v14"}),a.jsx("path",{d:"M5 12h14"})]}),mI=({websites:e,error:t,pendingDeleteWebsiteId:i,isSaving:r,isGenerating:o,generationReason:u,executionModelLabel:d,onOpen:m,onSave:y,onDelete:g,onGenerate:b})=>{const[p,v]=_.useState("list"),[w,N]=_.useState(null),[j,T]=_.useState(Rx),M=_.useMemo(()=>e.find(O=>O.id===w)??null,[w,e]),P=()=>{T(Rx),N(null),v("edit")},I=O=>{T({name:O.name,description:O.description,url:O.url}),N(O.id),v("edit")},k=()=>{y({websiteId:M==null?void 0:M.id,draft:j}),r||(v("list"),N(null))};return a.jsxs("div",{className:"session-run-panel",children:[a.jsxs("div",{className:"session-run-panel__header",children:[a.jsxs("div",{className:"session-run-panel__header-copy",children:[a.jsxs("div",{className:"session-run-panel__title-row",children:[a.jsx("h2",{className:"session-run-panel__title",children:"项目网页"}),a.jsxs("span",{className:"session-run-panel__count",children:[e.length," 条"]})]}),a.jsxs("div",{className:"session-run-panel__hint",children:["一键生成使用模型:",d]})]}),a.jsxs("div",{className:"session-run-panel__header-actions",children:[a.jsx("button",{type:"button",className:`session-run-panel__icon-button ${o?"is-loading":""}`,"aria-label":o?"正在一键生成项目网页":"一键生成项目网页",title:o?"正在一键生成项目网页":"一键生成项目网页","aria-busy":o,disabled:o,onClick:b,children:a.jsx(cI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":"新增项目网页",title:"新增项目网页",onClick:P,children:a.jsx(hI,{})})]})]}),t?a.jsx("div",{className:"session-run-panel__notice is-error",children:t}):null,o?a.jsx("div",{className:"session-run-panel__notice is-loading",role:"status","aria-live":"polite",children:"正在分析项目并生成推荐网页…"}):null,u?a.jsx("div",{className:"session-run-panel__hint",children:u}):null,p==="edit"?a.jsxs("div",{className:"session-run-panel__card",children:[a.jsx("h3",{className:"session-run-panel__section-title",children:M?"编辑网页":"新增网页"}),a.jsxs("div",{className:"session-run-panel__form-grid",children:[a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"名称"}),a.jsx("input",{value:j.name,onChange:O=>T(Q=>({...Q,name:O.target.value})),className:"session-run-panel__input",placeholder:"例如:前端首页"})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"说明"}),a.jsx("input",{value:j.description??"",onChange:O=>T(Q=>({...Q,description:O.target.value||null})),className:"session-run-panel__input",placeholder:"给自己留一个短说明"})]}),a.jsxs("label",{className:"session-run-panel__field is-full",children:[a.jsx("span",{children:"地址"}),a.jsx("input",{value:j.url,onChange:O=>T(Q=>({...Q,url:O.target.value})),className:"session-run-panel__input",placeholder:"http://localhost:5173"})]})]}),a.jsxs("div",{className:"session-run-panel__form-actions",children:[a.jsx("button",{type:"button",className:"session-run-panel__ghost-button",onClick:()=>v("list"),children:"取消"}),a.jsx("button",{type:"button",className:"session-run-panel__primary-button",disabled:!j.name.trim()||!j.url.trim()||r,onClick:k,children:r?"保存中...":M?"保存修改":"保存网页"})]})]}):null,a.jsx("div",{className:"session-run-panel__list",children:e.length>0?e.map(O=>a.jsxs("article",{className:"session-run-panel__command-card",children:[a.jsxs("div",{className:"session-run-panel__command-head",children:[a.jsxs("button",{type:"button",className:"session-run-panel__command-main",onClick:()=>I(O),children:[a.jsxs("div",{className:"session-run-panel__command-heading",children:[a.jsx("span",{className:"session-run-panel__command-name",children:O.name}),O.description?a.jsx("span",{className:"session-run-panel__command-description",children:O.description}):null]}),a.jsx("div",{className:"session-run-panel__command-line",children:O.url})]}),a.jsxs("div",{className:"session-run-panel__command-actions",children:[a.jsx("a",{className:"session-run-panel__icon-button is-primary","aria-label":`打开 ${O.name}`,title:`打开 ${O.name}`,href:O.url,target:"_blank",rel:"noreferrer",onClick:()=>m(O),children:a.jsx(uI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":`编辑 ${O.name}`,title:`编辑 ${O.name}`,onClick:()=>I(O),children:a.jsx(dI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-danger","aria-label":`删除 ${O.name}`,title:`删除 ${O.name}`,disabled:i===O.id,onClick:()=>g(O.id),children:a.jsx(fI,{})})]})]}),a.jsx("div",{className:"session-run-panel__command-footer",children:a.jsx("div",{className:"session-run-panel__command-meta",children:a.jsx("span",{className:"session-run-panel__command-pill",children:"网页"})})})]},O.id)):a.jsxs("div",{className:"session-run-panel__empty",children:[a.jsx("div",{className:"session-run-panel__empty-title",children:"还没有项目网页"}),a.jsx("div",{className:"session-run-panel__empty-copy",children:"可以手动新增,或直接点击一键生成。"})]})})]})},pI=/\u001b\[([0-9;]*)m/g,gI={stdout:"",stderr:"stderr",system:"system"},Ax={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"},c0={fg:null,bg:null,bold:!1,dim:!1,underline:!1},_I=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6 18 18"}),a.jsx("path",{d:"M18 6 6 18"})]}),yI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M8 4H4v4"}),a.jsx("path",{d:"M16 4h4v4"}),a.jsx("path",{d:"M8 20H4v-4"}),a.jsx("path",{d:"M16 20h4v-4"}),a.jsx("path",{d:"M9 9 4 4"}),a.jsx("path",{d:"m15 9 5-5"}),a.jsx("path",{d:"m9 15-5 5"}),a.jsx("path",{d:"m15 15 5 5"})]}),vI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M9 4H4v5"}),a.jsx("path",{d:"M15 4h5v5"}),a.jsx("path",{d:"M9 20H4v-5"}),a.jsx("path",{d:"M15 20h5v-5"}),a.jsx("path",{d:"m4 9 5-5"}),a.jsx("path",{d:"m20 9-5-5"}),a.jsx("path",{d:"m4 15 5 5"}),a.jsx("path",{d:"m20 15-5 5"})]}),bI=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)},Ix=(e,t)=>{const i=[e];return t.bold&&i.push("is-bold"),t.dim&&i.push("is-dim"),t.underline&&i.push("is-underline"),t.fg&&i.push(`is-fg-${t.fg}`),t.bg&&i.push(`is-bg-${t.bg}`),i.join(" ")},xI=(e,t)=>{if(t===0)return{...c0};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 i=Ax[t];if(i)return{...e,fg:i};const r=Ax[t-10];return r&&t>=40?{...e,bg:r}:e},SI=(e,t)=>{const i=[];let r=0,o={...c0};for(const u of e.matchAll(pI)){const d=u.index??0;d>r&&i.push({text:e.slice(r,d),className:Ix(t,o)});const m=(u[1]??"").split(";").map(y=>Number.parseInt(y||"0",10)).filter(y=>Number.isFinite(y));m.length===0?o={...c0}:o=m.reduce(xI,o),r=d+u[0].length}return r<e.length&&i.push({text:e.slice(r),className:Ix(t,o)}),i.length===0&&i.push({text:e,className:t}),i},S5=_.memo(({chunks:e})=>{const t=_.useMemo(()=>e.map(i=>{const r=gI[i.stream],o=["session-terminal-output__segment",`is-${i.stream}`].join(" ");return{cursor:i.cursor,label:r,segments:SI(i.text,o)}}),[e]);return a.jsx(a.Fragment,{children:t.map(i=>a.jsxs("span",{className:"session-terminal-output__chunk",children:[i.label?a.jsx("span",{className:"session-terminal-output__label",children:i.label}):null,i.segments.map((r,o)=>a.jsx("span",{className:r.className,children:r.text},`${i.cursor}:${o}`))]},i.cursor))})});S5.displayName="TerminalOutput";const jI=({terminals:e,activeTerminalId:t,outputs:i,error:r,compact:o=!1,canToggleFullscreen:u=!1,isFullscreen:d=!1,onSelectTerminal:m,onCloseTerminal:y,onToggleFullscreen:g})=>{const b=_.useRef(null),p=e.find(w=>w.id===t)??e[0]??null,v=p?i[p.id]:null;return _.useEffect(()=>{const w=b.current;w&&(w.scrollTop=w.scrollHeight)},[v==null?void 0:v.chunks,p==null?void 0:p.id]),e.length===0?a.jsx("section",{className:`session-terminal-panel ${o?"is-compact":""}`,children:a.jsxs("div",{className:"session-terminal-panel__empty",children:[a.jsx("div",{className:"session-terminal-panel__empty-title",children:"还没有运行中的命令"}),a.jsx("p",{className:"session-terminal-panel__empty-copy",children:"从右上角的运行按钮启动一个项目命令后,这里会实时显示终端输出。"})]})}):a.jsxs("section",{className:`session-terminal-panel ${o?"is-compact":""}`,children:[a.jsxs("div",{className:"session-terminal-panel__tabs",children:[a.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 a.jsxs("div",{className:`session-terminal-panel__tab ${N?"is-active":""}`,children:[a.jsxs("button",{type:"button",className:"session-terminal-panel__tab-button",role:"tab","aria-selected":N,onClick:()=>m(w.id),children:[a.jsx("span",{className:`session-terminal-panel__tab-dot is-${w.status}`,"aria-hidden":"true"}),a.jsx("span",{className:"session-terminal-panel__tab-title",children:w.title}),a.jsx("span",{className:"session-terminal-panel__tab-time",children:bI(w.last_output_at??w.updated_at)})]}),a.jsx("button",{type:"button",className:"session-terminal-panel__tab-close","aria-label":`关闭 ${w.title}`,onClick:j=>{j.stopPropagation(),y(w.id)},children:a.jsx(_I,{})})]},w.id)})}),u&&g?a.jsx("button",{type:"button",className:"session-terminal-panel__fullscreen-button",onClick:g,"aria-label":d?"退出终端全屏":"终端全屏",title:d?"退出终端全屏":"终端全屏",children:d?a.jsx(vI,{}):a.jsx(yI,{})}):null]}),p?a.jsxs(a.Fragment,{children:[r?a.jsx("div",{className:"session-terminal-panel__notice is-error",children:r}):null,v!=null&&v.error?a.jsx("div",{className:"session-terminal-panel__notice is-error",children:v.error}):null,v!=null&&v.truncated?a.jsx("div",{className:"session-terminal-panel__notice",children:"终端输出过长,已自动显示服务端仍保留的最近内容。"}):null,a.jsx("div",{ref:b,className:"session-terminal-panel__output-wrap",children:a.jsx("pre",{className:"session-terminal-output",children:v&&v.chunks.length>0?a.jsx(S5,{chunks:v.chunks}):v!=null&&v.isLoading?a.jsx("span",{className:"session-terminal-output__placeholder",children:"正在读取终端输出..."}):a.jsx("span",{className:"session-terminal-output__placeholder",children:"这个终端暂时还没有输出。"})})})]}):null]})},wI=_.memo(function({conversationMainRef:t,conversationScrollRef:i,isDesktopSidebar:r,sidebarShift:o,isSidebarDragging:u,title:d,titleActions:m,topbarActions:y,onOpenSidebar:g,threadContent:b,connectionStatus:p,sessionRecoveryStatus:v,isConnectionDetailOpen:w,onToggleConnectionDetail:N,showThinkingStatus:j}){const T={transform:`translateX(${o}px)`,transition:u?"none":void 0};return a.jsxs("div",{ref:t,className:`conversation-main ${r?"has-desktop-sidebar":""}`,style:T,children:[a.jsxs("div",{className:"conversation-topbar",children:[r?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:g,"aria-label":"打开侧边栏",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]}),a.jsx("div",{className:"conversation-topbar__meta",children:a.jsxs("div",{className:"conversation-topbar__title-row",children:[a.jsx("h1",{children:d}),m]})}),y]}),a.jsx("div",{ref:i,className:"conversation-scroll",children:a.jsxs("div",{className:"conversation-thread",children:[b,p.state!=="connected"?a.jsx("section",{className:"conversation-entry is-connection-status",children:a.jsxs("div",{className:"connection-status",children:[a.jsx("button",{type:"button",className:"connection-status__pill",onClick:M=>{M.stopPropagation(),N()},children:a.jsx("span",{children:p.state==="failed"?"连接异常":`Reconnecting... ${p.attempt}/${p.maxAttempts}`})}),w&&p.error?a.jsx("div",{className:"connection-status__tooltip",role:"tooltip",children:p.error}):null]})}):null,p.state==="connected"&&v.state!=="idle"?a.jsx("section",{className:"conversation-entry is-connection-status",children:a.jsxs("div",{className:"connection-status",children:[a.jsx("div",{className:"connection-status__pill",children:a.jsx("span",{children:v.state==="recovering"?"恢复会话中...":"会话恢复失败"})}),v.state==="failed"&&v.error?a.jsx("div",{className:"connection-status__tooltip",role:"tooltip",children:v.error}):null]})}):null,j?a.jsx("section",{className:"conversation-entry is-thinking-status",children:a.jsx("div",{className:"thinking-status-pill",children:a.jsx("span",{children:"正在思考"})})}):null]})})]})}),NI="panda:last-session-id",kI=.4,EI=104,CI=1800*1e3,TI=15e3,MI=120*1e3,Dx=1100,j5="panda:desktop-sidebar-width",Wf="panda:desktop-sidebar-width-version",Kf="2026-03-24-narrow",RI=300,w5=232,Du=w5,AI=460,Ox=72,l_=72,Lx=120,u0=54,Px=300,II=640,DI=4200,o_="local-model-panel:",OI=160,LI={id:"",agent_id:"",name:"",display_name:null,pinned:!1,path:""},PI={id:"",agent_id:"",project_id:"",provider:"codex",archived:!1,title:"",last_event_at:"",pinned:!1,run_state:"idle",run_state_changed_at:null,subagent:null},UI={...PI,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}},zI=(e,t)=>{if(!t)return e??null;if(e!=null&&e.sessions.some(o=>o.id===t.sessionId))return e;const i=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)??[]],r=[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:i,project_stats:i.map(o=>{const u=r.filter(m=>m.project_id===o.id),d=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:(d==null?void 0:d.archived_session_count)??0,hidden_history_count:(d==null?void 0:d.hidden_history_count)??0}}),sessions:r,active_session_id:t.sessionId}},BI={session_id:"",generated_at:"",view:"tail",anchor_entry_id:null,has_earlier_entries:!1,entries:[]},$I=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"6",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"12",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"18",cy:"12",r:"1",fill:"currentColor",stroke:"none"})]}),Ux=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"9",y:"9",width:"10",height:"10",rx:"2"}),a.jsx("path",{d:"M7 15H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v1"})]}),zx=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m7.5 12.5 3 3 6-7"})}),HI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6l12 12"}),a.jsx("path",{d:"M18 6 6 18"})]}),FI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"m9 18-6-6 6-6"}),a.jsx("path",{d:"m15 6 6 6-6 6"})]}),qI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"6",cy:"6",r:"2.2"}),a.jsx("circle",{cx:"18",cy:"6",r:"2.2"}),a.jsx("circle",{cx:"12",cy:"18",r:"2.2"}),a.jsx("path",{d:"M8 7.6 10.5 16"}),a.jsx("path",{d:"M16 7.6 13.5 16"}),a.jsx("path",{d:"M8.2 6h7.6"})]}),WI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2.5"}),a.jsx("path",{d:"m7.5 9 2.8 3-2.8 3"}),a.jsx("path",{d:"M12.8 15H16.5"})]}),KI=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.1",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M7 5.5 18 12 7 18.5Z"})}),QI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"8.4"}),a.jsx("path",{d:"M3.8 12h16.4"}),a.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"})]}),GI=()=>a.jsx(dT,{"aria-hidden":"true",strokeWidth:1.9}),Bx=()=>a.jsx(yT,{"aria-hidden":"true",strokeWidth:1.9}),nc=12,YI=_.memo(function({isActive:t,label:i,path:r,tokenKey:o,onToggle:u}){const d=_.useRef(null),m=_.useRef(null),[y,g]=_.useState(void 0);return _.useEffect(()=>{if(!t){g(void 0);return}const b=()=>{const v=d.current,w=m.current;if(!v||!w)return;const N=v.getBoundingClientRect(),j=typeof window<"u"?window.innerWidth:document.documentElement.clientWidth,T=typeof window<"u"?window.innerHeight:document.documentElement.clientHeight,M=Math.max(220,Math.min(520,j-nc*2));w.style.width=`${M}px`,w.style.maxWidth=`${M}px`;const P=w.getBoundingClientRect(),I=Math.min(Math.max(N.left,nc),Math.max(nc,j-nc-M)),k=N.top-P.height-8,O=k>=nc?k:Math.min(N.bottom+8,T-nc-P.height);g({left:`${I}px`,top:`${Math.max(nc,O)}px`,width:`${M}px`,maxWidth:`${M}px`})},p=window.requestAnimationFrame(b);return window.addEventListener("resize",b),document.addEventListener("scroll",b,!0),()=>{window.cancelAnimationFrame(p),window.removeEventListener("resize",b),document.removeEventListener("scroll",b,!0)}},[t,r]),a.jsxs("span",{ref:d,className:`conversation-inline-link ${t?"is-active":""}`,children:[a.jsx("span",{role:"button",tabIndex:0,className:"conversation-inline-link__button",onClick:b=>{b.stopPropagation(),u()},onKeyDown:b=>{b.key!=="Enter"&&b.key!==" "||(b.preventDefault(),b.stopPropagation(),u())},children:i}),t&&typeof document<"u"?ra.createPortal(a.jsx("span",{ref:m,className:"conversation-inline-link__tooltip",role:"tooltip",style:y,children:r}),document.body):null]},o)}),$x=(e,t)=>{const i=new Map;for(const r of e)i.set(r.cursor,r);for(const r of t)i.set(r.cursor,r);return[...i.values()].sort((r,o)=>r.cursor-o.cursor)},VI=800,py=(e,t,i)=>{const r=e.get(t);if(r!==void 0)return e.delete(t),e.set(t,r),r;const o=i();if(e.set(t,o),e.size>VI){const u=e.keys().next().value;u&&e.delete(u)}return o},XI=new Map,ZI=new Map,JI=new Map,d0=()=>cl(()=>import("./session-diff-preview-kDHdPa6S.js"),__vite__mapDeps([0,1])),eD=_.lazy(async()=>({default:(await d0()).SessionDiffPreview})),f0=(e,t,i)=>a.jsx(_.Suspense,{fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在载入差异详情…"}),children:a.jsx(eD,{diffText:e,filePath:t,emptyMessage:i})}),tD=e=>a.jsx("span",{className:"conversation-inline-link",children:a.jsx("span",{className:"conversation-inline-link__button",title:e,children:N5(e)})}),nD=/<proposed_plan>([\s\S]*?)<\/proposed_plan>/g,sD=e=>py(XI,e,()=>f5(e)),_h=e=>e.replace(/\\/g,"/"),aD=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),iD=e=>{var r,o,u,d,m,y;const t=/^\s*(\d+)\.\s+(.+)$/.exec(e);if(t){const g=/^\[( |x|X)\]\s+(.+)$/.exec(t[2]??"");return{ordered:!0,ordinal:Number.parseInt(t[1]??"",10),checked:g?((r=g[1])==null?void 0:r.toLowerCase())==="x":null,text:((o=g==null?void 0:g[2])==null?void 0:o.trim())??((u=t[2])==null?void 0:u.trim())??""}}const i=/^\s*[-*+]\s+(.+)$/.exec(e);if(i){const g=/^\[( |x|X)\]\s+(.+)$/.exec(i[1]??"");return{ordered:!1,ordinal:null,checked:g?((d=g[1])==null?void 0:d.toLowerCase())==="x":null,text:((m=g==null?void 0:g[2])==null?void 0:m.trim())??((y=i[1])==null?void 0:y.trim())??""}}return null},Hx=e=>/^\s{0,3}>\s?(.*)$/.exec(e),rD=e=>/^\s{0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(e),h0=e=>{const i=e.trim().replace(/^\|/,"").replace(/\|$/,""),r=[];let o="";for(let u=0;u<i.length;u+=1){const d=i[u];if(d==="\\"&&i[u+1]==="|"){o+="|",u+=1;continue}if(d==="|"){r.push(o.trim()),o="";continue}o+=d}return r.push(o.trim()),r},lD=e=>{if(!e.includes("|"))return null;const t=h0(e);if(t.length===0)return null;const i=[];for(const r of t){const o=r.replace(/\s/g,"");if(!/^:?-{3,}:?$/.test(o))return null;const u=o.startsWith(":"),d=o.endsWith(":");i.push(u&&d?"center":d?"right":u?"left":null)}return i},c_=(e,t,i)=>Array.from({length:t},(r,o)=>e[o]??i),Fx=e=>["conversation-markdown-table__cell",e?`is-align-${e}`:""].filter(Boolean).join(" "),oD=e=>`h${Math.min(Math.max(e,1),6)}`,cD=e=>["conversation-markdown-list",e.some(t=>t.checked!==null)?"has-task-items":""].filter(Boolean).join(" "),uD=e=>{var i;const t=/^\/([A-Za-z][A-Za-z0-9._-]*)/.exec(e.trim());return((i=t==null?void 0:t[1])==null?void 0:i.toLowerCase())??""},dD=e=>e.kind==="system"&&e.title==="context_compacted",qx=e=>e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e)),fD=e=>py(ZI,e,()=>{var m;const t=e.replace(/\r\n/g,`
|
|
201
|
+
`),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:${(D==null?void 0:D.id)??Gr}`,command_name:pe||"unknown",command_text:se,title:`/${pe||"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}oe.mutate({projectId:ye?null:D.id,chatOnly:ye,input:se,title:TA(se,F),attachments:F,model:k,titleGenerationModel:O3(),reasoningEffort:Q,serviceTier:G?"fast":void 0,planMode:ae,yoloMode:ne})}};return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`conversation-main conversation-main--new-thread ${u?"has-desktop-sidebar":""}`,style:be,children:[a.jsxs("div",{className:"conversation-topbar",children:[u?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:y,"aria-label":"打开侧边栏",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]}),a.jsx("div",{className:"conversation-topbar__meta",children:a.jsx("div",{className:"conversation-topbar__title-row",children:a.jsx("h1",{"aria-label":"未命名会话",children:" "})})})]}),a.jsx("div",{className:"conversation-scroll conversation-scroll--empty",children:a.jsx("div",{className:"conversation-thread conversation-thread--empty",children:z?a.jsx(fA,{agentId:e.id,projects:t,title:"选择目录",subtitle:"",onProjectCreated:se=>{p.setQueriesData({queryKey:hs},pe=>wC(pe,se)),j(se.id),g(se.id),X("composer")}}):a.jsx("section",{className:"new-thread-hero",children:a.jsxs("div",{className:"new-thread-hero__stack",children:[a.jsx(mA,{}),a.jsxs("label",{className:"new-thread-hero__selector",children:[a.jsx("span",{className:"new-thread-hero__selector-label",children:"在线程中发起会话"}),a.jsxs("select",{className:"new-thread-hero__select",value:N??"",onChange:se=>{const pe=se.target.value||null;j(pe),g(pe)},children:[t.map(se=>a.jsx("option",{value:se.id,children:se.display_name??se.name},se.id)),a.jsx("option",{value:Gr,children:"仅聊天"})]})]}),je?a.jsx("div",{className:"new-thread-hero__path",children:je}):ye?a.jsx("div",{className:"new-thread-hero__hint",children:"当前会话不会绑定项目,只保留聊天上下文。"}):a.jsx("div",{className:"new-thread-hero__hint",children:"选择一个线程后,直接输入第一条消息即可开始。"}),u?null:a.jsx("button",{type:"button",className:"new-thread-hero__directory-trigger",onClick:()=>X("directory-picker"),children:"新增目录线程"})]})})})})]}),z?null:a.jsx(p5,{isDesktopSidebar:u,sidebarShift:d,isSidebarDragging:m,composerError:T,onDismissComposerError:()=>M(null),interactionRequests:[],pendingInteractionRequestId:null,onRespondInteraction:()=>{},parentSession:null,backgroundAgentSessions:[],isBackgroundAgentsOpen:!1,planSnapshot:null,onToggleBackgroundAgents:()=>{},onOpenSession:()=>{},getBackgroundAgentStatusLabel:()=>"",getBackgroundAgentAccent:()=>"var(--color-accent-primary)",formatBackgroundAgentsLabel:se=>`${se} background agents`,hasBackgroundAgentStrip:!1,commandPanel:P,isCommandPanelPending:!1,onDismissCommandPanel:()=>I(null),onCommandPanelOptionSelect:se=>{O(se),I(pe=>pe&&{...pe,status:"completed",body:`新会话默认模型已切换为 ${Fp(se,ue)}。现在可以继续输入真正的首条消息。`,updated_at:new Date().toISOString(),input_type:"none",options:[]})},onCommandPanelTextSubmit:()=>{},projectId:(D==null?void 0:D.id)??null,agentId:e.id,draft:v,pendingAttachments:F,canSendInput:!!D||ye,inputPlaceholder:ye?"发起仅聊天会话…":D?`向 ${D.display_name??D.name} 发起第一条任务…`:"先选择线程,再输入第一条任务",readOnlyPlaceholder:"先选择线程,再输入第一条任务",onDraftChange:w,onUploadFiles:se=>{const pe=[...se];pe.length!==0&&(M(null),Promise.all(pe.map(ke=>cy(ke))).then(ke=>{B(Ze=>[...Ze,...ke])}).catch(ke=>{M(ke instanceof Error?ke.message:"无法读取附件")}))},onRemoveAttachment:se=>{B(pe=>pe.filter(ke=>ke.id!==se))},onSubmit:De,showStopIcon:!1,isSendPending:oe.isPending,onInterrupt:()=>{},isFastModeEnabled:G,isPlanModeEnabled:ae,isYoloModeEnabled:ne,onToggleFastMode:()=>Z(se=>!se),onTogglePlanMode:()=>he(se=>!se),onToggleYoloMode:()=>Ce(se=>!se),showModeBadges:!0,selectedModel:k,modelOptions:ue,selectedReasoning:Q,onSelectModel:O,onSelectReasoning:se=>J(se),contextUsage:null,isContextUsageOpen:!1,onToggleContextUsage:()=>{},usedPercent:0,remainingPercent:0,usedTokensLabel:"0",totalTokensLabel:"0",showJumpToBottom:!1,onJumpToBottom:()=>{}})]})},g5="panda:session-timeline-snapshots",op=1,AA=1440*60*1e3,_5=12,IA=e=>{if(typeof window>"u")return null;try{const t=window.localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}},DA=(e,t)=>{if(!(typeof window>"u"))try{window.localStorage.setItem(e,JSON.stringify(t))}catch{}},y5=()=>{const e=IA(g5);if(!e||e.version!==op||!Array.isArray(e.items))return{version:op,items:[]};const t=Date.now(),i=e.items.filter(r=>!!(r&&typeof r.sessionId=="string"&&typeof r.storedAt=="number"&&r.snapshot&&typeof r.snapshot=="object")).filter(r=>t-r.storedAt<=AA).sort((r,o)=>o.storedAt-r.storedAt).slice(0,_5);return{version:op,items:i}},OA=e=>{const i=y5().items.find(r=>r.sessionId===e);return i?i.snapshot:null},LA=e=>{if(!e||e.view!=="full_compact")return;const t=Date.now(),i=y5(),r=[{sessionId:e.session_id,storedAt:t,snapshot:e},...i.items.filter(o=>o.sessionId!==e.session_id)].slice(0,_5);DA(g5,{version:op,items:r})},PA=e=>{var t,i,r;return["session-tool-detail",((t=e==null?void 0:e.scope)==null?void 0:t.sessionId)??"",(i=e==null?void 0:e.scope)!=null&&i.sessionId?"":((r=e==null?void 0:e.scope)==null?void 0:r.agentId)??"",(e==null?void 0:e.sessionId)??"",(e==null?void 0:e.entryId)??""]};function UA(e){return cs({queryKey:PA(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 cn(e.scope)).client.getSessionToolCallDetail(e.sessionId,e.entryId),refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1})}const v5=e=>{var t,i,r;return["workspace-session-detail",((t=e==null?void 0:e.scope)==null?void 0:t.sessionId)??"",(i=e==null?void 0:e.scope)!=null&&i.sessionId?"":((r=e==null?void 0:e.scope)==null?void 0:r.agentId)??"",(e==null?void 0:e.sessionId)??""]};function zA(e){return cs({queryKey:v5(e),enabled:!!((e==null?void 0:e.enabled)??!0)&&!!(e!=null&&e.sessionId),queryFn:async()=>e!=null&&e.sessionId?(await cn(e.scope)).client.getWorkspaceSessionDetail(e.sessionId):null,refetchInterval:!1,refetchOnMount:!1,refetchOnWindowFocus:!1,retry:1})}const BA={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},$A=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:e.provider,mode:"managed",health:"active",branch:"",worktree:"",summary:"",latest_assistant_message:null,context_usage:null,capability:BA}),HA=(e,t)=>e?!t||t.id!==e.id?$A(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,provider:e.provider}:t??null,Sx=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},FA=(e,t,i)=>{if(!e||e.session.id!==t)return e;const{last_event_at:r,...o}=i;let u={...e.session,...o};if(typeof r=="string"&&r.trim()){const d=new Date(r).getTime(),m=new Date(e.session.last_event_at).getTime();Number.isFinite(d)&&(!Number.isFinite(m)||d>m)&&(u={...u,last_event_at:r})}return{...e,session:u}},jx=_.lazy(async()=>({default:(await cl(()=>import("./session-diff-preview-5oB0rJ5W.js"),__vite__mapDeps([0,1]))).SessionDiffPreview})),i_=["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)"],b5=14,x5=10,Ql=24,Iu=48,r_=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m9 6 6 6-6 6"})}),qA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M20 11a8 8 0 1 0 2.2 5.5"}),a.jsx("path",{d:"M20 4v7h-7"})]}),WA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M3 12a9 9 0 1 0 2.64-6.36"}),a.jsx("path",{d:"M3 4v5h5"}),a.jsx("path",{d:"M12 7v5l3 2"})]}),wx=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M9 14 4 9l5-5"}),a.jsx("path",{d:"M4 9h8a8 8 0 1 1 0 16h-1"})]}),Nx=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M7.5 12.5 10.5 15.5 16.5 8.5"}),a.jsx("circle",{cx:"12",cy:"12",r:"8.5"})]}),KA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 16V5"}),a.jsx("path",{d:"m7.5 9.5 4.5-4.5 4.5 4.5"}),a.jsx("path",{d:"M5 19h14"})]}),QA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6 18 18"}),a.jsx("path",{d:"M18 6 6 18"})]}),GA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M7 4v10"}),a.jsx("path",{d:"M7 14a4 4 0 0 0 4 4h6"}),a.jsx("path",{d:"M17 6a4 4 0 0 0-4 4H7"}),a.jsx("circle",{cx:"7",cy:"4",r:"2"}),a.jsx("circle",{cx:"17",cy:"6",r:"2"}),a.jsx("circle",{cx:"17",cy:"18",r:"2"})]}),YA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"4",y:"5",width:"16",height:"11",rx:"2"}),a.jsx("path",{d:"M8 19h8"}),a.jsx("path",{d:"M10 16v3"}),a.jsx("path",{d:"M14 16v3"})]}),VA=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.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"})}),XA=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M7 4v10"}),a.jsx("path",{d:"M7 14a4 4 0 0 0 4 4h6"}),a.jsx("path",{d:"M7 10a4 4 0 0 1 4-4h6"}),a.jsx("circle",{cx:"7",cy:"4",r:"2"}),a.jsx("circle",{cx:"17",cy:"6",r:"2"}),a.jsx("circle",{cx:"17",cy:"18",r:"2"})]}),Gl=({label:e,icon:t,onClick:i,disabled:r=!1,variant:o="default",pending:u=!1,className:d})=>a.jsx("button",{type:"button",className:`session-git-panel__icon-button is-${o} ${u?"is-pending":""} ${d??""}`.trim(),onClick:i,disabled:r,"aria-label":e,title:e,children:a.jsx("span",{className:"session-git-panel__icon-button-glyph","aria-hidden":"true",children:t})}),kx=e=>{switch(e){case"added":return"A";case"deleted":return"D";case"renamed":return"R";case"untracked":return"U";default:return"M"}},ZA=e=>e.status==="renamed"&&e.previous_path?`该变更仅包含重命名:${e.previous_path} -> ${e.path}`:e.status==="deleted"?"该文件已删除,没有可展示的补丁内容。":e.status==="untracked"?"该文件还没有可展示的补丁内容。":"此变更没有可展示的补丁内容。",JA=(e,t)=>t&&t.diff.trim()?"此变更没有可展示的补丁内容。":e.status==="renamed"&&e.previous_path?`该提交仅包含重命名:${e.previous_path} -> ${e.path}`:e.status==="deleted"?"该文件在这次提交中已删除,没有可展示的补丁内容。":"该文件在这次提交中没有可展示的补丁内容。",Pf=e=>i_[e%i_.length]??i_[0],tc=e=>x5+e*b5,Km=(e,t)=>`${e}\0${t}`,my=e=>Array.isArray(e.parent_oids)?e.parent_oids.filter(Boolean):[],eI=e=>Array.isArray(e.refs)?e.refs.filter(Boolean):[],tI=e=>{var u;const t={};let i=[],r=0;const o=()=>{const d=r;return r+=1,d};for(const d of e){let m=i.findIndex(w=>w.oid===d.oid);m<0&&(i=[...i,{oid:d.oid,colorIndex:o()}],m=i.length-1);const y=i.map(w=>({...w})),g=((u=y[m])==null?void 0:u.colorIndex)??o(),b=[...new Set(my(d))],p=y.map(w=>({...w}));b.length>0?p[m]={oid:b[0],colorIndex:g}:p.splice(m,1);const v=[];if(b.length>0){const w=p.findIndex(N=>N.oid===b[0]);v.push(w>=0?w:m)}b.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()})),v.push(j)}),t[d.oid]={beforeLanes:y,afterLanes:p,laneIndex:m,nodeColorIndex:g,parentLaneIndexes:v},i=p.filter((w,N,j)=>j.findIndex(T=>T.oid===w.oid)===N)}return t},nI=({commit:e,row:t,isLocalHead:i,isRemoteHead:r,isFirstRow:o,maxLaneCount:u})=>{const d=my(e).length,m=Math.max(u,t.beforeLanes.length,t.afterLanes.length,1),y=Math.max(40,x5*2+(m-1)*b5),g=tc(t.laneIndex),b=d>1?4.7:3.9,p=Math.max(0,Ql-b-1.1),v={"--session-git-graph-width":`${Math.max(48,Math.ceil(y*(56/Iu)))}px`};return a.jsx("span",{className:"session-git-history__graph",style:v,children:a.jsxs("svg",{className:`session-git-history__graph-svg ${d>1?"is-merge":""}`,viewBox:`0 0 ${y} ${Iu}`,preserveAspectRatio:"xMinYMid meet","aria-hidden":"true",children:[t.beforeLanes.map((w,N)=>a.jsx("path",{d:`M ${tc(N)} ${o?p:0} L ${tc(N)} ${p}`,stroke:Pf(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?tc(j):tc(N),M=tc(N),P=T===M?`M ${M} ${Ql} L ${M} ${Iu}`:`M ${T} ${Ql} C ${T} 27 ${M} 31 ${M} ${Iu}`;return a.jsx("path",{d:P,stroke:Pf(w.colorIndex),strokeWidth:"2",strokeLinecap:"round",fill:"none"},`after:${w.oid}:${N}`)}),t.parentLaneIndexes.map((w,N)=>{var P;const j=tc(w),T=Pf(((P=t.afterLanes[w])==null?void 0:P.colorIndex)??t.nodeColorIndex),M=j===g?`M ${g} ${Ql} L ${j} ${Iu}`:`M ${g} ${Ql} C ${g} 27 ${j} 31 ${j} ${Iu}`;return a.jsx("path",{d:M,stroke:T,strokeWidth:N>0||d>1?"2.2":"2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",opacity:N>0||d>1?.96:.88},`parent:${e.oid}:${N}`)}),a.jsx("circle",{cx:g,cy:Ql,r:b,fill:"var(--color-surface-panel)",stroke:Pf(t.nodeColorIndex),strokeWidth:d>1?"1.8":"1.55"}),a.jsx("circle",{cx:g,cy:Ql,r:i||r?1.6:1.05,fill:Pf(t.nodeColorIndex)}),i&&r?a.jsx("circle",{cx:g,cy:Ql,r:"6.4",fill:"none",stroke:"color-mix(in oklab, var(--color-accent-primary) 22%, transparent)",strokeWidth:"1",strokeDasharray:"1.5 3"}):null]})})},sI=({workspace:e,history:t,isLoading:i,isHistoryLoading:r,error:o,historyError:u,onRefresh:d,onRefreshHistory:m,onRequestHistory:y,onDiscardFile:g,onDiscardAll:b,onCommitAll:p,onSwitchBranch:v,onPush:w,onLoadWorkspaceFileDiff:N,onLoadHistoryFileDiff:j,pendingAction:T,compact:M=!1})=>{const[P,I]=_.useState("changes"),[k,O]=_.useState({}),[Q,J]=_.useState({}),[F,B]=_.useState({}),[G,Z]=_.useState({}),[ae,he]=_.useState({}),[ne,Ce]=_.useState({}),[R,X]=_.useState({}),[le,ue]=_.useState({}),[ye,D]=_.useState({}),[oe,je]=_.useState(!1),[z,be]=_.useState(null),[De,se]=_.useState(""),[pe,ke]=_.useState(null),Ze=_.useRef(null);_.useEffect(()=>{O(ve=>{if(!(e!=null&&e.files.length))return{};const V=new Set(e.files.map(ce=>ce.path));let q=!1;const de={};for(const[ce,Ae]of Object.entries(ve)){if(!V.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:ve});const te=new Set((e==null?void 0:e.files.map(ve=>ve.path))??[]);J(ve=>{let V=!1;const q={};for(const[de,ce]of Object.entries(ve)){if(!te.has(de)){V=!0;continue}q[de]=ce}return V?q:ve}),B(ve=>{let V=!1;const q={};for(const[de,ce]of Object.entries(ve)){if(!te.has(de)){V=!0;continue}q[de]=ce}return V?q:ve}),Z(ve=>{let V=!1;const q={};for(const[de,ce]of Object.entries(ve)){if(!te.has(de)){V=!0;continue}q[de]=ce}return V?q:ve})},[e==null?void 0:e.files]),_.useEffect(()=>{const te=new Set((t==null?void 0:t.commits.map(V=>V.oid))??[]),ve=new Set((t==null?void 0:t.commits.flatMap(V=>V.files.map(q=>Km(V.oid,q.path))))??[]);he(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!te.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:V}),Ce(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!te.has(ce)){q=!0;continue}if(Ae&&!ve.has(Km(ce,Ae))){q=!0,de[ce]=null;continue}de[ce]=Ae}return q?de:V}),X(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!ve.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:V}),ue(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!ve.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:V}),D(V=>{let q=!1;const de={};for(const[ce,Ae]of Object.entries(V)){if(!ve.has(ce)){q=!0;continue}de[ce]=Ae}return q?de:V})},[t==null?void 0:t.commits]),_.useEffect(()=>{if(!oe)return;const te=ve=>{var V;(V=Ze.current)!=null&&V.contains(ve.target)||je(!1)};return window.addEventListener("pointerdown",te),()=>{window.removeEventListener("pointerdown",te)}},[oe]),_.useEffect(()=>{e&&(z==="commit"&&(T==null?void 0:T.action)!=="commit-all"&&e.files.length===0&&(be(null),se("")),pe&&e.branch===pe&&(ke(null),be(null),se(""),je(!1)))},[z,T==null?void 0:T.action,pe,e]),_.useEffect(()=>{e!=null&&e.branches.length||je(!1)},[e==null?void 0:e.branches]),_.useEffect(()=>{J({}),B({}),Z({})},[e==null?void 0:e.updated_at]);const zt=(e==null?void 0:e.files)??[],Fe=(t==null?void 0:t.commits)??[],kt=zt.length>0,Bt=Fe.length>0,Gt=(T==null?void 0:T.action)==="discard-all",Xt=(T==null?void 0:T.action)==="commit-all",Ft=(T==null?void 0:T.action)==="switch-branch",qe=(T==null?void 0:T.action)==="push",dt=P==="changes",un=z==="switch-branch"&&pe?`提交后切换到 ${pe}`:"提交全部改动",$t=_.useMemo(()=>{if(!e)return null;const te=[];return e.upstream_branch&&te.push(e.upstream_branch),e.ahead_count>0&&te.push(`ahead ${e.ahead_count}`),e.behind_count>0&&te.push(`behind ${e.behind_count}`),te.join(" · ")},[e]),An=_.useMemo(()=>{if(!t)return null;const te=[t.branch];return t.upstream_branch&&te.push(t.upstream_branch),te.join(" · ")},[t]),Nn=_.useMemo(()=>P==="history"?tI(Fe):{},[P,Fe]),Tt=_.useMemo(()=>P!=="history"?1:Math.max(1,...Object.values(Nn).map(te=>Math.max(te.beforeLanes.length,te.afterLanes.length,te.laneIndex+1))),[P,Nn]),lt=(te,ve)=>{Q[te]||F[te]||(B(V=>({...V,[te]:!0})),Z(V=>{const q={...V};return delete q[te],q}),N(te,ve).then(V=>{J(q=>({...q,[te]:V}))}).catch(V=>{Z(q=>({...q,[te]:V instanceof Error?V.message:"无法读取该文件的差异。"}))}).finally(()=>{B(V=>{const q={...V};return delete q[te],q})}))};_.useEffect(()=>{if(!(P!=="changes"||zt.length===0))for(const te of zt)k[te.path]&<(te.path,te.previous_path)},[P,k,zt,N,Q,F]);const Et=()=>{be(null),se(""),ke(null)},rt=()=>{ke(null),be(te=>te==="commit"?(se(""),null):"commit")},st=()=>{const te=De.trim();if(te){if(z==="switch-branch"&&pe){Promise.resolve(v(pe,te)).catch(()=>{});return}p(te)}},Dt=te=>{if(!(!e||te===e.branch||T)){if(je(!1),e.files.length>0){ke(te),be("switch-branch");return}Promise.resolve(v(te)).catch(()=>{})}},an=()=>{if(dt){d();return}m()},re=()=>{I(te=>{const ve=te==="changes"?"history":"changes";return ve==="history"&&y(),ve})},we=(te,ve)=>{const V=Km(te.oid,ve.path),q=ne[te.oid]===ve.path;Ce(de=>({...de,[te.oid]:q?null:ve.path})),!(q||R[V]||le[V])&&(ue(de=>({...de,[V]:!0})),D(de=>{const ce={...de};return delete ce[V],ce}),j(te.oid,ve.path,ve.previous_path).then(de=>{X(ce=>({...ce,[V]:de}))}).catch(de=>{D(ce=>({...ce,[V]:de instanceof Error?de.message:"无法读取该文件的提交差异。"}))}).finally(()=>{ue(de=>{const ce={...de};return delete ce[V],ce})}))},Re=te=>{const ve=new Date(te);return Number.isNaN(ve.getTime())?te:new Intl.DateTimeFormat("zh-CN",{month:"numeric",day:"numeric",hour:"2-digit",minute:"2-digit"}).format(ve)};return a.jsxs("section",{className:`session-git-panel ${M?"is-compact":""}`,children:[a.jsxs("div",{className:"session-git-panel__header",children:[a.jsxs("div",{className:"session-git-panel__heading",ref:Ze,children:[a.jsxs("button",{type:"button",className:"session-git-panel__branch-button",onClick:()=>je(te=>!te),disabled:!e||!!T,"aria-haspopup":"menu","aria-expanded":oe,title:e?`切换分支:${e.branch}`:"分支加载中",children:[a.jsx("span",{className:"session-git-panel__branch-icon","aria-hidden":"true",children:a.jsx(GA,{})}),a.jsx("span",{className:"session-git-panel__branch",children:(e==null?void 0:e.branch)??"加载中"}),a.jsx("span",{className:`session-git-panel__branch-chevron ${oe?"is-open":""}`,"aria-hidden":"true",children:a.jsx(r_,{})})]}),oe&&e?a.jsx("div",{className:"session-git-panel__branch-menu",role:"menu","aria-label":"分支列表",children:e.branches.map(te=>{const ve=te===e.branch,V=(T==null?void 0:T.action)==="switch-branch"&&T.branch===te;return a.jsxs("button",{type:"button",className:`session-git-panel__branch-option ${ve?"is-current":""}`,onClick:()=>Dt(te),disabled:ve||!!T,role:"menuitemradio","aria-checked":ve,title:ve?`${te}(当前)`:`切换到 ${te}`,children:[a.jsx("span",{className:"session-git-panel__branch-option-name",children:te}),ve?a.jsx("span",{className:"session-git-panel__branch-option-meta",children:"当前"}):null,V?a.jsx("span",{className:"session-git-panel__branch-option-meta",children:"切换中"}):null]},te)})}):null]}),a.jsxs("div",{className:"session-git-panel__toolbar",children:[a.jsx(Gl,{label:dt?"切换到提交历史":"返回修改列表",icon:a.jsx(WA,{}),onClick:re,disabled:!!T,variant:dt?"default":"primary",className:dt?void 0:"is-active"}),a.jsx(Gl,{label:dt?i?"正在刷新":"刷新":r?"正在刷新历史":"刷新历史",icon:a.jsx(qA,{}),onClick:an,disabled:dt?i||!!T:r,pending:dt?i:r}),dt&&kt?a.jsxs(a.Fragment,{children:[a.jsx(Gl,{label:Gt?"正在撤回全部修改":"撤回全部修改",icon:a.jsx(wx,{}),onClick:b,disabled:!!T,variant:"danger",pending:Gt}),a.jsx(Gl,{label:Xt?"正在提交全部修改":z==="commit"?"收起提交编辑器":"提交全部修改",icon:a.jsx(Nx,{}),onClick:rt,disabled:!!T,variant:"primary",pending:Xt})]}):null,dt&&!kt?a.jsx(Gl,{label:qe?"正在推送当前分支":"推送当前分支",icon:a.jsx(KA,{}),onClick:w,disabled:!!T,variant:"primary",pending:qe}):null]})]}),dt&&e?a.jsxs("div",{className:"session-git-panel__summary",children:[a.jsx("span",{className:"session-git-panel__summary-text",children:kt?`${zt.length} 个文件待处理`:"当前工作区没有待提交改动"}),$t?a.jsx("span",{className:"session-git-panel__summary-meta",children:$t}):null]}):null,!dt&&t?a.jsxs("div",{className:"session-git-panel__summary",children:[a.jsx("span",{className:"session-git-panel__summary-text",children:Bt?`${Fe.length} 条最近提交`:"当前分支还没有提交历史"}),An?a.jsx("span",{className:"session-git-panel__summary-meta",children:An}):null]}):null,dt&&z&&kt?a.jsxs("div",{className:"session-git-panel__composer",children:[a.jsx("div",{className:"session-git-panel__composer-title",children:un}),a.jsxs("div",{className:"session-git-panel__composer-row",children:[a.jsx("input",{value:De,onChange:te=>se(te.target.value),placeholder:"输入 commit message",className:"session-git-panel__input",disabled:!!T}),a.jsx(Gl,{label:z==="switch-branch"?"提交并切换分支":"确认提交",icon:a.jsx(Nx,{}),onClick:st,disabled:!De.trim()||!!T,variant:"primary",pending:Xt||Ft}),a.jsx(Gl,{label:"取消提交",icon:a.jsx(QA,{}),onClick:Et,disabled:!!T})]})]}):null,dt&&o?a.jsx("div",{className:"session-git-panel__notice is-error",children:o}):null,!dt&&u?a.jsx("div",{className:"session-git-panel__notice is-error",children:u}):null,dt&&i&&!e?a.jsx("div",{className:"session-git-panel__empty",children:"正在读取当前工作区改动…"}):null,!dt&&r&&!t?a.jsx("div",{className:"session-git-panel__empty",children:"正在读取当前分支提交历史…"}):null,dt&&!i&&e&&!kt?a.jsx("div",{className:"session-git-panel__empty",children:"当前分支没有待提交改动。你现在可以直接推送当前分支。"}):null,!dt&&!r&&t&&!Bt?a.jsx("div",{className:"session-git-panel__empty",children:"当前分支还没有提交历史。"}):null,dt&&kt?a.jsx("div",{className:"session-git-panel__list",children:zt.map(te=>{const ve=!!k[te.path],V=(T==null?void 0:T.action)==="discard-file"&&T.path===te.path,q=Q[te.path],de=!!F[te.path],ce=G[te.path]??null;return a.jsxs("article",{className:`session-git-file ${ve?"is-expanded":""}`,children:[a.jsxs("div",{className:"session-git-file__head",children:[a.jsxs("button",{type:"button",className:"session-git-file__toggle",onClick:()=>{const Ae=!ve;O(Ee=>({...Ee,[te.path]:Ae})),Ae&<(te.path,te.previous_path)},"aria-expanded":ve,children:[a.jsxs("span",{className:"session-git-file__main",children:[a.jsx("span",{className:"session-git-file__path",children:te.path}),te.previous_path?a.jsxs("span",{className:"session-git-file__rename",children:["来自 ",te.previous_path]}):null]}),a.jsxs("span",{className:"session-git-file__meta",children:[a.jsx("span",{className:`session-git-file__status is-${te.status}`,children:kx(te.status)}),a.jsxs("span",{className:"session-git-file__counts",children:[a.jsxs("span",{className:"is-add",children:["+",te.additions]}),a.jsxs("span",{className:"is-remove",children:["-",te.deletions]})]}),a.jsx("span",{className:"session-git-file__chevron","aria-hidden":"true",children:a.jsx(r_,{})})]})]}),a.jsx(Gl,{label:V?`正在撤回 ${te.path}`:`撤回 ${te.path}`,icon:a.jsx(wx,{}),onClick:()=>g(te.path),disabled:!!T,variant:"danger",pending:V,className:"session-git-file__action"})]}),ve?a.jsx("div",{className:"session-git-file__detail",children:ce?a.jsx("div",{className:"session-git-panel__notice is-error",children:ce}):de?a.jsx("div",{className:"patch-file-card__empty",children:"正在读取该文件的差异…"}):a.jsx(_.Suspense,{fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),children:a.jsx(jx,{diffText:(q==null?void 0:q.diff)??"",filePath:te.path,emptyMessage:ZA(te)})})}):null]},te.path)})}):null,!dt&&Bt?a.jsx("div",{className:"session-git-history",children:Fe.map((te,ve)=>{const V=!!ae[te.oid],q=my(te),de=ne[te.oid]??null,ce=Nn[te.oid],Ae=(t==null?void 0:t.head_oid)===te.oid,Ee=(t==null?void 0:t.upstream_head_oid)===te.oid,$e=eI(te).filter(Pe=>!Pe||Pe===(t==null?void 0:t.branch)||Pe===(t==null?void 0:t.upstream_branch)||Pe===`HEAD -> ${t==null?void 0:t.branch}`?!1:Pe!=="HEAD");return a.jsxs("article",{className:`session-git-history__item ${V?"is-expanded":""} ${q.length>1?"is-merge":""} ${Ae?"is-local-head":""} ${Ee?"is-remote-head":""}`.trim(),children:[a.jsxs("button",{type:"button",className:"session-git-history__toggle",onClick:()=>he(Pe=>({...Pe,[te.oid]:!Pe[te.oid]})),"aria-expanded":V,children:[ce?a.jsx(nI,{commit:te,row:ce,isLocalHead:Ae,isRemoteHead:Ee,isFirstRow:ve===0,maxLaneCount:Tt}):null,a.jsxs("span",{className:"session-git-history__content",children:[a.jsx("span",{className:"session-git-history__subject",children:te.subject}),a.jsxs("span",{className:"session-git-history__meta",children:[a.jsx("span",{children:te.short_oid}),a.jsx("span",{children:te.author_name}),a.jsx("span",{children:Re(te.committed_at)})]})]}),a.jsxs("span",{className:"session-git-history__refs",children:[Ae?a.jsx("span",{className:"session-git-history__ref is-local",title:"本地当前 HEAD",children:a.jsx(YA,{})}):null,Ee?a.jsx("span",{className:"session-git-history__ref is-remote",title:t!=null&&t.upstream_branch?`云端位置:${t.upstream_branch}`:"云端位置",children:a.jsx(VA,{})}):null,q.length>1?a.jsx("span",{className:"session-git-history__ref is-merge",title:"合并提交",children:a.jsx(XA,{})}):null,$e.slice(0,2).map(Pe=>a.jsx("span",{className:"session-git-history__ref is-label",title:Pe,children:Pe},`${te.oid}:${Pe}`))]}),a.jsx("span",{className:"session-git-history__chevron","aria-hidden":"true",children:a.jsx(r_,{})})]}),V?a.jsx("div",{className:"session-git-history__files",children:a.jsx("div",{className:"session-git-history__files-list",children:te.files.map(Pe=>{const ht=de===Pe.path,Xe=Km(te.oid,Pe.path),tn=R[Xe],Le=!!le[Xe],rn=ye[Xe]??null;return a.jsxs("div",{className:`session-git-history-file-row ${ht?"is-selected":""}`,children:[a.jsxs("button",{type:"button",className:`session-git-history-file ${ht?"is-selected":""}`,onClick:()=>we(te,Pe),"aria-pressed":ht,children:[a.jsx("span",{className:`session-git-file__status is-${Pe.status}`,children:kx(Pe.status)}),a.jsx("span",{className:"session-git-history-file__path",children:Pe.path}),Pe.previous_path?a.jsxs("span",{className:"session-git-history-file__rename",children:["来自 ",Pe.previous_path]}):null,a.jsx("span",{className:"session-git-history-file__meta",children:tn?a.jsxs("span",{className:"session-git-history-file__counts",children:[a.jsxs("span",{className:"is-add",children:["+",tn.additions]}),a.jsxs("span",{className:"is-remove",children:["-",tn.deletions]})]}):Le?a.jsx("span",{className:"session-git-history-file__loading",children:"读取中…"}):a.jsx("span",{className:"session-git-history-file__hint",children:"点击查看"})})]}),ht?a.jsxs("div",{className:"session-git-history__diff is-inline",children:[a.jsxs("div",{className:"session-git-history__diff-header",children:[a.jsx("span",{className:"session-git-history__diff-path",children:Pe.path}),Pe.previous_path?a.jsxs("span",{className:"session-git-history__diff-rename",children:["来自 ",Pe.previous_path]}):null]}),rn?a.jsx("div",{className:"session-git-panel__notice is-error",children:rn}):Le?a.jsx("div",{className:"patch-file-card__empty",children:"正在读取该文件的提交差异…"}):a.jsx(_.Suspense,{fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),children:a.jsx(jx,{diffText:(tn==null?void 0:tn.diff)??"",filePath:Pe.path,emptyMessage:JA(Pe,tn??null)})})]}):null]},`${te.oid}:${Pe.path}`)})})}):null]},te.oid)})}):null]})},Ex={name:"",description:null,command:"",kill_command:null,cwd:null,shell:"auto",node_version:null,port:null},Cx=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m8 6 9 6-9 6z"})}),Tx=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("rect",{x:"6.5",y:"6.5",width:"11",height:"11",rx:"1.8"})}),aI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"m12 3 1.4 4.6L18 9l-4.6 1.4L12 15l-1.4-4.6L6 9l4.6-1.4Z"}),a.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"})]}),iI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"m13.5 6.5 4 4"})]}),rI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M4.5 7h15"}),a.jsx("path",{d:"M9.5 4.5h5"}),a.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"}),a.jsx("path",{d:"M10 10.5v5.2"}),a.jsx("path",{d:"M14 10.5v5.2"})]}),lI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 5v14"}),a.jsx("path",{d:"M5 12h14"})]}),Mx={auto:"自动",powershell:"PowerShell",cmd:"CMD",bash:"Bash"},oI=({commands:e,nodeRuntime:t,error:i,pendingRunCommandId:r,pendingKillCommandId:o,pendingDeleteCommandId:u,isSaving:d,isGenerating:m,isStartingAll:y,isStoppingAll:g,generationReason:b,executionModelLabel:p,onRun:v,onRunAll:w,onRunAllKill:N,onRunKill:j,onSave:T,onDelete:M,onGenerate:P})=>{var Ce;const[I,k]=_.useState("list"),[O,Q]=_.useState(null),[J,F]=_.useState(Ex),B=_.useMemo(()=>e.find(R=>R.id===O)??null,[e,O]),G=_.useMemo(()=>{const R=[...(t==null?void 0:t.versions)??[]];return J.node_version&&!R.includes(J.node_version)&&R.unshift(J.node_version),R},[J.node_version,t==null?void 0:t.versions]),Z=_.useMemo(()=>e.filter(R=>!!R.kill_command).length,[e]),ae=()=>{F(Ex),Q(null),k("edit")},he=R=>{F({name:R.name,description:R.description,command:R.command,kill_command:R.kill_command,cwd:R.cwd,shell:R.shell,node_version:R.node_version,port:R.port}),Q(R.id),k("edit")},ne=()=>{T({commandId:B==null?void 0:B.id,draft:J}),d||(k("list"),Q(null))};return a.jsxs("div",{className:"session-run-panel",children:[a.jsxs("div",{className:"session-run-panel__header",children:[a.jsxs("div",{className:"session-run-panel__header-copy",children:[a.jsxs("div",{className:"session-run-panel__title-row",children:[a.jsx("h2",{className:"session-run-panel__title",children:"项目命令"}),a.jsxs("span",{className:"session-run-panel__count",children:[e.length," 条"]})]}),a.jsxs("div",{className:"session-run-panel__hint",children:["一键生成使用模型:",p]})]}),a.jsxs("div",{className:"session-run-panel__header-actions",children:[a.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:a.jsx(Cx,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-warning","aria-label":g?"正在一键停止项目命令":"一键停止项目命令",title:g?"正在一键停止项目命令":"一键停止项目命令",disabled:Z===0||y||g,onClick:N,children:a.jsx(Tx,{})}),a.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:P,children:a.jsx(aI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":"新增项目命令",title:"新增项目命令",onClick:ae,children:a.jsx(lI,{})})]})]}),i?a.jsx("div",{className:"session-run-panel__notice is-error",children:i}):null,m?a.jsx("div",{className:"session-run-panel__notice is-loading",role:"status","aria-live":"polite",children:"正在分析项目并生成推荐命令…"}):null,b?a.jsx("div",{className:"session-run-panel__hint",children:b}):null,I==="edit"?a.jsxs("div",{className:"session-run-panel__card",children:[a.jsx("h3",{className:"session-run-panel__section-title",children:B?"编辑命令":"新增命令"}),a.jsxs("div",{className:"session-run-panel__form-grid",children:[a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"名称"}),a.jsx("input",{value:J.name,onChange:R=>F(X=>({...X,name:R.target.value})),className:"session-run-panel__input",placeholder:"例如:启动前端"})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"说明"}),a.jsx("input",{value:J.description??"",onChange:R=>F(X=>({...X,description:R.target.value||null})),className:"session-run-panel__input",placeholder:"给自己留一个短说明"})]}),a.jsxs("label",{className:"session-run-panel__field is-full",children:[a.jsx("span",{children:"命令"}),a.jsx("textarea",{value:J.command,onChange:R=>F(X=>({...X,command:R.target.value})),className:"session-run-panel__textarea",placeholder:"pnpm dev",rows:4})]}),a.jsxs("label",{className:"session-run-panel__field is-full",children:[a.jsx("span",{children:"停止命令"}),a.jsx("textarea",{value:J.kill_command??"",onChange:R=>F(X=>({...X,kill_command:R.target.value||null})),className:"session-run-panel__textarea",placeholder:"留空表示不需要单独停止",rows:3})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"工作目录"}),a.jsx("input",{value:J.cwd??"",onChange:R=>F(X=>({...X,cwd:R.target.value||null})),className:"session-run-panel__input",placeholder:"留空表示项目根目录"})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"端口"}),a.jsx("input",{value:J.port??"",onChange:R=>{const X=Number.parseInt(R.target.value,10);F(le=>({...le,port:Number.isFinite(X)&&X>0?X:null}))},className:"session-run-panel__input",placeholder:"例如:5173",inputMode:"numeric"})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"Shell"}),a.jsx("select",{value:J.shell,onChange:R=>F(X=>({...X,shell:R.target.value})),className:"session-run-panel__select",children:Object.entries(Mx).map(([R,X])=>a.jsx("option",{value:R,children:X},R))})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"Node 环境"}),a.jsxs("select",{value:J.node_version??"",onChange:R=>F(X=>({...X,node_version:R.target.value||null})),className:"session-run-panel__select",children:[a.jsx("option",{value:"",children:"默认环境"}),G.map(R=>a.jsxs("option",{value:R,children:["Node ",R,t!=null&&t.versions.includes(R)?"":"(未检测到)"]},R))]})]})]}),a.jsx("div",{className:"session-run-panel__hint",children:t!=null&&t.versions.length?"Node 版本只会临时注入当前命令,不会修改系统全局环境。":((Ce=t==null?void 0:t.error)==null?void 0:Ce.trim())||"未检测到可用的 nvm Node 版本,将按默认环境运行。"}),a.jsxs("div",{className:"session-run-panel__form-actions",children:[a.jsx("button",{type:"button",className:"session-run-panel__ghost-button",onClick:()=>k("list"),children:"取消"}),a.jsx("button",{type:"button",className:"session-run-panel__primary-button",disabled:!J.name.trim()||!J.command.trim()||d,onClick:ne,children:d?"保存中...":B?"保存修改":"保存命令"})]})]}):null,a.jsx("div",{className:"session-run-panel__list",children:e.length>0?e.map(R=>a.jsxs("article",{className:"session-run-panel__command-card",children:[a.jsxs("div",{className:"session-run-panel__command-head",children:[a.jsxs("button",{type:"button",className:"session-run-panel__command-main",onClick:()=>he(R),children:[a.jsxs("div",{className:"session-run-panel__command-heading",children:[a.jsx("span",{className:"session-run-panel__command-name",children:R.name}),R.description?a.jsx("span",{className:"session-run-panel__command-description",children:R.description}):null]}),a.jsx("div",{className:"session-run-panel__command-line",children:R.command})]}),a.jsxs("div",{className:"session-run-panel__command-actions",children:[R.kill_command?a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-warning","aria-label":`执行 ${R.name} 的停止命令`,title:`执行 ${R.name} 的停止命令`,disabled:o===R.id,onClick:()=>j(R.id),children:a.jsx(Tx,{})}):null,a.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":`编辑 ${R.name}`,title:`编辑 ${R.name}`,onClick:()=>he(R),children:a.jsx(iI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-danger","aria-label":`删除 ${R.name}`,title:`删除 ${R.name}`,disabled:u===R.id,onClick:()=>M(R.id),children:a.jsx(rI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-primary","aria-label":`运行 ${R.name}`,title:`运行 ${R.name}`,disabled:r===R.id,onClick:()=>v(R.id),children:a.jsx(Cx,{})})]})]}),a.jsx("div",{className:"session-run-panel__command-footer",children:a.jsxs("div",{className:"session-run-panel__command-meta",children:[a.jsx("span",{className:"session-run-panel__command-pill",children:Mx[R.shell]}),R.node_version?a.jsxs("span",{className:"session-run-panel__command-pill is-node",children:["Node ",R.node_version]}):null,R.port?a.jsxs("span",{className:"session-run-panel__command-pill",children:[":",R.port]}):null,R.kill_command?a.jsx("span",{className:"session-run-panel__command-pill is-kill",children:"可停止"}):null,a.jsx("span",{className:"session-run-panel__command-pill",children:R.cwd?R.cwd:"项目根目录"})]})})]},R.id)):a.jsxs("div",{className:"session-run-panel__empty",children:[a.jsx("div",{className:"session-run-panel__empty-title",children:"还没有项目命令"}),a.jsx("div",{className:"session-run-panel__empty-copy",children:"可以手动新增,或直接点击一键生成。"})]})})]})},Rx={name:"",description:null,url:""},cI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"m12 3 1.4 4.6L18 9l-4.6 1.4L12 15l-1.4-4.6L6 9l4.6-1.4Z"}),a.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"})]}),uI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"8.5"}),a.jsx("path",{d:"M3.8 12h16.4"}),a.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"})]}),dI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.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"}),a.jsx("path",{d:"m13.5 6.5 4 4"})]}),fI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M4.5 7h15"}),a.jsx("path",{d:"M9.5 4.5h5"}),a.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"}),a.jsx("path",{d:"M10 10.5v5.2"}),a.jsx("path",{d:"M14 10.5v5.2"})]}),hI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M12 5v14"}),a.jsx("path",{d:"M5 12h14"})]}),mI=({websites:e,error:t,pendingDeleteWebsiteId:i,isSaving:r,isGenerating:o,generationReason:u,executionModelLabel:d,onOpen:m,onSave:y,onDelete:g,onGenerate:b})=>{const[p,v]=_.useState("list"),[w,N]=_.useState(null),[j,T]=_.useState(Rx),M=_.useMemo(()=>e.find(O=>O.id===w)??null,[w,e]),P=()=>{T(Rx),N(null),v("edit")},I=O=>{T({name:O.name,description:O.description,url:O.url}),N(O.id),v("edit")},k=()=>{y({websiteId:M==null?void 0:M.id,draft:j}),r||(v("list"),N(null))};return a.jsxs("div",{className:"session-run-panel",children:[a.jsxs("div",{className:"session-run-panel__header",children:[a.jsxs("div",{className:"session-run-panel__header-copy",children:[a.jsxs("div",{className:"session-run-panel__title-row",children:[a.jsx("h2",{className:"session-run-panel__title",children:"项目网页"}),a.jsxs("span",{className:"session-run-panel__count",children:[e.length," 条"]})]}),a.jsxs("div",{className:"session-run-panel__hint",children:["一键生成使用模型:",d]})]}),a.jsxs("div",{className:"session-run-panel__header-actions",children:[a.jsx("button",{type:"button",className:`session-run-panel__icon-button ${o?"is-loading":""}`,"aria-label":o?"正在一键生成项目网页":"一键生成项目网页",title:o?"正在一键生成项目网页":"一键生成项目网页","aria-busy":o,disabled:o,onClick:b,children:a.jsx(cI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":"新增项目网页",title:"新增项目网页",onClick:P,children:a.jsx(hI,{})})]})]}),t?a.jsx("div",{className:"session-run-panel__notice is-error",children:t}):null,o?a.jsx("div",{className:"session-run-panel__notice is-loading",role:"status","aria-live":"polite",children:"正在分析项目并生成推荐网页…"}):null,u?a.jsx("div",{className:"session-run-panel__hint",children:u}):null,p==="edit"?a.jsxs("div",{className:"session-run-panel__card",children:[a.jsx("h3",{className:"session-run-panel__section-title",children:M?"编辑网页":"新增网页"}),a.jsxs("div",{className:"session-run-panel__form-grid",children:[a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"名称"}),a.jsx("input",{value:j.name,onChange:O=>T(Q=>({...Q,name:O.target.value})),className:"session-run-panel__input",placeholder:"例如:前端首页"})]}),a.jsxs("label",{className:"session-run-panel__field",children:[a.jsx("span",{children:"说明"}),a.jsx("input",{value:j.description??"",onChange:O=>T(Q=>({...Q,description:O.target.value||null})),className:"session-run-panel__input",placeholder:"给自己留一个短说明"})]}),a.jsxs("label",{className:"session-run-panel__field is-full",children:[a.jsx("span",{children:"地址"}),a.jsx("input",{value:j.url,onChange:O=>T(Q=>({...Q,url:O.target.value})),className:"session-run-panel__input",placeholder:"http://localhost:5173"})]})]}),a.jsxs("div",{className:"session-run-panel__form-actions",children:[a.jsx("button",{type:"button",className:"session-run-panel__ghost-button",onClick:()=>v("list"),children:"取消"}),a.jsx("button",{type:"button",className:"session-run-panel__primary-button",disabled:!j.name.trim()||!j.url.trim()||r,onClick:k,children:r?"保存中...":M?"保存修改":"保存网页"})]})]}):null,a.jsx("div",{className:"session-run-panel__list",children:e.length>0?e.map(O=>a.jsxs("article",{className:"session-run-panel__command-card",children:[a.jsxs("div",{className:"session-run-panel__command-head",children:[a.jsxs("button",{type:"button",className:"session-run-panel__command-main",onClick:()=>I(O),children:[a.jsxs("div",{className:"session-run-panel__command-heading",children:[a.jsx("span",{className:"session-run-panel__command-name",children:O.name}),O.description?a.jsx("span",{className:"session-run-panel__command-description",children:O.description}):null]}),a.jsx("div",{className:"session-run-panel__command-line",children:O.url})]}),a.jsxs("div",{className:"session-run-panel__command-actions",children:[a.jsx("a",{className:"session-run-panel__icon-button is-primary","aria-label":`打开 ${O.name}`,title:`打开 ${O.name}`,href:O.url,target:"_blank",rel:"noreferrer",onClick:()=>m(O),children:a.jsx(uI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button","aria-label":`编辑 ${O.name}`,title:`编辑 ${O.name}`,onClick:()=>I(O),children:a.jsx(dI,{})}),a.jsx("button",{type:"button",className:"session-run-panel__icon-button is-danger","aria-label":`删除 ${O.name}`,title:`删除 ${O.name}`,disabled:i===O.id,onClick:()=>g(O.id),children:a.jsx(fI,{})})]})]}),a.jsx("div",{className:"session-run-panel__command-footer",children:a.jsx("div",{className:"session-run-panel__command-meta",children:a.jsx("span",{className:"session-run-panel__command-pill",children:"网页"})})})]},O.id)):a.jsxs("div",{className:"session-run-panel__empty",children:[a.jsx("div",{className:"session-run-panel__empty-title",children:"还没有项目网页"}),a.jsx("div",{className:"session-run-panel__empty-copy",children:"可以手动新增,或直接点击一键生成。"})]})})]})},pI=/\u001b\[([0-9;]*)m/g,gI={stdout:"",stderr:"stderr",system:"system"},Ax={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"},c0={fg:null,bg:null,bold:!1,dim:!1,underline:!1},_I=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6 18 18"}),a.jsx("path",{d:"M18 6 6 18"})]}),yI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M8 4H4v4"}),a.jsx("path",{d:"M16 4h4v4"}),a.jsx("path",{d:"M8 20H4v-4"}),a.jsx("path",{d:"M16 20h4v-4"}),a.jsx("path",{d:"M9 9 4 4"}),a.jsx("path",{d:"m15 9 5-5"}),a.jsx("path",{d:"m9 15-5 5"}),a.jsx("path",{d:"m15 15 5 5"})]}),vI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M9 4H4v5"}),a.jsx("path",{d:"M15 4h5v5"}),a.jsx("path",{d:"M9 20H4v-5"}),a.jsx("path",{d:"M15 20h5v-5"}),a.jsx("path",{d:"m4 9 5-5"}),a.jsx("path",{d:"m20 9-5-5"}),a.jsx("path",{d:"m4 15 5 5"}),a.jsx("path",{d:"m20 15-5 5"})]}),bI=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)},Ix=(e,t)=>{const i=[e];return t.bold&&i.push("is-bold"),t.dim&&i.push("is-dim"),t.underline&&i.push("is-underline"),t.fg&&i.push(`is-fg-${t.fg}`),t.bg&&i.push(`is-bg-${t.bg}`),i.join(" ")},xI=(e,t)=>{if(t===0)return{...c0};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 i=Ax[t];if(i)return{...e,fg:i};const r=Ax[t-10];return r&&t>=40?{...e,bg:r}:e},SI=(e,t)=>{const i=[];let r=0,o={...c0};for(const u of e.matchAll(pI)){const d=u.index??0;d>r&&i.push({text:e.slice(r,d),className:Ix(t,o)});const m=(u[1]??"").split(";").map(y=>Number.parseInt(y||"0",10)).filter(y=>Number.isFinite(y));m.length===0?o={...c0}:o=m.reduce(xI,o),r=d+u[0].length}return r<e.length&&i.push({text:e.slice(r),className:Ix(t,o)}),i.length===0&&i.push({text:e,className:t}),i},S5=_.memo(({chunks:e})=>{const t=_.useMemo(()=>e.map(i=>{const r=gI[i.stream],o=["session-terminal-output__segment",`is-${i.stream}`].join(" ");return{cursor:i.cursor,label:r,segments:SI(i.text,o)}}),[e]);return a.jsx(a.Fragment,{children:t.map(i=>a.jsxs("span",{className:"session-terminal-output__chunk",children:[i.label?a.jsx("span",{className:"session-terminal-output__label",children:i.label}):null,i.segments.map((r,o)=>a.jsx("span",{className:r.className,children:r.text},`${i.cursor}:${o}`))]},i.cursor))})});S5.displayName="TerminalOutput";const jI=({terminals:e,activeTerminalId:t,outputs:i,error:r,compact:o=!1,canToggleFullscreen:u=!1,isFullscreen:d=!1,onSelectTerminal:m,onCloseTerminal:y,onToggleFullscreen:g})=>{const b=_.useRef(null),p=e.find(w=>w.id===t)??e[0]??null,v=p?i[p.id]:null;return _.useEffect(()=>{const w=b.current;w&&(w.scrollTop=w.scrollHeight)},[v==null?void 0:v.chunks,p==null?void 0:p.id]),e.length===0?a.jsx("section",{className:`session-terminal-panel ${o?"is-compact":""}`,children:a.jsxs("div",{className:"session-terminal-panel__empty",children:[a.jsx("div",{className:"session-terminal-panel__empty-title",children:"还没有运行中的命令"}),a.jsx("p",{className:"session-terminal-panel__empty-copy",children:"从右上角的运行按钮启动一个项目命令后,这里会实时显示终端输出。"})]})}):a.jsxs("section",{className:`session-terminal-panel ${o?"is-compact":""}`,children:[a.jsxs("div",{className:"session-terminal-panel__tabs",children:[a.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 a.jsxs("div",{className:`session-terminal-panel__tab ${N?"is-active":""}`,children:[a.jsxs("button",{type:"button",className:"session-terminal-panel__tab-button",role:"tab","aria-selected":N,onClick:()=>m(w.id),children:[a.jsx("span",{className:`session-terminal-panel__tab-dot is-${w.status}`,"aria-hidden":"true"}),a.jsx("span",{className:"session-terminal-panel__tab-title",children:w.title}),a.jsx("span",{className:"session-terminal-panel__tab-time",children:bI(w.last_output_at??w.updated_at)})]}),a.jsx("button",{type:"button",className:"session-terminal-panel__tab-close","aria-label":`关闭 ${w.title}`,onClick:j=>{j.stopPropagation(),y(w.id)},children:a.jsx(_I,{})})]},w.id)})}),u&&g?a.jsx("button",{type:"button",className:"session-terminal-panel__fullscreen-button",onClick:g,"aria-label":d?"退出终端全屏":"终端全屏",title:d?"退出终端全屏":"终端全屏",children:d?a.jsx(vI,{}):a.jsx(yI,{})}):null]}),p?a.jsxs(a.Fragment,{children:[r?a.jsx("div",{className:"session-terminal-panel__notice is-error",children:r}):null,v!=null&&v.error?a.jsx("div",{className:"session-terminal-panel__notice is-error",children:v.error}):null,v!=null&&v.truncated?a.jsx("div",{className:"session-terminal-panel__notice",children:"终端输出过长,已自动显示服务端仍保留的最近内容。"}):null,a.jsx("div",{ref:b,className:"session-terminal-panel__output-wrap",children:a.jsx("pre",{className:"session-terminal-output",children:v&&v.chunks.length>0?a.jsx(S5,{chunks:v.chunks}):v!=null&&v.isLoading?a.jsx("span",{className:"session-terminal-output__placeholder",children:"正在读取终端输出..."}):a.jsx("span",{className:"session-terminal-output__placeholder",children:"这个终端暂时还没有输出。"})})})]}):null]})},wI=_.memo(function({conversationMainRef:t,conversationScrollRef:i,isDesktopSidebar:r,sidebarShift:o,isSidebarDragging:u,title:d,titleActions:m,topbarActions:y,onOpenSidebar:g,threadContent:b,connectionStatus:p,sessionRecoveryStatus:v,isConnectionDetailOpen:w,onToggleConnectionDetail:N,showThinkingStatus:j}){const T={transform:`translateX(${o}px)`,transition:u?"none":void 0};return a.jsxs("div",{ref:t,className:`conversation-main ${r?"has-desktop-sidebar":""}`,style:T,children:[a.jsxs("div",{className:"conversation-topbar",children:[r?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:g,"aria-label":"打开侧边栏",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]}),a.jsx("div",{className:"conversation-topbar__meta",children:a.jsxs("div",{className:"conversation-topbar__title-row",children:[a.jsx("h1",{children:d}),m]})}),y]}),a.jsx("div",{ref:i,className:"conversation-scroll",children:a.jsxs("div",{className:"conversation-thread",children:[b,p.state!=="connected"?a.jsx("section",{className:"conversation-entry is-connection-status",children:a.jsxs("div",{className:"connection-status",children:[a.jsx("button",{type:"button",className:"connection-status__pill",onClick:M=>{M.stopPropagation(),N()},children:a.jsx("span",{children:p.state==="failed"?"连接异常":`Reconnecting... ${p.attempt}/${p.maxAttempts}`})}),w&&p.error?a.jsx("div",{className:"connection-status__tooltip",role:"tooltip",children:p.error}):null]})}):null,p.state==="connected"&&v.state!=="idle"?a.jsx("section",{className:"conversation-entry is-connection-status",children:a.jsxs("div",{className:"connection-status",children:[a.jsx("div",{className:"connection-status__pill",children:a.jsx("span",{children:v.state==="recovering"?"恢复会话中...":"会话恢复失败"})}),v.state==="failed"&&v.error?a.jsx("div",{className:"connection-status__tooltip",role:"tooltip",children:v.error}):null]})}):null,j?a.jsx("section",{className:"conversation-entry is-thinking-status",children:a.jsx("div",{className:"thinking-status-pill",children:a.jsx("span",{children:"正在思考"})})}):null]})})]})}),NI="panda:last-session-id",kI=.4,EI=104,CI=1800*1e3,TI=15e3,MI=120*1e3,Dx=1100,j5="panda:desktop-sidebar-width",Wf="panda:desktop-sidebar-width-version",Kf="2026-03-24-narrow",RI=300,w5=232,Du=w5,AI=460,Ox=72,l_=72,Lx=120,u0=54,Px=300,II=640,DI=4200,o_="local-model-panel:",OI=160,LI={id:"",agent_id:"",name:"",display_name:null,pinned:!1,path:""},PI={id:"",agent_id:"",project_id:"",provider:"codex",archived:!1,title:"",last_event_at:"",pinned:!1,run_state:"idle",run_state_changed_at:null,subagent:null},UI={...PI,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}},zI=(e,t)=>{if(!t)return e??null;if(e!=null&&e.sessions.some(o=>o.id===t.sessionId))return e;const i=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)??[]],r=[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:i,project_stats:i.map(o=>{const u=r.filter(m=>m.project_id===o.id),d=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:(d==null?void 0:d.archived_session_count)??0,hidden_history_count:(d==null?void 0:d.hidden_history_count)??0}}),sessions:r,active_session_id:t.sessionId}},BI={session_id:"",generated_at:"",view:"tail",anchor_entry_id:null,has_earlier_entries:!1,entries:[]},$I=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"6",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"12",cy:"12",r:"1",fill:"currentColor",stroke:"none"}),a.jsx("circle",{cx:"18",cy:"12",r:"1",fill:"currentColor",stroke:"none"})]}),Ux=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"9",y:"9",width:"10",height:"10",rx:"2"}),a.jsx("path",{d:"M7 15H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v1"})]}),zx=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"m7.5 12.5 3 3 6-7"})}),HI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"M6 6l12 12"}),a.jsx("path",{d:"M18 6 6 18"})]}),FI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("path",{d:"m9 18-6-6 6-6"}),a.jsx("path",{d:"m15 6 6 6-6 6"})]}),qI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"6",cy:"6",r:"2.2"}),a.jsx("circle",{cx:"18",cy:"6",r:"2.2"}),a.jsx("circle",{cx:"12",cy:"18",r:"2.2"}),a.jsx("path",{d:"M8 7.6 10.5 16"}),a.jsx("path",{d:"M16 7.6 13.5 16"}),a.jsx("path",{d:"M8.2 6h7.6"})]}),WI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2.5"}),a.jsx("path",{d:"m7.5 9 2.8 3-2.8 3"}),a.jsx("path",{d:"M12.8 15H16.5"})]}),KI=()=>a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.1",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:a.jsx("path",{d:"M7 5.5 18 12 7 18.5Z"})}),QI=()=>a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[a.jsx("circle",{cx:"12",cy:"12",r:"8.4"}),a.jsx("path",{d:"M3.8 12h16.4"}),a.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"})]}),GI=()=>a.jsx(dT,{"aria-hidden":"true",strokeWidth:1.9}),Bx=()=>a.jsx(yT,{"aria-hidden":"true",strokeWidth:1.9}),nc=12,YI=_.memo(function({isActive:t,label:i,path:r,tokenKey:o,onToggle:u}){const d=_.useRef(null),m=_.useRef(null),[y,g]=_.useState(void 0);return _.useEffect(()=>{if(!t){g(void 0);return}const b=()=>{const v=d.current,w=m.current;if(!v||!w)return;const N=v.getBoundingClientRect(),j=typeof window<"u"?window.innerWidth:document.documentElement.clientWidth,T=typeof window<"u"?window.innerHeight:document.documentElement.clientHeight,M=Math.max(220,Math.min(520,j-nc*2));w.style.width=`${M}px`,w.style.maxWidth=`${M}px`;const P=w.getBoundingClientRect(),I=Math.min(Math.max(N.left,nc),Math.max(nc,j-nc-M)),k=N.top-P.height-8,O=k>=nc?k:Math.min(N.bottom+8,T-nc-P.height);g({left:`${I}px`,top:`${Math.max(nc,O)}px`,width:`${M}px`,maxWidth:`${M}px`})},p=window.requestAnimationFrame(b);return window.addEventListener("resize",b),document.addEventListener("scroll",b,!0),()=>{window.cancelAnimationFrame(p),window.removeEventListener("resize",b),document.removeEventListener("scroll",b,!0)}},[t,r]),a.jsxs("span",{ref:d,className:`conversation-inline-link ${t?"is-active":""}`,children:[a.jsx("span",{role:"button",tabIndex:0,className:"conversation-inline-link__button",onClick:b=>{b.stopPropagation(),u()},onKeyDown:b=>{b.key!=="Enter"&&b.key!==" "||(b.preventDefault(),b.stopPropagation(),u())},children:i}),t&&typeof document<"u"?ra.createPortal(a.jsx("span",{ref:m,className:"conversation-inline-link__tooltip",role:"tooltip",style:y,children:r}),document.body):null]},o)}),$x=(e,t)=>{const i=new Map;for(const r of e)i.set(r.cursor,r);for(const r of t)i.set(r.cursor,r);return[...i.values()].sort((r,o)=>r.cursor-o.cursor)},VI=800,py=(e,t,i)=>{const r=e.get(t);if(r!==void 0)return e.delete(t),e.set(t,r),r;const o=i();if(e.set(t,o),e.size>VI){const u=e.keys().next().value;u&&e.delete(u)}return o},XI=new Map,ZI=new Map,JI=new Map,d0=()=>cl(()=>import("./session-diff-preview-5oB0rJ5W.js"),__vite__mapDeps([0,1])),eD=_.lazy(async()=>({default:(await d0()).SessionDiffPreview})),f0=(e,t,i)=>a.jsx(_.Suspense,{fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在载入差异详情…"}),children:a.jsx(eD,{diffText:e,filePath:t,emptyMessage:i})}),tD=e=>a.jsx("span",{className:"conversation-inline-link",children:a.jsx("span",{className:"conversation-inline-link__button",title:e,children:N5(e)})}),nD=/<proposed_plan>([\s\S]*?)<\/proposed_plan>/g,sD=e=>py(XI,e,()=>f5(e)),_h=e=>e.replace(/\\/g,"/"),aD=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),iD=e=>{var r,o,u,d,m,y;const t=/^\s*(\d+)\.\s+(.+)$/.exec(e);if(t){const g=/^\[( |x|X)\]\s+(.+)$/.exec(t[2]??"");return{ordered:!0,ordinal:Number.parseInt(t[1]??"",10),checked:g?((r=g[1])==null?void 0:r.toLowerCase())==="x":null,text:((o=g==null?void 0:g[2])==null?void 0:o.trim())??((u=t[2])==null?void 0:u.trim())??""}}const i=/^\s*[-*+]\s+(.+)$/.exec(e);if(i){const g=/^\[( |x|X)\]\s+(.+)$/.exec(i[1]??"");return{ordered:!1,ordinal:null,checked:g?((d=g[1])==null?void 0:d.toLowerCase())==="x":null,text:((m=g==null?void 0:g[2])==null?void 0:m.trim())??((y=i[1])==null?void 0:y.trim())??""}}return null},Hx=e=>/^\s{0,3}>\s?(.*)$/.exec(e),rD=e=>/^\s{0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/.test(e),h0=e=>{const i=e.trim().replace(/^\|/,"").replace(/\|$/,""),r=[];let o="";for(let u=0;u<i.length;u+=1){const d=i[u];if(d==="\\"&&i[u+1]==="|"){o+="|",u+=1;continue}if(d==="|"){r.push(o.trim()),o="";continue}o+=d}return r.push(o.trim()),r},lD=e=>{if(!e.includes("|"))return null;const t=h0(e);if(t.length===0)return null;const i=[];for(const r of t){const o=r.replace(/\s/g,"");if(!/^:?-{3,}:?$/.test(o))return null;const u=o.startsWith(":"),d=o.endsWith(":");i.push(u&&d?"center":d?"right":u?"left":null)}return i},c_=(e,t,i)=>Array.from({length:t},(r,o)=>e[o]??i),Fx=e=>["conversation-markdown-table__cell",e?`is-align-${e}`:""].filter(Boolean).join(" "),oD=e=>`h${Math.min(Math.max(e,1),6)}`,cD=e=>["conversation-markdown-list",e.some(t=>t.checked!==null)?"has-task-items":""].filter(Boolean).join(" "),uD=e=>{var i;const t=/^\/([A-Za-z][A-Za-z0-9._-]*)/.exec(e.trim());return((i=t==null?void 0:t[1])==null?void 0:i.toLowerCase())??""},dD=e=>e.kind==="system"&&e.title==="context_compacted",qx=e=>e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e)),fD=e=>py(ZI,e,()=>{var m;const t=e.replace(/\r\n/g,`
|
|
202
202
|
`).split(`
|
|
203
203
|
`),i=[];let r=[],o=null;const u=()=>{r.length!==0&&(i.push({kind:"paragraph",lines:[...r]}),r=[])},d=()=>{if(!o||o.items.length===0){o=null;return}i.push({kind:"list",ordered:o.ordered,items:[...o.items]}),o=null};for(let y=0;y<t.length;y+=1){const g=t[y],b=/^\s{0,3}(```+|~~~+)[ \t]*([^`]*)$/.exec(g);if(b){u(),d();const j=b[1]??"```",T=(b[2]??"").trim(),M=T?((m=T.split(/\s+/,1)[0])==null?void 0:m.toLowerCase())??null:null,P=new RegExp(`^\\s{0,3}${aD(j)}\\s*$`),I=[];for(y+=1;y<t.length&&!P.test(t[y]??"");)I.push(t[y]??""),y+=1;i.push({kind:"code",rawInfo:T,language:M,content:I.join(`
|
|
204
204
|
`)});continue}const p=/^\s{0,3}(#{1,6})\s+(.+?)\s*$/.exec(g),v=Hx(g),w=iD(g),N=g.includes("|")&&y+1<t.length?lD(t[y+1]??""):null;if(p){u(),d(),i.push({kind:"heading",level:p[1].length,text:p[2].replace(/\s+#+\s*$/,"").trim()});continue}if(v){u(),d();const j=[v[1]??""];for(;y+1<t.length;){const T=Hx(t[y+1]??"");if(!T)break;j.push(T[1]??""),y+=1}i.push({kind:"blockquote",lines:j});continue}if(rD(g)){u(),d(),i.push({kind:"thematic-break"});continue}if(N){u(),d();const j=h0(g),T=Math.max(j.length,N.length),M=[];for(y+=2;y<t.length;){const P=t[y]??"";if(!P.trim()||!P.includes("|"))break;M.push(c_(h0(P),T,"")),y+=1}y-=1,i.push({kind:"table",headers:c_(j,T,""),alignments:c_(N,T,null),rows:M});continue}if(w){u(),(!o||o.ordered!==w.ordered)&&(d(),o={ordered:w.ordered,items:[]}),o.items.push({text:w.text,ordinal:w.ordinal,checked:w.checked});continue}if(!g.trim()){u();continue}d(),r.push(g)}return u(),d(),i}),hD=e=>py(JI,e,()=>{const t=[];let i=0;e.replace(nD,(o,u,d)=>{const m=e.slice(i,d);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()}),i=d+o.length,o});const r=e.slice(i);return r.trim()&&t.push({kind:"markdown",content:r.trim()}),t.length===0&&e.trim()&&t.push({kind:"markdown",content:e.trim()}),t}),mD=e=>{const t=e.files.filter(i=>!!i.item_id);return t.length>0?t:e.files.filter(i=>!i.item_id)},Wx=(e,t,i)=>{const r=new Map(((i==null?void 0:i.files)??[]).map(d=>[d.path,d])),o=e.files.filter(d=>!d.item_id);if(o.length>0)return o.map(d=>{var m;return{changeSetId:e.id,path:d.path,pathLabel:rl(d.path,t),additions:d.additions,deletions:d.deletions,itemId:d.item_id,diffAvailable:d.diff_available,diffText:(m=r.get(d.path))==null?void 0:m.diffText,emptyMessage:"此变更没有可展示的补丁内容"}});const u=new Map;for(const d of e.files)u.set(d.path,d);return[...u.values()].map(d=>{var m;return{changeSetId:e.id,path:d.path,pathLabel:rl(d.path,t),additions:d.additions,deletions:d.deletions,itemId:d.item_id,diffAvailable:d.diff_available,diffText:(m=r.get(d.path))==null?void 0:m.diffText,emptyMessage:"此变更没有可展示的补丁内容"}})},cp=(e,t,i)=>`${e}:${i??"summary"}:${t}`,u_=e=>`turn-summary:${e}`,Kx=(e,t)=>`${e}:${t}`,pD=e=>{var i;const t=d6(e);return t>=0?((i=e[t])==null?void 0:i.id)??null:null},Qx=(e,t,i)=>({session_id:e,generated_at:new Date().toISOString(),view:"tail",anchor_entry_id:pD(t),has_earlier_entries:i,entries:t}),gy=e=>Array.isArray(e),gD=e=>bN(e),Qm=e=>gy(e)?e:Array.isArray(e==null?void 0:e.entries)?e.entries:[],Gm=e=>gy(e)?gD(e):(e==null?void 0:e.has_earlier_entries)??!1,_D=e=>gy(e)?"tail":(e==null?void 0:e.view)??"tail",yD=(e,t)=>{const i=new Map((e??[]).map(r=>[r.id,r]));for(const r of t)i.set(r.id,r);return[...i.values()].sort((r,o)=>+new Date(r.started_at)-+new Date(o.started_at))},vD=e=>`${e} background agent${e===1?"":"s"}`,bD=e=>e.startsWith("Reconnecting...")?"retrying":"error",xD=e=>e.startsWith("Reconnecting...")?"Codex 重连中":"Codex 运行异常",N5=e=>{const t=_h(e).replace(/\/+$/,""),i=t.split("/");return i[i.length-1]||t},Gx=e=>`${e.kind}\0${e.title}\0${e.body}\0${e.accent}`,SD=(e,t)=>{if(!t||t.length===0||e.length===0)return e;let i=0;for(;i<e.length&&i<t.length&&Gx(e[i])===Gx(t[i]);)i+=1;return i<=0||i>=e.length?e:e.slice(i)},jD=e=>{const t=e.trim();if(!t.startsWith("<subagent_notification>"))return null;const i=t.indexOf("{");if(i<0)return null;const r=t.lastIndexOf("}");if(r<=i)return null;try{const o=JSON.parse(t.slice(i,r+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 d=o.status&&typeof o.status=="object"?o.status:null,m=u(d==null?void 0:d.completed),y=u(d==null?void 0:d.errored),g=u(d==null?void 0:d.working),b=u(d==null?void 0:d.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(b)return{agentId:typeof o.agent_id=="string"?o.agent_id:null,body:b||"子代理已关闭",state:"shutdown"}}catch{return null}return null},d_=["#2f72d8","#d06a3b","#2d9b7f","#8c62d9","#bf5b7f","#b78b2d"],k5=e=>{const t=(e??"").trim();if(!t)return d_[0];let i=0;for(let r=0;r<t.length;r+=1)i=i*31+t.charCodeAt(r)>>>0;return d_[i%d_.length]},wD=e=>{var t;return k5(((t=e.subagent)==null?void 0:t.nickname)??e.title??e.id)},E5=e=>{let t=-1,i=-1;return e.forEach((r,o)=>{if(!(r.kind!=="system"||r.title!=="status")){if(r.body==="开始处理请求"){t=o;return}r.body==="处理完成"&&(i=o)}}),t>i?t:-1},ND=e=>{var i;const t=E5(e);return t<0?null:((i=e[t])==null?void 0:i.timestamp)??null},kD=e=>{const t=E5(e);if(t<0)return new Set;const i=[],r=new Set;for(const o of e.slice(t)){if(o.kind!=="tool")continue;if(o.title!=="tool-output"){if(i.push({name:o.title}),o.title==="close_agent"){const d=o.session_ids[0]??null;d&&r.delete(d)}continue}const u=i.shift()??null;if((u==null?void 0:u.name)==="spawn_agent"){const d=o.session_ids[0]??null;d&&r.add(d)}}return r},ED=e=>e.run_state==="running"?"is working":e.run_state==="completed"?"completed":"is awaiting instruction",C5=1e4,Uf=1200,T5=e=>new Set(((e==null?void 0:e.files)??[]).map(t=>_h(t.path))),M5=(e,t)=>{if(t.size===0)return 0;let i=0;for(const r of e.files)t.has(_h(r.path))&&(i+=1);return i},CD=(e,t,i)=>{const r=+new Date(t);if(!Number.isFinite(r))return!1;const o=T5(i);return e.some(u=>{if(u.source!=="app-server")return!1;const d=+new Date(u.updated_at);return!Number.isFinite(d)||Math.abs(d-r)>C5?!1:o.size===0?!0:M5(u,o)>0})},TD=(e,t)=>{if(!e)return"已处理";const i=Math.max(0,new Date(t).getTime()-new Date(e).getTime()),r=Math.max(0,Math.round(i/1e3)),o=Math.floor(r/60),u=r%60;return o<=0?`已处理 ${u}s`:`已处理 ${o}m ${u}s`},rl=(e,t)=>{const i=_h(e),r=t?_h(t).replace(/\/+$/,""):"";return r&&i.toLowerCase().startsWith(`${r.toLowerCase()}/`)?i.slice(r.length+1):i},R5=(e,t)=>!e||e.files.length===0?null:{files:e.files.map(i=>({path:i.path,displayPath:rl(i.path,t),operation:"update",additions:i.additions,deletions:i.deletions,diffText:""})),additions:e.additions,deletions:e.deletions},A5=(e,t)=>{const i=e.split(/\r?\n/),r=[];let o=null,u=[];const d=()=>{o&&(r.push({...o,diffText:u.join(`
|
|
205
205
|
`).trim()}),o=null,u=[])};for(const m of i){const y=m.replace(/\r$/,""),g=y.trimStart();if(y.startsWith("*** Add File: ")){d();const b=y.slice(14).trim();o={path:b,displayPath:rl(b,t),operation:"add",additions:0,deletions:0,diffText:""};continue}if(y.startsWith("*** Update File: ")){d();const b=y.slice(17).trim();o={path:b,displayPath:rl(b,t),operation:"update",additions:0,deletions:0,diffText:""};continue}if(y.startsWith("*** Delete File: ")){d();const b=y.slice(17).trim();o={path:b,displayPath:rl(b,t),operation:"delete",additions:0,deletions:0,diffText:""};continue}if(o){if(y.startsWith("*** End Patch")){d();continue}if(y.startsWith("*** ")){d();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 d(),r.length===0?null:{files:r,additions:r.reduce((m,y)=>m+y.additions,0),deletions:r.reduce((m,y)=>m+y.deletions,0)}},MD=e=>{if(e.length===0)return null;const t=new Map;for(const r of e)for(const o of r.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(`
|
|
206
206
|
`),u.operation=o.operation}const i=[...t.values()];return{files:i,additions:i.reduce((r,o)=>r+o.additions,0),deletions:i.reduce((r,o)=>r+o.deletions,0)}},Ym=(e,t=EI)=>{const i=e.replace(/\s+/g," ").trim();return i.length<=t?i:`${i.slice(0,t-1).trimEnd()}…`},_y=e=>{try{return JSON.parse(e)}catch{return null}},RD=e=>{const t=_y(e.body);if(t){const i=["command","cmd","path","pattern","q","input"];for(const r of i){const o=t[r];if(typeof o=="string"&&o.trim())return Ym(o)}}return e.title&&e.title!=="tool-output"?e.body.trim().startsWith("{")||e.body.trim().startsWith("[")?Ym(e.title.replace(/-/g," ")):Ym(e.body||e.title):Ym(e.body||"工具执行")},AD=e=>{if(e.title==="apply_patch")return e.body.trim();const t=_y(e.body);return t&&typeof t.command=="string"&&t.command.trim()?t.command.trim():e.body.trim()||e.title},ID=e=>e.map(t=>{const i=_y(t.body);return i&&typeof i.output=="string"?i.output.trim():t.body.trim()}).filter(Boolean).join(`
|
|
207
207
|
|
|
208
|
-
`),DD=e=>e.kind==="entry"&&e.entry.kind==="user",I5=e=>e.kind==="entry"&&e.entry.kind==="assistant",OD=e=>DD(e)||I5(e),LD=e=>e.kind==="tool-group"?!0:e.entry.kind==="assistant"||e.entry.kind==="thinking"||e.entry.kind==="tool",PD=e=>{if(e.length<=1)return e;const t=[];for(const i of e){const r=t[t.length-1];if(r&&r.kind==="entry"&&i.kind==="entry"&&r.entry.kind==="assistant"&&i.entry.kind==="assistant"&&r.entry.body.trim()===i.entry.body.trim()){t[t.length-1]=i;continue}t.push(i)}return t},UD=e=>`展开 ${e.length} 条过程消息`,zD=e=>`收起 ${e.length} 条过程消息`,BD=(e,t)=>{const i=PD(e.items),{completion:r}=e,o=i.findLastIndex(m=>I5(m));if(o===-1||!r||!t)return{id:e.id,startedAt:e.startedAt,visibleStartItems:o===-1?i:i.slice(0,o),hiddenItems:[],visibleEndItems:o===-1?[]:i.slice(o),completion:r};const u=[],d=[];return i.forEach((m,y)=>{if(y!==o){if(OD(m)){u.push(m);return}d.push(m)}}),{id:e.id,startedAt:e.startedAt,visibleStartItems:u,hiddenItems:d,visibleEndItems:[i[o]],completion:r}},$D=(e,t)=>{const i=[];let r=[],o=null;const u=()=>{for(const m of r)i.push({kind:"item",id:m.kind==="entry"?m.entry.id:m.group.id,item:m});r=[]},d=()=>{o&&((o.items.length>0||o.completion)&&i.push({kind:"turn",turn:BD(o,t)}),o=null)};for(const m of e){if(m.kind==="turn-start"){d(),o={id:m.id,startedAt:m.startedAt,items:r,completion:null},r=[];continue}if(m.kind==="turn-complete"){if(o){o.completion=m;continue}o={id:m.id,startedAt:null,items:r,completion:m},r=[];continue}if(o){if(o.completion&&!LD(m)){d(),r.push(m);continue}o.items.push(m);continue}r.push(m)}return d(),u(),i},HD=e=>e.run_state!=="running"&&Date.now()-new Date(e.last_event_at).getTime()>=CI,FD=(e,t)=>{var g,b;const i=t==null?void 0:t.projectPath,r=(t==null?void 0:t.compactCompletedTurns)??!1,o=[];let u=null,d=!1,m=null,y=[];for(let p=0;p<e.length;p+=1){const v=e[p];if(v.kind==="system"&&v.body==="开始处理请求"){o.push({kind:"turn-start",id:v.id,startedAt:v.timestamp}),m=v.timestamp,y=[];continue}if(v.kind==="system"&&v.body==="处理完成"){o.push({kind:"turn-complete",id:v.id,durationLabel:TD(m,v.timestamp),patchSummary:MD(y),completedAt:v.timestamp}),m=null,y=[];continue}if(v.kind==="tool"&&v.title!=="tool-output"){const w=[];let N=p+1;for(;N<e.length&&((g=e[N])==null?void 0:g.kind)==="tool"&&((b=e[N])==null?void 0:b.title)==="tool-output";)w.push(e[N]),N+=1;u=v.id;const j=v.title==="apply_patch"?R5(v.patch_summary,i)??A5(v.body,i):null;j&&y.push(j),w.length===0&&(d=!0),o.push({kind:"tool-group",group:{id:v.id,commandEntry:v,outputEntries:w,patchSummary:j}}),p=N-1;continue}if(v.kind==="tool"&&v.title==="tool-output"){o.push({kind:"tool-group",group:{id:v.id,commandEntry:v,outputEntries:[],patchSummary:null}}),u=v.id;continue}o.push({kind:"entry",entry:v})}return{blocks:$D(o,r),lastToolGroupId:u,hasRunningToolGroup:d}},qD=e=>e.kind==="entry"?e.entry.timestamp:e.group.commandEntry.timestamp,WD=(e,t)=>{var d,m;const i=[...e.visibleStartItems,...e.hiddenItems,...e.visibleEndItems].map(qD).filter(y=>!!y),r=i.length>0?i[i.length-1]:null,o=e.startedAt??i[0]??((d=e.completion)==null?void 0:d.completedAt)??null,u=((m=e.completion)==null?void 0:m.completedAt)??r??o;return{startMs:o?+new Date(o):null,endMs:u?+new Date(u):null,nextStartMs:t!=null&&t.startedAt?+new Date(t.startedAt):null}},KD=(e,t)=>{const i=+new Date(e.started_at),r=e.completed_at?+new Date(e.completed_at):null,o=t.startMs??(t.endMs!==null?t.endMs-Uf:null),u=t.nextStartMs??(t.endMs!==null?t.endMs+Uf:Number.POSITIVE_INFINITY);return o!==null&&i<o-Uf?!1:i<=u+Uf?!0:r!==null&&r<=u+Uf},QD=(e,t)=>{if(t===null)return Number.POSITIVE_INFINITY;const i=+new Date(e.updated_at);return Number.isFinite(i)?Math.abs(i-t):Number.POSITIVE_INFINITY},GD=(e,t)=>{const i=[...t].sort((d,m)=>+new Date(d.started_at)-+new Date(m.started_at)),r=new Set,o=e.filter(d=>d.kind==="turn"),u=new Map(o.map((d,m)=>[d.turn.id,m]));return e.map(d=>{var j,T,M;if(d.kind!=="turn")return d;const m=u.get(d.turn.id)??-1,y=m>=0?((j=o[m+1])==null?void 0:j.turn)??null:null,g=WD(d.turn,y),b=((T=d.turn.completion)==null?void 0:T.patchSummary)??null,p=T5(b),w=((M=i.filter(P=>!r.has(P.id)).map(P=>({changeSet:P,overlapCount:M5(P,p),updatedAtDistance:QD(P,g.endMs)})).filter(P=>P.overlapCount>0&&P.updatedAtDistance<=C5).sort((P,I)=>I.overlapCount!==P.overlapCount?I.overlapCount-P.overlapCount:P.changeSet.source!==I.changeSet.source?P.changeSet.source==="app-server"?-1:1:P.updatedAtDistance!==I.updatedAtDistance?P.updatedAtDistance-I.updatedAtDistance:+new Date(P.changeSet.started_at)-+new Date(I.changeSet.started_at))[0])==null?void 0:M.changeSet)??i.find(P=>r.has(P.id)?!1:KD(P,g))??null;return w&&r.add(w.id),{kind:"turn",turn:d.turn,changeSet:w}})},YD=()=>typeof window>"u"?248:Math.max(0,Math.min(248,window.innerWidth-84)),m0=e=>Math.max(w5,Math.min(AI,e)),VD=()=>{if(typeof window>"u")return Du;try{const e=window.localStorage.getItem(j5),t=window.localStorage.getItem(Wf);if(!e)return window.localStorage.setItem(Wf,Kf),Du;const i=Number(e);if(!Number.isFinite(i))return window.localStorage.setItem(Wf,Kf),Du;const o=t!==Kf||i===RI||i>Du?Du:i;return window.localStorage.setItem(Wf,Kf),m0(o)}catch{return Du}};function Vm({active:e,render:t,fallback:i=null}){const[r,o]=_.useState(!e);return _.useEffect(()=>{if(!e){o(!1);return}o(!1);const u=window.requestAnimationFrame(()=>{o(!0)});return()=>{window.cancelAnimationFrame(u)}},[e]),e?r?a.jsx(a.Fragment,{children:t()}):a.jsx(a.Fragment,{children:i}):null}const XD=_.memo(function({sessionId:t,group:i,projectPath:r}){const[o,u]=_.useState({}),d=i.commandEntry.detail_available||i.outputEntries.some(j=>j.detail_available),m=UA({sessionId:t,entryId:i.commandEntry.id,scope:{sessionId:t},enabled:d}),y=m.data,g=(y==null?void 0:y.command_entry)??i.commandEntry,b=y!=null&&y.output_entries&&y.output_entries.length>0?y.output_entries:i.outputEntries,p=g.title==="apply_patch"?A5(g.body,r)??R5(g.patch_summary,r)??i.patchSummary:i.patchSummary,v=AD(g),w=ID(b),N=j=>{u(T=>({...T,[j]:!T[j]}))};return m.isPending&&d&&!y?a.jsx("div",{className:"patch-file-card__empty",children:"正在加载工具详情…"}):g.title==="apply_patch"&&p?p.files.length>1?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"tool-entry__patch-list",children:p.files.map(j=>{const T=`${i.id}:${j.path}`,M=!!o[T];return a.jsxs("div",{className:`tool-entry tool-entry--patch-file ${M?"is-expanded":""}`,children:[a.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>N(T),"aria-expanded":M,children:[a.jsxs("div",{className:"tool-entry__summary",children:[a.jsx("span",{className:"tool-entry__status",children:"已编辑"}),a.jsx("span",{className:"tool-entry__command",children:tD(j.displayPath)}),a.jsxs("span",{className:"tool-entry__counts",children:[a.jsxs("span",{className:"is-add",children:["+",j.additions]}),a.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),a.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),M?a.jsx("div",{className:"tool-entry__details",children:j.diffText.trim()?a.jsxs("div",{className:"patch-file-card",children:[a.jsxs("div",{className:"patch-file-card__header",children:[a.jsx("div",{className:"patch-file-card__path",children:j.displayPath}),a.jsxs("div",{className:"patch-file-card__counts",children:[a.jsxs("span",{className:"is-add",children:["+",j.additions]}),a.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),a.jsx("div",{className:"patch-file-card__diff",children:f0(j.diffText,j.path,"此变更没有可展示的补丁内容")})]}):a.jsx("div",{className:"patch-file-card__empty",children:"此变更没有可展示的补丁内容"})}):null]},T)})}),m.isError?a.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]}):a.jsxs("div",{className:"tool-entry__patch-list",children:[p.files.map(j=>a.jsxs("div",{className:"patch-file-card",children:[a.jsxs("div",{className:"patch-file-card__header",children:[a.jsx("div",{className:"patch-file-card__path",children:j.displayPath}),a.jsxs("div",{className:"patch-file-card__counts",children:[a.jsxs("span",{className:"is-add",children:["+",j.additions]}),a.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),a.jsx("div",{className:"patch-file-card__diff",children:f0(j.diffText,j.path,"此变更没有可展示的补丁内容")})]},`${i.id}-${j.path}`)),m.isError?a.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"tool-entry__section",children:[a.jsx("div",{className:"tool-entry__label",children:"命令"}),a.jsx("pre",{className:"tool-entry__pre",children:v})]}),w?a.jsxs("div",{className:"tool-entry__section",children:[a.jsx("div",{className:"tool-entry__label",children:"输出"}),a.jsx("pre",{className:"tool-entry__pre",children:w})]}):null,m.isError?a.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]})}),ZD=_.memo(function({sessionId:t,sessions:i,sessionRunState:r,isDesktopSidebar:o,projectPath:u,renderedBlocks:d,lastToolGroupId:m,sessionChangeSets:y,isSubagentTimelinePending:g,isInitialTimelinePending:b,hasTimeline:p,proposedPlanReplyDrafts:v,pendingProposedPlanReplyEntryId:w,canRespondToProposedPlan:N,onProposedPlanReplyDraftChange:j,onSubmitProposedPlanReply:T,onPreviewImage:M,changeSetDiffs:P,changeSetDiffErrors:I,loadingChangeSetDiffKeys:k,onLoadSessionChangeSets:O,onLoadChangeSetFileDiff:Q,onLoadFullTimeline:J,timelineLoadState:F,canRollbackChangeSets:B,pendingRollbackTurnId:G,rollbackTurnError:Z,rolledBackTurnIds:ae,onRollbackTurn:he}){const[ne,Ce]=_.useState({}),[R,X]=_.useState({}),[le,ue]=_.useState({}),[ye,D]=_.useState(null),[oe,je]=_.useState(null),[z,be]=_.useState(null),De=_.useRef(null),se=_.useRef(null),pe=_.useMemo(()=>{var V;return((V=[...d].reverse().find(q=>q.kind==="turn"&&!!q.turn.completion))==null?void 0:V.turn.id)??null},[d]);_.useEffect(()=>{const V=q=>{const de=q.target;de instanceof Element&&de.closest(".conversation-inline-link")||D(null)};return window.addEventListener("pointerdown",V),()=>{window.removeEventListener("pointerdown",V)}},[]),_.useEffect(()=>()=>{De.current!==null&&window.clearTimeout(De.current),se.current!==null&&window.clearTimeout(se.current)},[]);const ke=V=>{Ce(q=>({...q,[V]:!q[V]}))},Ze=V=>{X(q=>({...q,[V]:!q[V]}))},zt=V=>{ue(q=>({...q,[V]:!q[V]}))};_.useEffect(()=>{var q;const V=new Map;for(const de of d){if(de.kind!=="turn")continue;const ce=de.changeSet;if(!ce||ce.status!=="completed"||ce.files.length===0)continue;const Ae=u_(de.turn.id),Ee=Wx(ce,u,((q=de.turn.completion)==null?void 0:q.patchSummary)??null);for(const $e of Ee){if(!$e.changeSetId||!$e.diffAvailable)continue;const Pe=Kx(Ae,$e.path);if(!le[Pe])continue;const ht=cp($e.changeSetId,$e.path,$e.itemId);P[ht]||k[ht]||V.set(ht,{changeSetId:$e.changeSetId,path:$e.path,itemId:$e.itemId??null})}}for(const de of V.values())Q(de)},[P,le,k,Q,u,d]);const Fe=async V=>{var ce;const q=V.trim();if(!q)return!1;const de=()=>{const Ae=document.createElement("textarea");Ae.value=q,Ae.setAttribute("readonly","true"),Ae.style.position="fixed",Ae.style.opacity="0",Ae.style.pointerEvents="none",document.body.appendChild(Ae),Ae.select(),document.execCommand("copy"),document.body.removeChild(Ae)};try{return(ce=navigator.clipboard)!=null&&ce.writeText?await navigator.clipboard.writeText(q):de(),!0}catch{return!1}},kt=async(V,q)=>{await Fe(q)&&(je(V),De.current!==null&&window.clearTimeout(De.current),De.current=window.setTimeout(()=>{je(ce=>ce===V?null:ce),De.current=null},1400))},Bt=async(V,q)=>{await Fe(q)&&(be(V),se.current!==null&&window.clearTimeout(se.current),se.current=window.setTimeout(()=>{be(ce=>ce===V?null:ce),se.current=null},1400))};function Gt(V,q,de){return f0(V,q,de)}function Xt(V,q,de){const ce=ye===de,Ae=()=>{D(Ee=>Ee===de?null:de)};return a.jsx(YI,{isActive:ce,label:V,path:q,tokenKey:de,onToggle:Ae},de)}function Ft(V,q,de=rl(V,u)){return Xt(N5(de),de,q)}function qe(V,q){return sD(V).map((ce,Ae)=>{const Ee=`${q}-${Ae}`;return ce.kind==="text"?a.jsx("span",{children:ce.value},Ee):ce.kind==="code"?a.jsx("code",{className:"conversation-inline-code",children:ce.value},Ee):ce.kind==="strong"?a.jsx("strong",{children:qe(ce.value,`${Ee}-strong`)},Ee):ce.kind==="emphasis"?a.jsx("em",{children:qe(ce.value,`${Ee}-emphasis`)},Ee):ce.kind==="strikethrough"?a.jsx("del",{children:qe(ce.value,`${Ee}-strikethrough`)},Ee):ce.kind==="skill"?a.jsx("span",{className:"conversation-skill-token",children:ce.raw},Ee):ce.kind==="command"?a.jsx("span",{className:"conversation-command-token",children:ce.raw},Ee):Xt(ce.label,ce.path,Ee)})}function dt(V,q){return fD(V).map((ce,Ae)=>{const Ee=`${q}-block-${Ae}`;if(ce.kind==="heading"){const $e=Math.min(Math.max(ce.level,1),6),Pe=oD($e);return a.jsx(Pe,{className:`conversation-markdown-heading is-level-${$e}`,children:qe(ce.text,`${Ee}-heading`)},Ee)}if(ce.kind==="blockquote")return a.jsx("blockquote",{className:"conversation-markdown-blockquote",children:ce.lines.map(($e,Pe)=>a.jsxs("span",{children:[Pe>0?a.jsx("br",{}):null,qe($e,`${Ee}-quote-line-${Pe}`)]},`${Ee}-quote-line-${Pe}`))},Ee);if(ce.kind==="thematic-break")return a.jsx("hr",{className:"conversation-markdown-thematic-break"},Ee);if(ce.kind==="list"){const $e=ce.ordered?"ol":"ul";return a.jsx($e,{className:cD(ce.items),children:ce.items.map((Pe,ht)=>a.jsxs("li",{value:ce.ordered?Pe.ordinal??void 0:void 0,className:Pe.checked!==null?"is-task-item":void 0,children:[Pe.checked!==null?a.jsx("input",{type:"checkbox",checked:Pe.checked,readOnly:!0,tabIndex:-1,"aria-label":Pe.checked?"已完成":"未完成"}):null,qe(Pe.text,`${Ee}-item-${ht}`)]},`${Ee}-item-${ht}`))},Ee)}if(ce.kind==="table")return a.jsx("div",{className:"conversation-markdown-table__scroll",children:a.jsxs("table",{className:"conversation-markdown-table",children:[a.jsx("thead",{children:a.jsx("tr",{children:ce.headers.map(($e,Pe)=>a.jsx("th",{scope:"col",className:Fx(ce.alignments[Pe]??null),children:qe($e,`${Ee}-header-${Pe}`)},`${Ee}-header-${Pe}`))})}),a.jsx("tbody",{children:ce.rows.map(($e,Pe)=>a.jsx("tr",{children:$e.map((ht,Xe)=>a.jsx("td",{className:Fx(ce.alignments[Xe]??null),children:qe(ht,`${Ee}-row-${Pe}-cell-${Xe}`)},`${Ee}-row-${Pe}-cell-${Xe}`))},`${Ee}-row-${Pe}`))})]})},Ee);if(ce.kind==="code"){const $e=`${Ee}-meta`;return a.jsxs("div",{className:"conversation-markdown-code-block",children:[ce.rawInfo?a.jsxs("div",{className:"conversation-markdown-code-block__meta",children:[a.jsx("span",{className:"conversation-markdown-code-block__meta-label",children:ce.rawInfo}),a.jsxs("button",{type:"button",className:`conversation-markdown-code-block__copy ${z===$e?"is-copied":""}`,onClick:()=>{Bt($e,ce.content)},"aria-label":z===$e?"已复制代码块内容":"复制代码块内容",children:[a.jsx("span",{className:"conversation-markdown-code-block__copy-icon","aria-hidden":"true",children:z===$e?a.jsx(zx,{}):a.jsx(Ux,{})}),a.jsx("span",{className:"sr-only",children:z===$e?"已复制":"复制"})]})]}):null,a.jsx("pre",{className:"conversation-markdown-code-block__pre",children:a.jsx("code",{children:ce.content})})]},Ee)}return a.jsx("p",{className:"conversation-markdown-paragraph",children:ce.lines.map(($e,Pe)=>a.jsxs("span",{children:[Pe>0?a.jsx("br",{}):null,qe($e,`${Ee}-line-${Pe}`)]},`${Ee}-line-${Pe}`))},Ee)})}function un(V,q,de){const ce=`${V.id}:proposed-plan:${de}`,Ae=v[ce]??"",Ee=w===ce,$e=!N||Ee;return a.jsxs("div",{className:"proposed-plan-card",children:[a.jsx("div",{className:"proposed-plan-card__content",children:dt(q,`${ce}:content`)}),a.jsxs("div",{className:"proposed-plan-card__footer",children:[a.jsx("div",{className:"proposed-plan-card__title",children:"实施此计划?"}),a.jsxs("div",{className:"proposed-plan-card__actions",children:[a.jsx("button",{type:"button",className:"proposed-plan-card__confirm",disabled:$e,onClick:()=>{T(ce,"是,实施此计划")},children:Ee?"回复中…":"是,实施此计划"}),a.jsxs("div",{className:"proposed-plan-card__custom",children:[a.jsx("input",{type:"text",className:"proposed-plan-card__input",value:Ae,disabled:$e,placeholder:"否,请告知如何调整",onChange:Pe=>{j(ce,Pe.target.value)},onKeyDown:Pe=>{Pe.key!=="Enter"||!Ae.trim()||$e||(Pe.preventDefault(),T(ce,Ae))}}),a.jsx("button",{type:"button",className:"proposed-plan-card__submit",disabled:$e||!Ae.trim(),onClick:()=>{T(ce,Ae)},children:Ee?"回复中…":"回复"})]})]})]})]},ce)}function $t(V){const q=hD(V.body);return q.some(ce=>ce.kind==="proposed-plan")?q.map((ce,Ae)=>{const Ee=`${V.id}-content-${Ae}`;return ce.kind==="markdown"?a.jsx("div",{className:"conversation-entry__rich-block",children:dt(ce.content,Ee)},Ee):un(V,ce.content,Ae)}):dt(V.body,V.id)}function An(V){const q=C6([],V.attachments);if(q.length===0)return null;const de=q.filter(ax),ce=q.filter(Ae=>!ax(Ae));return a.jsxs("div",{className:"conversation-entry__attachments",children:[de.length>0?a.jsx("div",{className:"conversation-entry__attachment-grid",children:de.map(Ae=>{const Ee=qp(Ae.size_bytes),$e=Ae.name??"图片",Pe=`图片${Ee?` · ${Ee}`:""}`,ht=a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"conversation-entry__attachment-media",children:Ae.content_url?a.jsxs(a.Fragment,{children:[a.jsx("img",{src:Ae.content_url,alt:$e,loading:"lazy"}),a.jsx("span",{className:"conversation-entry__attachment-badge",children:"预览"})]}):a.jsx("div",{className:"conversation-entry__attachment-fallback",children:"无法预览"})}),a.jsxs("div",{className:"conversation-entry__attachment-caption",children:[a.jsx("span",{className:"conversation-entry__attachment-title",children:$e}),a.jsx("span",{className:"conversation-entry__attachment-meta",children:Pe})]})]});return Ae.content_url?a.jsx("button",{type:"button",className:"conversation-entry__attachment-card is-image",onClick:()=>M({src:Ae.content_url,label:$e,meta:Pe}),"aria-label":`预览 ${$e}`,children:ht},`${V.id}:${Ae.id}`):a.jsx("div",{className:"conversation-entry__attachment-card is-image",children:ht},`${V.id}:${Ae.id}`)})}):null,ce.length>0?a.jsx("div",{className:"conversation-entry__file-list",children:ce.map(Ae=>{const Ee=qp(Ae.size_bytes),$e=a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"conversation-entry__file-icon","aria-hidden":"true",children:a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8Z"}),a.jsx("path",{d:"M14 3v5h5"}),a.jsx("path",{d:"M9 13h6"}),a.jsx("path",{d:"M9 17h4"})]})}),a.jsxs("span",{className:"conversation-entry__file-copy",children:[a.jsx("span",{className:"conversation-entry__file-title",children:Ae.name??"附件"}),a.jsxs("span",{className:"conversation-entry__file-meta",children:["文件",Ee?` · ${Ee}`:""]})]})]});return Ae.content_url?a.jsx("a",{className:"conversation-entry__file-card",href:Ae.content_url,download:Ae.name??void 0,target:"_blank",rel:"noreferrer",children:$e},`${V.id}:${Ae.id}`):a.jsx("div",{className:"conversation-entry__file-card",children:$e},`${V.id}:${Ae.id}`)})}):null]})}function Nn(V,q){return a.jsx("div",{className:"turn-patch-summary__files",children:q.map(de=>{const ce=Kx(V,de.path),Ae=!!le[ce],Ee=de.changeSetId?cp(de.changeSetId,de.path,de.itemId):null,$e=Ee?P[Ee]:void 0,Pe=Ee?k[Ee]===!0:!1,ht=Ee?I[Ee]??null:null,Xe=($e==null?void 0:$e.file.diff)??de.diffText??"",tn=($e==null?void 0:$e.empty_message)??de.emptyMessage;return a.jsxs("div",{className:`turn-patch-file ${Ae?"is-expanded":""}`,children:[a.jsxs("button",{type:"button",className:"turn-patch-file__toggle",onClick:()=>{zt(ce),de.changeSetId||O(),Ee&&de.changeSetId&&de.diffAvailable&&!$e&&!Pe&&Q({changeSetId:de.changeSetId,path:de.path,itemId:de.itemId??null})},"aria-expanded":Ae,children:[a.jsx("div",{className:"turn-patch-file__path",children:de.pathLabel}),a.jsxs("div",{className:"turn-patch-file__meta",children:[a.jsxs("span",{className:"turn-patch-summary__counts",children:[a.jsxs("span",{className:"is-add",children:["+",de.additions]}),a.jsxs("span",{className:"is-remove",children:["-",de.deletions]})]}),a.jsx("span",{className:"turn-patch-file__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]})]}),Ae?a.jsx("div",{className:"turn-patch-file__detail",children:Pe?a.jsx("div",{className:"patch-file-card__empty",children:"正在载入差异详情…"}):ht?a.jsx("div",{className:"patch-file-card__empty",children:ht}):de.diffAvailable===!1&&!Xe.trim()?a.jsx("div",{className:"patch-file-card__empty",children:tn}):a.jsx(Vm,{active:Ae,fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),render:()=>Gt(Xe,de.path,tn)})}):null]},ce)})})}function Tt(V){return mD(V).map(q=>{const de=`live:${V.id}:${q.item_id??"summary"}:${q.path}`,ce=!!le[de],Ae=V.status==="running",Ee=cp(V.id,q.path,q.item_id),$e=P[Ee],Pe=k[Ee]===!0,ht=I[Ee]??null,Xe=($e==null?void 0:$e.file.diff)??"",tn=($e==null?void 0:$e.empty_message)??"此变更还没有可展示的补丁内容";return a.jsx("section",{className:"conversation-entry is-tool-group",children:a.jsxs("div",{className:`tool-entry ${Ae?"is-running":"is-complete"} ${ce?"is-expanded":""} is-patch`,children:[a.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>{zt(de),q.diff_available&&!$e&&!Pe&&Q({changeSetId:V.id,path:q.path,itemId:q.item_id??null})},"aria-expanded":ce,children:[a.jsxs("div",{className:"tool-entry__summary",children:[a.jsx("span",{className:"tool-entry__status",children:"已编辑"}),a.jsx("span",{className:"tool-entry__command",children:Ft(q.path,`${de}:live-link`,rl(q.path,u))}),a.jsxs("span",{className:"tool-entry__counts",children:[a.jsxs("span",{className:"is-add",children:["+",q.additions]}),a.jsxs("span",{className:"is-remove",children:["-",q.deletions]})]})]}),a.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),ce?a.jsx("div",{className:"tool-entry__details",children:Pe?a.jsx("div",{className:"patch-file-card__empty",children:"正在载入详情…"}):ht?a.jsx("div",{className:"patch-file-card__empty",children:ht}):!q.diff_available&&!Xe.trim()?a.jsx("div",{className:"patch-file-card__empty",children:tn}):a.jsx(Vm,{active:ce,fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>a.jsx("div",{className:"tool-entry__patch-list",children:a.jsxs("div",{className:"patch-file-card",children:[a.jsxs("div",{className:"patch-file-card__header",children:[a.jsx("div",{className:"patch-file-card__path",children:rl(q.path,u)}),a.jsxs("div",{className:"patch-file-card__counts",children:[a.jsxs("span",{className:"is-add",children:["+",q.additions]}),a.jsxs("span",{className:"is-remove",children:["-",q.deletions]})]})]}),a.jsx("div",{className:"patch-file-card__diff",children:Gt(Xe,q.path,tn)})]})})})}):null]})},de)})}const lt=V=>{const q=B&&pe===V&&!ae[V],de=(Z==null?void 0:Z.turnId)===V?Z.message:null;return{isEligible:q,isPending:G===V,error:de}};function Et(V,q,de,ce){const Ae=Wx(V,u,ce),Ee=Ae.reduce((ht,Xe)=>ht+Xe.additions,0),$e=Ae.reduce((ht,Xe)=>ht+Xe.deletions,0),Pe=lt(q);return a.jsxs("div",{className:"turn-patch-summary",children:[a.jsxs("div",{className:"turn-patch-summary__header",children:[a.jsxs("div",{className:"turn-patch-summary__title",children:[a.jsxs("span",{children:[Ae.length," 个文件已更改"]}),a.jsxs("span",{className:"turn-patch-summary__counts",children:[a.jsxs("span",{className:"is-add",children:["+",Ee]}),a.jsxs("span",{className:"is-remove",children:["-",$e]})]})]}),Pe.isEligible?a.jsx("div",{className:"turn-patch-summary__actions",children:a.jsx("button",{type:"button",className:"turn-patch-summary__action",onClick:()=>he(q),disabled:Pe.isPending,"aria-label":Pe.isPending?"正在回滚这轮改动":"回滚这轮改动",title:Pe.isPending?"正在回滚这轮改动":"回滚这轮改动",children:a.jsx(Bx,{})})}):null]}),Pe.error?a.jsx("div",{className:"turn-patch-summary__notice is-error",children:Pe.error}):null,Nn(de,Ae)]})}function rt(V,q,de){const ce=lt(V);return a.jsxs("div",{className:"turn-patch-summary",children:[a.jsxs("div",{className:"turn-patch-summary__header",children:[a.jsxs("div",{className:"turn-patch-summary__title",children:[a.jsxs("span",{children:[de.files.length," 个文件已更改"]}),a.jsxs("span",{className:"turn-patch-summary__counts",children:[a.jsxs("span",{className:"is-add",children:["+",de.additions]}),a.jsxs("span",{className:"is-remove",children:["-",de.deletions]})]})]}),ce.isEligible?a.jsx("div",{className:"turn-patch-summary__actions",children:a.jsx("button",{type:"button",className:"turn-patch-summary__action",onClick:()=>he(V),disabled:ce.isPending,"aria-label":ce.isPending?"正在回滚这轮改动":"回滚这轮改动",title:ce.isPending?"正在回滚这轮改动":"回滚这轮改动",children:a.jsx(Bx,{})})}):null]}),ce.error?a.jsx("div",{className:"turn-patch-summary__notice is-error",children:ce.error}):null,Nn(q,de.files.map(Ae=>({path:Ae.path,pathLabel:Ae.displayPath,additions:Ae.additions,deletions:Ae.deletions,diffText:Ae.diffText,emptyMessage:"此变更没有可展示的补丁内容"})))]})}function st(V,q){var Xe,tn;const de=q.agentId?i.find(Le=>Le.id===q.agentId)??null:null,ce=k5(((Xe=de==null?void 0:de.subagent)==null?void 0:Xe.nickname)??(de==null?void 0:de.title)??q.agentId),Ae=`subagent:${V.id}`,Ee=!!ne[Ae],$e=q.state==="working",Pe=q.state==="completed"?"子代理返回":q.state==="shutdown"?"子代理已关闭":q.state==="errored"?"子代理异常":"子代理处理中",ht=((tn=de==null?void 0:de.subagent)==null?void 0:tn.nickname)??(de==null?void 0:de.title)??"子代理";return a.jsx("section",{className:"conversation-entry is-tool-group",children:a.jsxs("div",{className:`tool-entry is-subagent ${$e?"is-running":"is-complete"} ${Ee?"is-expanded":""}`,style:{"--subagent-accent":ce},children:[a.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>ke(Ae),"aria-expanded":Ee,children:[a.jsxs("div",{className:"tool-entry__summary",children:[a.jsx("span",{className:"tool-entry__status",children:Pe}),a.jsx("span",{className:"tool-entry__command tool-entry__command--agent",children:ht})]}),a.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),Ee?a.jsx("div",{className:"tool-entry__details",children:a.jsx(Vm,{active:Ee,fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>a.jsxs("div",{className:"tool-entry__section",children:[a.jsx("div",{className:"tool-entry__label",children:ht}),a.jsx("div",{className:"tool-entry__markdown",children:dt(q.body,`${V.id}-subagent`)})]})})}):null]})},V.id)}function Dt(V){var ce,Ae;if(V.kind==="tool-group"){const{group:Ee}=V;if(Ee.commandEntry.title==="apply_patch"&&CD(y,Ee.commandEntry.timestamp,Ee.patchSummary))return null;const $e=!!ne[Ee.id],Pe=r==="running"&&m===Ee.id&&Ee.outputEntries.length===0,ht=Ee.commandEntry.title==="apply_patch"&&!!Ee.patchSummary,Xe=ht&&(((ce=Ee.patchSummary)==null?void 0:ce.files.length)??0)>1,tn=ht?Ee.patchSummary.files.length===1?Ee.patchSummary.files[0].displayPath:`${Ee.patchSummary.files.length} 个文件`:RD(Ee.commandEntry);return a.jsx("section",{className:"conversation-entry is-tool-group",children:a.jsxs("div",{className:`tool-entry ${Pe?"is-running":"is-complete"} ${$e?"is-expanded":""} ${ht?"is-patch":""} ${Xe?"has-flat-patch-list":""}`,children:[a.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>ke(Ee.id),"aria-expanded":$e,children:[a.jsxs("div",{className:"tool-entry__summary",children:[a.jsx("span",{className:"tool-entry__status",children:ht?"已编辑":Pe?"正在执行":"已执行"}),a.jsx("span",{className:"tool-entry__command",children:ht&&((Ae=Ee.patchSummary)==null?void 0:Ae.files.length)===1?Ft(Ee.patchSummary.files[0].path,`${Ee.id}:patch-link`,Ee.patchSummary.files[0].displayPath):tn}),ht&&Ee.patchSummary?a.jsxs("span",{className:"tool-entry__counts",children:[a.jsxs("span",{className:"is-add",children:["+",Ee.patchSummary.additions]}),a.jsxs("span",{className:"is-remove",children:["-",Ee.patchSummary.deletions]})]}):null]}),a.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),$e?a.jsx("div",{className:"tool-entry__details",children:a.jsx(Vm,{active:$e,fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>a.jsx(XD,{sessionId:t,group:Ee,projectPath:u})})}):null]})},Ee.id)}const q=V.entry,de=q.kind==="user"?jD(q.body):null;if(de)return st(q,de);if(q.kind==="thinking")return r!=="running"?null:a.jsx("section",{className:"conversation-entry is-thinking-status",children:a.jsx("div",{className:"thinking-status-pill",children:a.jsx("span",{children:"正在思考"})})},q.id);if(dD(q))return a.jsx("section",{className:"conversation-context-compact",children:a.jsx("div",{className:"context-compact-divider",children:a.jsx("span",{children:"背景信息已自动压缩"})})},q.id);if(q.kind==="system"&&q.title==="system_prompt")return null;if(q.kind==="system"&&q.title==="runtime-status"){const Ee=bD(q.body);return a.jsx("section",{className:"conversation-entry is-runtime-status",children:a.jsxs("div",{className:`runtime-status-entry is-${Ee}`,children:[a.jsx("div",{className:"runtime-status-entry__label",children:xD(q.body)}),a.jsx("pre",{className:"runtime-status-entry__body",children:q.body})]})},q.id)}return a.jsx("section",{className:`conversation-entry ${q.kind==="user"?"is-user":"is-system"} is-${q.kind}`,children:q.kind==="user"?a.jsxs("div",{className:"conversation-entry__stack",children:[a.jsxs("div",{className:"conversation-entry__body",children:[q.body.trim()?dt(q.body,q.id):null,q.attachments.length>0?An(q):null]}),q.body.trim()?a.jsxs("button",{type:"button",className:`conversation-entry__copy ${oe===q.id?"is-copied":""}`,onClick:()=>{kt(q.id,q.body)},"aria-label":oe===q.id?"已复制消息":"复制消息",children:[a.jsx("span",{className:"conversation-entry__copy-icon","aria-hidden":"true",children:oe===q.id?a.jsx(zx,{}):a.jsx(Ux,{})}),a.jsx("span",{className:"sr-only",children:oe===q.id?"已复制":"复制"})]}):null]}):a.jsxs("div",{className:"conversation-entry__body",children:[q.body.trim()?q.kind==="assistant"?$t(q):dt(q.body,q.id):null,q.attachments.length>0?An(q):null]})},q.id)}if(g)return a.jsx("div",{className:"empty-panel",children:"正在载入子代理会话…"});if(b)return a.jsxs("div",{className:"empty-panel empty-panel--loading",role:"status","aria-live":"polite","aria-busy":"true",children:[a.jsxs("span",{className:"empty-panel__loading-dots","aria-hidden":"true",children:[a.jsx("span",{className:"empty-panel__loading-dot"}),a.jsx("span",{className:"empty-panel__loading-dot"}),a.jsx("span",{className:"empty-panel__loading-dot"})]}),a.jsx("span",{className:"sr-only",children:"正在加载会话记录"})]});if(!p)return a.jsx("div",{className:"empty-panel",children:"这个会话还没有历史记录。"});const an=F.canLoadEarlierEntries||F.isPulling||F.isLoadingFull,re=F.isPulling||F.isLoadingFull||F.triggerSource==="click",we=F.isLoadingFull?"正在加载全部对话…":F.isPulling?F.isReadyToLoad?"松开加载全部":"下拉加载更多":o?"加载全部对话":"点击加载全部",Re=F.isLoadingFull||F.triggerSource==="click"?u0:F.indicatorOffset,te={opacity:re?1:0,transform:`translate3d(-50%, calc(-100% + ${Re}px), 0) scale(${re?1:.92})`},ve={transform:`rotate(${F.indicatorRotation}deg)`};return a.jsxs(a.Fragment,{children:[an?a.jsx("section",{className:`conversation-entry is-history-loader ${F.isReadyToLoad?"is-ready":""}`,children:a.jsxs("div",{className:`timeline-history-loader ${F.isLoadingFull?"is-loading":""} ${F.triggerSource==="click"?"is-click-loading":""}`,children:[a.jsx("span",{className:"timeline-history-loader__indicator",style:te,"aria-hidden":"true",children:a.jsx("span",{className:"timeline-history-loader__indicator-surface",children:a.jsx("span",{className:"timeline-history-loader__indicator-track",style:ve,children:a.jsx("span",{className:`timeline-history-loader__indicator-spin ${F.isLoadingFull?"is-loading":""}`,children:a.jsx("span",{className:"timeline-history-loader__indicator-icon",children:a.jsx(GI,{})})})})})}),a.jsx("div",{className:"turn-complete-divider timeline-history-loader__divider",children:F.isLoadingFull?a.jsx("span",{className:"timeline-history-loader__content is-loading",children:a.jsx("span",{children:we})}):a.jsx("button",{type:"button",className:`timeline-history-loader__button ${F.isPulling?"is-pulling":""}`,onClick:()=>J("click"),children:we})})]})}):null,d.map(V=>{var Pe;if(V.kind==="item")return Dt(V.item);const{turn:q}=V,de=V.changeSet,ce=((Pe=q.completion)==null?void 0:Pe.patchSummary)??null,Ae=!!R[q.id],Ee=q.hiddenItems.length>0&&!Ae,$e=Ae?zD(q.hiddenItems):UD(q.hiddenItems);return a.jsxs("section",{className:"conversation-turn",children:[q.visibleStartItems.map(ht=>Dt(ht)),q.hiddenItems.length>0?a.jsxs("div",{className:"conversation-turn__history",children:[a.jsxs("button",{type:"button",className:`turn-history-toggle ${Ae?"is-expanded":""}`,onClick:()=>Ze(q.id),"aria-expanded":Ae,children:[a.jsx("span",{className:"turn-history-toggle__label",children:$e}),a.jsx("span",{className:"turn-history-toggle__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),Ee?null:q.hiddenItems.map(ht=>Dt(ht))]}):null,q.completion&&q.visibleEndItems.length>0?a.jsx("section",{className:"conversation-turn-complete",children:a.jsx("div",{className:"turn-complete-divider",children:a.jsx("span",{children:q.completion.durationLabel})})}):null,q.visibleEndItems.map(ht=>Dt(ht)),de&&de.source==="app-server"&&de.files.length>0?Tt(de):null,q.completion&&q.visibleEndItems.length===0?a.jsx("section",{className:"conversation-turn-complete",children:a.jsx("div",{className:"turn-complete-divider",children:a.jsx("span",{children:q.completion.durationLabel})})}):null,de&&de.status==="completed"&&de.files.length>0?Et(de,q.id,u_(q.id),ce):ce?rt(q.id,u_(q.id),ce):null]},q.id)})]})}),JD=({sessionId:e,workspaceDirectorySnapshot:t=null,workspaceAgentIndicatorState:i,embedded:r=!1,isDesktopSidebar:o,sidebarOffset:u=0,isSidebarDragging:d=!1,onOpenSidebar:m,onSelectSession:y,onExitToNodes:g}={})=>{var Jc,Di,Oi,Cl,eu,tu,Tl,Ml,Vd,Xd,Dr,Fo,Zd,nu,su,_a,Na,Li,au;const{sessionId:b}=Mc({strict:!1}),p=e??b??"",v=W0(p),w=(v==null?void 0:v.agentId)??vo(),N=Hi(),j=Ka(),{data:T}=e5({scope:{sessionId:p,agentId:w??void 0},selectedSessionId:p,enabled:!r&&!t}),M=_.useMemo(()=>zI(t??T,v),[T,v,t]),P=(M==null?void 0:M.sessions.find(x=>x.id===p))??null,I=!!(P||v!=null&&v.session),k=zA({sessionId:p,scope:{sessionId:p,agentId:w??void 0},enabled:!!p}),{historyState:O,archivedState:Q,loadMoreHistory:J,loadMoreProjectlessHistory:F,loadMoreArchived:B,loadMoreProjectlessArchived:G,reset:Z}=n5({scope:{sessionId:p},selectedSessionId:p}),ae=_.useRef(null),he=_.useRef(null),ne=_.useRef(null),Ce=_.useRef(null),R=_.useRef(null),[X,le]=_.useState(!1),[ue,ye]=_.useState(()=>typeof window<"u"&&window.innerWidth>=Dx),[D,oe]=_.useState(()=>VD()),[je,z]=_.useState(!1),[be,De]=_.useState(""),[se,pe]=_.useState([]),[ke,Ze]=_.useState(null),[zt,Fe]=_.useState(null),[kt,Bt]=_.useState(null),[Gt,Xt]=_.useState(()=>sy()),[Ft,qe]=_.useState(()=>L3()),[dt,un]=_.useState(()=>P4(p)),[$t,An]=_.useState(()=>U4(p)),[Nn,Tt]=_.useState(()=>z4(p)),lt=ly(),Et=_.useMemo(()=>lt.map(({id:x,...L})=>L),[lt]),[rt,st]=_.useState({}),[Dt,an]=_.useState(null),[re,we]=_.useState(!1),[Re,te]=_.useState(!1),[ve,V]=_.useState(""),[q,de]=_.useState(!1),[ce,Ae]=_.useState(!1),[Ee,$e]=_.useState(null),[Pe,ht]=_.useState(null),[Xe,tn]=_.useState(!1),[Le,rn]=_.useState(!1),[hn,ns]=_.useState("code"),[Xs,$s]=_.useState(!1),[oa,On]=_.useState(null),[Ss,Kt]=_.useState(null),[Zs,us]=_.useState({}),[Ln,Ot]=_.useState(null),[Wn,Sn]=_.useState(!1),[Jn,js]=_.useState(!1),[Hs,ca]=_.useState(!1),[Fs,Js]=_.useState(!1),[ua,da]=_.useState(null),[fa,In]=_.useState(null),[ws,Os]=_.useState({}),[ee,Be]=_.useState(!1),[Ke,Lt]=_.useState({state:"connected",attempt:0,maxAttempts:5}),[Zt,Pt]=_.useState({sessionId:p??null,pending:!!p,error:null}),[At,mn]=_.useState({state:"idle"}),jn=_.useRef({}),kn=_.useRef(M),pn=_.useRef(null);_.useEffect(()=>{Jf(Gt)},[Gt]),_.useEffect(()=>{P3(Ft)},[Ft]),_.useEffect(()=>{Et.length!==0&&(Et.some(x=>x.value===Gt)||Xt(Et[0].value))},[Et,Gt]),_.useEffect(()=>{un(P4(p)),An(U4(p)),Tt(z4(p)),Bt(null),ns("code"),$s(!1),On(null),Kt(null),us({}),Ot(null),Sn(!1),js(!1),ca(!1),Js(!1),da(null),In(null),Os({}),es({}),Ws({}),pr({}),qi(0),ea(!1),ji(!1),gr(null),wi.current=null,Ni.current=null,_r.current=null,Ga.current=null,C.current=!1,W.current=!!p},[p]),_.useEffect(()=>{jn.current=ws},[ws]),_.useEffect(()=>{kn.current=M},[M]),_.useEffect(()=>{U3(p,dt)},[dt,p]),_.useEffect(()=>{z3(p,$t)},[$t,p]),_.useEffect(()=>{B3(p,Nn)},[Nn,p]),_.useEffect(()=>{st({}),an(null)},[p]),_.useEffect(()=>{vt.current=null},[p]),_.useEffect(()=>{if(!ke)return;const x=K=>{K.key==="Escape"&&Ze(null)},L=document.body.style.overflow;return document.body.style.overflow="hidden",window.addEventListener("keydown",x),()=>{document.body.style.overflow=L,window.removeEventListener("keydown",x)}},[ke]);const[U,Ne]=_.useState(!1),Ue=_.useRef(null),Qe=_.useRef(null),at=_.useRef(null),Je=_.useRef(0),vt=_.useRef(null),ot=_.useRef(0),nn=_.useRef(0),Jt=_.useRef(0),qt=_.useRef(null),St=_.useRef(null),En=_.useRef(0),gt=_.useRef(null),ss=_.useRef(!1),Ns=_.useRef(!1),ks=_.useRef(!1),as=_.useRef(0),Es=_.useRef(p??null),is=_.useRef({sessionId:p??null,agentId:null,embedded:r}),[Cs,es]=_.useState({}),[qs,Ws]=_.useState({}),[Ks,pr]=_.useState({}),[Fi,qi]=_.useState(0),[Wi,ea]=_.useState(!1),[Ma,ji]=_.useState(!1),[Qa,gr]=_.useState(null),wi=_.useRef(null),Ni=_.useRef(null),_r=_.useRef(null),Ga=_.useRef(null),C=_.useRef(!1),W=_.useRef(!1),He=_.useRef(new Set),tt=_.useCallback(x=>{if(x.length===0)return;const L=x.map(Se=>`${Se}:`),K=Se=>L.some(Ge=>Se.startsWith(Ge));es(Se=>Object.fromEntries(Object.entries(Se).filter(([Ge])=>!K(Ge)))),Ws(Se=>Object.fromEntries(Object.entries(Se).filter(([Ge])=>!K(Ge)))),pr(Se=>Object.fromEntries(Object.entries(Se).filter(([Ge])=>!K(Ge))))},[]),Rt=_.useCallback(x=>{He.current.add(x)},[]),ct=_.useCallback(x=>{He.current.delete(x)},[]),Nt=_.useRef(null),Yn=_.useRef(null),Kn=_.useRef(null),Ya=_.useRef(null),Ra=_.useRef(D),ii=_.useRef(null),Va=_.useRef(null);let ge=HA(P,(Jc=k.data)==null?void 0:Jc.session)??(v==null?void 0:v.session)??null;const gn=(M==null?void 0:M.agent)??null;let ta=(M==null?void 0:M.projects.find(x=>x.id===(ge==null?void 0:ge.project_id)))??(v==null?void 0:v.project);const xo=!!(ge&&ge.project_id===""),xa=(ge==null?void 0:ge.capability.can_show_git)??!1,na=(ge==null?void 0:ge.capability.can_show_terminal)??!1;is.current={sessionId:p??null,agentId:(ge==null?void 0:ge.agent_id)??(gn==null?void 0:gn.id)??w,embedded:r};const sn=_.useCallback(()=>{var L;const x=(ge==null?void 0:ge.agent_id)??(gn==null?void 0:gn.id)??w;return x&&((L=St.current)==null?void 0:L.agentId)===x?Promise.resolve(St.current.target):cn({sessionId:p,agentId:x})},[gn==null?void 0:gn.id,w,ge==null?void 0:ge.agent_id,p]),ri=_.useCallback(async x=>{if(r){y==null||y(x);return}Ea(x),sl(x),gn!=null&&gn.id&&fr(gn.id),await N({to:"/",replace:!0})},[gn==null?void 0:gn.id,r,N,y]),yr=_.useCallback(async()=>{if(r){g==null||g();return}await N({to:"/nodes"})},[r,N,g]),So=x=>x instanceof Element&&!!x.closest('button, textarea, input, a, [role="button"], [role="dialog"]'),Dc=x=>{if(!(x instanceof Element))return!1;const L=x.closest(".conversation-markdown-code-block__pre, .conversation-markdown-table__scroll");return!!(L&&L.scrollWidth-L.clientWidth>1)},jo=x=>So(x)||Dc(x),ki=()=>{const x=ne.current;if(!x)return;const L=()=>{x.scrollTo({top:x.scrollHeight,behavior:"auto"})};L(),window.requestAnimationFrame(()=>{L(),window.requestAnimationFrame(L)})},wo=_.useCallback(()=>{const x=ne.current;return x?x.scrollHeight-x.scrollTop-x.clientHeight<=Ox:!0},[]),ul=_.useCallback(x=>{(x!=null&&x.force||wo())&&ki()},[wo]),kd=()=>{const x=ne.current;if(!x){Be(!1);return}const L=x.scrollHeight-x.scrollTop-x.clientHeight;Be(L>Ox)},Ts=_.useCallback(x=>{j.setQueriesData({queryKey:hs},x)},[j]),Ed=_.useCallback((x,L)=>{j.setQueryData(v5({sessionId:x,scope:{sessionId:x}}),K=>FA(K??void 0,x,L)??K)},[j]),sg=(M==null?void 0:M.projects)??[],vr=(M==null?void 0:M.sessions)??[],ag=(M==null?void 0:M.project_stats)??[],Rh=O[gh]??al,Ah=Q[gh]??al,Pn=_.useMemo(()=>{var x;return(x=ge==null?void 0:ge.subagent)!=null&&x.parent_session_id?vr.find(L=>{var K;return L.id===((K=ge==null?void 0:ge.subagent)==null?void 0:K.parent_session_id)})??null:null},[(Di=ge==null?void 0:ge.subagent)==null?void 0:Di.parent_session_id,vr]),dl=_.useCallback(x=>{const L=x.session_id;L&&(j.setQueryData(ic(L),K=>d5(K,x.entries)),j.setQueryData(["timeline",L],K=>{const Se=ZR(K,x);return Se.view==="full_compact"&&LA(Se),Se}))},[j]),Ih=_.useCallback(x=>{var xt,_n;const L=x.session_id;if(!L)return;const K=is.current.sessionId===L;dl(x.timeline),j.setQueryData(["interactions",L],x.interactions),K&&$e(Cn=>Cn&&x.interactions.some(fs=>fs.id===Cn)?Cn:null),j.setQueryData(["plan",L],x.plan_snapshot),x.change_sets.length>0?(tt(x.change_sets.map(Cn=>Cn.id)),j.setQueryData(["change-sets",L],x.change_sets),Rt(L)):He.current.has(L)||(j.setQueryData(["change-sets",L],[]),ct(L)),j.setQueryData(["session-run-workbench",L],x.run_workbench);const Se=(xt=x.timeline.entries.at(-1))==null?void 0:xt.timestamp,Ge=Se&&(!x.session_patch.last_event_at||+new Date(Se)>+new Date(x.session_patch.last_event_at))?{...x.session_patch,last_event_at:Se}:x.session_patch,bt=Sx(Ge);bt&&Ed(L,bt);const ze=t0(Ge);ze&&Lp(kn.current??void 0,L)&&Ts(Cn=>Ff(Cn,L,ze)),K&&(x.session_patch.run_state==="running"||x.session_patch.run_state==="completed"||x.session_patch.run_state==="idle")&&(de(x.session_patch.run_state==="running"),x.session_patch.run_state!=="running"&&Ae(!1)),K&&((_n=x.run_workbench)!=null&&_n.terminal_snapshot)&&Os(Cn=>{var Ye;const fs=new Set((Ye=x.run_workbench)==null?void 0:Ye.terminal_snapshot.terminals.map(_s=>_s.id)),Rs={};for(const[_s,xs]of Object.entries(Cn))fs.has(_s)&&(Rs[_s]=xs);return Rs}),Pn!=null&&Pn.id&&j.invalidateQueries({queryKey:["timeline",Pn.id,"prefix-source"],exact:!0})},[dl,tt,Ed,Rt,Pn==null?void 0:Pn.id,j,ct]),fl=_.useCallback(async x=>{var Se;if(!p)return null;const L=p;if(((Se=qt.current)==null?void 0:Se.sessionId)===L)return qt.current.promise;const K=(async()=>{var bt;const Ge=++Je.current;mn({state:"recovering"});try{const xt=await(await sn()).client.getSessionBootstrap(p);return Je.current!==Ge?null:(Ih(xt),nn.current=Date.now(),mn({state:"idle"}),xt)}catch(ze){return Je.current!==Ge||mn({state:"failed",error:ze instanceof Error?ze.message:x==="initial"?"会话加载失败。":"会话同步失败。"}),null}finally{((bt=qt.current)==null?void 0:bt.sessionId)===L&&(qt.current=null)}})();return qt.current={sessionId:L,promise:K},K},[Ih,sn,p]),br=_.useCallback(x=>{p&&(Jt.current>0||(Jt.current=Date.now(),fl(x).then(L=>{Pt({sessionId:p,pending:!1,error:L?null:"Unable to load session bootstrap."})}).catch(L=>{Pt({sessionId:p,pending:!1,error:L instanceof Error?L.message:"Unable to load session bootstrap."})})))},[fl,p]),Dh=_.useCallback(async()=>{if(!p||He.current.has(p))return;const L=await(await sn()).client.getSessionChangeSets(p);tt(L.map(K=>K.id)),j.setQueryData(["change-sets",p],L),Rt(p)},[tt,Rt,j,sn,p]),No=_.useCallback(async(x="click")=>{if(!p||Ma)return;const L=ne.current;L&&(Ga.current=L.scrollHeight,C.current=!0),gr(x),ji(!0);const K=Date.now();try{const Ge=await(await sn()).client.getSessionTimeline(p,{view:"full_compact"});dl(Ge)}finally{if(x==="click"){const Se=II-(Date.now()-K);Se>0&&await new Promise(Ge=>{window.setTimeout(Ge,Se)})}ji(!1),qi(0),ea(!1),gr(null)}},[dl,Ma,sn,p]),Cd=_.useCallback(async x=>{if(!p)return;const L=cp(x.changeSetId,x.path,x.itemId);if(!(Cs[L]||Ks[L])){pr(K=>({...K,[L]:!0})),Ws(K=>({...K,[L]:void 0}));try{const Se=await(await sn()).client.getSessionChangeSetFileDiff(p,x);es(Ge=>({...Ge,[L]:Se}))}catch(K){Ws(Se=>({...Se,[L]:K instanceof Error?K.message:"无法读取这个文件的差异详情。"}))}finally{pr(K=>({...K,[L]:!1}))}}},[Cs,Ks,sn,p]),Sa=cs({queryKey:["timeline",p],enabled:!1,queryFn:async()=>BI,initialData:p?OA(p)??j.getQueryData(["timeline",p]):void 0,refetchInterval:!1}),hl=cs({queryKey:ic(p),enabled:!1,queryFn:async()=>[],initialData:[]});_.useEffect(()=>{const x=v==null?void 0:v.optimisticEntry;!p||(v==null?void 0:v.sessionId)!==p||!x||j.setQueryData(ic(p),L=>L!=null&&L.some(K=>K.id===x.id)?L:r0(L,x))},[v,j,p]),_.useEffect(()=>{var L;(v==null?void 0:v.sessionId)!==p||!(((L=k.data)==null?void 0:L.session.id)===p||T!=null&&T.sessions.some(K=>K.id===p))||bE(p)},[T,v==null?void 0:v.sessionId,(Oi=k.data)==null?void 0:Oi.session.id,p]);const Oh=Qm(Sa.data),ml=hl.data??[],Oc=Oh.length>0||ml.length>0||!!(v!=null&&v.optimisticEntry),xr=cs({queryKey:["timeline",Pn==null?void 0:Pn.id,"prefix-source"],enabled:!!(Pn!=null&&Pn.id),queryFn:async()=>(await(await cn({sessionId:Pn.id,projectId:Pn.project_id,agentId:Pn.agent_id})).client.getSessionTimeline(Pn.id,{view:"tail"})).entries,refetchInterval:!1}),Lh=_.useMemo(()=>{const x=Qm(Sa.data);return ge!=null&&ge.subagent?new Set:kD(x)},[ge==null?void 0:ge.subagent,Sa.data]),Lc=_.useMemo(()=>ND(Qm(Sa.data)),[Sa.data]),Td=_.useMemo(()=>ge!=null&&ge.subagent?[]:vr.filter(x=>{var L;return x.id!==p&&((L=x.subagent)==null?void 0:L.parent_session_id)===p&&!x.archived}).filter(x=>{if(x.run_state==="running")return!0;if(!((ge==null?void 0:ge.run_state)==="running"||q))return!1;if(Lh.has(x.id))return!0;if(!Lc)return!1;const L=new Date(Lc).getTime(),K=new Date(x.last_event_at).getTime();return Number.isFinite(L)&&Number.isFinite(K)&&K>=L-MI}).sort((x,L)=>+new Date(L.last_event_at)-+new Date(x.last_event_at)),[Lc,q,Lh,ge==null?void 0:ge.run_state,ge==null?void 0:ge.subagent,p,vr]);_.useEffect(()=>{if(!p){pn.current=null,ks.current=!1,as.current=0,Es.current=null,Pt({sessionId:null,pending:!1,error:null}),Lt({state:"connected",attempt:0,maxAttempts:5});return}const x=!Oc;Pt({sessionId:p,pending:x,error:null}),nn.current=x?0:Date.now(),Jt.current=0},[Oc,p]),_.useEffect(()=>{if(!p||!Zt.pending)return;if(Ke.state==="failed"){br("initial");return}if(Ke.state!=="connected")return;const x=ot.current;if(x<=0)return;const L=window.setTimeout(()=>{nn.current>=x||br("initial")},1200);return()=>{window.clearTimeout(L)}},[Ke.state,Zt.pending,br,p]),_.useEffect(()=>{if(!p||Ke.state!=="connected"||Zt.pending||Oc||!ks.current||Es.current!==p)return;const x=as.current;if(x<=0)return;const L=window.setTimeout(()=>{if(ks.current&&as.current===x){if(nn.current>=x){ks.current=!1,as.current=0,Es.current=null;return}ks.current=!1,as.current=0,Es.current=null,fl("connected")}},1200);return()=>{window.clearTimeout(L)}},[Ke.state,fl,Oc,Zt.pending,p]);const ko=cs({queryKey:["change-sets",p],enabled:!1,queryFn:async()=>p?(await sn()).client.getSessionChangeSets(p):[],initialData:p?j.getQueryData(["change-sets",p])??[]:[],refetchInterval:!1}),li=cs({queryKey:["session-git-workspace",p],enabled:!!(p&&xa&&hn==="git"),queryFn:async()=>(await sn()).client.getSessionGitWorkspace(p),refetchInterval:!1}),oi=cs({queryKey:["session-git-history",p],enabled:!1,queryFn:async()=>(await sn()).client.getSessionGitHistory(p),refetchInterval:!1}),Ei=cs({queryKey:["session-run-workbench",p],enabled:!!p&&na&&(Wn||Jn||hn==="terminal"),queryFn:async()=>p?(await sn()).client.getSessionRunWorkbench(p):null,initialData:p?j.getQueryData(["session-run-workbench",p])??null:null,refetchInterval:!1}),Eo=_.useCallback(async x=>{if(!p)return;const L=["session-run-workbench",p],K=j.getQueryData(L);if(K){j.setQueryData(L,x(K));return}const Ge=await(await sn()).client.getSessionRunWorkbench(p);j.setQueryData(L,x(Ge))},[j,sn,p]),Ki=cs({queryKey:["plan",p],enabled:!1,queryFn:async()=>null,initialData:p?j.getQueryData(["plan",p])??null:null,refetchInterval:!1}),Co=cs({queryKey:["interactions",p],enabled:!1,queryFn:async()=>[],initialData:p?j.getQueryData(["interactions",p])??[]:[],refetchInterval:!1}),pl=_.useCallback(async(x,L)=>{if(p){Os(K=>{var Se,Ge,bt;return{...K,[x]:{chunks:((Se=K[x])==null?void 0:Se.chunks)??[],nextCursor:((Ge=K[x])==null?void 0:Ge.nextCursor)??0,truncated:((bt=K[x])==null?void 0:bt.truncated)??!1,isLoading:!0,error:null}}});try{const K=await sn(),Se=jn.current[x],Ge=await K.client.getSessionTerminalOutput({sessionId:p,terminalId:x,cursor:L!=null&&L.force||Se!=null&&Se.truncated||Se==null?void 0:Se.nextCursor});Os(bt=>{const ze=bt[x],xt=L!=null&&L.force||Ge.truncated||!ze?Ge.chunks:$x(ze.chunks,Ge.chunks);return{...bt,[x]:{chunks:xt,nextCursor:Ge.next_cursor,truncated:Ge.truncated,isLoading:!1,error:null}}})}catch(K){Os(Se=>{var Ge,bt,ze;return{...Se,[x]:{chunks:((Ge=Se[x])==null?void 0:Ge.chunks)??[],nextCursor:((bt=Se[x])==null?void 0:bt.nextCursor)??0,truncated:((ze=Se[x])==null?void 0:ze.truncated)??!1,isLoading:!1,error:K instanceof Error?K.message:"无法读取终端输出。"}}})}}},[p]);_.useEffect(()=>{var Se,Ge;const x=(Se=Ei.data)==null?void 0:Se.terminal_snapshot.active_terminal_id,L=(Ge=Ei.data)==null?void 0:Ge.terminal_snapshot.terminals.find(bt=>bt.id===x);if(!x||!L)return;const K=ws[x];(!K||K.truncated||K.nextCursor<L.output_cursor)&&pl(x)},[pl,Ei.data,ws]);const Md=!!(ge!=null&&ge.subagent&&(Pn!=null&&Pn.id)&&xr.isPending&&!xr.data),gl=_.useMemo(()=>{const x=Qm(Sa.data);return ge!=null&&ge.subagent?Pn!=null&&Pn.id&&xr.isPending&&!xr.data?[]:SD(x,xr.data):x},[Pn==null?void 0:Pn.id,xr.data,xr.isPending,ge==null?void 0:ge.subagent,Sa.data]),_l=_.useMemo(()=>XR(gl,hl.data),[gl,hl.data]);_.useEffect(()=>{p&&window.localStorage.setItem(NI,p)},[p]),_.useEffect(()=>{const x=at.current;x&&((hl.data??[]).some(L=>L.id===x.optimisticEntryId)||(at.current=null))},[hl.data]),_.useEffect(()=>{rn(!1)},[p]),_.useEffect(()=>{V((ge==null?void 0:ge.title)??""),te(!1)},[ge==null?void 0:ge.title,p]),_.useEffect(()=>{Ae(!1)},[p]),_.useEffect(()=>()=>{Ue.current&&window.clearTimeout(Ue.current),Qe.current&&window.clearTimeout(Qe.current),Va.current&&window.cancelAnimationFrame(Va.current)},[]),_.useEffect(()=>{if(Qe.current&&(window.clearTimeout(Qe.current),Qe.current=null),!!zt)return Qe.current=window.setTimeout(()=>{Fe(null),Qe.current=null},DI),()=>{Qe.current&&(window.clearTimeout(Qe.current),Qe.current=null)}},[zt]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(j5,String(m0(D))),window.localStorage.setItem(Wf,Kf)}catch{}},[D]),_.useEffect(()=>{Ra.current=D},[D]),_.useEffect(()=>{if(typeof window>"u")return;const x=()=>{const L=window.innerWidth>=Dx;ye(L),L&&le(!1)};return x(),window.addEventListener("resize",x),()=>{window.removeEventListener("resize",x)}},[]),_.useEffect(()=>{if(!je)return;const x=K=>{const Se=Ya.current;if(!Se)return;const Ge=K.clientX-Se.startX,bt=m0(Se.startWidth+Ge);ii.current=bt,Va.current===null&&(Va.current=window.requestAnimationFrame(()=>{Va.current=null;const ze=ii.current,xt=ae.current;ze===null||!xt||xt.style.setProperty("--desktop-sidebar-width",`${ze}px`)}))},L=()=>{Va.current!==null&&(window.cancelAnimationFrame(Va.current),Va.current=null);const K=ii.current??Ra.current;ii.current=null,Ya.current=null,z(!1),Ra.current=K,oe(K)};return window.addEventListener("pointermove",x),window.addEventListener("pointerup",L),window.addEventListener("pointercancel",L),()=>{window.removeEventListener("pointermove",x),window.removeEventListener("pointerup",L),window.removeEventListener("pointercancel",L)}},[je]),_.useEffect(()=>{const x=L=>{const K=L.target;tn(!1),Ne(!1),!(K instanceof Element&&(K.closest(".conversation-topbar__actions")||K.closest(".conversation-topbar__title-actions")||K.closest(".picker-sheet")||K.closest(".picker-sheet-wrap")))&&(we(!1),Sn(!1),js(!1))};return window.addEventListener("pointerdown",x),()=>{window.removeEventListener("pointerdown",x)}},[]),_.useEffect(()=>{const x=ae.current;if(!x||ue)return;const L=bt=>{const ze=bt.touches[0];bt.touches.length!==1||!ze||jo(bt.target)||(Yn.current={startX:ze.clientX,startY:ze.clientY})},K=bt=>{if(bt.touches.length!==1)return;const ze=bt.touches[0];if(!Kn.current){const _n=Yn.current;if(!_n)return;const Cn=ze.clientX-_n.startX,fs=ze.clientY-_n.startY;if(Math.abs(Cn)<8&&Math.abs(fs)<8)return;if(Math.abs(Cn)<=Math.abs(fs)){Yn.current=null;return}xl(_n.startX,_n.startY)}Qc(ze.clientX,ze.clientY)&&bt.preventDefault()},Se=bt=>{if(Yn.current=null,!Kn.current)return;const ze=bt.changedTouches[0];if(!ze){Kn.current=null,fi(null);return}Zi(ze.clientX,ze.clientY)},Ge=()=>{Yn.current=null,Kn.current=null,fi(null)};return x.addEventListener("touchstart",L,{passive:!0,capture:!0}),x.addEventListener("touchmove",K,{passive:!1,capture:!0}),x.addEventListener("touchend",Se,{capture:!0}),x.addEventListener("touchcancel",Ge,{capture:!0}),()=>{x.removeEventListener("touchstart",L,{capture:!0}),x.removeEventListener("touchmove",K,{capture:!0}),x.removeEventListener("touchend",Se,{capture:!0}),x.removeEventListener("touchcancel",Ge,{capture:!0})}},[ue,X]),_.useEffect(()=>{const x=ne.current;if(!x)return;if(C.current&&Ga.current!==null){const K=Ga.current,Se=x.scrollHeight;x.scrollTop+=Math.max(0,Se-K),C.current=!1,Ga.current=null;return}if(!p||!W.current||gl.length===0)return;ki();const L=window.setTimeout(()=>{ki(),W.current=!1},120);return()=>{window.clearTimeout(L)}},[gl.length,p]),_.useEffect(()=>{const x=ne.current;if(!x)return;const L=()=>{kd()};return L(),x.addEventListener("scroll",L,{passive:!0}),window.addEventListener("resize",L),()=>{x.removeEventListener("scroll",L),window.removeEventListener("resize",L)}},[gl.length,p]),_.useEffect(()=>{const x=ne.current;if(!x)return;const L=Sa.data,K=Gm(L)&&!Ma,Se=()=>{wi.current=null,Ni.current=null,qi(0),ea(!1)},Ge=()=>{const Cn=K&&Ni.current!==null&&Fi>=l_;Se(),Cn&&No("pull")},bt=Cn=>{var fs,Rs;!K||Cn.touches.length!==1||x.scrollTop>0||So(Cn.target)||(wi.current=((fs=Cn.touches[0])==null?void 0:fs.clientX)??null,Ni.current=((Rs=Cn.touches[0])==null?void 0:Rs.clientY)??null)},ze=Cn=>{if(Cn.defaultPrevented)return;const fs=wi.current,Rs=Ni.current;if(fs===null||Rs===null||Cn.touches.length!==1)return;const Ye=Cn.touches[0],_s=((Ye==null?void 0:Ye.clientX)??fs)-fs,xs=((Ye==null?void 0:Ye.clientY)??Rs)-Rs;if(Math.abs(_s)>Math.abs(xs)){Se();return}if(xs<=0){qi(0),ea(!1);return}if(x.scrollTop>0){Se();return}Cn.cancelable&&Cn.preventDefault(),ea(!0),qi(Math.min(Lx,xs))},xt=()=>{Ge()},_n=()=>{Se()};return x.addEventListener("touchstart",bt,{passive:!0}),x.addEventListener("touchmove",ze,{passive:!1}),x.addEventListener("touchend",xt),x.addEventListener("touchcancel",_n),()=>{x.removeEventListener("touchstart",bt),x.removeEventListener("touchmove",ze),x.removeEventListener("touchend",xt),x.removeEventListener("touchcancel",_n)}},[Ma,No,Fi,Sa.data]),_.useEffect(()=>{var bt,ze;if(!p){gt.current!==null&&(clearTimeout(gt.current),gt.current=null),(bt=St.current)==null||bt.stream.setSessionId(null);return}let x=!1;const L=++En.current,K=is.current.agentId,Se=()=>{gt.current!==null&&(clearTimeout(gt.current),gt.current=null)},Ge=()=>{r||(Se(),gt.current=setTimeout(()=>{gt.current=null;const xt=is.current;qf(j,{scope:{sessionId:xt.sessionId,agentId:xt.agentId},selectedSessionId:xt.sessionId})},OI))};return K&&((ze=St.current)==null?void 0:ze.agentId)===K?(St.current.stream.setSessionId(p),()=>{x=!0}):(sn().then(xt=>{var fs,Rs;if(x||En.current!==L)return;const _n=xt.client.getConnectionKey();if(((fs=St.current)==null?void 0:fs.key)===_n){St.current.stream.setSessionId(p);return}(Rs=St.current)==null||Rs.stream.close(),ss.current=!1,Ns.current=!1;const Cn=xt.client.createEventStream(Ye=>{var iu,ru,Jd,ef,Yh,lu,ou,cu,Qs,rs,qo,Rl,Wo,uu,mi,Ko,du,fu,tf,nf,sf,af,rf,lf;const _s=typeof((iu=Ye.payload)==null?void 0:iu.sessionId)=="string"?Ye.payload.sessionId:null,xs=is.current.sessionId,wn=_s===xs?xs:null,Xn=typeof((ru=Ye.payload)==null?void 0:ru.projectId)=="string"?Ye.payload.projectId:null;if(Ye.type==="agent.online"){if(Ns.current){Ns.current=!1;return}Z(),Ge();return}if(Ye.type==="timeline.reset"&&wn){nn.current=Date.now(),ks.current=!1,as.current=0,Es.current=null,Pt({sessionId:wn,pending:!1,error:null});const pt=Array.isArray((Jd=Ye.payload)==null?void 0:Jd.entries)?Ye.payload.entries:[],yn=typeof((ef=Ye.payload)==null?void 0:ef.hasEarlierEntries)=="boolean"?Ye.payload.hasEarlierEntries:Gm(j.getQueryData(["timeline",wn]));dl(Qx(wn,pt,yn));const Hn=(Yh=pt[pt.length-1])==null?void 0:Yh.timestamp;Hn&&Ts(vn=>n0(vn,wn,Hn)),window.requestAnimationFrame(kd);return}if(Ye.type==="interaction.reset"&&wn){const pt=Array.isArray((lu=Ye.payload)==null?void 0:lu.requests)?Ye.payload.requests:[];j.setQueryData(["interactions",wn],pt),$e(yn=>yn&&pt.some(Hn=>Hn.id===yn)?yn:null);return}if(Ye.type==="plan.reset"&&wn){const pt=(ou=Ye.payload)!=null&&ou.planSnapshot&&typeof Ye.payload.planSnapshot=="object"?Ye.payload.planSnapshot:null;j.setQueryData(["plan",wn],pt);return}if(Ye.type==="timeline.delta"&&wn){const pt=Array.isArray((cu=Ye.payload)==null?void 0:cu.entries)?Ye.payload.entries:[],yn=typeof((Qs=Ye.payload)==null?void 0:Qs.hasEarlierEntries)=="boolean"?Ye.payload.hasEarlierEntries:Gm(j.getQueryData(["timeline",wn]));dl(Qx(wn,u5(void 0,pt),yn));const Hn=(rs=pt[pt.length-1])==null?void 0:rs.timestamp;Hn&&Ts(vn=>n0(vn,wn,Hn)),ul(),window.requestAnimationFrame(kd);return}if(Ye.type==="interaction.delta"&&wn){const pt=Array.isArray((qo=Ye.payload)==null?void 0:qo.requests)?Ye.payload.requests:[],yn=Array.isArray((Rl=Ye.payload)==null?void 0:Rl.resolvedRequestIds)?Ye.payload.resolvedRequestIds.filter(Hn=>typeof Hn=="string"&&Hn.trim().length>0):[];j.setQueryData(["interactions",wn],Hn=>{const vn=new Map((Hn??[]).map(Zn=>[Zn.id,Zn]));for(const Zn of pt)vn.set(Zn.id,Zn);for(const Zn of yn)vn.delete(Zn);return[...vn.values()].sort((Zn,pi)=>+new Date(pi.updated_at)-+new Date(Zn.updated_at))}),yn.length>0&&$e(Hn=>Hn&&yn.includes(Hn)?null:Hn);return}if(Ye.type==="plan.delta"&&wn){const pt=(Wo=Ye.payload)!=null&&Wo.planSnapshot&&typeof Ye.payload.planSnapshot=="object"?Ye.payload.planSnapshot:null;j.setQueryData(["plan",wn],pt);return}if(Ye.type==="changeset.reset"&&wn){const pt=Array.isArray((uu=Ye.payload)==null?void 0:uu.changeSets)?Ye.payload.changeSets:[];pt.length>0?(tt(pt.map(yn=>yn.id)),j.setQueryData(["change-sets",wn],pt),Rt(wn)):He.current.has(wn)||(j.setQueryData(["change-sets",wn],[]),ct(wn));return}if(Ye.type==="changeset.delta"&&wn){const pt=Array.isArray((mi=Ye.payload)==null?void 0:mi.changeSets)?Ye.payload.changeSets:[];tt(pt.map(yn=>yn.id)),j.setQueryData(["change-sets",wn],yn=>yD(yn,pt));return}if(Ye.type==="terminal.snapshot"&&wn){const pt=(Ko=Ye.payload)!=null&&Ko.snapshot&&typeof Ye.payload.snapshot=="object"?Ye.payload.snapshot:null;if(!pt)return;j.setQueryData(["session-run-workbench",wn],yn=>yn&&{...yn,terminal_snapshot:pt}),Os(yn=>{const Hn=new Set(pt.terminals.map(Zn=>Zn.id)),vn={};for(const[Zn,pi]of Object.entries(yn))Hn.has(Zn)&&(vn[Zn]=pi);return vn});return}if(Ye.type==="terminal.delta"&&wn){const pt=(du=Ye.payload)!=null&&du.terminal&&typeof Ye.payload.terminal=="object"?Ye.payload.terminal:null,yn=Array.isArray((fu=Ye.payload)==null?void 0:fu.chunks)?Ye.payload.chunks:[],Hn=typeof((tf=Ye.payload)==null?void 0:tf.activeTerminalId)=="string"?Ye.payload.activeTerminalId:null;if(!pt)return;j.setQueryData(["session-run-workbench",wn],vn=>{if(!vn)return vn;const Zn=vn.terminal_snapshot.terminals.filter(hu=>hu.id!==pt.id),pi=vn.terminal_snapshot.terminals.findIndex(hu=>hu.id===pt.id),Qo=[...Zn];return pi<=0?Qo.unshift(pt):Qo.splice(pi,0,pt),{...vn,terminal_snapshot:{...vn.terminal_snapshot,active_terminal_id:Hn,updated_at:pt.updated_at,terminals:Qo}}}),Os(vn=>{var pi;if(yn.length===0)return vn;const Zn=vn[pt.id];return{...vn,[pt.id]:{chunks:$x((Zn==null?void 0:Zn.chunks)??[],yn),nextCursor:typeof((pi=Ye.payload)==null?void 0:pi.nextCursor)=="number"?Ye.payload.nextCursor:pt.output_cursor,truncated:(Zn==null?void 0:Zn.truncated)??!1,isLoading:!1,error:null}}});return}if(Ye.type==="thread.updated"&&Xn){const pt=typeof((nf=Ye.payload)==null?void 0:nf.action)=="string"?Ye.payload.action:"",yn=(sf=Ye.payload)!=null&&sf.projectPatch&&typeof Ye.payload.projectPatch=="object"?Ye.payload.projectPatch:null,Hn=Array.isArray((af=Ye.payload)==null?void 0:af.orderedProjectIds)?Ye.payload.orderedProjectIds.filter(vn=>typeof vn=="string"&&vn.trim().length>0):[];if((pt==="pin"||pt==="unpin"||pt==="rename")&&yn){Ts(vn=>Wu(vn,Xn,yn));return}if(pt==="reorder"&&Hn.length>0){Ts(vn=>Up(vn,Hn));return}if(pt==="remove"||pt==="archive"){Z(),Ts(vn=>zp(vn,Xn));return}if(pt==="unarchive"){Z(),Ge();return}}if(Ye.type==="session.updated"&&_s){const pt=(rf=Ye.payload)!=null&&rf.sessionPatch&&typeof Ye.payload.sessionPatch=="object"?t0(Ye.payload.sessionPatch):null,yn=(lf=Ye.payload)!=null&&lf.sessionPatch&&typeof Ye.payload.sessionPatch=="object"?Sx(Ye.payload.sessionPatch):null;yn&&Ed(_s,yn);const Hn=Lp(kn.current??void 0,_s);if(pt&&Hn)Ts(vn=>Ff(vn,_s,pt));else{if(is.current.embedded&&_s===xs&&!kn.current)return;if(Hn)return;Ge()}wn&&((pt==null?void 0:pt.run_state)==="running"||(pt==null?void 0:pt.run_state)==="completed"||(pt==null?void 0:pt.run_state)==="idle")&&(de(pt.run_state==="running"),pt.run_state!=="running"&&Ae(!1));return}Ye.type==="turn.completed"&&wn&&(de(!1),Ae(!1),j.setQueryData(["plan",wn],null))},{sessionId:p,reconnectWhenHidden:!0,onStatus:Ye=>{if(Lt(Ye),Ye.state==="connected"){const _s=Date.now(),xs=ss.current;ot.current=_s,ks.current=xs,as.current=xs?_s:0,Es.current=xs?p:null,Ns.current=!0,xs&&(Z(),Ge()),ss.current=!0,Ne(!1);return}Je.current+=1,mn({state:"idle"})}});St.current={key:_n,agentId:K,target:xt,stream:Cn},Cn.setSessionId(p)}).catch(xt=>{x||En.current!==L||Lt({state:"failed",attempt:0,maxAttempts:5,error:xt instanceof Error?xt.message:"Unable to connect to live session."})}),()=>{x=!0})},[r,sn,p]),_.useEffect(()=>()=>{var x;En.current+=1,gt.current!==null&&(clearTimeout(gt.current),gt.current=null),(x=St.current)==null||x.stream.close(),St.current=null},[]),_.useEffect(()=>{if(!p||(ge==null?void 0:ge.run_state)!=="running"||ge.context_usage)return;if(vt.current!==p){vt.current=p;return}let x=!1;const L=window.setTimeout(()=>{x||k.refetch()},1200);return()=>{x=!0,window.clearTimeout(L)}},[p,ge==null?void 0:ge.context_usage,ge==null?void 0:ge.run_state,k.refetch]),_.useEffect(()=>{var Ge,bt;if(!p||!I||!ge||!ta&&!xo||((Ge=k.data)==null?void 0:Ge.session.id)===p||k.isFetching||pn.current===p||typeof window>"u")return;pn.current=p;const x=window,L=()=>{k.refetch()},K=(bt=x.requestIdleCallback)==null?void 0:bt.call(x,L,{timeout:1500}),Se=K===void 0?window.setTimeout(L,320):null;return()=>{var ze;K!==void 0&&((ze=x.cancelIdleCallback)==null||ze.call(x,K)),Se!==null&&window.clearTimeout(Se)}},[ta,ge,(Cl=k.data)==null?void 0:Cl.session.id,k.isFetching,k.refetch,I,p]),_.useEffect(()=>{we(!1)},[ue,p]);const Ph=_.useCallback(x=>{var L;Bt(x),((L=x.effect)==null?void 0:L.type)==="set_session_model"&&(Xt(x.effect.model),x.effect.reasoning_effort&&qe(x.effect.reasoning_effort))},[]),Qi=Gn({mutationFn:async x=>(await sn()).client.sendSessionInput(x),onMutate:async x=>{await j.cancelQueries({queryKey:["timeline",x.sessionId]}),Fe(null),Ae(!1),de(!0),an(x.proposedPlanEntryId??null);const L=x.clearComposer!==!1;L&&(De(""),pe([])),Ue.current&&window.clearTimeout(Ue.current);const K=new Date().toISOString(),Se=`${uy}${x.sessionId}:${Date.now()}`;at.current=L?{optimisticEntryId:Se,draft:x.input,attachments:x.attachments}:null,j.setQueryData(ic(x.sessionId),Ge=>r0(Ge,{id:Se,kind:"user",title:"你",body:x.input,body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:K,accent:"primary",attachments:l5(x.attachments)})),Ts(Ge=>Ff(Ge,x.sessionId,{run_state:"running",run_state_changed_at:K,last_event_at:K}))},onSuccess:async(x,L)=>{an(null),L.proposedPlanEntryId&&st(K=>{const Se={...K};return delete Se[L.proposedPlanEntryId],Se}),await j.invalidateQueries({queryKey:hs}),await j.invalidateQueries({queryKey:["plan",L.sessionId]}),await j.invalidateQueries({queryKey:["change-sets",L.sessionId]}),Ue.current=null},onError:(x,L)=>{an(null),de(!1);const K=at.current;K&&(j.setQueryData(ic(L.sessionId),Se=>JR(Se,K.optimisticEntryId)),De(Se=>Se||K.draft),pe(Se=>Se.length>0?Se:K.attachments),at.current=null),Fe(x instanceof Error?x.message:"无法发送消息")}}),Pc=Gn({mutationFn:async x=>(await sn()).client.executeSessionCommand(x),onMutate:x=>{Fe(null),De(""),pe([]);const L=x.input.slice(1).trim().split(/\s+/)[0]??"",K=new Date().toISOString();Bt({panel_id:`command-panel-pending-${Date.now()}`,session_id:x.sessionId,command_name:L,command_text:x.input,title:`正在执行 /${L}`,description:null,status:"running",body:"命令执行中…",submitted_at:K,updated_at:K,input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null})},onSuccess:async x=>{Ph(x.panel),await j.invalidateQueries({queryKey:hs})},onError:(x,L)=>{Bt(null),De(K=>K||L.input),Fe(x instanceof Error?x.message:"无法执行命令")}}),yl=Gn({mutationFn:async x=>(await sn()).client.respondToSessionCommand(x),onMutate:()=>{Fe(null)},onSuccess:async x=>{Ph(x.panel),await j.invalidateQueries({queryKey:hs})},onError:x=>{Fe(x instanceof Error?x.message:"无法继续执行命令")}}),Uh=Gn({mutationFn:async x=>(await sn()).client.respondToSessionInteraction(x),onMutate:async x=>{Fe(null),$e(x.requestId),j.setQueryData(["interactions",x.sessionId],L=>(L??[]).map(K=>K.id===x.requestId?{...K,status:"submitting",updated_at:new Date().toISOString()}:K))},onSuccess:async(x,L)=>{await j.invalidateQueries({queryKey:["interactions",L.sessionId]})},onError:(x,L)=>{j.setQueryData(["interactions",L.sessionId],K=>(K??[]).map(Se=>Se.id===L.requestId?{...Se,status:"pending"}:Se)),$e(null),Fe(x instanceof Error?x.message:"无法提交确认回复")}}),ds=Gn({mutationFn:async x=>(await sn()).client.interruptSession(x),onMutate:async x=>{Fe(null),Ae(!0),de(!1),Ue.current&&(window.clearTimeout(Ue.current),Ue.current=null);const L=new Date().toISOString();Ts(K=>Ff(K,x,{run_state:"completed",run_state_changed_at:L,last_event_at:L})),j.setQueryData(["plan",x],null)},onSuccess:(x,L)=>{Ae(!1),j.invalidateQueries({queryKey:hs}),j.invalidateQueries({queryKey:["timeline",L]}),j.invalidateQueries({queryKey:["change-sets",L]})},onError:(x,L)=>{Ae(!1),de(!0),j.invalidateQueries({queryKey:hs}),j.invalidateQueries({queryKey:["plan",L]}),Fe(x instanceof Error?x.message:"无法中断会话")}});_.useEffect(()=>{!p||!ge||ce||ds.isPending||de(ge.run_state==="running")},[ds.isPending,ce,ge,ge==null?void 0:ge.run_state,p]);const Vn=Gn({mutationFn:async x=>(await cn({sessionId:x.sessionId})).client.updateSession(x)}),To=Gn({mutationFn:async x=>(await cn({projectId:x.projectId,agentId:x.agentId})).client.updateThread(x)}),ha=Gn({mutationFn:async x=>(await sn()).client.executeSessionGitAction({sessionId:p,action:x.action,path:x.path,branch:x.branch,message:x.message}),onMutate:async()=>{On(null)},onSuccess:(x,L)=>{j.setQueryData(["session-git-workspace",p],x.workspace),(L.action==="commit-all"||L.action==="switch-branch")&&j.invalidateQueries({queryKey:["session-git-history",p]})},onError:x=>{On(x instanceof Error?x.message:"无法执行 git 操作")}}),Mo=Gn({mutationFn:async x=>(await sn()).client.executeSessionTurnAction({sessionId:p,turnId:x.turnId,action:"rollback"}),onMutate:()=>{Kt(null)},onSuccess:x=>{Kt(null),us(L=>({...L,[x.turn_id]:!0})),j.setQueryData(["session-git-workspace",p],x.workspace)},onError:(x,L)=>{Kt({turnId:L.turnId,message:x instanceof Error?x.message:"无法回滚这轮改动"})}}),ci=Gn({mutationFn:async x=>(await sn()).client.saveSessionRunCommand({sessionId:p,action:x.action,commandId:x.commandId,command:x.command}),onMutate:()=>{Ot(null)},onSuccess:async({catalog:x})=>{await Eo(L=>({...L,command_catalog:x}))},onError:x=>{Ot(x instanceof Error?x.message:"无法保存项目命令。")}}),Xa=Gn({mutationFn:async x=>(await sn()).client.saveSessionRunWebsite({sessionId:p,action:x.action,websiteId:x.websiteId,website:x.website}),onMutate:()=>{Ot(null)},onSuccess:async({catalog:x})=>{await Eo(L=>({...L,website_catalog:x}))},onError:x=>{Ot(x instanceof Error?x.message:"无法保存项目网页。")}}),Uc=Gn({mutationFn:async()=>(await sn()).client.generateSessionRunCommand({sessionId:p,prompt:"",model:lp()}),onMutate:()=>{Ot(null),da(null)},onSuccess:async({generation:x,catalog:L})=>{await Eo(K=>({...K,command_catalog:L})),da(x.reason)},onError:x=>{Ot(x instanceof Error?x.message:"无法一键生成项目命令。")}}),Ci=Gn({mutationFn:async()=>(await sn()).client.generateSessionRunWebsite({sessionId:p,prompt:"",model:lp()}),onMutate:()=>{Ot(null),In(null)},onSuccess:async({generation:x,catalog:L})=>{await Eo(K=>({...K,website_catalog:L})),In(x.reason)},onError:x=>{Ot(x instanceof Error?x.message:"无法一键生成项目网页。")}}),ms=Gn({mutationFn:async x=>(await sn()).client.executeSessionTerminalAction({sessionId:p,action:x.action,commandId:x.commandId,terminalId:x.terminalId}),onMutate:()=>{Ot(null)},onSuccess:async(x,L)=>{j.setQueryData(["session-run-workbench",p],K=>K&&{...K,terminal_snapshot:x.snapshot}),(L.action==="run-command"||L.action==="run-kill-command")&&x.terminal&&(Sn(!1),ns("terminal"),await pl(x.terminal.id,{force:!0})),L.action==="focus"&&L.terminalId&&await pl(L.terminalId),L.action==="close"&&L.terminalId&&Os(K=>{const Se={...K};return delete Se[L.terminalId],Se})},onError:x=>{Ot(x instanceof Error?x.message:"无法执行终端操作。")}}),Gi=ko.data??[],zc=ge&&_D(Sa.data)!=="tail"?HD(ge):!1,Ro=_.useMemo(()=>FD(_l,{projectPath:ta==null?void 0:ta.path,compactCompletedTurns:zc}),[zc,ta==null?void 0:ta.path,_l]),Ti=_.useMemo(()=>GD(Ro.blocks,Gi),[Ro.blocks,Gi]),Sr=_.useMemo(()=>{const x=Sa.data,L=Gm(x),K=Math.max(0,Math.min(Lx,Fi)),Se=Math.max(0,Math.min(1,K/l_));return{hasEarlierEntries:L,canLoadEarlierEntries:L,isPulling:Wi,pullDistance:K,isReadyToLoad:K>=l_,isLoadingFull:Ma,indicatorOffset:Ma?u0:Math.min(u0,K*.75),indicatorRotation:Ma?Px:Math.round(Se*Px),triggerSource:Qa}},[Ma,Wi,Qa,Fi,Sa.data]),jr=[...Ti].reverse().find(x=>x.kind==="turn"&&!x.turn.completion)??null;_.useEffect(()=>{var Se;if(typeof window>"u")return;const x=window,L=(Se=x.requestIdleCallback)==null?void 0:Se.call(x,()=>{d0()},{timeout:1500}),K=L===void 0?window.setTimeout(()=>{d0()},320):null;return()=>{var Ge;L!==void 0&&((Ge=x.cancelIdleCallback)==null||Ge.call(x,L)),K!==null&&window.clearTimeout(K)}},[]);const Ao=!!(ge&&(ta||xo)),wr=!!p&&k.isPending&&!ge;ge??(ge=UI),ta??(ta=LI);const Rd=!!p&&Zt.sessionId!==p,Ad=!!p&&!Ao&&(Zt.pending||Rd||wr),zh=Ad?"正在载入会话…":k.error instanceof Error?k.error.message:Zt.error?Zt.error:"没有找到这个会话。",Id=ge.capability.can_send_input&&!ce,Dd=Id&&(i===void 0||i==="online"),Bc=(Co.data??[]).filter(x=>x.status==="pending"||x.status==="submitting"),Od=(ge.run_state==="running"||q)&&!ce||ds.isPending,Io=Id&&Bc.length===0&&!Od&&!Qi.isPending,Do=(gn==null?void 0:gn.id)??ge.agent_id,Aa=_.useCallback((x,L)=>{st(K=>{if(!L.trim()){if(!(x in K))return K;const Se={...K};return delete Se[x],Se}return{...K,[x]:L}})},[]),Oo=_.useCallback((x,L)=>{const K=L.trim();!K||!Io||Qi.mutate({sessionId:ge.id,input:K,attachments:[],model:Gt,reasoningEffort:Ft,serviceTier:dt?"fast":void 0,planMode:$t,yoloMode:Nn,clearComposer:!1,proposedPlanEntryId:x})},[Io,dt,$t,Nn,Gt,Ft,Qi,ge.id]),ja=_.useCallback(x=>{Mo.mutate({turnId:x})},[Mo]),Nr=Mo.isPending?((eu=Mo.variables)==null?void 0:eu.turnId)??null:null,Ld=_.useMemo(()=>a.jsx(ZD,{sessionId:ge.id,sessions:vr,sessionRunState:ge.run_state,isDesktopSidebar:r?!!o:ue,projectPath:ta.path,renderedBlocks:Ti,lastToolGroupId:Ro.lastToolGroupId,sessionChangeSets:Gi,isSubagentTimelinePending:Md,isInitialTimelinePending:!!p&&_l.length===0&&(Zt.pending||Rd),hasTimeline:_l.length>0,proposedPlanReplyDrafts:rt,pendingProposedPlanReplyEntryId:Dt,canRespondToProposedPlan:Io,onProposedPlanReplyDraftChange:Aa,onSubmitProposedPlanReply:Oo,onPreviewImage:Ze,changeSetDiffs:Cs,changeSetDiffErrors:qs,loadingChangeSetDiffKeys:Ks,onLoadSessionChangeSets:Dh,onLoadChangeSetFileDiff:Cd,onLoadFullTimeline:()=>{No()},timelineLoadState:Sr,canRollbackChangeSets:xa,pendingRollbackTurnId:Nr,rollbackTurnError:Ss,rolledBackTurnIds:Zs,onRollbackTurn:ja},ge.id),[xa,Io,qs,Cs,Aa,Oo,r,ue,o,Md,Dh,Cd,No,Ks,ja,Dt,ta.path,rt,Ti,Ro.lastToolGroupId,Nr,Ss,Zs,ge.id,ge.run_state,Gi,vr,_l.length,Sr]),ui=_.useCallback(async(x,L,K)=>{var Se;Fe(null),we(!1),L==="pin"||L==="unpin"?ra.flushSync(()=>{Ts(Ge=>Pp(Ge,x,{pinned:L==="pin"}))}):L==="rename"&&(K!=null&&K.trim())&&Ts(Ge=>Pp(Ge,x,{title:K.trim()}));try{const Ge=await Vn.mutateAsync({sessionId:x,action:L,name:K}),bt=(Se=Ge.affectedSessionIds)!=null&&Se.length?Ge.affectedSessionIds:[x];if(L==="delete"){Ts(ze=>p3(ze,bt)),Z();for(const ze of bt)j.removeQueries({queryKey:["timeline",ze],exact:!0}),j.removeQueries({queryKey:ic(ze),exact:!0}),j.removeQueries({queryKey:["change-sets",ze],exact:!0}),ct(ze)}else Ts(ze=>m3(ze,bt,{...L==="rename"&&(K!=null&&K.trim())?{title:K.trim()}:{pinned:L==="pin"}}));if(x===ge.id&&L==="delete"){const ze=Ge.nextSessionId;ze?await ri(ze):await yr()}}catch(Ge){j.invalidateQueries({queryKey:hs}),Fe(Ge instanceof Error?Ge.message:"无法更新会话")}},[yr,ri,j,Z,ct,ge.id,Vn]),$c=_.useCallback(async(x,L,K)=>{var Ge,bt;Fe(null),we(!1);const Se=(Ge=K==null?void 0:K.name)==null?void 0:Ge.trim();L==="pin"||L==="unpin"?ra.flushSync(()=>{Ts(ze=>Wu(ze,x,{pinned:L==="pin"}))}):L==="rename"&&Se?Ts(ze=>Wu(ze,x,{display_name:Se})):L==="reorder"&&((bt=K==null?void 0:K.orderedProjectIds)!=null&&bt.length)?Ts(ze=>Up(ze,K.orderedProjectIds??[])):L==="remove"||L==="archive"?(Ts(ze=>zp(ze,x)),Z()):L==="unarchive"&&(Z(),j.invalidateQueries({queryKey:hs}));try{const ze=await To.mutateAsync({projectId:x,agentId:(gn==null?void 0:gn.id)??ge.agent_id,action:L,name:K==null?void 0:K.name,orderedProjectIds:K==null?void 0:K.orderedProjectIds});if(L==="remove"||L==="archive"||L==="unarchive"){const xt=ze.nextSessionId;xt?await ri(xt):await yr()}}catch(ze){j.invalidateQueries({queryKey:hs}),Fe(ze instanceof Error?ze.message:"无法更新线程")}},[yr,ri,j,Z,To]),Hc=_.useCallback(async x=>{Do&&(fr(Do),Ea(null),sl(null),Hu(x),await N({to:"/"}))},[Do,N]),kr=((tu=Ki.data)==null?void 0:tu.steps.some(x=>x.status==="pending"||x.status==="in_progress"))??!1,Pd=ge.run_state==="running"||q,Fc=!!((Tl=Ki.data)!=null&&Tl.updated_at&&Date.now()-new Date(Ki.data.updated_at).getTime()<=TI),vl=Ki.data&&(kr||Pd&&Fc)?Ki.data:null,Za=ge.context_usage,ma=Za?Math.round(Za.percent_used):0,Ud=Math.max(0,100-ma),Mi=Za?{"--usage-progress":`${Math.max(0,Math.min(100,Za.percent_used))}%`}:void 0,Bh=Ke.state==="connected"&&At.state==="idle"&&Pd&&!ce&&!ds.isPending&&!(jr!=null&&jr.turn.completion),qc=!!Pn||Td.length>0;_.useEffect(()=>{p&&(Je.current+=1,mn({state:"idle"}))},[p]),_.useEffect(()=>{if(!Ee)return;(Co.data??[]).some(L=>L.id===Ee&&L.status==="submitting")||$e(null)},[Co.data,Ee]),_.useEffect(()=>{var x;!p||!Ao||ge.run_state==="running"||Qi.isPending||ds.isPending||jr||(x=Ki.data)!=null&&x.is_active||(Ue.current&&(window.clearTimeout(Ue.current),Ue.current=null),de(!1))},[jr,Ao,ds.isPending,(Ml=Ki.data)==null?void 0:Ml.is_active,Qi.isPending,ge,ge==null?void 0:ge.run_state,p]);const Ls=ue?0:YD(),zd=ue||X,Bd=ue?0:Pe??(X?Ls:0),$d=Re&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{te(!1),V(ge.title)},"aria-label":"关闭重命名会话面板"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered",children:[a.jsx("div",{className:"sheet-panel__title",children:"重命名会话"}),a.jsx("input",{className:"sheet-panel__input",value:ve,onChange:x=>V(x.target.value),placeholder:"输入会话名称",autoFocus:!0}),a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{te(!1),V(ge.title)},children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:!ve.trim()||Vn.isPending&&((Vd=Vn.variables)==null?void 0:Vd.sessionId)===ge.id,onClick:()=>{ui(ge.id,"rename",ve.trim()),te(!1)},children:"保存"})]})]})})]}),document.body):null,$h=!(r?o:ue)&&re&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"picker-sheet-wrap",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"picker-sheet__scrim",onClick:()=>we(!1),"aria-label":"关闭会话操作菜单"}),a.jsxs("div",{className:"picker-sheet",children:[a.jsx("div",{className:"picker-sheet__header",children:a.jsx("strong",{children:ge.title})}),a.jsxs("div",{className:"picker-sheet__list",children:[a.jsx("button",{type:"button",className:"picker-sheet__item",disabled:Vn.isPending&&((Xd=Vn.variables)==null?void 0:Xd.sessionId)===ge.id,onClick:()=>void ui(ge.id,ge.pinned?"unpin":"pin"),children:a.jsx("span",{children:ge.pinned?"取消置顶会话":"置顶会话"})}),a.jsx("button",{type:"button",className:"picker-sheet__item",disabled:Vn.isPending&&((Dr=Vn.variables)==null?void 0:Dr.sessionId)===ge.id,onClick:()=>{we(!1),te(!0)},children:a.jsx("span",{children:"重命名会话"})}),a.jsx("button",{type:"button",className:"picker-sheet__item is-danger",disabled:Vn.isPending&&((Fo=Vn.variables)==null?void 0:Fo.sessionId)===ge.id,onClick:()=>void ui(ge.id,"delete"),children:a.jsx("span",{children:"删除会话"})})]})]})]}),document.body):null,Ia=ue?1:Ls>0?Bd/Ls:0,Er=!ue&&Pe!==null,bl=ue?{"--desktop-sidebar-width":`${D}px`}:void 0,Ms=r?!!o:ue,Cr=r?u:Bd,pa=r?d:Er,Da=ha.isPending?ha.variables??null:null,Yi=oa??(li.error instanceof Error?li.error.message:null),di=oi.error instanceof Error?oi.error.message:null,wa=Ln??(Ei.error instanceof Error?Ei.error.message:null),ps=Ei.data??null,Ja=(ps==null?void 0:ps.terminal_snapshot)??null,Ri=(ps==null?void 0:ps.command_catalog.commands)??[],Wc=(ps==null?void 0:ps.website_catalog.websites)??[],Kc=Fp(lp(),Et),bs=(Ja==null?void 0:Ja.terminals.find(x=>x.id===Ja.active_terminal_id))??(Ja==null?void 0:Ja.terminals[0])??null,Un=na&&hn==="terminal",en=xa&&hn==="git",ga=Ms&&Un&&Xs,Oa=en&&Ms,Tr=(Un||en)&&Ms&&!ga,Vi=(Un||en)&&!Ms,Hd=ms.isPending&&((Zd=ms.variables)==null?void 0:Zd.action)==="run-command"?ms.variables.commandId??null:null,Hh=ms.isPending&&((nu=ms.variables)==null?void 0:nu.action)==="run-kill-command"?ms.variables.commandId??null:null,Mr=ci.isPending&&((su=ci.variables)==null?void 0:su.action)==="delete"?ci.variables.commandId??null:null,Xi=Xa.isPending&&((_a=Xa.variables)==null?void 0:_a.action)==="delete"?Xa.variables.websiteId??null:null;_.useEffect(()=>{!Ms&&Xs&&$s(!1)},[Xs,Ms]);const fi=x=>{Nt.current=x,ht(x)},xl=(x,L,K)=>(Kn.current={mode:X?"close":"open",startX:x,startY:L,axis:"pending",pointerId:K},!0),Qc=(x,L)=>{const K=Kn.current;if(!K)return!1;const Se=x-K.startX,Ge=L-K.startY;if(K.axis==="pending"){if(Math.abs(Se)<8&&Math.abs(Ge)<8)return!1;if(K.axis=Math.abs(Se)>Math.abs(Ge)?"x":"y",K.axis==="y")return Kn.current=null,fi(null),!1}const bt=K.mode==="open"?Math.max(0,Math.min(Ls,Se)):Math.max(0,Math.min(Ls,Ls+Se));return fi(bt),!0},Zi=(x,L)=>{const K=Kn.current;if(!K)return;const Se=x-K.startX,Ge=L-K.startY;if(K.axis==="pending"&&Math.abs(Ge)>48){Kn.current=null,fi(null);return}const ze=(K.axis==="x"?Nt.current??(K.mode==="open"?Math.max(0,Math.min(Ls,Se)):Math.max(0,Math.min(Ls,Ls+Se))):X?Ls:0)>=Ls*kI;le(ze),Kn.current=null,fi(null)},hi=_.useCallback(()=>{if(r){m==null||m();return}le(!0)},[r,m]),Ji=_.useCallback(()=>{Ne(x=>!x)},[]),Ai=_.useCallback(()=>{Fe(null)},[]),Fd=_.useCallback(()=>{rn(x=>!x)},[]),qd=_.useCallback(x=>{ri(x)},[ri]),Rr=_.useCallback(x=>{const L=new Date().toISOString();if(Et.length===0){Bt({panel_id:`${o_}${Date.now()}`,session_id:ge.id,command_name:"model",command_text:x,title:"选择模型",description:"选择后会更新当前会话后续发送时使用的模型。",status:"completed",body:"当前没有可选模型,请先去设置页维护模型列表。",submitted_at:L,updated_at:L,input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null});return}Bt({panel_id:`${o_}${Date.now()}`,session_id:ge.id,command_name:"model",command_text:x,title:"选择模型",description:"选择后会更新当前会话后续发送时使用的模型。",status:"awaiting_input",body:"在下面选择一个模型。",submitted_at:L,updated_at:L,input_type:"choice",options:Et.map(K=>({id:K.value,label:K.label,description:K.description??null})),input_placeholder:null,submit_label:null,effect:null})},[Et,ge.id]),Gc=_.useCallback(()=>{if(Dd){if(hy(be)){if(se.length>0){Fe("命令暂不支持附件,请先移除附件后再执行。");return}if(uD(be)==="model"){Fe(null),De(""),Rr(be);return}Pc.mutate({sessionId:ge.id,input:be});return}Qi.mutate({sessionId:ge.id,input:be.trim(),attachments:se,model:Gt,reasoningEffort:Ft,serviceTier:dt?"fast":void 0,planMode:$t,yoloMode:Nn})}},[Dd,be,dt,$t,Nn,Pc,Rr,se,Gt,Ft,Qi,ge.id]),Ar=_.useCallback(()=>{Bt(null)},[]),Ps=_.useCallback(x=>{if(kt){if(kt.panel_id.startsWith(o_)){Xt(x),Bt(L=>L&&{...L,status:"completed",body:`后续消息将优先使用 ${Fp(x,Et)}。`,updated_at:new Date().toISOString(),input_type:"none",options:[]});return}yl.mutate({sessionId:ge.id,panelId:kt.panel_id,optionId:x})}},[kt,yl,Et,ge.id]),Yc=_.useCallback(x=>{kt&&yl.mutate({sessionId:ge.id,panelId:kt.panel_id,text:x})},[kt,yl,ge.id]),Fh=_.useCallback(x=>{Uh.mutate({sessionId:ge.id,requestId:x.requestId,optionId:x.optionId??null,text:x.text??null,answers:x.answers})},[Uh,ge.id]),ig=_.useCallback(x=>{const L=[...x];L.length!==0&&(Fe(null),Promise.all(L.map(K=>cy(K))).then(K=>{pe(Se=>[...Se,...K])}).catch(K=>{Fe(K instanceof Error?K.message:"无法读取附件")}))},[]),rg=_.useCallback(x=>{pe(L=>L.filter(K=>K.id!==x))},[]),lg=_.useCallback(()=>{ds.isPending||ce||ds.mutate(ge.id)},[ds,ce,ge.id]),gs=_.useCallback(()=>{tn(x=>!x)},[]),er=_.useCallback(x=>{x==="git"&&!xa||x==="terminal"&&!na||(On(null),Ot(null),Sn(!1),js(!1),$s(!1),ns(x))},[xa,na]);_.useEffect(()=>{if(!Tr)return;const x=L=>{var Se,Ge;const K=L.target;K instanceof Node&&((Se=Ce.current)!=null&&Se.contains(K)||(Ge=R.current)!=null&&Ge.contains(K)||er("code"))};return window.addEventListener("pointerdown",x),()=>{window.removeEventListener("pointerdown",x)}},[er,Tr]);const Lo=_.useCallback(()=>{On(null),li.refetch()},[li]),Po=_.useCallback(()=>{oi.refetch()},[oi]),Wd=_.useCallback(()=>{oi.data||oi.isFetching||oi.refetch()},[oi]),Sl=_.useCallback(x=>{ha.mutate({action:"discard-file",path:x})},[ha]),jl=_.useCallback(()=>{ha.mutate({action:"discard-all"})},[ha]),og=_.useCallback(x=>{ha.mutate({action:"commit-all",message:x})},[ha]),qh=_.useCallback(async(x,L)=>{On(null);const K=(L==null?void 0:L.trim())??"";K&&await ha.mutateAsync({action:"commit-all",message:K}),await ha.mutateAsync({action:"switch-branch",branch:x})},[ha]),cg=_.useCallback(()=>{ha.mutate({action:"push"})},[ha]),Wh=_.useCallback(async(x,L,K)=>(await sn()).client.getSessionGitHistoryFileDiff(ge.id,{commitOid:x,path:L,previousPath:K}),[sn,ge.id]),Ir=_.useCallback(async(x,L)=>(await sn()).client.getSessionGitWorkspaceFileDiff(ge.id,{path:x,previousPath:L}),[sn,ge.id]),Vc=_.useCallback(x=>{ms.mutate({action:"run-command",commandId:x})},[ms]),Uo=_.useCallback(async()=>{if(!(Ri.length===0||Hs||Fs)){ca(!0);try{for(const x of Ri)await ms.mutateAsync({action:"run-command",commandId:x.id})}finally{ca(!1)}}},[Hs,Fs,Ri,ms]),Kd=_.useCallback(async()=>{if(Hs||Fs)return;const x=Ri.filter(L=>!!L.kill_command);if(x.length!==0){Js(!0);try{for(const L of x)await ms.mutateAsync({action:"run-kill-command",commandId:L.id})}finally{Js(!1)}}},[Hs,Fs,Ri,ms]),wl=_.useCallback(x=>{ms.mutate({action:"run-kill-command",commandId:x})},[ms]),Xc=_.useCallback(x=>{ci.mutate({action:x.commandId?"update":"create",commandId:x.commandId,command:x.draft})},[ci]),zo=_.useCallback(x=>{ci.mutate({action:"delete",commandId:x})},[ci]),Bo=_.useCallback(()=>{Uc.mutate()},[Uc]),Qd=_.useCallback(x=>{Xa.mutate({action:x.websiteId?"update":"create",websiteId:x.websiteId,website:x.draft})},[Xa]),Gd=_.useCallback(x=>{Xa.mutate({action:"delete",websiteId:x})},[Xa]),tr=_.useCallback(()=>{Ci.mutate()},[Ci]),nr=_.useCallback(()=>{js(!1)},[]),Kh=_.useCallback(x=>{ms.mutate({action:"focus",terminalId:x}),ns("terminal")},[ms]),Qh=_.useCallback(x=>{ms.mutate({action:"close",terminalId:x})},[ms]),Nl=_.useCallback(()=>{!Ms||!na||(ns("terminal"),$s(x=>!x))},[na,Ms]),kl=_.useMemo(()=>{var x,L,K;return a.jsxs("div",{className:"conversation-topbar__title-actions",children:[a.jsx("button",{type:"button",className:"conversation-topbar__more",onClick:()=>we(Se=>!Se),"aria-label":"更多会话选项",children:a.jsx($I,{})}),re&&Ms?a.jsxs("div",{className:"topbar-menu",role:"menu",children:[a.jsx("button",{type:"button",className:"topbar-menu__item",disabled:Vn.isPending&&((x=Vn.variables)==null?void 0:x.sessionId)===ge.id,onClick:()=>void ui(ge.id,ge.pinned?"unpin":"pin"),children:ge.pinned?"取消置顶会话":"置顶会话"}),a.jsx("button",{type:"button",className:"topbar-menu__item",disabled:Vn.isPending&&((L=Vn.variables)==null?void 0:L.sessionId)===ge.id,onClick:()=>{we(!1),te(!0)},children:"重命名会话"}),a.jsx("button",{type:"button",className:"topbar-menu__item is-danger",disabled:Vn.isPending&&((K=Vn.variables)==null?void 0:K.sessionId)===ge.id,onClick:()=>void ui(ge.id,"delete"),children:"删除会话"})]}):null]})},[ui,re,Ms,ge.id,ge.pinned,Vn.isPending,(Na=Vn.variables)==null?void 0:Na.sessionId]),$o=_.useMemo(()=>na||xa?a.jsxs("div",{className:"conversation-topbar__actions",children:[na?a.jsxs("div",{className:"conversation-topbar__run-group",children:[a.jsx("button",{type:"button",className:`conversation-topbar__run-button ${Wn?"is-active":""}`,onClick:()=>{js(!1),Sn(x=>!x)},"aria-expanded":Wn,"aria-haspopup":"dialog","aria-label":"打开项目命令列表",children:a.jsx(KI,{})}),Wn?a.jsx("div",{className:"conversation-run-popover",role:"dialog","aria-label":"项目命令列表",children:a.jsx(oI,{commands:Ri,nodeRuntime:(ps==null?void 0:ps.node_runtime)??null,error:wa,pendingRunCommandId:Hd,pendingKillCommandId:Hh,pendingDeleteCommandId:Mr,isSaving:ci.isPending,isGenerating:Uc.isPending,isStartingAll:Hs,isStoppingAll:Fs,generationReason:ua,executionModelLabel:Kc,onRun:Vc,onRunAll:Uo,onRunAllKill:Kd,onRunKill:wl,onSave:Xc,onDelete:zo,onGenerate:Bo})}):null]}):null,na?a.jsxs("div",{className:"conversation-topbar__run-group",children:[a.jsx("button",{type:"button",className:`conversation-topbar__run-button ${Jn?"is-active":""}`,onClick:()=>{Sn(!1),js(x=>!x)},"aria-expanded":Jn,"aria-haspopup":"dialog","aria-label":"打开项目网页列表",children:a.jsx(QI,{})}),Jn?a.jsx("div",{className:"conversation-run-popover",role:"dialog","aria-label":"项目网页列表",children:a.jsx(mI,{websites:Wc,error:wa,pendingDeleteWebsiteId:Xi,isSaving:Xa.isPending,isGenerating:Ci.isPending,generationReason:fa,executionModelLabel:Kc,onOpen:nr,onSave:Qd,onDelete:Gd,onGenerate:tr})}):null]}):null,na||xa?a.jsxs("div",{ref:R,className:"conversation-topbar__view-toggle","aria-label":"切换工作台面板",children:[a.jsx("button",{type:"button",className:`conversation-topbar__view-button ${hn==="code"?"is-active":""}`,onClick:()=>er("code"),"aria-pressed":hn==="code","aria-label":"切换到代码会话视图",children:a.jsx(FI,{})}),na?a.jsx("button",{type:"button",className:`conversation-topbar__view-button ${hn==="terminal"?"is-active":""}`,onClick:()=>er("terminal"),"aria-pressed":hn==="terminal","aria-label":"切换到终端视图",children:a.jsx(WI,{})}):null,xa?a.jsx("button",{type:"button",className:`conversation-topbar__view-button ${hn==="git"?"is-active":""}`,onClick:()=>er("git"),"aria-pressed":hn==="git","aria-label":"切换到 git 视图",children:a.jsx(qI,{})}):null]}):null]}):null,[hn,xa,na,ua,fa,Hs,Fs,Kc,Uc.isPending,Ci.isPending,zo,Bo,Gd,tr,nr,Vc,Uo,Kd,Xc,Qd,er,Wn,Jn,Mr,Xi,Hd,Ri,Wc,wa,ci.isPending,Xa.isPending]),Ho=a.jsx(sI,{workspace:li.data??null,history:oi.data??null,isLoading:li.isPending,isHistoryLoading:oi.isFetching,error:Yi,historyError:di,onRefresh:Lo,onRefreshHistory:Po,onRequestHistory:Wd,onDiscardFile:Sl,onDiscardAll:jl,onCommitAll:og,onSwitchBranch:qh,onPush:cg,onLoadWorkspaceFileDiff:Ir,onLoadHistoryFileDiff:Wh,pendingAction:Da,compact:Oa}),Zc=a.jsx(jI,{terminals:(Ja==null?void 0:Ja.terminals)??[],activeTerminalId:(bs==null?void 0:bs.id)??null,outputs:ws,error:wa,compact:Tr||ga,canToggleFullscreen:Ms,isFullscreen:ga,onSelectTerminal:Kh,onCloseTerminal:Qh,onToggleFullscreen:Nl}),Gh=a.jsx(p5,{isDesktopSidebar:Ms,sidebarShift:Cr,isSidebarDragging:pa,composerError:zt,onDismissComposerError:Ai,interactionRequests:Bc,pendingInteractionRequestId:Ee,onRespondInteraction:Fh,parentSession:Pn,backgroundAgentSessions:Td,isBackgroundAgentsOpen:Le,planSnapshot:vl,onToggleBackgroundAgents:Fd,onOpenSession:qd,getBackgroundAgentStatusLabel:ED,getBackgroundAgentAccent:wD,formatBackgroundAgentsLabel:vD,hasBackgroundAgentStrip:qc,commandPanel:kt,isCommandPanelPending:Pc.isPending||yl.isPending,onDismissCommandPanel:Ar,onCommandPanelOptionSelect:Ps,onCommandPanelTextSubmit:Yc,projectId:ge.project_id,agentId:(gn==null?void 0:gn.id)??ge.agent_id,draft:be,pendingAttachments:se,canSendInput:Id,canSubmitInput:Dd,isInputLocked:Bc.length>0,readOnlyPlaceholder:Bc.length>0?"请先处理上方确认请求":void 0,onDraftChange:De,onUploadFiles:ig,onRemoveAttachment:rg,onSubmit:Gc,showStopIcon:Od,isSendPending:Qi.isPending||Pc.isPending||yl.isPending,onInterrupt:lg,isFastModeEnabled:dt,isPlanModeEnabled:$t,isYoloModeEnabled:Nn,onToggleFastMode:()=>un(x=>!x),onTogglePlanMode:()=>An(x=>!x),onToggleYoloMode:()=>Tt(x=>!x),showModeBadges:!0,selectedModel:Gt,modelOptions:Et,selectedReasoning:Ft,onSelectModel:Xt,onSelectReasoning:x=>qe(x),contextUsage:Za,isContextUsageOpen:Xe,onToggleContextUsage:gs,contextUsageRingStyle:Mi,usedPercent:ma,remainingPercent:Ud,usedTokensLabel:qx((Za==null?void 0:Za.used_tokens)??0),totalTokensLabel:qx((Za==null?void 0:Za.total_tokens)??0),showJumpToBottom:ee,onJumpToBottom:ki}),sr=Un?Zc:Ho,Yd=Vi||ga,Ii=Yd?a.jsxs("div",{ref:he,className:`conversation-main ${Ms?"has-desktop-sidebar":""} ${ga?"is-terminal-fullscreen":""}`,style:{transform:`translateX(${Cr}px)`,transition:pa?"none":void 0},children:[a.jsxs("div",{className:"conversation-topbar",children:[Ms?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:hi,"aria-label":"打开侧边栏",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]}),a.jsx("div",{className:"conversation-topbar__meta",children:a.jsxs("div",{className:"conversation-topbar__title-row",children:[a.jsx("h1",{children:ge.title}),kl]})}),$o]}),a.jsx("div",{ref:ne,className:`conversation-scroll ${Yd?"conversation-scroll--workbench":""}`,children:a.jsx("div",{className:`session-workbench-surface ${ga?"is-terminal-fullscreen":""}`,children:sr})})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`session-detail-workspace ${Tr?"has-workbench-panel":""}`,children:[a.jsx(wI,{conversationMainRef:he,conversationScrollRef:ne,isDesktopSidebar:Ms,sidebarShift:Cr,isSidebarDragging:pa,title:ge.title,titleActions:kl,topbarActions:$o,onOpenSidebar:hi,threadContent:Ld,connectionStatus:Ke,sessionRecoveryStatus:At,isConnectionDetailOpen:U,onToggleConnectionDetail:Ji,showThinkingStatus:Bh}),Tr?a.jsx("aside",{ref:Ce,className:"session-workbench-rail",children:sr}):null]}),ga?null:Gh]}),El=a.jsxs(a.Fragment,{children:[$d,$h,ke&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"attachment-lightbox",role:"dialog","aria-modal":"true","aria-label":`预览 ${ke.label}`,children:[a.jsx("button",{type:"button",className:"attachment-lightbox__scrim",onClick:()=>Ze(null),"aria-label":"关闭图片预览"}),a.jsxs("div",{className:"attachment-lightbox__panel",children:[a.jsx("button",{type:"button",className:"attachment-lightbox__close",onClick:()=>Ze(null),"aria-label":"关闭图片预览",children:a.jsx(HI,{})}),a.jsx("div",{className:"attachment-lightbox__frame",children:a.jsx("img",{src:ke.src,alt:ke.label,className:"attachment-lightbox__image"})}),a.jsxs("div",{className:"attachment-lightbox__meta",children:[a.jsx("div",{className:"attachment-lightbox__title",children:ke.label}),a.jsx("div",{className:"attachment-lightbox__hint",children:ke.meta})]})]})]}),document.body):null]});if(!Ao){const x=a.jsx("div",{className:"conversation-main conversation-main--empty",children:Ad?a.jsxs("div",{className:"empty-panel empty-panel--loading",role:"status","aria-live":"polite","aria-busy":"true",children:[a.jsxs("span",{className:"empty-panel__loading-dots","aria-hidden":"true",children:[a.jsx("span",{className:"empty-panel__loading-dot"}),a.jsx("span",{className:"empty-panel__loading-dot"}),a.jsx("span",{className:"empty-panel__loading-dot"})]}),a.jsx("span",{className:"sr-only",children:"正在加载会话"})]}):a.jsx("div",{className:"empty-panel",children:zh})});return r?a.jsxs(a.Fragment,{children:[x,El]}):a.jsxs("div",{className:"conversation-page",children:[x,El]})}return r?a.jsxs(a.Fragment,{children:[Ii,El]}):a.jsxs("div",{ref:ae,className:`conversation-page ${ue?"has-desktop-sidebar":""}`,style:bl,onPointerDown:x=>{ue||x.pointerType!=="touch"&&(x.pointerType==="mouse"&&x.button!==0||jo(x.target)||(xl(x.clientX,x.clientY,x.pointerId),x.currentTarget.setPointerCapture(x.pointerId)))},onPointerMove:x=>{if(ue||x.pointerType==="touch")return;const L=Kn.current;!L||L.pointerId!==x.pointerId||!Qc(x.clientX,x.clientY)||x.preventDefault()},onPointerUp:x=>{if(ue||x.pointerType==="touch")return;const L=Kn.current;!L||L.pointerId!==x.pointerId||Zi(x.clientX,x.clientY)},onPointerCancel:x=>{if(ue||x.pointerType==="touch")return;const L=Kn.current;!L||L.pointerId!==x.pointerId||(Kn.current=null,fi(null))},children:[a.jsx(a5,{open:zd,progress:Ia,isDragging:Er,desktopPinned:ue,isDesktopResizing:je,onClose:()=>{ue||(le(!1),fi(null))},onDesktopResizeStart:x=>{ii.current=Ra.current,Ya.current={startX:x,startWidth:Ra.current},z(!0)},currentAgent:gn??void 0,agentIndicatorState:gn?i??(gn.status==="online"?"online":"offline"):void 0,projects:sg,sessions:vr,projectStats:ag,historySessionsByProject:Object.fromEntries(Object.entries(O).map(([x,L])=>[x,L.sessions])),archivedSessionsByProject:Object.fromEntries(Object.entries(Q).map(([x,L])=>[x,L.sessions])),chatHistorySessions:Rh.sessions,chatArchivedSessions:Ah.sessions,historyPageStateByProject:O,archivedPageStateByProject:Q,chatHistoryPageState:Rh,chatArchivedPageState:Ah,activeSessionId:ge.id,onCreateSession:x=>{Hc(x)},onCreateChat:()=>{Hc(Gr)},onSessionAction:ui,onThreadAction:$c,onLoadMoreHistory:x=>{J(x)},onLoadMoreChatHistory:()=>{F()},onLoadMoreArchived:x=>{B(x)},onLoadMoreChatArchived:()=>{G()},pendingSessionActionId:Vn.isPending?((Li=Vn.variables)==null?void 0:Li.sessionId)??null:null,pendingThreadActionId:To.isPending?((au=To.variables)==null?void 0:au.projectId)??null:null}),Ii,El]})},eO=({mode:e,agentName:t,agentStatus:i,onOpenNodes:r,onCreateThread:o})=>{if(e==="node")return a.jsxs("section",{className:"session-empty-state is-node-mode",children:[a.jsx("div",{className:"session-empty-state__eyebrow",children:"Panda Workspace"}),a.jsx("div",{className:"session-empty-state__actions",children:a.jsx("button",{type:"button",className:"session-empty-state__button is-primary",onClick:r,children:"选择节点"})})]});const u=i==="online";return a.jsxs("section",{className:"session-empty-state is-session-mode",children:[a.jsxs("div",{className:"session-empty-state__status-row",children:[a.jsx("span",{className:`session-empty-state__status-dot is-${u?"online":"offline"}`,"aria-hidden":"true"}),a.jsxs("div",{className:"session-empty-state__eyebrow",children:["节点 · ",t??"当前节点"]})]}),a.jsxs("div",{className:"session-empty-state__actions",children:[o?a.jsx("button",{type:"button",className:"session-empty-state__button is-primary",onClick:o,children:"新建会话"}):null,a.jsx("button",{type:"button",className:"session-empty-state__button",onClick:r,children:"切换节点"})]})]})},Yx=1100,D5="panda:desktop-sidebar-width",Qf="panda:desktop-sidebar-width-version",Gf="2026-03-24-narrow",tO=300,O5=232,Ou=O5,nO=460,f_=.4,sO=56,aO=56,iO=160,Vx=5,rO=_.lazy(async()=>({default:(await cl(()=>import("./session-file-preview-page-B5cY0GxO.js").then(t=>t.s),__vite__mapDeps([2,1]))).SessionFilePreviewPage})),Xx=e=>{const t=new Date((e==null?void 0:e.generated_at)??"").getTime();return Number.isFinite(t)?t:0},lO=(e,t)=>{var r;if(!t)return;let i;for(const[,o]of e)!o||!(((r=o.agent)==null?void 0:r.id)===t||o.projects.some(d=>d.agent_id===t)||o.sessions.some(d=>d.agent_id===t))||(!i||Xx(o)>Xx(i))&&(i=o);return i},oO=()=>typeof window>"u"?248:Math.max(0,Math.min(248,window.innerWidth-84)),cO=()=>typeof window>"u"?0:Math.max(window.innerWidth,0),p0=e=>Math.max(O5,Math.min(nO,e)),uO=()=>{if(typeof window>"u")return Ou;try{const e=window.localStorage.getItem(D5),t=window.localStorage.getItem(Qf);if(!e)return window.localStorage.setItem(Qf,Gf),Ou;const i=Number(e);if(!Number.isFinite(i))return window.localStorage.setItem(Qf,Gf),Ou;const o=t!==Gf||i===tO||i>Ou?Ou:i;return window.localStorage.setItem(Qf,Gf),p0(o)}catch{return Ou}},L5=()=>{var ws,Os;const e=qa(ee=>ee.openSettingsOverlay),{agentId:t}=Mc({strict:!1}),i=Hi(),r=Ka(),o=_.useRef(null),[u,d]=_.useState(()=>vo()),[m,y]=_.useState(()=>SE()??Rp()),[g,b]=_.useState(()=>jE()),[p,v]=_.useState(()=>wE()?"directory-picker":"composer"),[w,N]=_.useState(!1),[j,T]=_.useState(!1),[M,P]=_.useState(()=>typeof window<"u"&&window.innerWidth>=Yx),[I,k]=_.useState(()=>uO()),[O,Q]=_.useState(!1),[J,F]=_.useState({state:"connected",attempt:0,maxAttempts:Vx}),[B,G]=_.useState(null),[Z,ae]=_.useState(null),he=_.useRef(null),ne=_.useRef(null),Ce=_.useRef(null),R=_.useRef(null),X=_.useRef(null),le=_.useRef(I),ue=_.useRef(null),ye=_.useRef(null),D=_.useRef(null),oe=_.useRef(0),je=_.useRef(null),z=_.useRef(!1),be=_.useRef(!1),De=_.useRef(!1),se=_.useRef(null),pe=_.useRef(null),ke=t??u??null,Ze=ke?{agentId:ke}:void 0,Fe=r.getQueryData(s0({scope:Ze}))??lO(r.getQueriesData({queryKey:hs}),ke),kt=m&&!(Fe!=null&&Fe.sessions.some(ee=>ee.id===m))?m:null,Bt=_.useRef({agentId:ke,selectedSessionIdHint:kt});kh(ke);const Gt=oy({enabled:!1}),Xt=Gt.data,Ft=e5({scope:Ze,selectedSessionId:kt,enabled:!!ke}),qe=Ft.data??Fe,{historyState:dt,archivedState:un,loadMoreHistory:$t,loadMoreProjectlessHistory:An,loadMoreArchived:Nn,loadMoreProjectlessArchived:Tt,reset:lt}=n5({scope:Ze,selectedSessionId:m??null}),Et=[...Object.values(dt).flatMap(ee=>ee.sessions),...Object.values(un).flatMap(ee=>ee.sessions)];_.useEffect(()=>{t&&(d(t),fr(t),y(null))},[t]),_.useEffect(()=>{qe&&(d(ee=>{var Be;return ee&&(((Be=qe.agent)==null?void 0:Be.id)===ee||Xt!=null&&Xt.agents.some(Ke=>Ke.id===ee))?ee:null}),y(ee=>ee&&(qe.sessions.some(Be=>Be.id===ee)||Et.some(Be=>Be.id===ee)||Ft.isPending||Ft.isFetching||Ft.isError)?ee:null))},[Xt==null?void 0:Xt.agents,Et,qe,Ft.isError,Ft.isFetching,Ft.isPending]),_.useEffect(()=>{t||u||(A6(),i({to:"/nodes",replace:!0}))},[i,t,u]),_.useEffect(()=>{if(!qe||t||!u||m)return;const ee=Rp(),Be=qe.sessions.find(Ke=>Ke.id===ee)??null;Be&&(y(Be.id),Ea(Be.id))},[t,u,m,qe]);const rt=(ke?(Xt==null?void 0:Xt.agents.find(ee=>ee.id===ke))??null:null)??null,st=_.useMemo(()=>{const ee=(qe==null?void 0:qe.agent)??(rt?{id:rt.id,name:rt.name,display_name:rt.display_name,status:rt.status}:null);if(!ee)return null;const Be=(rt==null?void 0:rt.status)??ee.status,Ke=(rt==null?void 0:rt.name)??ee.name,Lt=(rt==null?void 0:rt.display_name)??ee.display_name;return ee.status===Be&&ee.name===Ke&&ee.display_name===Lt?ee:{...ee,name:Ke,display_name:Lt,status:Be}},[rt,qe==null?void 0:qe.agent]),Dt=st?XM(st.status,J.state):void 0,an=(qe==null?void 0:qe.projects)??[],re=(qe==null?void 0:qe.sessions)??[],we=(qe==null?void 0:qe.project_stats)??[],Re=dt[gh]??al,te=un[gh]??al,ve=m?re.find(ee=>ee.id===m)??null:null,V=ve?an.find(ee=>ee.id===ve.project_id)??null:null,q=!!(ve&&V);_.useEffect(()=>{T(!1),ae(null),ne.current=null},[ve==null?void 0:ve.id,V==null?void 0:V.id]);const de=!!ke&&!st&&(Gt.isPending||Gt.isFetching||Ft.isPending||Ft.isFetching),ce=!!m&&!re.some(ee=>ee.id===m)&&(Ft.isPending||Ft.isFetching),Ae=de||ce,Ee=(ve==null?void 0:ve.id)??(Ae?m??null:null);Bt.current={agentId:(st==null?void 0:st.id)??ke,selectedSessionIdHint:kt},_.useEffect(()=>{const ee=(rt==null?void 0:rt.status)??null,Be=se.current;se.current=ee;const Ke=(ke==null?void 0:ke.trim())??"";if(!Ke||ee!=="online"){ee!=="online"&&(pe.current=null);return}if(!(Be!=="online"||!qe))return;const Zt=`${Ke}:${Be!=="online"?"online":"missing"}:${kt??""}`;pe.current!==Zt&&(pe.current=Zt,qf(r,{scope:{agentId:Ke},selectedSessionId:kt}))},[ke,rt==null?void 0:rt.status,r,qe,kt]),_.useEffect(()=>{var Zt;if(!Bt.current.agentId){je.current!==null&&(clearTimeout(je.current),je.current=null),(Zt=D.current)==null||Zt.stream.close(),D.current=null,z.current=!1,be.current=!1,De.current=!1;return}let ee=!1;const Be=++oe.current,Ke=()=>{je.current!==null&&(clearTimeout(je.current),je.current=null)},Lt=Pt=>{const At=(Pt==null?void 0:Pt.includeHubDirectory)??!1;Ke(),je.current=setTimeout(()=>{je.current=null;const mn=Bt.current,jn=[qf(r,{scope:mn.agentId?{agentId:mn.agentId}:void 0,selectedSessionId:mn.selectedSessionIdHint})];At&&jn.unshift(y3(r)),Promise.allSettled(jn)},iO)};return cn({agentId:Bt.current.agentId}).then(Pt=>{var jn,kn;if(ee||oe.current!==Be)return;const At=Pt.client.getConnectionKey();if(((jn=D.current)==null?void 0:jn.key)===At)return;(kn=D.current)==null||kn.stream.close(),z.current=!1,be.current=!1,De.current=!1;const mn=Pt.client.createEventStream(pn=>{var Ue,Qe,at,Je,vt,ot;const U=typeof((Ue=pn.payload)==null?void 0:Ue.sessionId)=="string"?pn.payload.sessionId:null,Ne=typeof((Qe=pn.payload)==null?void 0:Qe.projectId)=="string"?pn.payload.projectId:null;if(pn.type==="agent.online"){if(De.current){De.current=!1;return}lt(),Lt({includeHubDirectory:!0});return}if(pn.type==="thread.updated"&&Ne){const nn=typeof((at=pn.payload)==null?void 0:at.action)=="string"?pn.payload.action:"",Jt=(Je=pn.payload)!=null&&Je.projectPatch&&typeof pn.payload.projectPatch=="object"?pn.payload.projectPatch:null,qt=Array.isArray((vt=pn.payload)==null?void 0:vt.orderedProjectIds)?pn.payload.orderedProjectIds.filter(St=>typeof St=="string"&&St.trim().length>0):[];if((nn==="pin"||nn==="unpin"||nn==="rename")&&Jt){r.setQueriesData({queryKey:hs},St=>Wu(St,Ne,Jt));return}if(nn==="reorder"&&qt.length>0){r.setQueriesData({queryKey:hs},St=>Up(St,qt));return}if(nn==="remove"||nn==="archive"){lt(),r.setQueriesData({queryKey:hs},St=>zp(St,Ne));return}if(nn==="unarchive"){lt();const St=Bt.current;qf(r,{scope:St.agentId?{agentId:St.agentId}:void 0,selectedSessionId:St.selectedSessionIdHint});return}}if(pn.type==="session.updated"&&U){const nn=(ot=pn.payload)!=null&&ot.sessionPatch&&typeof pn.payload.sessionPatch=="object"?t0(pn.payload.sessionPatch):null,Jt=Bt.current,qt=r.getQueryData(s0({scope:Jt.agentId?{agentId:Jt.agentId}:void 0,selectedSessionId:Jt.selectedSessionIdHint})),St=Lp(qt,U);if(nn&&St){r.setQueriesData({queryKey:hs},En=>Ff(En,U,nn));return}if(St)return;qf(r,{scope:Jt.agentId?{agentId:Jt.agentId}:void 0,selectedSessionId:Jt.selectedSessionIdHint})}},{onStatus:pn=>{if(F(pn),pn.state==="connected"){De.current=!0,z.current&&be.current&&(be.current=!1,lt(),Lt({includeHubDirectory:Pt.mode==="hub"})),z.current=!0;return}z.current&&(be.current=!0)}});D.current={key:At,stream:mn}}).catch(Pt=>{ee||oe.current!==Be||F({state:"failed",attempt:0,maxAttempts:Vx,error:Pt instanceof Error?Pt.message:"无法建立节点工作区连接"})}),()=>{ee=!0}},[st==null?void 0:st.id,st==null?void 0:st.status,ke,r,lt]),_.useEffect(()=>()=>{var ee;oe.current+=1,je.current!==null&&(clearTimeout(je.current),je.current=null),(ee=D.current)==null||ee.stream.close(),D.current=null},[]),_.useEffect(()=>{le.current=I},[I]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(D5,String(p0(I))),window.localStorage.setItem(Qf,Gf)}catch{}},[I]),_.useEffect(()=>{if(typeof window>"u")return;const ee=()=>{const Be=window.innerWidth>=Yx;P(Be),Be&&(N(!1),G(null))};return ee(),window.addEventListener("resize",ee),()=>{window.removeEventListener("resize",ee)}},[]),_.useEffect(()=>{if(!O)return;const ee=Ke=>{const Lt=X.current;if(!Lt)return;const Zt=Ke.clientX-Lt.startX,Pt=p0(Lt.startWidth+Zt);ue.current=Pt,ye.current===null&&(ye.current=window.requestAnimationFrame(()=>{ye.current=null;const At=ue.current;At!==null&&k(At)}))},Be=()=>{ye.current!==null&&(window.cancelAnimationFrame(ye.current),ye.current=null);const Ke=ue.current??le.current;ue.current=null,X.current=null,Q(!1),le.current=Ke,k(Ke)};return window.addEventListener("pointermove",ee),window.addEventListener("pointerup",Be),()=>{window.removeEventListener("pointermove",ee),window.removeEventListener("pointerup",Be)}},[O]),_.useEffect(()=>()=>{ye.current!==null&&window.cancelAnimationFrame(ye.current)},[]);const $e=Gn({mutationFn:async ee=>{const Be=tn(ee.sessionId);return(await cn({sessionId:ee.sessionId,agentId:(Be==null?void 0:Be.agent_id)??(st==null?void 0:st.id)??u??t})).client.updateSession(ee)}}),Pe=Gn({mutationFn:async ee=>(await cn({projectId:ee.projectId,agentId:ee.agentId})).client.updateThread(ee)}),ht=Gn({mutationFn:async ee=>(await cn({agentId:ee.agentId})).client.createImageSession({title:"新绘图"})}),Xe=ee=>{r.setQueriesData({queryKey:hs},ee)},tn=ee=>re.find(Be=>Be.id===ee)??Et.find(Be=>Be.id===ee)??((ve==null?void 0:ve.id)===ee?ve:null),Le=async(ee,Be,Ke)=>{var Pt;const Lt=await $e.mutateAsync({sessionId:ee,action:Be,name:Ke}),Zt=(Pt=Lt.affectedSessionIds)!=null&&Pt.length?Lt.affectedSessionIds:[ee];if(Be==="delete"?(Xe(At=>p3(At,Zt)),lt()):Xe(At=>m3(At,Zt,{...Be==="rename"&&(Ke!=null&&Ke.trim())?{title:Ke.trim()}:{pinned:Be==="pin"}})),Be==="delete"&&m===ee){const At=Lt.nextSessionId;At?(Ea(At),y(At)):(Ea(null),y(null))}},rn=async(ee,Be,Ke)=>{var Pt,At;const Lt=await Pe.mutateAsync({projectId:ee,agentId:(st==null?void 0:st.id)??u??t??"",action:Be,name:Ke==null?void 0:Ke.name,orderedProjectIds:Ke==null?void 0:Ke.orderedProjectIds}),Zt=(Pt=Ke==null?void 0:Ke.name)==null?void 0:Pt.trim();Be==="pin"||Be==="unpin"?Xe(mn=>Wu(mn,ee,{pinned:Be==="pin"})):Be==="rename"&&Zt?Xe(mn=>Wu(mn,ee,{display_name:Zt})):Be==="reorder"&&((At=Ke==null?void 0:Ke.orderedProjectIds)!=null&&At.length)?Xe(mn=>Up(mn,Ke.orderedProjectIds??[])):Be==="remove"||Be==="archive"?(Xe(mn=>zp(mn,ee)),lt()):Be==="unarchive"&&(lt(),r.invalidateQueries({queryKey:hs})),ve&&ve.project_id===ee&&(Be==="remove"||Be==="archive"||Be==="unarchive")&&(Lt.nextSessionId?(Ea(Lt.nextSessionId),y(Lt.nextSessionId)):(Ea(null),y(null)))},hn=async ee=>{st&&(fr(st.id),Ea(null),sl(null),Hf(!1),Hu(ee),b(ee),v("composer"),y(null),await i({to:"/"}))},ns=async()=>{st&&(M||(N(!1),Jn(null)),fr(st.id),Ea(null),sl(null),Hu(null),Hf(!0),b(null),v("directory-picker"),y(null),await i({to:"/"}))},Xs=async ee=>{await hn(ee)},$s=async()=>{const ee=(st==null?void 0:st.id)??ke;if(!ee)return;const Be=await ht.mutateAsync({agentId:ee});Xe(Ke=>Bp(Ke,Be.session)),await oa(Be.session.id)},oa=async ee=>{const Be=tn(ee);b(null),v("composer"),Hf(!1),Hu(null),sl(null),Be&&!re.some(Lt=>Lt.id===ee)&&Xe(Lt=>Bp(Lt,Be)),y(ee),Ea(ee);const Ke=(Be==null?void 0:Be.agent_id)??(st==null?void 0:st.id)??ke;Ke&&(d(Ke),fr(Ke)),t&&await i({to:"/",replace:!0})},On=M?0:oO(),Ss=M?0:cO(),Kt=M||w,Zs=M?0:B??(w?On:0),us=M?0:Z??(j?Ss:0),Ln=M?1:On>0?Zs/On:0,Ot=!M&&B!==null,Wn=!M&&Z!==null,Sn=M?{"--desktop-sidebar-width":`${I}px`}:{"--workspace-preview-shift":`${us}px`},Jn=ee=>{he.current=ee,G(ee)},js=ee=>{ne.current=ee,ae(ee)},Hs=ee=>ee instanceof Element&&!!ee.closest('button, textarea, input, a, [role="dialog"]'),ca=ee=>{if(!(ee instanceof Element))return!1;const Be=ee.closest(".conversation-markdown-code-block__pre, .conversation-markdown-table__scroll");return!!(Be&&Be.scrollWidth-Be.clientWidth>1)},Fs=ee=>Hs(ee)||ca(ee),Js=(ee,Be,Ke)=>(R.current={target:"sidebar",mode:w?"close":"open",startX:ee,startY:Be,axis:"pending",pointerId:Ke},!0),ua=(ee,Be,Ke)=>q?(R.current={target:"preview",mode:"open",startX:ee,startY:Be,axis:"pending",pointerId:Ke},!0):!1,da=(ee,Be)=>{const Ke=R.current;if(!Ke)return!1;const Lt=ee-Ke.startX,Zt=Be-Ke.startY;if(Ke.axis==="pending"){if(Math.abs(Lt)<8&&Math.abs(Zt)<8)return!1;if(Ke.axis=Math.abs(Lt)>Math.abs(Zt)?"x":"y",Ke.axis==="y")return R.current=null,Jn(null),!1}if(Ke.target==="preview"){const At=Math.max(0,Math.min(Ss,-Lt));return js(At),!0}const Pt=Ke.mode==="open"?Math.max(0,Math.min(On,Lt)):Math.max(0,Math.min(On,On+Lt));return Jn(Pt),!0},fa=(ee,Be)=>{const Ke=R.current;if(!Ke)return;const Lt=ee-Ke.startX,Zt=Be-Ke.startY;if(Ke.axis==="pending"&&Math.abs(Zt)>48){R.current=null,Jn(null);return}if(Ke.target==="preview"){const jn=(Ke.axis==="x"?ne.current??Math.max(0,Math.min(Ss,-Lt)):j?Ss:0)>=Math.min(aO,Ss*f_);T(jn),jn&&(N(!1),Jn(null)),R.current=null,js(null);return}const Pt=Ke.axis==="x"?he.current??(Ke.mode==="open"?Math.max(0,Math.min(On,Lt)):Math.max(0,Math.min(On,On+Lt))):w?On:0,At=Ke.mode==="open"?Pt>=Math.min(sO,On*f_):Pt>=On*f_;N(At),R.current=null,Jn(null)};_.useEffect(()=>{const ee=o.current;if(!ee||M)return;const Be=Pt=>{if(j)return;const At=Pt.touches[0];Pt.touches.length!==1||!At||Fs(Pt.target)||(Ce.current={startX:At.clientX,startY:At.clientY})},Ke=Pt=>{if(Pt.touches.length!==1)return;const At=Pt.touches[0];if(!R.current){const jn=Ce.current;if(!jn)return;const kn=At.clientX-jn.startX,pn=At.clientY-jn.startY;if(Math.abs(kn)<8&&Math.abs(pn)<8)return;if(Math.abs(kn)<=Math.abs(pn)){Ce.current=null;return}const U=w&&kn<0,Ne=!j&&!w&&kn>0,Ue=!w&&!j&&kn<0&&q,Qe=U||Ne?Js(jn.startX,jn.startY):Ue?ua(jn.startX,jn.startY):!1;if(Ce.current=null,!Qe)return}da(At.clientX,At.clientY)&&Pt.cancelable&&Pt.preventDefault()},Lt=Pt=>{if(Ce.current=null,!R.current)return;const At=Pt.changedTouches[0];if(!At){R.current=null,Jn(null),js(null);return}fa(At.clientX,At.clientY)},Zt=()=>{Ce.current=null,R.current=null,Jn(null),js(null)};return ee.addEventListener("touchstart",Be,{passive:!0,capture:!0}),ee.addEventListener("touchmove",Ke,{passive:!1,capture:!0}),ee.addEventListener("touchend",Lt,{capture:!0}),ee.addEventListener("touchcancel",Zt,{capture:!0}),()=>{ee.removeEventListener("touchstart",Be,{capture:!0}),ee.removeEventListener("touchmove",Ke,{capture:!0}),ee.removeEventListener("touchend",Lt,{capture:!0}),ee.removeEventListener("touchcancel",Zt,{capture:!0})}},[q,M,j,w]);const In=()=>a.jsx(a.Fragment,{children:a.jsxs("div",{className:`conversation-main ${M?"has-desktop-sidebar":""}`,style:{transform:`translateX(${Zs}px)`,transition:Ot?"none":void 0},children:[a.jsx("div",{className:"conversation-topbar",children:M?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:()=>N(!0),"aria-label":"打开侧边栏",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]})}),a.jsx("div",{className:"conversation-scroll conversation-scroll--empty",children:a.jsx("div",{className:"conversation-thread conversation-thread--empty",children:a.jsx(eO,{mode:"node",agentName:st?Cc(st):void 0,agentStatus:(st==null?void 0:st.status)??null,onOpenNodes:()=>{i({to:"/nodes"})}})})})]})});return a.jsxs("div",{ref:o,className:`conversation-page ${M?"has-desktop-sidebar":""}`,style:Sn,onPointerDown:ee=>{M||j||ee.pointerType!=="touch"&&(ee.pointerType==="mouse"&&ee.button!==0||Fs(ee.target)||(Js(ee.clientX,ee.clientY,ee.pointerId),ee.currentTarget.setPointerCapture(ee.pointerId)))},onPointerMove:ee=>{if(M||ee.pointerType==="touch")return;const Be=R.current;!Be||Be.pointerId!==ee.pointerId||!da(ee.clientX,ee.clientY)||ee.preventDefault()},onPointerUp:ee=>{if(M||ee.pointerType==="touch")return;const Be=R.current;!Be||Be.pointerId!==ee.pointerId||fa(ee.clientX,ee.clientY)},onPointerCancel:ee=>{if(M||ee.pointerType==="touch")return;const Be=R.current;!Be||Be.pointerId!==ee.pointerId||(R.current=null,Jn(null),js(null))},children:[a.jsx(a5,{open:Kt,progress:Ln,isDragging:Ot,desktopPinned:M,isDesktopResizing:O,onClose:()=>{M||(N(!1),Jn(null))},onDesktopResizeStart:ee=>{ue.current=le.current,X.current={startX:ee,startWidth:le.current},Q(!0)},currentAgent:st??void 0,agentIndicatorState:Dt,projects:an,sessions:re,projectStats:we,historySessionsByProject:Object.fromEntries(Object.entries(dt).map(([ee,Be])=>[ee,Be.sessions])),archivedSessionsByProject:Object.fromEntries(Object.entries(un).map(([ee,Be])=>[ee,Be.sessions])),chatHistorySessions:Re.sessions,chatArchivedSessions:te.sessions,historyPageStateByProject:dt,archivedPageStateByProject:un,chatHistoryPageState:Re,chatArchivedPageState:te,activeSessionId:ve==null?void 0:ve.id,onCreateSession:ee=>{Xs(ee)},onCreateChat:()=>{Xs(Gr)},onCreateImageSession:()=>{$s()},onCreateDirectoryThread:()=>{ns()},onSelectSession:ee=>{oa(ee)},onSessionAction:Le,onThreadAction:rn,onOpenSettings:e,onLoadMoreHistory:ee=>{$t(ee)},onLoadMoreChatHistory:()=>{An()},onLoadMoreArchived:ee=>{Nn(ee)},onLoadMoreChatArchived:()=>{Tt()},pendingSessionActionId:$e.isPending?((ws=$e.variables)==null?void 0:ws.sessionId)??null:null,pendingThreadActionId:Pe.isPending?((Os=Pe.variables)==null?void 0:Os.projectId)??null:null}),a.jsxs("div",{className:`conversation-workspace-stack ${j||Wn?"is-preview-open":""} ${Wn?"is-dragging":""}`,children:[a.jsx("div",{className:"conversation-workspace-stack__page is-primary",children:Ee?(ve==null?void 0:ve.provider)==="image"?a.jsx(HR,{sessionId:Ee,workspaceDirectorySnapshot:qe??null,workspaceAgentIndicatorState:Dt,embedded:!0,isDesktopSidebar:M,sidebarOffset:Zs,isSidebarDragging:Ot,onOpenSidebar:()=>{T(!1),N(!0)}}):a.jsx(JD,{sessionId:Ee,workspaceDirectorySnapshot:qe??null,workspaceAgentIndicatorState:Dt,embedded:!0,isDesktopSidebar:M,sidebarOffset:Zs,isSidebarDragging:Ot,onOpenSidebar:()=>{T(!1),N(!0)},onSelectSession:ee=>{ee&&oa(ee)},onExitToNodes:()=>{sl(null),Ea(null),y(null),i({to:"/nodes"})}}):st?ve?null:a.jsx(RA,{currentAgent:st,projects:an,sessions:re,initialProjectId:g,entryView:p,isDesktopSidebar:M,sidebarOffset:Zs,isSidebarDragging:Ot,onOpenSidebar:()=>{T(!1),N(!0)},onProjectSelected:ee=>{b(ee),v("composer"),Hf(!1)},onSessionCreated:ee=>{oa(ee)}}):In()}),a.jsx("div",{className:"conversation-workspace-stack__page is-preview",children:a.jsx("div",{className:"session-file-preview-pane",children:ve&&V&&(j||Z!==null)?a.jsx(_.Suspense,{fallback:a.jsx("div",{className:"session-file-preview-pane__fallback",children:"正在载入预览页…"}),children:a.jsx(rO,{agentId:(st==null?void 0:st.id)??ke,sessionId:ve.id,projectName:V.display_name||V.name,projectPath:V.path,isActive:j,onBack:()=>{T(!1),js(null)}},ve.id)}):null})})]})]})},dO=24,fO=32,hO=72,Zx="panda:native-safe-area-change",yy=e=>{const t=Number(e);if(!Number.isFinite(t))return 0;const i=typeof window<"u"&&Number.isFinite(window.devicePixelRatio)&&window.devicePixelRatio>0?window.devicePixelRatio:1;return Math.max(0,t/i)},h_=e=>`${Math.round(yy(e)*100)/100}px`,mO=e=>`${Math.round(e*100)/100}px`,pO=e=>{const t=yy(e);if(!Yp())return`${Math.round(t*100)/100}px`;const i=Math.min(fO,Math.max(dO,t+1));return`${Math.round(i*100)/100}px`},gO=()=>{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},_O=e=>{var o;if(!ba())return"0px";const t=gO(),i=yy((o=e==null?void 0:e.getKeyboardInsetPx)==null?void 0:o.call(e)),r=t>0?t:i;return r<hO?"0px":mO(r)},yO=()=>{var i,r,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",pO((i=e.getTopInsetPx)==null?void 0:i.call(e))),t.setProperty("--native-safe-area-right",h_((r=e.getRightInsetPx)==null?void 0:r.call(e))),t.setProperty("--native-safe-area-bottom",h_((o=e.getBottomInsetPx)==null?void 0:o.call(e))),t.setProperty("--native-safe-area-left",h_((u=e.getLeftInsetPx)==null?void 0:u.call(e)))),t.setProperty("--native-keyboard-inset-bottom",_O(e))},vO=()=>{var u,d;if(typeof window>"u"||typeof document>"u")return()=>{};const e=()=>{yO()},t=new Set,i=m=>{const y=window.setTimeout(()=>{t.delete(y),e()},m);t.add(y)},r=()=>{e(),i(120),i(280)};let o=null;return e(),i(0),i(250),i(800),window.addEventListener("load",e,{once:!0}),window.addEventListener("resize",e),window.addEventListener("orientationchange",e),window.addEventListener(Zx,e),document.addEventListener("visibilitychange",e),document.addEventListener("focusin",r,!0),document.addEventListener("focusout",r,!0),(u=window.visualViewport)==null||u.addEventListener("resize",e),(d=window.visualViewport)==null||d.addEventListener("scroll",e),w3.addListener("resume",e).then(m=>{o=()=>{m.remove()}}).catch(()=>{}),()=>{var m,y;window.removeEventListener("resize",e),window.removeEventListener("orientationchange",e),window.removeEventListener(Zx,e),document.removeEventListener("visibilitychange",e),document.removeEventListener("focusin",r,!0),document.removeEventListener("focusout",r,!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()}},m_=new OS,bO=async()=>{},xO=_.lazy(async()=>({default:(await cl(()=>import("./diagnostics-page-BX9ilH-j.js"),__vite__mapDeps([3,4]))).DiagnosticsPage})),SO=()=>a.jsx(_.Suspense,{fallback:a.jsx("main",{className:"diagnostics-page",children:a.jsx("div",{className:"diagnostics-shell",children:a.jsx("section",{className:"diagnostics-card",children:a.jsx("p",{children:"正在载入诊断页…"})})})}),children:a.jsx(xO,{})}),Ic=L7({component:FM}),jO=Rc({getParentRoute:()=>Ic,path:"/",component:L5}),wO=Rc({getParentRoute:()=>Ic,path:"/nodes",component:QM}),NO=Rc({getParentRoute:()=>Ic,path:"/session/$sessionId",component:VM}),kO=Rc({getParentRoute:()=>Ic,path:"/new-thread/$agentId",component:L5}),EO=Rc({getParentRoute:()=>Ic,path:"/settings",component:J3}),CO=Rc({getParentRoute:()=>Ic,path:"/diagnostics",component:SO}),TO=Ic.addChildren([jO,wO,NO,kO,EO,CO]),MO=q7({routeTree:TO,defaultPreload:"intent"});typeof document<"u"&&(G3(Q3()),vO());bO().catch(()=>{}).then(async()=>{await DE(),await fC(m_),mC(m_)}).finally(()=>{nS.createRoot(document.getElementById("root")).render(a.jsx(LS,{client:m_,children:a.jsx(Q7,{router:MO})}))});export{Ub as B,QC as C,id as E,L_ as L,ES as Q,vd as S,q2 as W,hh as X,cl as _,h2 as a,Ka as b,PS as c,BS as d,qS as e,$S as f,HS as g,zs as h,KS as i,a as j,ob as k,FS as l,la as m,Bs as n,cn as o,cs as p,IO as q,_ as r,up as s,Z0 as t,Hi as u,Q9 as v,O1 as w};
|
|
208
|
+
`),DD=e=>e.kind==="entry"&&e.entry.kind==="user",I5=e=>e.kind==="entry"&&e.entry.kind==="assistant",OD=e=>DD(e)||I5(e),LD=e=>e.kind==="tool-group"?!0:e.entry.kind==="assistant"||e.entry.kind==="thinking"||e.entry.kind==="tool",PD=e=>{if(e.length<=1)return e;const t=[];for(const i of e){const r=t[t.length-1];if(r&&r.kind==="entry"&&i.kind==="entry"&&r.entry.kind==="assistant"&&i.entry.kind==="assistant"&&r.entry.body.trim()===i.entry.body.trim()){t[t.length-1]=i;continue}t.push(i)}return t},UD=e=>`展开 ${e.length} 条过程消息`,zD=e=>`收起 ${e.length} 条过程消息`,BD=(e,t)=>{const i=PD(e.items),{completion:r}=e,o=i.findLastIndex(m=>I5(m));if(o===-1||!r||!t)return{id:e.id,startedAt:e.startedAt,visibleStartItems:o===-1?i:i.slice(0,o),hiddenItems:[],visibleEndItems:o===-1?[]:i.slice(o),completion:r};const u=[],d=[];return i.forEach((m,y)=>{if(y!==o){if(OD(m)){u.push(m);return}d.push(m)}}),{id:e.id,startedAt:e.startedAt,visibleStartItems:u,hiddenItems:d,visibleEndItems:[i[o]],completion:r}},$D=(e,t)=>{const i=[];let r=[],o=null;const u=()=>{for(const m of r)i.push({kind:"item",id:m.kind==="entry"?m.entry.id:m.group.id,item:m});r=[]},d=()=>{o&&((o.items.length>0||o.completion)&&i.push({kind:"turn",turn:BD(o,t)}),o=null)};for(const m of e){if(m.kind==="turn-start"){d(),o={id:m.id,startedAt:m.startedAt,items:r,completion:null},r=[];continue}if(m.kind==="turn-complete"){if(o){o.completion=m;continue}o={id:m.id,startedAt:null,items:r,completion:m},r=[];continue}if(o){if(o.completion&&!LD(m)){d(),r.push(m);continue}o.items.push(m);continue}r.push(m)}return d(),u(),i},HD=e=>e.run_state!=="running"&&Date.now()-new Date(e.last_event_at).getTime()>=CI,FD=(e,t)=>{var g,b;const i=t==null?void 0:t.projectPath,r=(t==null?void 0:t.compactCompletedTurns)??!1,o=[];let u=null,d=!1,m=null,y=[];for(let p=0;p<e.length;p+=1){const v=e[p];if(v.kind==="system"&&v.body==="开始处理请求"){o.push({kind:"turn-start",id:v.id,startedAt:v.timestamp}),m=v.timestamp,y=[];continue}if(v.kind==="system"&&v.body==="处理完成"){o.push({kind:"turn-complete",id:v.id,durationLabel:TD(m,v.timestamp),patchSummary:MD(y),completedAt:v.timestamp}),m=null,y=[];continue}if(v.kind==="tool"&&v.title!=="tool-output"){const w=[];let N=p+1;for(;N<e.length&&((g=e[N])==null?void 0:g.kind)==="tool"&&((b=e[N])==null?void 0:b.title)==="tool-output";)w.push(e[N]),N+=1;u=v.id;const j=v.title==="apply_patch"?R5(v.patch_summary,i)??A5(v.body,i):null;j&&y.push(j),w.length===0&&(d=!0),o.push({kind:"tool-group",group:{id:v.id,commandEntry:v,outputEntries:w,patchSummary:j}}),p=N-1;continue}if(v.kind==="tool"&&v.title==="tool-output"){o.push({kind:"tool-group",group:{id:v.id,commandEntry:v,outputEntries:[],patchSummary:null}}),u=v.id;continue}o.push({kind:"entry",entry:v})}return{blocks:$D(o,r),lastToolGroupId:u,hasRunningToolGroup:d}},qD=e=>e.kind==="entry"?e.entry.timestamp:e.group.commandEntry.timestamp,WD=(e,t)=>{var d,m;const i=[...e.visibleStartItems,...e.hiddenItems,...e.visibleEndItems].map(qD).filter(y=>!!y),r=i.length>0?i[i.length-1]:null,o=e.startedAt??i[0]??((d=e.completion)==null?void 0:d.completedAt)??null,u=((m=e.completion)==null?void 0:m.completedAt)??r??o;return{startMs:o?+new Date(o):null,endMs:u?+new Date(u):null,nextStartMs:t!=null&&t.startedAt?+new Date(t.startedAt):null}},KD=(e,t)=>{const i=+new Date(e.started_at),r=e.completed_at?+new Date(e.completed_at):null,o=t.startMs??(t.endMs!==null?t.endMs-Uf:null),u=t.nextStartMs??(t.endMs!==null?t.endMs+Uf:Number.POSITIVE_INFINITY);return o!==null&&i<o-Uf?!1:i<=u+Uf?!0:r!==null&&r<=u+Uf},QD=(e,t)=>{if(t===null)return Number.POSITIVE_INFINITY;const i=+new Date(e.updated_at);return Number.isFinite(i)?Math.abs(i-t):Number.POSITIVE_INFINITY},GD=(e,t)=>{const i=[...t].sort((d,m)=>+new Date(d.started_at)-+new Date(m.started_at)),r=new Set,o=e.filter(d=>d.kind==="turn"),u=new Map(o.map((d,m)=>[d.turn.id,m]));return e.map(d=>{var j,T,M;if(d.kind!=="turn")return d;const m=u.get(d.turn.id)??-1,y=m>=0?((j=o[m+1])==null?void 0:j.turn)??null:null,g=WD(d.turn,y),b=((T=d.turn.completion)==null?void 0:T.patchSummary)??null,p=T5(b),w=((M=i.filter(P=>!r.has(P.id)).map(P=>({changeSet:P,overlapCount:M5(P,p),updatedAtDistance:QD(P,g.endMs)})).filter(P=>P.overlapCount>0&&P.updatedAtDistance<=C5).sort((P,I)=>I.overlapCount!==P.overlapCount?I.overlapCount-P.overlapCount:P.changeSet.source!==I.changeSet.source?P.changeSet.source==="app-server"?-1:1:P.updatedAtDistance!==I.updatedAtDistance?P.updatedAtDistance-I.updatedAtDistance:+new Date(P.changeSet.started_at)-+new Date(I.changeSet.started_at))[0])==null?void 0:M.changeSet)??i.find(P=>r.has(P.id)?!1:KD(P,g))??null;return w&&r.add(w.id),{kind:"turn",turn:d.turn,changeSet:w}})},YD=()=>typeof window>"u"?248:Math.max(0,Math.min(248,window.innerWidth-84)),m0=e=>Math.max(w5,Math.min(AI,e)),VD=()=>{if(typeof window>"u")return Du;try{const e=window.localStorage.getItem(j5),t=window.localStorage.getItem(Wf);if(!e)return window.localStorage.setItem(Wf,Kf),Du;const i=Number(e);if(!Number.isFinite(i))return window.localStorage.setItem(Wf,Kf),Du;const o=t!==Kf||i===RI||i>Du?Du:i;return window.localStorage.setItem(Wf,Kf),m0(o)}catch{return Du}};function Vm({active:e,render:t,fallback:i=null}){const[r,o]=_.useState(!e);return _.useEffect(()=>{if(!e){o(!1);return}o(!1);const u=window.requestAnimationFrame(()=>{o(!0)});return()=>{window.cancelAnimationFrame(u)}},[e]),e?r?a.jsx(a.Fragment,{children:t()}):a.jsx(a.Fragment,{children:i}):null}const XD=_.memo(function({sessionId:t,group:i,projectPath:r}){const[o,u]=_.useState({}),d=i.commandEntry.detail_available||i.outputEntries.some(j=>j.detail_available),m=UA({sessionId:t,entryId:i.commandEntry.id,scope:{sessionId:t},enabled:d}),y=m.data,g=(y==null?void 0:y.command_entry)??i.commandEntry,b=y!=null&&y.output_entries&&y.output_entries.length>0?y.output_entries:i.outputEntries,p=g.title==="apply_patch"?A5(g.body,r)??R5(g.patch_summary,r)??i.patchSummary:i.patchSummary,v=AD(g),w=ID(b),N=j=>{u(T=>({...T,[j]:!T[j]}))};return m.isPending&&d&&!y?a.jsx("div",{className:"patch-file-card__empty",children:"正在加载工具详情…"}):g.title==="apply_patch"&&p?p.files.length>1?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"tool-entry__patch-list",children:p.files.map(j=>{const T=`${i.id}:${j.path}`,M=!!o[T];return a.jsxs("div",{className:`tool-entry tool-entry--patch-file ${M?"is-expanded":""}`,children:[a.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>N(T),"aria-expanded":M,children:[a.jsxs("div",{className:"tool-entry__summary",children:[a.jsx("span",{className:"tool-entry__status",children:"已编辑"}),a.jsx("span",{className:"tool-entry__command",children:tD(j.displayPath)}),a.jsxs("span",{className:"tool-entry__counts",children:[a.jsxs("span",{className:"is-add",children:["+",j.additions]}),a.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),a.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),M?a.jsx("div",{className:"tool-entry__details",children:j.diffText.trim()?a.jsxs("div",{className:"patch-file-card",children:[a.jsxs("div",{className:"patch-file-card__header",children:[a.jsx("div",{className:"patch-file-card__path",children:j.displayPath}),a.jsxs("div",{className:"patch-file-card__counts",children:[a.jsxs("span",{className:"is-add",children:["+",j.additions]}),a.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),a.jsx("div",{className:"patch-file-card__diff",children:f0(j.diffText,j.path,"此变更没有可展示的补丁内容")})]}):a.jsx("div",{className:"patch-file-card__empty",children:"此变更没有可展示的补丁内容"})}):null]},T)})}),m.isError?a.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]}):a.jsxs("div",{className:"tool-entry__patch-list",children:[p.files.map(j=>a.jsxs("div",{className:"patch-file-card",children:[a.jsxs("div",{className:"patch-file-card__header",children:[a.jsx("div",{className:"patch-file-card__path",children:j.displayPath}),a.jsxs("div",{className:"patch-file-card__counts",children:[a.jsxs("span",{className:"is-add",children:["+",j.additions]}),a.jsxs("span",{className:"is-remove",children:["-",j.deletions]})]})]}),a.jsx("div",{className:"patch-file-card__diff",children:f0(j.diffText,j.path,"此变更没有可展示的补丁内容")})]},`${i.id}-${j.path}`)),m.isError?a.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"tool-entry__section",children:[a.jsx("div",{className:"tool-entry__label",children:"命令"}),a.jsx("pre",{className:"tool-entry__pre",children:v})]}),w?a.jsxs("div",{className:"tool-entry__section",children:[a.jsx("div",{className:"tool-entry__label",children:"输出"}),a.jsx("pre",{className:"tool-entry__pre",children:w})]}):null,m.isError?a.jsx("div",{className:"patch-file-card__empty",children:m.error instanceof Error?m.error.message:"无法加载工具详情。"}):null]})}),ZD=_.memo(function({sessionId:t,sessions:i,sessionRunState:r,isDesktopSidebar:o,projectPath:u,renderedBlocks:d,lastToolGroupId:m,sessionChangeSets:y,isSubagentTimelinePending:g,isInitialTimelinePending:b,hasTimeline:p,proposedPlanReplyDrafts:v,pendingProposedPlanReplyEntryId:w,canRespondToProposedPlan:N,onProposedPlanReplyDraftChange:j,onSubmitProposedPlanReply:T,onPreviewImage:M,changeSetDiffs:P,changeSetDiffErrors:I,loadingChangeSetDiffKeys:k,onLoadSessionChangeSets:O,onLoadChangeSetFileDiff:Q,onLoadFullTimeline:J,timelineLoadState:F,canRollbackChangeSets:B,pendingRollbackTurnId:G,rollbackTurnError:Z,rolledBackTurnIds:ae,onRollbackTurn:he}){const[ne,Ce]=_.useState({}),[R,X]=_.useState({}),[le,ue]=_.useState({}),[ye,D]=_.useState(null),[oe,je]=_.useState(null),[z,be]=_.useState(null),De=_.useRef(null),se=_.useRef(null),pe=_.useMemo(()=>{var V;return((V=[...d].reverse().find(q=>q.kind==="turn"&&!!q.turn.completion))==null?void 0:V.turn.id)??null},[d]);_.useEffect(()=>{const V=q=>{const de=q.target;de instanceof Element&&de.closest(".conversation-inline-link")||D(null)};return window.addEventListener("pointerdown",V),()=>{window.removeEventListener("pointerdown",V)}},[]),_.useEffect(()=>()=>{De.current!==null&&window.clearTimeout(De.current),se.current!==null&&window.clearTimeout(se.current)},[]);const ke=V=>{Ce(q=>({...q,[V]:!q[V]}))},Ze=V=>{X(q=>({...q,[V]:!q[V]}))},zt=V=>{ue(q=>({...q,[V]:!q[V]}))};_.useEffect(()=>{var q;const V=new Map;for(const de of d){if(de.kind!=="turn")continue;const ce=de.changeSet;if(!ce||ce.status!=="completed"||ce.files.length===0)continue;const Ae=u_(de.turn.id),Ee=Wx(ce,u,((q=de.turn.completion)==null?void 0:q.patchSummary)??null);for(const $e of Ee){if(!$e.changeSetId||!$e.diffAvailable)continue;const Pe=Kx(Ae,$e.path);if(!le[Pe])continue;const ht=cp($e.changeSetId,$e.path,$e.itemId);P[ht]||k[ht]||V.set(ht,{changeSetId:$e.changeSetId,path:$e.path,itemId:$e.itemId??null})}}for(const de of V.values())Q(de)},[P,le,k,Q,u,d]);const Fe=async V=>{var ce;const q=V.trim();if(!q)return!1;const de=()=>{const Ae=document.createElement("textarea");Ae.value=q,Ae.setAttribute("readonly","true"),Ae.style.position="fixed",Ae.style.opacity="0",Ae.style.pointerEvents="none",document.body.appendChild(Ae),Ae.select(),document.execCommand("copy"),document.body.removeChild(Ae)};try{return(ce=navigator.clipboard)!=null&&ce.writeText?await navigator.clipboard.writeText(q):de(),!0}catch{return!1}},kt=async(V,q)=>{await Fe(q)&&(je(V),De.current!==null&&window.clearTimeout(De.current),De.current=window.setTimeout(()=>{je(ce=>ce===V?null:ce),De.current=null},1400))},Bt=async(V,q)=>{await Fe(q)&&(be(V),se.current!==null&&window.clearTimeout(se.current),se.current=window.setTimeout(()=>{be(ce=>ce===V?null:ce),se.current=null},1400))};function Gt(V,q,de){return f0(V,q,de)}function Xt(V,q,de){const ce=ye===de,Ae=()=>{D(Ee=>Ee===de?null:de)};return a.jsx(YI,{isActive:ce,label:V,path:q,tokenKey:de,onToggle:Ae},de)}function Ft(V,q,de=rl(V,u)){return Xt(N5(de),de,q)}function qe(V,q){return sD(V).map((ce,Ae)=>{const Ee=`${q}-${Ae}`;return ce.kind==="text"?a.jsx("span",{children:ce.value},Ee):ce.kind==="code"?a.jsx("code",{className:"conversation-inline-code",children:ce.value},Ee):ce.kind==="strong"?a.jsx("strong",{children:qe(ce.value,`${Ee}-strong`)},Ee):ce.kind==="emphasis"?a.jsx("em",{children:qe(ce.value,`${Ee}-emphasis`)},Ee):ce.kind==="strikethrough"?a.jsx("del",{children:qe(ce.value,`${Ee}-strikethrough`)},Ee):ce.kind==="skill"?a.jsx("span",{className:"conversation-skill-token",children:ce.raw},Ee):ce.kind==="command"?a.jsx("span",{className:"conversation-command-token",children:ce.raw},Ee):Xt(ce.label,ce.path,Ee)})}function dt(V,q){return fD(V).map((ce,Ae)=>{const Ee=`${q}-block-${Ae}`;if(ce.kind==="heading"){const $e=Math.min(Math.max(ce.level,1),6),Pe=oD($e);return a.jsx(Pe,{className:`conversation-markdown-heading is-level-${$e}`,children:qe(ce.text,`${Ee}-heading`)},Ee)}if(ce.kind==="blockquote")return a.jsx("blockquote",{className:"conversation-markdown-blockquote",children:ce.lines.map(($e,Pe)=>a.jsxs("span",{children:[Pe>0?a.jsx("br",{}):null,qe($e,`${Ee}-quote-line-${Pe}`)]},`${Ee}-quote-line-${Pe}`))},Ee);if(ce.kind==="thematic-break")return a.jsx("hr",{className:"conversation-markdown-thematic-break"},Ee);if(ce.kind==="list"){const $e=ce.ordered?"ol":"ul";return a.jsx($e,{className:cD(ce.items),children:ce.items.map((Pe,ht)=>a.jsxs("li",{value:ce.ordered?Pe.ordinal??void 0:void 0,className:Pe.checked!==null?"is-task-item":void 0,children:[Pe.checked!==null?a.jsx("input",{type:"checkbox",checked:Pe.checked,readOnly:!0,tabIndex:-1,"aria-label":Pe.checked?"已完成":"未完成"}):null,qe(Pe.text,`${Ee}-item-${ht}`)]},`${Ee}-item-${ht}`))},Ee)}if(ce.kind==="table")return a.jsx("div",{className:"conversation-markdown-table__scroll",children:a.jsxs("table",{className:"conversation-markdown-table",children:[a.jsx("thead",{children:a.jsx("tr",{children:ce.headers.map(($e,Pe)=>a.jsx("th",{scope:"col",className:Fx(ce.alignments[Pe]??null),children:qe($e,`${Ee}-header-${Pe}`)},`${Ee}-header-${Pe}`))})}),a.jsx("tbody",{children:ce.rows.map(($e,Pe)=>a.jsx("tr",{children:$e.map((ht,Xe)=>a.jsx("td",{className:Fx(ce.alignments[Xe]??null),children:qe(ht,`${Ee}-row-${Pe}-cell-${Xe}`)},`${Ee}-row-${Pe}-cell-${Xe}`))},`${Ee}-row-${Pe}`))})]})},Ee);if(ce.kind==="code"){const $e=`${Ee}-meta`;return a.jsxs("div",{className:"conversation-markdown-code-block",children:[ce.rawInfo?a.jsxs("div",{className:"conversation-markdown-code-block__meta",children:[a.jsx("span",{className:"conversation-markdown-code-block__meta-label",children:ce.rawInfo}),a.jsxs("button",{type:"button",className:`conversation-markdown-code-block__copy ${z===$e?"is-copied":""}`,onClick:()=>{Bt($e,ce.content)},"aria-label":z===$e?"已复制代码块内容":"复制代码块内容",children:[a.jsx("span",{className:"conversation-markdown-code-block__copy-icon","aria-hidden":"true",children:z===$e?a.jsx(zx,{}):a.jsx(Ux,{})}),a.jsx("span",{className:"sr-only",children:z===$e?"已复制":"复制"})]})]}):null,a.jsx("pre",{className:"conversation-markdown-code-block__pre",children:a.jsx("code",{children:ce.content})})]},Ee)}return a.jsx("p",{className:"conversation-markdown-paragraph",children:ce.lines.map(($e,Pe)=>a.jsxs("span",{children:[Pe>0?a.jsx("br",{}):null,qe($e,`${Ee}-line-${Pe}`)]},`${Ee}-line-${Pe}`))},Ee)})}function un(V,q,de){const ce=`${V.id}:proposed-plan:${de}`,Ae=v[ce]??"",Ee=w===ce,$e=!N||Ee;return a.jsxs("div",{className:"proposed-plan-card",children:[a.jsx("div",{className:"proposed-plan-card__content",children:dt(q,`${ce}:content`)}),a.jsxs("div",{className:"proposed-plan-card__footer",children:[a.jsx("div",{className:"proposed-plan-card__title",children:"实施此计划?"}),a.jsxs("div",{className:"proposed-plan-card__actions",children:[a.jsx("button",{type:"button",className:"proposed-plan-card__confirm",disabled:$e,onClick:()=>{T(ce,"是,实施此计划")},children:Ee?"回复中…":"是,实施此计划"}),a.jsxs("div",{className:"proposed-plan-card__custom",children:[a.jsx("input",{type:"text",className:"proposed-plan-card__input",value:Ae,disabled:$e,placeholder:"否,请告知如何调整",onChange:Pe=>{j(ce,Pe.target.value)},onKeyDown:Pe=>{Pe.key!=="Enter"||!Ae.trim()||$e||(Pe.preventDefault(),T(ce,Ae))}}),a.jsx("button",{type:"button",className:"proposed-plan-card__submit",disabled:$e||!Ae.trim(),onClick:()=>{T(ce,Ae)},children:Ee?"回复中…":"回复"})]})]})]})]},ce)}function $t(V){const q=hD(V.body);return q.some(ce=>ce.kind==="proposed-plan")?q.map((ce,Ae)=>{const Ee=`${V.id}-content-${Ae}`;return ce.kind==="markdown"?a.jsx("div",{className:"conversation-entry__rich-block",children:dt(ce.content,Ee)},Ee):un(V,ce.content,Ae)}):dt(V.body,V.id)}function An(V){const q=C6([],V.attachments);if(q.length===0)return null;const de=q.filter(ax),ce=q.filter(Ae=>!ax(Ae));return a.jsxs("div",{className:"conversation-entry__attachments",children:[de.length>0?a.jsx("div",{className:"conversation-entry__attachment-grid",children:de.map(Ae=>{const Ee=qp(Ae.size_bytes),$e=Ae.name??"图片",Pe=`图片${Ee?` · ${Ee}`:""}`,ht=a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"conversation-entry__attachment-media",children:Ae.content_url?a.jsxs(a.Fragment,{children:[a.jsx("img",{src:Ae.content_url,alt:$e,loading:"lazy"}),a.jsx("span",{className:"conversation-entry__attachment-badge",children:"预览"})]}):a.jsx("div",{className:"conversation-entry__attachment-fallback",children:"无法预览"})}),a.jsxs("div",{className:"conversation-entry__attachment-caption",children:[a.jsx("span",{className:"conversation-entry__attachment-title",children:$e}),a.jsx("span",{className:"conversation-entry__attachment-meta",children:Pe})]})]});return Ae.content_url?a.jsx("button",{type:"button",className:"conversation-entry__attachment-card is-image",onClick:()=>M({src:Ae.content_url,label:$e,meta:Pe}),"aria-label":`预览 ${$e}`,children:ht},`${V.id}:${Ae.id}`):a.jsx("div",{className:"conversation-entry__attachment-card is-image",children:ht},`${V.id}:${Ae.id}`)})}):null,ce.length>0?a.jsx("div",{className:"conversation-entry__file-list",children:ce.map(Ae=>{const Ee=qp(Ae.size_bytes),$e=a.jsxs(a.Fragment,{children:[a.jsx("span",{className:"conversation-entry__file-icon","aria-hidden":"true",children:a.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8Z"}),a.jsx("path",{d:"M14 3v5h5"}),a.jsx("path",{d:"M9 13h6"}),a.jsx("path",{d:"M9 17h4"})]})}),a.jsxs("span",{className:"conversation-entry__file-copy",children:[a.jsx("span",{className:"conversation-entry__file-title",children:Ae.name??"附件"}),a.jsxs("span",{className:"conversation-entry__file-meta",children:["文件",Ee?` · ${Ee}`:""]})]})]});return Ae.content_url?a.jsx("a",{className:"conversation-entry__file-card",href:Ae.content_url,download:Ae.name??void 0,target:"_blank",rel:"noreferrer",children:$e},`${V.id}:${Ae.id}`):a.jsx("div",{className:"conversation-entry__file-card",children:$e},`${V.id}:${Ae.id}`)})}):null]})}function Nn(V,q){return a.jsx("div",{className:"turn-patch-summary__files",children:q.map(de=>{const ce=Kx(V,de.path),Ae=!!le[ce],Ee=de.changeSetId?cp(de.changeSetId,de.path,de.itemId):null,$e=Ee?P[Ee]:void 0,Pe=Ee?k[Ee]===!0:!1,ht=Ee?I[Ee]??null:null,Xe=($e==null?void 0:$e.file.diff)??de.diffText??"",tn=($e==null?void 0:$e.empty_message)??de.emptyMessage;return a.jsxs("div",{className:`turn-patch-file ${Ae?"is-expanded":""}`,children:[a.jsxs("button",{type:"button",className:"turn-patch-file__toggle",onClick:()=>{zt(ce),de.changeSetId||O(),Ee&&de.changeSetId&&de.diffAvailable&&!$e&&!Pe&&Q({changeSetId:de.changeSetId,path:de.path,itemId:de.itemId??null})},"aria-expanded":Ae,children:[a.jsx("div",{className:"turn-patch-file__path",children:de.pathLabel}),a.jsxs("div",{className:"turn-patch-file__meta",children:[a.jsxs("span",{className:"turn-patch-summary__counts",children:[a.jsxs("span",{className:"is-add",children:["+",de.additions]}),a.jsxs("span",{className:"is-remove",children:["-",de.deletions]})]}),a.jsx("span",{className:"turn-patch-file__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]})]}),Ae?a.jsx("div",{className:"turn-patch-file__detail",children:Pe?a.jsx("div",{className:"patch-file-card__empty",children:"正在载入差异详情…"}):ht?a.jsx("div",{className:"patch-file-card__empty",children:ht}):de.diffAvailable===!1&&!Xe.trim()?a.jsx("div",{className:"patch-file-card__empty",children:tn}):a.jsx(Vm,{active:Ae,fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开差异…"}),render:()=>Gt(Xe,de.path,tn)})}):null]},ce)})})}function Tt(V){return mD(V).map(q=>{const de=`live:${V.id}:${q.item_id??"summary"}:${q.path}`,ce=!!le[de],Ae=V.status==="running",Ee=cp(V.id,q.path,q.item_id),$e=P[Ee],Pe=k[Ee]===!0,ht=I[Ee]??null,Xe=($e==null?void 0:$e.file.diff)??"",tn=($e==null?void 0:$e.empty_message)??"此变更还没有可展示的补丁内容";return a.jsx("section",{className:"conversation-entry is-tool-group",children:a.jsxs("div",{className:`tool-entry ${Ae?"is-running":"is-complete"} ${ce?"is-expanded":""} is-patch`,children:[a.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>{zt(de),q.diff_available&&!$e&&!Pe&&Q({changeSetId:V.id,path:q.path,itemId:q.item_id??null})},"aria-expanded":ce,children:[a.jsxs("div",{className:"tool-entry__summary",children:[a.jsx("span",{className:"tool-entry__status",children:"已编辑"}),a.jsx("span",{className:"tool-entry__command",children:Ft(q.path,`${de}:live-link`,rl(q.path,u))}),a.jsxs("span",{className:"tool-entry__counts",children:[a.jsxs("span",{className:"is-add",children:["+",q.additions]}),a.jsxs("span",{className:"is-remove",children:["-",q.deletions]})]})]}),a.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),ce?a.jsx("div",{className:"tool-entry__details",children:Pe?a.jsx("div",{className:"patch-file-card__empty",children:"正在载入详情…"}):ht?a.jsx("div",{className:"patch-file-card__empty",children:ht}):!q.diff_available&&!Xe.trim()?a.jsx("div",{className:"patch-file-card__empty",children:tn}):a.jsx(Vm,{active:ce,fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>a.jsx("div",{className:"tool-entry__patch-list",children:a.jsxs("div",{className:"patch-file-card",children:[a.jsxs("div",{className:"patch-file-card__header",children:[a.jsx("div",{className:"patch-file-card__path",children:rl(q.path,u)}),a.jsxs("div",{className:"patch-file-card__counts",children:[a.jsxs("span",{className:"is-add",children:["+",q.additions]}),a.jsxs("span",{className:"is-remove",children:["-",q.deletions]})]})]}),a.jsx("div",{className:"patch-file-card__diff",children:Gt(Xe,q.path,tn)})]})})})}):null]})},de)})}const lt=V=>{const q=B&&pe===V&&!ae[V],de=(Z==null?void 0:Z.turnId)===V?Z.message:null;return{isEligible:q,isPending:G===V,error:de}};function Et(V,q,de,ce){const Ae=Wx(V,u,ce),Ee=Ae.reduce((ht,Xe)=>ht+Xe.additions,0),$e=Ae.reduce((ht,Xe)=>ht+Xe.deletions,0),Pe=lt(q);return a.jsxs("div",{className:"turn-patch-summary",children:[a.jsxs("div",{className:"turn-patch-summary__header",children:[a.jsxs("div",{className:"turn-patch-summary__title",children:[a.jsxs("span",{children:[Ae.length," 个文件已更改"]}),a.jsxs("span",{className:"turn-patch-summary__counts",children:[a.jsxs("span",{className:"is-add",children:["+",Ee]}),a.jsxs("span",{className:"is-remove",children:["-",$e]})]})]}),Pe.isEligible?a.jsx("div",{className:"turn-patch-summary__actions",children:a.jsx("button",{type:"button",className:"turn-patch-summary__action",onClick:()=>he(q),disabled:Pe.isPending,"aria-label":Pe.isPending?"正在回滚这轮改动":"回滚这轮改动",title:Pe.isPending?"正在回滚这轮改动":"回滚这轮改动",children:a.jsx(Bx,{})})}):null]}),Pe.error?a.jsx("div",{className:"turn-patch-summary__notice is-error",children:Pe.error}):null,Nn(de,Ae)]})}function rt(V,q,de){const ce=lt(V);return a.jsxs("div",{className:"turn-patch-summary",children:[a.jsxs("div",{className:"turn-patch-summary__header",children:[a.jsxs("div",{className:"turn-patch-summary__title",children:[a.jsxs("span",{children:[de.files.length," 个文件已更改"]}),a.jsxs("span",{className:"turn-patch-summary__counts",children:[a.jsxs("span",{className:"is-add",children:["+",de.additions]}),a.jsxs("span",{className:"is-remove",children:["-",de.deletions]})]})]}),ce.isEligible?a.jsx("div",{className:"turn-patch-summary__actions",children:a.jsx("button",{type:"button",className:"turn-patch-summary__action",onClick:()=>he(V),disabled:ce.isPending,"aria-label":ce.isPending?"正在回滚这轮改动":"回滚这轮改动",title:ce.isPending?"正在回滚这轮改动":"回滚这轮改动",children:a.jsx(Bx,{})})}):null]}),ce.error?a.jsx("div",{className:"turn-patch-summary__notice is-error",children:ce.error}):null,Nn(q,de.files.map(Ae=>({path:Ae.path,pathLabel:Ae.displayPath,additions:Ae.additions,deletions:Ae.deletions,diffText:Ae.diffText,emptyMessage:"此变更没有可展示的补丁内容"})))]})}function st(V,q){var Xe,tn;const de=q.agentId?i.find(Le=>Le.id===q.agentId)??null:null,ce=k5(((Xe=de==null?void 0:de.subagent)==null?void 0:Xe.nickname)??(de==null?void 0:de.title)??q.agentId),Ae=`subagent:${V.id}`,Ee=!!ne[Ae],$e=q.state==="working",Pe=q.state==="completed"?"子代理返回":q.state==="shutdown"?"子代理已关闭":q.state==="errored"?"子代理异常":"子代理处理中",ht=((tn=de==null?void 0:de.subagent)==null?void 0:tn.nickname)??(de==null?void 0:de.title)??"子代理";return a.jsx("section",{className:"conversation-entry is-tool-group",children:a.jsxs("div",{className:`tool-entry is-subagent ${$e?"is-running":"is-complete"} ${Ee?"is-expanded":""}`,style:{"--subagent-accent":ce},children:[a.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>ke(Ae),"aria-expanded":Ee,children:[a.jsxs("div",{className:"tool-entry__summary",children:[a.jsx("span",{className:"tool-entry__status",children:Pe}),a.jsx("span",{className:"tool-entry__command tool-entry__command--agent",children:ht})]}),a.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),Ee?a.jsx("div",{className:"tool-entry__details",children:a.jsx(Vm,{active:Ee,fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>a.jsxs("div",{className:"tool-entry__section",children:[a.jsx("div",{className:"tool-entry__label",children:ht}),a.jsx("div",{className:"tool-entry__markdown",children:dt(q.body,`${V.id}-subagent`)})]})})}):null]})},V.id)}function Dt(V){var ce,Ae;if(V.kind==="tool-group"){const{group:Ee}=V;if(Ee.commandEntry.title==="apply_patch"&&CD(y,Ee.commandEntry.timestamp,Ee.patchSummary))return null;const $e=!!ne[Ee.id],Pe=r==="running"&&m===Ee.id&&Ee.outputEntries.length===0,ht=Ee.commandEntry.title==="apply_patch"&&!!Ee.patchSummary,Xe=ht&&(((ce=Ee.patchSummary)==null?void 0:ce.files.length)??0)>1,tn=ht?Ee.patchSummary.files.length===1?Ee.patchSummary.files[0].displayPath:`${Ee.patchSummary.files.length} 个文件`:RD(Ee.commandEntry);return a.jsx("section",{className:"conversation-entry is-tool-group",children:a.jsxs("div",{className:`tool-entry ${Pe?"is-running":"is-complete"} ${$e?"is-expanded":""} ${ht?"is-patch":""} ${Xe?"has-flat-patch-list":""}`,children:[a.jsxs("button",{type:"button",className:"tool-entry__toggle",onClick:()=>ke(Ee.id),"aria-expanded":$e,children:[a.jsxs("div",{className:"tool-entry__summary",children:[a.jsx("span",{className:"tool-entry__status",children:ht?"已编辑":Pe?"正在执行":"已执行"}),a.jsx("span",{className:"tool-entry__command",children:ht&&((Ae=Ee.patchSummary)==null?void 0:Ae.files.length)===1?Ft(Ee.patchSummary.files[0].path,`${Ee.id}:patch-link`,Ee.patchSummary.files[0].displayPath):tn}),ht&&Ee.patchSummary?a.jsxs("span",{className:"tool-entry__counts",children:[a.jsxs("span",{className:"is-add",children:["+",Ee.patchSummary.additions]}),a.jsxs("span",{className:"is-remove",children:["-",Ee.patchSummary.deletions]})]}):null]}),a.jsx("span",{className:"tool-entry__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),$e?a.jsx("div",{className:"tool-entry__details",children:a.jsx(Vm,{active:$e,fallback:a.jsx("div",{className:"patch-file-card__empty",children:"正在展开详情…"}),render:()=>a.jsx(XD,{sessionId:t,group:Ee,projectPath:u})})}):null]})},Ee.id)}const q=V.entry,de=q.kind==="user"?jD(q.body):null;if(de)return st(q,de);if(q.kind==="thinking")return r!=="running"?null:a.jsx("section",{className:"conversation-entry is-thinking-status",children:a.jsx("div",{className:"thinking-status-pill",children:a.jsx("span",{children:"正在思考"})})},q.id);if(dD(q))return a.jsx("section",{className:"conversation-context-compact",children:a.jsx("div",{className:"context-compact-divider",children:a.jsx("span",{children:"背景信息已自动压缩"})})},q.id);if(q.kind==="system"&&q.title==="system_prompt")return null;if(q.kind==="system"&&q.title==="runtime-status"){const Ee=bD(q.body);return a.jsx("section",{className:"conversation-entry is-runtime-status",children:a.jsxs("div",{className:`runtime-status-entry is-${Ee}`,children:[a.jsx("div",{className:"runtime-status-entry__label",children:xD(q.body)}),a.jsx("pre",{className:"runtime-status-entry__body",children:q.body})]})},q.id)}return a.jsx("section",{className:`conversation-entry ${q.kind==="user"?"is-user":"is-system"} is-${q.kind}`,children:q.kind==="user"?a.jsxs("div",{className:"conversation-entry__stack",children:[a.jsxs("div",{className:"conversation-entry__body",children:[q.body.trim()?dt(q.body,q.id):null,q.attachments.length>0?An(q):null]}),q.body.trim()?a.jsxs("button",{type:"button",className:`conversation-entry__copy ${oe===q.id?"is-copied":""}`,onClick:()=>{kt(q.id,q.body)},"aria-label":oe===q.id?"已复制消息":"复制消息",children:[a.jsx("span",{className:"conversation-entry__copy-icon","aria-hidden":"true",children:oe===q.id?a.jsx(zx,{}):a.jsx(Ux,{})}),a.jsx("span",{className:"sr-only",children:oe===q.id?"已复制":"复制"})]}):null]}):a.jsxs("div",{className:"conversation-entry__body",children:[q.body.trim()?q.kind==="assistant"?$t(q):dt(q.body,q.id):null,q.attachments.length>0?An(q):null]})},q.id)}if(g)return a.jsx("div",{className:"empty-panel",children:"正在载入子代理会话…"});if(b)return a.jsxs("div",{className:"empty-panel empty-panel--loading",role:"status","aria-live":"polite","aria-busy":"true",children:[a.jsxs("span",{className:"empty-panel__loading-dots","aria-hidden":"true",children:[a.jsx("span",{className:"empty-panel__loading-dot"}),a.jsx("span",{className:"empty-panel__loading-dot"}),a.jsx("span",{className:"empty-panel__loading-dot"})]}),a.jsx("span",{className:"sr-only",children:"正在加载会话记录"})]});if(!p)return a.jsx("div",{className:"empty-panel",children:"这个会话还没有历史记录。"});const an=F.canLoadEarlierEntries||F.isPulling||F.isLoadingFull,re=F.isPulling||F.isLoadingFull||F.triggerSource==="click",we=F.isLoadingFull?"正在加载全部对话…":F.isPulling?F.isReadyToLoad?"松开加载全部":"下拉加载更多":o?"加载全部对话":"点击加载全部",Re=F.isLoadingFull||F.triggerSource==="click"?u0:F.indicatorOffset,te={opacity:re?1:0,transform:`translate3d(-50%, calc(-100% + ${Re}px), 0) scale(${re?1:.92})`},ve={transform:`rotate(${F.indicatorRotation}deg)`};return a.jsxs(a.Fragment,{children:[an?a.jsx("section",{className:`conversation-entry is-history-loader ${F.isReadyToLoad?"is-ready":""}`,children:a.jsxs("div",{className:`timeline-history-loader ${F.isLoadingFull?"is-loading":""} ${F.triggerSource==="click"?"is-click-loading":""}`,children:[a.jsx("span",{className:"timeline-history-loader__indicator",style:te,"aria-hidden":"true",children:a.jsx("span",{className:"timeline-history-loader__indicator-surface",children:a.jsx("span",{className:"timeline-history-loader__indicator-track",style:ve,children:a.jsx("span",{className:`timeline-history-loader__indicator-spin ${F.isLoadingFull?"is-loading":""}`,children:a.jsx("span",{className:"timeline-history-loader__indicator-icon",children:a.jsx(GI,{})})})})})}),a.jsx("div",{className:"turn-complete-divider timeline-history-loader__divider",children:F.isLoadingFull?a.jsx("span",{className:"timeline-history-loader__content is-loading",children:a.jsx("span",{children:we})}):a.jsx("button",{type:"button",className:`timeline-history-loader__button ${F.isPulling?"is-pulling":""}`,onClick:()=>J("click"),children:we})})]})}):null,d.map(V=>{var Pe;if(V.kind==="item")return Dt(V.item);const{turn:q}=V,de=V.changeSet,ce=((Pe=q.completion)==null?void 0:Pe.patchSummary)??null,Ae=!!R[q.id],Ee=q.hiddenItems.length>0&&!Ae,$e=Ae?zD(q.hiddenItems):UD(q.hiddenItems);return a.jsxs("section",{className:"conversation-turn",children:[q.visibleStartItems.map(ht=>Dt(ht)),q.hiddenItems.length>0?a.jsxs("div",{className:"conversation-turn__history",children:[a.jsxs("button",{type:"button",className:`turn-history-toggle ${Ae?"is-expanded":""}`,onClick:()=>Ze(q.id),"aria-expanded":Ae,children:[a.jsx("span",{className:"turn-history-toggle__label",children:$e}),a.jsx("span",{className:"turn-history-toggle__chevron","aria-hidden":"true",children:a.jsx("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:a.jsx("path",{d:"m9 6 6 6-6 6"})})})]}),Ee?null:q.hiddenItems.map(ht=>Dt(ht))]}):null,q.completion&&q.visibleEndItems.length>0?a.jsx("section",{className:"conversation-turn-complete",children:a.jsx("div",{className:"turn-complete-divider",children:a.jsx("span",{children:q.completion.durationLabel})})}):null,q.visibleEndItems.map(ht=>Dt(ht)),de&&de.source==="app-server"&&de.files.length>0?Tt(de):null,q.completion&&q.visibleEndItems.length===0?a.jsx("section",{className:"conversation-turn-complete",children:a.jsx("div",{className:"turn-complete-divider",children:a.jsx("span",{children:q.completion.durationLabel})})}):null,de&&de.status==="completed"&&de.files.length>0?Et(de,q.id,u_(q.id),ce):ce?rt(q.id,u_(q.id),ce):null]},q.id)})]})}),JD=({sessionId:e,workspaceDirectorySnapshot:t=null,workspaceAgentIndicatorState:i,embedded:r=!1,isDesktopSidebar:o,sidebarOffset:u=0,isSidebarDragging:d=!1,onOpenSidebar:m,onSelectSession:y,onExitToNodes:g}={})=>{var Jc,Di,Oi,Cl,eu,tu,Tl,Ml,Vd,Xd,Dr,Fo,Zd,nu,su,_a,Na,Li,au;const{sessionId:b}=Mc({strict:!1}),p=e??b??"",v=W0(p),w=(v==null?void 0:v.agentId)??vo(),N=Hi(),j=Ka(),{data:T}=e5({scope:{sessionId:p,agentId:w??void 0},selectedSessionId:p,enabled:!r&&!t}),M=_.useMemo(()=>zI(t??T,v),[T,v,t]),P=(M==null?void 0:M.sessions.find(x=>x.id===p))??null,I=!!(P||v!=null&&v.session),k=zA({sessionId:p,scope:{sessionId:p,agentId:w??void 0},enabled:!!p}),{historyState:O,archivedState:Q,loadMoreHistory:J,loadMoreProjectlessHistory:F,loadMoreArchived:B,loadMoreProjectlessArchived:G,reset:Z}=n5({scope:{sessionId:p},selectedSessionId:p}),ae=_.useRef(null),he=_.useRef(null),ne=_.useRef(null),Ce=_.useRef(null),R=_.useRef(null),[X,le]=_.useState(!1),[ue,ye]=_.useState(()=>typeof window<"u"&&window.innerWidth>=Dx),[D,oe]=_.useState(()=>VD()),[je,z]=_.useState(!1),[be,De]=_.useState(""),[se,pe]=_.useState([]),[ke,Ze]=_.useState(null),[zt,Fe]=_.useState(null),[kt,Bt]=_.useState(null),[Gt,Xt]=_.useState(()=>sy()),[Ft,qe]=_.useState(()=>L3()),[dt,un]=_.useState(()=>P4(p)),[$t,An]=_.useState(()=>U4(p)),[Nn,Tt]=_.useState(()=>z4(p)),lt=ly(),Et=_.useMemo(()=>lt.map(({id:x,...L})=>L),[lt]),[rt,st]=_.useState({}),[Dt,an]=_.useState(null),[re,we]=_.useState(!1),[Re,te]=_.useState(!1),[ve,V]=_.useState(""),[q,de]=_.useState(!1),[ce,Ae]=_.useState(!1),[Ee,$e]=_.useState(null),[Pe,ht]=_.useState(null),[Xe,tn]=_.useState(!1),[Le,rn]=_.useState(!1),[hn,ns]=_.useState("code"),[Xs,$s]=_.useState(!1),[oa,On]=_.useState(null),[Ss,Kt]=_.useState(null),[Zs,us]=_.useState({}),[Ln,Ot]=_.useState(null),[Wn,Sn]=_.useState(!1),[Jn,js]=_.useState(!1),[Hs,ca]=_.useState(!1),[Fs,Js]=_.useState(!1),[ua,da]=_.useState(null),[fa,In]=_.useState(null),[ws,Os]=_.useState({}),[ee,Be]=_.useState(!1),[Ke,Lt]=_.useState({state:"connected",attempt:0,maxAttempts:5}),[Zt,Pt]=_.useState({sessionId:p??null,pending:!!p,error:null}),[At,mn]=_.useState({state:"idle"}),jn=_.useRef({}),kn=_.useRef(M),pn=_.useRef(null);_.useEffect(()=>{Jf(Gt)},[Gt]),_.useEffect(()=>{P3(Ft)},[Ft]),_.useEffect(()=>{Et.length!==0&&(Et.some(x=>x.value===Gt)||Xt(Et[0].value))},[Et,Gt]),_.useEffect(()=>{un(P4(p)),An(U4(p)),Tt(z4(p)),Bt(null),ns("code"),$s(!1),On(null),Kt(null),us({}),Ot(null),Sn(!1),js(!1),ca(!1),Js(!1),da(null),In(null),Os({}),es({}),Ws({}),pr({}),qi(0),ea(!1),ji(!1),gr(null),wi.current=null,Ni.current=null,_r.current=null,Ga.current=null,C.current=!1,W.current=!!p},[p]),_.useEffect(()=>{jn.current=ws},[ws]),_.useEffect(()=>{kn.current=M},[M]),_.useEffect(()=>{U3(p,dt)},[dt,p]),_.useEffect(()=>{z3(p,$t)},[$t,p]),_.useEffect(()=>{B3(p,Nn)},[Nn,p]),_.useEffect(()=>{st({}),an(null)},[p]),_.useEffect(()=>{vt.current=null},[p]),_.useEffect(()=>{if(!ke)return;const x=K=>{K.key==="Escape"&&Ze(null)},L=document.body.style.overflow;return document.body.style.overflow="hidden",window.addEventListener("keydown",x),()=>{document.body.style.overflow=L,window.removeEventListener("keydown",x)}},[ke]);const[U,Ne]=_.useState(!1),Ue=_.useRef(null),Qe=_.useRef(null),at=_.useRef(null),Je=_.useRef(0),vt=_.useRef(null),ot=_.useRef(0),nn=_.useRef(0),Jt=_.useRef(0),qt=_.useRef(null),St=_.useRef(null),En=_.useRef(0),gt=_.useRef(null),ss=_.useRef(!1),Ns=_.useRef(!1),ks=_.useRef(!1),as=_.useRef(0),Es=_.useRef(p??null),is=_.useRef({sessionId:p??null,agentId:null,embedded:r}),[Cs,es]=_.useState({}),[qs,Ws]=_.useState({}),[Ks,pr]=_.useState({}),[Fi,qi]=_.useState(0),[Wi,ea]=_.useState(!1),[Ma,ji]=_.useState(!1),[Qa,gr]=_.useState(null),wi=_.useRef(null),Ni=_.useRef(null),_r=_.useRef(null),Ga=_.useRef(null),C=_.useRef(!1),W=_.useRef(!1),He=_.useRef(new Set),tt=_.useCallback(x=>{if(x.length===0)return;const L=x.map(Se=>`${Se}:`),K=Se=>L.some(Ge=>Se.startsWith(Ge));es(Se=>Object.fromEntries(Object.entries(Se).filter(([Ge])=>!K(Ge)))),Ws(Se=>Object.fromEntries(Object.entries(Se).filter(([Ge])=>!K(Ge)))),pr(Se=>Object.fromEntries(Object.entries(Se).filter(([Ge])=>!K(Ge))))},[]),Rt=_.useCallback(x=>{He.current.add(x)},[]),ct=_.useCallback(x=>{He.current.delete(x)},[]),Nt=_.useRef(null),Yn=_.useRef(null),Kn=_.useRef(null),Ya=_.useRef(null),Ra=_.useRef(D),ii=_.useRef(null),Va=_.useRef(null);let ge=HA(P,(Jc=k.data)==null?void 0:Jc.session)??(v==null?void 0:v.session)??null;const gn=(M==null?void 0:M.agent)??null;let ta=(M==null?void 0:M.projects.find(x=>x.id===(ge==null?void 0:ge.project_id)))??(v==null?void 0:v.project);const xo=!!(ge&&ge.project_id===""),xa=(ge==null?void 0:ge.capability.can_show_git)??!1,na=(ge==null?void 0:ge.capability.can_show_terminal)??!1;is.current={sessionId:p??null,agentId:(ge==null?void 0:ge.agent_id)??(gn==null?void 0:gn.id)??w,embedded:r};const sn=_.useCallback(()=>{var L;const x=(ge==null?void 0:ge.agent_id)??(gn==null?void 0:gn.id)??w;return x&&((L=St.current)==null?void 0:L.agentId)===x?Promise.resolve(St.current.target):cn({sessionId:p,agentId:x})},[gn==null?void 0:gn.id,w,ge==null?void 0:ge.agent_id,p]),ri=_.useCallback(async x=>{if(r){y==null||y(x);return}Ea(x),sl(x),gn!=null&&gn.id&&fr(gn.id),await N({to:"/",replace:!0})},[gn==null?void 0:gn.id,r,N,y]),yr=_.useCallback(async()=>{if(r){g==null||g();return}await N({to:"/nodes"})},[r,N,g]),So=x=>x instanceof Element&&!!x.closest('button, textarea, input, a, [role="button"], [role="dialog"]'),Dc=x=>{if(!(x instanceof Element))return!1;const L=x.closest(".conversation-markdown-code-block__pre, .conversation-markdown-table__scroll");return!!(L&&L.scrollWidth-L.clientWidth>1)},jo=x=>So(x)||Dc(x),ki=()=>{const x=ne.current;if(!x)return;const L=()=>{x.scrollTo({top:x.scrollHeight,behavior:"auto"})};L(),window.requestAnimationFrame(()=>{L(),window.requestAnimationFrame(L)})},wo=_.useCallback(()=>{const x=ne.current;return x?x.scrollHeight-x.scrollTop-x.clientHeight<=Ox:!0},[]),ul=_.useCallback(x=>{(x!=null&&x.force||wo())&&ki()},[wo]),kd=()=>{const x=ne.current;if(!x){Be(!1);return}const L=x.scrollHeight-x.scrollTop-x.clientHeight;Be(L>Ox)},Ts=_.useCallback(x=>{j.setQueriesData({queryKey:hs},x)},[j]),Ed=_.useCallback((x,L)=>{j.setQueryData(v5({sessionId:x,scope:{sessionId:x}}),K=>FA(K??void 0,x,L)??K)},[j]),sg=(M==null?void 0:M.projects)??[],vr=(M==null?void 0:M.sessions)??[],ag=(M==null?void 0:M.project_stats)??[],Rh=O[gh]??al,Ah=Q[gh]??al,Pn=_.useMemo(()=>{var x;return(x=ge==null?void 0:ge.subagent)!=null&&x.parent_session_id?vr.find(L=>{var K;return L.id===((K=ge==null?void 0:ge.subagent)==null?void 0:K.parent_session_id)})??null:null},[(Di=ge==null?void 0:ge.subagent)==null?void 0:Di.parent_session_id,vr]),dl=_.useCallback(x=>{const L=x.session_id;L&&(j.setQueryData(ic(L),K=>d5(K,x.entries)),j.setQueryData(["timeline",L],K=>{const Se=ZR(K,x);return Se.view==="full_compact"&&LA(Se),Se}))},[j]),Ih=_.useCallback(x=>{var xt,_n;const L=x.session_id;if(!L)return;const K=is.current.sessionId===L;dl(x.timeline),j.setQueryData(["interactions",L],x.interactions),K&&$e(Cn=>Cn&&x.interactions.some(fs=>fs.id===Cn)?Cn:null),j.setQueryData(["plan",L],x.plan_snapshot),x.change_sets.length>0?(tt(x.change_sets.map(Cn=>Cn.id)),j.setQueryData(["change-sets",L],x.change_sets),Rt(L)):He.current.has(L)||(j.setQueryData(["change-sets",L],[]),ct(L)),j.setQueryData(["session-run-workbench",L],x.run_workbench);const Se=(xt=x.timeline.entries.at(-1))==null?void 0:xt.timestamp,Ge=Se&&(!x.session_patch.last_event_at||+new Date(Se)>+new Date(x.session_patch.last_event_at))?{...x.session_patch,last_event_at:Se}:x.session_patch,bt=Sx(Ge);bt&&Ed(L,bt);const ze=t0(Ge);ze&&Lp(kn.current??void 0,L)&&Ts(Cn=>Ff(Cn,L,ze)),K&&(x.session_patch.run_state==="running"||x.session_patch.run_state==="completed"||x.session_patch.run_state==="idle")&&(de(x.session_patch.run_state==="running"),x.session_patch.run_state!=="running"&&Ae(!1)),K&&((_n=x.run_workbench)!=null&&_n.terminal_snapshot)&&Os(Cn=>{var Ye;const fs=new Set((Ye=x.run_workbench)==null?void 0:Ye.terminal_snapshot.terminals.map(_s=>_s.id)),Rs={};for(const[_s,xs]of Object.entries(Cn))fs.has(_s)&&(Rs[_s]=xs);return Rs}),Pn!=null&&Pn.id&&j.invalidateQueries({queryKey:["timeline",Pn.id,"prefix-source"],exact:!0})},[dl,tt,Ed,Rt,Pn==null?void 0:Pn.id,j,ct]),fl=_.useCallback(async x=>{var Se;if(!p)return null;const L=p;if(((Se=qt.current)==null?void 0:Se.sessionId)===L)return qt.current.promise;const K=(async()=>{var bt;const Ge=++Je.current;mn({state:"recovering"});try{const xt=await(await sn()).client.getSessionBootstrap(p);return Je.current!==Ge?null:(Ih(xt),nn.current=Date.now(),mn({state:"idle"}),xt)}catch(ze){return Je.current!==Ge||mn({state:"failed",error:ze instanceof Error?ze.message:x==="initial"?"会话加载失败。":"会话同步失败。"}),null}finally{((bt=qt.current)==null?void 0:bt.sessionId)===L&&(qt.current=null)}})();return qt.current={sessionId:L,promise:K},K},[Ih,sn,p]),br=_.useCallback(x=>{p&&(Jt.current>0||(Jt.current=Date.now(),fl(x).then(L=>{Pt({sessionId:p,pending:!1,error:L?null:"Unable to load session bootstrap."})}).catch(L=>{Pt({sessionId:p,pending:!1,error:L instanceof Error?L.message:"Unable to load session bootstrap."})})))},[fl,p]),Dh=_.useCallback(async()=>{if(!p||He.current.has(p))return;const L=await(await sn()).client.getSessionChangeSets(p);tt(L.map(K=>K.id)),j.setQueryData(["change-sets",p],L),Rt(p)},[tt,Rt,j,sn,p]),No=_.useCallback(async(x="click")=>{if(!p||Ma)return;const L=ne.current;L&&(Ga.current=L.scrollHeight,C.current=!0),gr(x),ji(!0);const K=Date.now();try{const Ge=await(await sn()).client.getSessionTimeline(p,{view:"full_compact"});dl(Ge)}finally{if(x==="click"){const Se=II-(Date.now()-K);Se>0&&await new Promise(Ge=>{window.setTimeout(Ge,Se)})}ji(!1),qi(0),ea(!1),gr(null)}},[dl,Ma,sn,p]),Cd=_.useCallback(async x=>{if(!p)return;const L=cp(x.changeSetId,x.path,x.itemId);if(!(Cs[L]||Ks[L])){pr(K=>({...K,[L]:!0})),Ws(K=>({...K,[L]:void 0}));try{const Se=await(await sn()).client.getSessionChangeSetFileDiff(p,x);es(Ge=>({...Ge,[L]:Se}))}catch(K){Ws(Se=>({...Se,[L]:K instanceof Error?K.message:"无法读取这个文件的差异详情。"}))}finally{pr(K=>({...K,[L]:!1}))}}},[Cs,Ks,sn,p]),Sa=cs({queryKey:["timeline",p],enabled:!1,queryFn:async()=>BI,initialData:p?OA(p)??j.getQueryData(["timeline",p]):void 0,refetchInterval:!1}),hl=cs({queryKey:ic(p),enabled:!1,queryFn:async()=>[],initialData:[]});_.useEffect(()=>{const x=v==null?void 0:v.optimisticEntry;!p||(v==null?void 0:v.sessionId)!==p||!x||j.setQueryData(ic(p),L=>L!=null&&L.some(K=>K.id===x.id)?L:r0(L,x))},[v,j,p]),_.useEffect(()=>{var L;(v==null?void 0:v.sessionId)!==p||!(((L=k.data)==null?void 0:L.session.id)===p||T!=null&&T.sessions.some(K=>K.id===p))||bE(p)},[T,v==null?void 0:v.sessionId,(Oi=k.data)==null?void 0:Oi.session.id,p]);const Oh=Qm(Sa.data),ml=hl.data??[],Oc=Oh.length>0||ml.length>0||!!(v!=null&&v.optimisticEntry),xr=cs({queryKey:["timeline",Pn==null?void 0:Pn.id,"prefix-source"],enabled:!!(Pn!=null&&Pn.id),queryFn:async()=>(await(await cn({sessionId:Pn.id,projectId:Pn.project_id,agentId:Pn.agent_id})).client.getSessionTimeline(Pn.id,{view:"tail"})).entries,refetchInterval:!1}),Lh=_.useMemo(()=>{const x=Qm(Sa.data);return ge!=null&&ge.subagent?new Set:kD(x)},[ge==null?void 0:ge.subagent,Sa.data]),Lc=_.useMemo(()=>ND(Qm(Sa.data)),[Sa.data]),Td=_.useMemo(()=>ge!=null&&ge.subagent?[]:vr.filter(x=>{var L;return x.id!==p&&((L=x.subagent)==null?void 0:L.parent_session_id)===p&&!x.archived}).filter(x=>{if(x.run_state==="running")return!0;if(!((ge==null?void 0:ge.run_state)==="running"||q))return!1;if(Lh.has(x.id))return!0;if(!Lc)return!1;const L=new Date(Lc).getTime(),K=new Date(x.last_event_at).getTime();return Number.isFinite(L)&&Number.isFinite(K)&&K>=L-MI}).sort((x,L)=>+new Date(L.last_event_at)-+new Date(x.last_event_at)),[Lc,q,Lh,ge==null?void 0:ge.run_state,ge==null?void 0:ge.subagent,p,vr]);_.useEffect(()=>{if(!p){pn.current=null,ks.current=!1,as.current=0,Es.current=null,Pt({sessionId:null,pending:!1,error:null}),Lt({state:"connected",attempt:0,maxAttempts:5});return}const x=!Oc;Pt({sessionId:p,pending:x,error:null}),nn.current=x?0:Date.now(),Jt.current=0},[Oc,p]),_.useEffect(()=>{if(!p||!Zt.pending)return;if(Ke.state==="failed"){br("initial");return}if(Ke.state!=="connected")return;const x=ot.current;if(x<=0)return;const L=window.setTimeout(()=>{nn.current>=x||br("initial")},1200);return()=>{window.clearTimeout(L)}},[Ke.state,Zt.pending,br,p]),_.useEffect(()=>{if(!p||Ke.state!=="connected"||Zt.pending||Oc||!ks.current||Es.current!==p)return;const x=as.current;if(x<=0)return;const L=window.setTimeout(()=>{if(ks.current&&as.current===x){if(nn.current>=x){ks.current=!1,as.current=0,Es.current=null;return}ks.current=!1,as.current=0,Es.current=null,fl("connected")}},1200);return()=>{window.clearTimeout(L)}},[Ke.state,fl,Oc,Zt.pending,p]);const ko=cs({queryKey:["change-sets",p],enabled:!1,queryFn:async()=>p?(await sn()).client.getSessionChangeSets(p):[],initialData:p?j.getQueryData(["change-sets",p])??[]:[],refetchInterval:!1}),li=cs({queryKey:["session-git-workspace",p],enabled:!!(p&&xa&&hn==="git"),queryFn:async()=>(await sn()).client.getSessionGitWorkspace(p),refetchInterval:!1}),oi=cs({queryKey:["session-git-history",p],enabled:!1,queryFn:async()=>(await sn()).client.getSessionGitHistory(p),refetchInterval:!1}),Ei=cs({queryKey:["session-run-workbench",p],enabled:!!p&&na&&(Wn||Jn||hn==="terminal"),queryFn:async()=>p?(await sn()).client.getSessionRunWorkbench(p):null,initialData:p?j.getQueryData(["session-run-workbench",p])??null:null,refetchInterval:!1}),Eo=_.useCallback(async x=>{if(!p)return;const L=["session-run-workbench",p],K=j.getQueryData(L);if(K){j.setQueryData(L,x(K));return}const Ge=await(await sn()).client.getSessionRunWorkbench(p);j.setQueryData(L,x(Ge))},[j,sn,p]),Ki=cs({queryKey:["plan",p],enabled:!1,queryFn:async()=>null,initialData:p?j.getQueryData(["plan",p])??null:null,refetchInterval:!1}),Co=cs({queryKey:["interactions",p],enabled:!1,queryFn:async()=>[],initialData:p?j.getQueryData(["interactions",p])??[]:[],refetchInterval:!1}),pl=_.useCallback(async(x,L)=>{if(p){Os(K=>{var Se,Ge,bt;return{...K,[x]:{chunks:((Se=K[x])==null?void 0:Se.chunks)??[],nextCursor:((Ge=K[x])==null?void 0:Ge.nextCursor)??0,truncated:((bt=K[x])==null?void 0:bt.truncated)??!1,isLoading:!0,error:null}}});try{const K=await sn(),Se=jn.current[x],Ge=await K.client.getSessionTerminalOutput({sessionId:p,terminalId:x,cursor:L!=null&&L.force||Se!=null&&Se.truncated||Se==null?void 0:Se.nextCursor});Os(bt=>{const ze=bt[x],xt=L!=null&&L.force||Ge.truncated||!ze?Ge.chunks:$x(ze.chunks,Ge.chunks);return{...bt,[x]:{chunks:xt,nextCursor:Ge.next_cursor,truncated:Ge.truncated,isLoading:!1,error:null}}})}catch(K){Os(Se=>{var Ge,bt,ze;return{...Se,[x]:{chunks:((Ge=Se[x])==null?void 0:Ge.chunks)??[],nextCursor:((bt=Se[x])==null?void 0:bt.nextCursor)??0,truncated:((ze=Se[x])==null?void 0:ze.truncated)??!1,isLoading:!1,error:K instanceof Error?K.message:"无法读取终端输出。"}}})}}},[p]);_.useEffect(()=>{var Se,Ge;const x=(Se=Ei.data)==null?void 0:Se.terminal_snapshot.active_terminal_id,L=(Ge=Ei.data)==null?void 0:Ge.terminal_snapshot.terminals.find(bt=>bt.id===x);if(!x||!L)return;const K=ws[x];(!K||K.truncated||K.nextCursor<L.output_cursor)&&pl(x)},[pl,Ei.data,ws]);const Md=!!(ge!=null&&ge.subagent&&(Pn!=null&&Pn.id)&&xr.isPending&&!xr.data),gl=_.useMemo(()=>{const x=Qm(Sa.data);return ge!=null&&ge.subagent?Pn!=null&&Pn.id&&xr.isPending&&!xr.data?[]:SD(x,xr.data):x},[Pn==null?void 0:Pn.id,xr.data,xr.isPending,ge==null?void 0:ge.subagent,Sa.data]),_l=_.useMemo(()=>XR(gl,hl.data),[gl,hl.data]);_.useEffect(()=>{p&&window.localStorage.setItem(NI,p)},[p]),_.useEffect(()=>{const x=at.current;x&&((hl.data??[]).some(L=>L.id===x.optimisticEntryId)||(at.current=null))},[hl.data]),_.useEffect(()=>{rn(!1)},[p]),_.useEffect(()=>{V((ge==null?void 0:ge.title)??""),te(!1)},[ge==null?void 0:ge.title,p]),_.useEffect(()=>{Ae(!1)},[p]),_.useEffect(()=>()=>{Ue.current&&window.clearTimeout(Ue.current),Qe.current&&window.clearTimeout(Qe.current),Va.current&&window.cancelAnimationFrame(Va.current)},[]),_.useEffect(()=>{if(Qe.current&&(window.clearTimeout(Qe.current),Qe.current=null),!!zt)return Qe.current=window.setTimeout(()=>{Fe(null),Qe.current=null},DI),()=>{Qe.current&&(window.clearTimeout(Qe.current),Qe.current=null)}},[zt]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(j5,String(m0(D))),window.localStorage.setItem(Wf,Kf)}catch{}},[D]),_.useEffect(()=>{Ra.current=D},[D]),_.useEffect(()=>{if(typeof window>"u")return;const x=()=>{const L=window.innerWidth>=Dx;ye(L),L&&le(!1)};return x(),window.addEventListener("resize",x),()=>{window.removeEventListener("resize",x)}},[]),_.useEffect(()=>{if(!je)return;const x=K=>{const Se=Ya.current;if(!Se)return;const Ge=K.clientX-Se.startX,bt=m0(Se.startWidth+Ge);ii.current=bt,Va.current===null&&(Va.current=window.requestAnimationFrame(()=>{Va.current=null;const ze=ii.current,xt=ae.current;ze===null||!xt||xt.style.setProperty("--desktop-sidebar-width",`${ze}px`)}))},L=()=>{Va.current!==null&&(window.cancelAnimationFrame(Va.current),Va.current=null);const K=ii.current??Ra.current;ii.current=null,Ya.current=null,z(!1),Ra.current=K,oe(K)};return window.addEventListener("pointermove",x),window.addEventListener("pointerup",L),window.addEventListener("pointercancel",L),()=>{window.removeEventListener("pointermove",x),window.removeEventListener("pointerup",L),window.removeEventListener("pointercancel",L)}},[je]),_.useEffect(()=>{const x=L=>{const K=L.target;tn(!1),Ne(!1),!(K instanceof Element&&(K.closest(".conversation-topbar__actions")||K.closest(".conversation-topbar__title-actions")||K.closest(".picker-sheet")||K.closest(".picker-sheet-wrap")))&&(we(!1),Sn(!1),js(!1))};return window.addEventListener("pointerdown",x),()=>{window.removeEventListener("pointerdown",x)}},[]),_.useEffect(()=>{const x=ae.current;if(!x||ue)return;const L=bt=>{const ze=bt.touches[0];bt.touches.length!==1||!ze||jo(bt.target)||(Yn.current={startX:ze.clientX,startY:ze.clientY})},K=bt=>{if(bt.touches.length!==1)return;const ze=bt.touches[0];if(!Kn.current){const _n=Yn.current;if(!_n)return;const Cn=ze.clientX-_n.startX,fs=ze.clientY-_n.startY;if(Math.abs(Cn)<8&&Math.abs(fs)<8)return;if(Math.abs(Cn)<=Math.abs(fs)){Yn.current=null;return}xl(_n.startX,_n.startY)}Qc(ze.clientX,ze.clientY)&&bt.preventDefault()},Se=bt=>{if(Yn.current=null,!Kn.current)return;const ze=bt.changedTouches[0];if(!ze){Kn.current=null,fi(null);return}Zi(ze.clientX,ze.clientY)},Ge=()=>{Yn.current=null,Kn.current=null,fi(null)};return x.addEventListener("touchstart",L,{passive:!0,capture:!0}),x.addEventListener("touchmove",K,{passive:!1,capture:!0}),x.addEventListener("touchend",Se,{capture:!0}),x.addEventListener("touchcancel",Ge,{capture:!0}),()=>{x.removeEventListener("touchstart",L,{capture:!0}),x.removeEventListener("touchmove",K,{capture:!0}),x.removeEventListener("touchend",Se,{capture:!0}),x.removeEventListener("touchcancel",Ge,{capture:!0})}},[ue,X]),_.useEffect(()=>{const x=ne.current;if(!x)return;if(C.current&&Ga.current!==null){const K=Ga.current,Se=x.scrollHeight;x.scrollTop+=Math.max(0,Se-K),C.current=!1,Ga.current=null;return}if(!p||!W.current||gl.length===0)return;ki();const L=window.setTimeout(()=>{ki(),W.current=!1},120);return()=>{window.clearTimeout(L)}},[gl.length,p]),_.useEffect(()=>{const x=ne.current;if(!x)return;const L=()=>{kd()};return L(),x.addEventListener("scroll",L,{passive:!0}),window.addEventListener("resize",L),()=>{x.removeEventListener("scroll",L),window.removeEventListener("resize",L)}},[gl.length,p]),_.useEffect(()=>{const x=ne.current;if(!x)return;const L=Sa.data,K=Gm(L)&&!Ma,Se=()=>{wi.current=null,Ni.current=null,qi(0),ea(!1)},Ge=()=>{const Cn=K&&Ni.current!==null&&Fi>=l_;Se(),Cn&&No("pull")},bt=Cn=>{var fs,Rs;!K||Cn.touches.length!==1||x.scrollTop>0||So(Cn.target)||(wi.current=((fs=Cn.touches[0])==null?void 0:fs.clientX)??null,Ni.current=((Rs=Cn.touches[0])==null?void 0:Rs.clientY)??null)},ze=Cn=>{if(Cn.defaultPrevented)return;const fs=wi.current,Rs=Ni.current;if(fs===null||Rs===null||Cn.touches.length!==1)return;const Ye=Cn.touches[0],_s=((Ye==null?void 0:Ye.clientX)??fs)-fs,xs=((Ye==null?void 0:Ye.clientY)??Rs)-Rs;if(Math.abs(_s)>Math.abs(xs)){Se();return}if(xs<=0){qi(0),ea(!1);return}if(x.scrollTop>0){Se();return}Cn.cancelable&&Cn.preventDefault(),ea(!0),qi(Math.min(Lx,xs))},xt=()=>{Ge()},_n=()=>{Se()};return x.addEventListener("touchstart",bt,{passive:!0}),x.addEventListener("touchmove",ze,{passive:!1}),x.addEventListener("touchend",xt),x.addEventListener("touchcancel",_n),()=>{x.removeEventListener("touchstart",bt),x.removeEventListener("touchmove",ze),x.removeEventListener("touchend",xt),x.removeEventListener("touchcancel",_n)}},[Ma,No,Fi,Sa.data]),_.useEffect(()=>{var bt,ze;if(!p){gt.current!==null&&(clearTimeout(gt.current),gt.current=null),(bt=St.current)==null||bt.stream.setSessionId(null);return}let x=!1;const L=++En.current,K=is.current.agentId,Se=()=>{gt.current!==null&&(clearTimeout(gt.current),gt.current=null)},Ge=()=>{r||(Se(),gt.current=setTimeout(()=>{gt.current=null;const xt=is.current;qf(j,{scope:{sessionId:xt.sessionId,agentId:xt.agentId},selectedSessionId:xt.sessionId})},OI))};return K&&((ze=St.current)==null?void 0:ze.agentId)===K?(St.current.stream.setSessionId(p),()=>{x=!0}):(sn().then(xt=>{var fs,Rs;if(x||En.current!==L)return;const _n=xt.client.getConnectionKey();if(((fs=St.current)==null?void 0:fs.key)===_n){St.current.stream.setSessionId(p);return}(Rs=St.current)==null||Rs.stream.close(),ss.current=!1,Ns.current=!1;const Cn=xt.client.createEventStream(Ye=>{var iu,ru,Jd,ef,Yh,lu,ou,cu,Qs,rs,qo,Rl,Wo,uu,mi,Ko,du,fu,tf,nf,sf,af,rf,lf;const _s=typeof((iu=Ye.payload)==null?void 0:iu.sessionId)=="string"?Ye.payload.sessionId:null,xs=is.current.sessionId,wn=_s===xs?xs:null,Xn=typeof((ru=Ye.payload)==null?void 0:ru.projectId)=="string"?Ye.payload.projectId:null;if(Ye.type==="agent.online"){if(Ns.current){Ns.current=!1;return}Z(),Ge();return}if(Ye.type==="timeline.reset"&&wn){nn.current=Date.now(),ks.current=!1,as.current=0,Es.current=null,Pt({sessionId:wn,pending:!1,error:null});const pt=Array.isArray((Jd=Ye.payload)==null?void 0:Jd.entries)?Ye.payload.entries:[],yn=typeof((ef=Ye.payload)==null?void 0:ef.hasEarlierEntries)=="boolean"?Ye.payload.hasEarlierEntries:Gm(j.getQueryData(["timeline",wn]));dl(Qx(wn,pt,yn));const Hn=(Yh=pt[pt.length-1])==null?void 0:Yh.timestamp;Hn&&Ts(vn=>n0(vn,wn,Hn)),window.requestAnimationFrame(kd);return}if(Ye.type==="interaction.reset"&&wn){const pt=Array.isArray((lu=Ye.payload)==null?void 0:lu.requests)?Ye.payload.requests:[];j.setQueryData(["interactions",wn],pt),$e(yn=>yn&&pt.some(Hn=>Hn.id===yn)?yn:null);return}if(Ye.type==="plan.reset"&&wn){const pt=(ou=Ye.payload)!=null&&ou.planSnapshot&&typeof Ye.payload.planSnapshot=="object"?Ye.payload.planSnapshot:null;j.setQueryData(["plan",wn],pt);return}if(Ye.type==="timeline.delta"&&wn){const pt=Array.isArray((cu=Ye.payload)==null?void 0:cu.entries)?Ye.payload.entries:[],yn=typeof((Qs=Ye.payload)==null?void 0:Qs.hasEarlierEntries)=="boolean"?Ye.payload.hasEarlierEntries:Gm(j.getQueryData(["timeline",wn]));dl(Qx(wn,u5(void 0,pt),yn));const Hn=(rs=pt[pt.length-1])==null?void 0:rs.timestamp;Hn&&Ts(vn=>n0(vn,wn,Hn)),ul(),window.requestAnimationFrame(kd);return}if(Ye.type==="interaction.delta"&&wn){const pt=Array.isArray((qo=Ye.payload)==null?void 0:qo.requests)?Ye.payload.requests:[],yn=Array.isArray((Rl=Ye.payload)==null?void 0:Rl.resolvedRequestIds)?Ye.payload.resolvedRequestIds.filter(Hn=>typeof Hn=="string"&&Hn.trim().length>0):[];j.setQueryData(["interactions",wn],Hn=>{const vn=new Map((Hn??[]).map(Zn=>[Zn.id,Zn]));for(const Zn of pt)vn.set(Zn.id,Zn);for(const Zn of yn)vn.delete(Zn);return[...vn.values()].sort((Zn,pi)=>+new Date(pi.updated_at)-+new Date(Zn.updated_at))}),yn.length>0&&$e(Hn=>Hn&&yn.includes(Hn)?null:Hn);return}if(Ye.type==="plan.delta"&&wn){const pt=(Wo=Ye.payload)!=null&&Wo.planSnapshot&&typeof Ye.payload.planSnapshot=="object"?Ye.payload.planSnapshot:null;j.setQueryData(["plan",wn],pt);return}if(Ye.type==="changeset.reset"&&wn){const pt=Array.isArray((uu=Ye.payload)==null?void 0:uu.changeSets)?Ye.payload.changeSets:[];pt.length>0?(tt(pt.map(yn=>yn.id)),j.setQueryData(["change-sets",wn],pt),Rt(wn)):He.current.has(wn)||(j.setQueryData(["change-sets",wn],[]),ct(wn));return}if(Ye.type==="changeset.delta"&&wn){const pt=Array.isArray((mi=Ye.payload)==null?void 0:mi.changeSets)?Ye.payload.changeSets:[];tt(pt.map(yn=>yn.id)),j.setQueryData(["change-sets",wn],yn=>yD(yn,pt));return}if(Ye.type==="terminal.snapshot"&&wn){const pt=(Ko=Ye.payload)!=null&&Ko.snapshot&&typeof Ye.payload.snapshot=="object"?Ye.payload.snapshot:null;if(!pt)return;j.setQueryData(["session-run-workbench",wn],yn=>yn&&{...yn,terminal_snapshot:pt}),Os(yn=>{const Hn=new Set(pt.terminals.map(Zn=>Zn.id)),vn={};for(const[Zn,pi]of Object.entries(yn))Hn.has(Zn)&&(vn[Zn]=pi);return vn});return}if(Ye.type==="terminal.delta"&&wn){const pt=(du=Ye.payload)!=null&&du.terminal&&typeof Ye.payload.terminal=="object"?Ye.payload.terminal:null,yn=Array.isArray((fu=Ye.payload)==null?void 0:fu.chunks)?Ye.payload.chunks:[],Hn=typeof((tf=Ye.payload)==null?void 0:tf.activeTerminalId)=="string"?Ye.payload.activeTerminalId:null;if(!pt)return;j.setQueryData(["session-run-workbench",wn],vn=>{if(!vn)return vn;const Zn=vn.terminal_snapshot.terminals.filter(hu=>hu.id!==pt.id),pi=vn.terminal_snapshot.terminals.findIndex(hu=>hu.id===pt.id),Qo=[...Zn];return pi<=0?Qo.unshift(pt):Qo.splice(pi,0,pt),{...vn,terminal_snapshot:{...vn.terminal_snapshot,active_terminal_id:Hn,updated_at:pt.updated_at,terminals:Qo}}}),Os(vn=>{var pi;if(yn.length===0)return vn;const Zn=vn[pt.id];return{...vn,[pt.id]:{chunks:$x((Zn==null?void 0:Zn.chunks)??[],yn),nextCursor:typeof((pi=Ye.payload)==null?void 0:pi.nextCursor)=="number"?Ye.payload.nextCursor:pt.output_cursor,truncated:(Zn==null?void 0:Zn.truncated)??!1,isLoading:!1,error:null}}});return}if(Ye.type==="thread.updated"&&Xn){const pt=typeof((nf=Ye.payload)==null?void 0:nf.action)=="string"?Ye.payload.action:"",yn=(sf=Ye.payload)!=null&&sf.projectPatch&&typeof Ye.payload.projectPatch=="object"?Ye.payload.projectPatch:null,Hn=Array.isArray((af=Ye.payload)==null?void 0:af.orderedProjectIds)?Ye.payload.orderedProjectIds.filter(vn=>typeof vn=="string"&&vn.trim().length>0):[];if((pt==="pin"||pt==="unpin"||pt==="rename")&&yn){Ts(vn=>Wu(vn,Xn,yn));return}if(pt==="reorder"&&Hn.length>0){Ts(vn=>Up(vn,Hn));return}if(pt==="remove"||pt==="archive"){Z(),Ts(vn=>zp(vn,Xn));return}if(pt==="unarchive"){Z(),Ge();return}}if(Ye.type==="session.updated"&&_s){const pt=(rf=Ye.payload)!=null&&rf.sessionPatch&&typeof Ye.payload.sessionPatch=="object"?t0(Ye.payload.sessionPatch):null,yn=(lf=Ye.payload)!=null&&lf.sessionPatch&&typeof Ye.payload.sessionPatch=="object"?Sx(Ye.payload.sessionPatch):null;yn&&Ed(_s,yn);const Hn=Lp(kn.current??void 0,_s);if(pt&&Hn)Ts(vn=>Ff(vn,_s,pt));else{if(is.current.embedded&&_s===xs&&!kn.current)return;if(Hn)return;Ge()}wn&&((pt==null?void 0:pt.run_state)==="running"||(pt==null?void 0:pt.run_state)==="completed"||(pt==null?void 0:pt.run_state)==="idle")&&(de(pt.run_state==="running"),pt.run_state!=="running"&&Ae(!1));return}Ye.type==="turn.completed"&&wn&&(de(!1),Ae(!1),j.setQueryData(["plan",wn],null))},{sessionId:p,reconnectWhenHidden:!0,onStatus:Ye=>{if(Lt(Ye),Ye.state==="connected"){const _s=Date.now(),xs=ss.current;ot.current=_s,ks.current=xs,as.current=xs?_s:0,Es.current=xs?p:null,Ns.current=!0,xs&&(Z(),Ge()),ss.current=!0,Ne(!1);return}Je.current+=1,mn({state:"idle"})}});St.current={key:_n,agentId:K,target:xt,stream:Cn},Cn.setSessionId(p)}).catch(xt=>{x||En.current!==L||Lt({state:"failed",attempt:0,maxAttempts:5,error:xt instanceof Error?xt.message:"Unable to connect to live session."})}),()=>{x=!0})},[r,sn,p]),_.useEffect(()=>()=>{var x;En.current+=1,gt.current!==null&&(clearTimeout(gt.current),gt.current=null),(x=St.current)==null||x.stream.close(),St.current=null},[]),_.useEffect(()=>{if(!p||(ge==null?void 0:ge.run_state)!=="running"||ge.context_usage)return;if(vt.current!==p){vt.current=p;return}let x=!1;const L=window.setTimeout(()=>{x||k.refetch()},1200);return()=>{x=!0,window.clearTimeout(L)}},[p,ge==null?void 0:ge.context_usage,ge==null?void 0:ge.run_state,k.refetch]),_.useEffect(()=>{var Ge,bt;if(!p||!I||!ge||!ta&&!xo||((Ge=k.data)==null?void 0:Ge.session.id)===p||k.isFetching||pn.current===p||typeof window>"u")return;pn.current=p;const x=window,L=()=>{k.refetch()},K=(bt=x.requestIdleCallback)==null?void 0:bt.call(x,L,{timeout:1500}),Se=K===void 0?window.setTimeout(L,320):null;return()=>{var ze;K!==void 0&&((ze=x.cancelIdleCallback)==null||ze.call(x,K)),Se!==null&&window.clearTimeout(Se)}},[ta,ge,(Cl=k.data)==null?void 0:Cl.session.id,k.isFetching,k.refetch,I,p]),_.useEffect(()=>{we(!1)},[ue,p]);const Ph=_.useCallback(x=>{var L;Bt(x),((L=x.effect)==null?void 0:L.type)==="set_session_model"&&(Xt(x.effect.model),x.effect.reasoning_effort&&qe(x.effect.reasoning_effort))},[]),Qi=Gn({mutationFn:async x=>(await sn()).client.sendSessionInput(x),onMutate:async x=>{await j.cancelQueries({queryKey:["timeline",x.sessionId]}),Fe(null),Ae(!1),de(!0),an(x.proposedPlanEntryId??null);const L=x.clearComposer!==!1;L&&(De(""),pe([])),Ue.current&&window.clearTimeout(Ue.current);const K=new Date().toISOString(),Se=`${uy}${x.sessionId}:${Date.now()}`;at.current=L?{optimisticEntryId:Se,draft:x.input,attachments:x.attachments}:null,j.setQueryData(ic(x.sessionId),Ge=>r0(Ge,{id:Se,kind:"user",title:"你",body:x.input,body_truncated:!1,detail_available:!1,patch_summary:null,session_ids:[],timestamp:K,accent:"primary",attachments:l5(x.attachments)})),Ts(Ge=>Ff(Ge,x.sessionId,{run_state:"running",run_state_changed_at:K,last_event_at:K}))},onSuccess:async(x,L)=>{an(null),L.proposedPlanEntryId&&st(K=>{const Se={...K};return delete Se[L.proposedPlanEntryId],Se}),await j.invalidateQueries({queryKey:hs}),await j.invalidateQueries({queryKey:["plan",L.sessionId]}),await j.invalidateQueries({queryKey:["change-sets",L.sessionId]}),Ue.current=null},onError:(x,L)=>{an(null),de(!1);const K=at.current;K&&(j.setQueryData(ic(L.sessionId),Se=>JR(Se,K.optimisticEntryId)),De(Se=>Se||K.draft),pe(Se=>Se.length>0?Se:K.attachments),at.current=null),Fe(x instanceof Error?x.message:"无法发送消息")}}),Pc=Gn({mutationFn:async x=>(await sn()).client.executeSessionCommand(x),onMutate:x=>{Fe(null),De(""),pe([]);const L=x.input.slice(1).trim().split(/\s+/)[0]??"",K=new Date().toISOString();Bt({panel_id:`command-panel-pending-${Date.now()}`,session_id:x.sessionId,command_name:L,command_text:x.input,title:`正在执行 /${L}`,description:null,status:"running",body:"命令执行中…",submitted_at:K,updated_at:K,input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null})},onSuccess:async x=>{Ph(x.panel),await j.invalidateQueries({queryKey:hs})},onError:(x,L)=>{Bt(null),De(K=>K||L.input),Fe(x instanceof Error?x.message:"无法执行命令")}}),yl=Gn({mutationFn:async x=>(await sn()).client.respondToSessionCommand(x),onMutate:()=>{Fe(null)},onSuccess:async x=>{Ph(x.panel),await j.invalidateQueries({queryKey:hs})},onError:x=>{Fe(x instanceof Error?x.message:"无法继续执行命令")}}),Uh=Gn({mutationFn:async x=>(await sn()).client.respondToSessionInteraction(x),onMutate:async x=>{Fe(null),$e(x.requestId),j.setQueryData(["interactions",x.sessionId],L=>(L??[]).map(K=>K.id===x.requestId?{...K,status:"submitting",updated_at:new Date().toISOString()}:K))},onSuccess:async(x,L)=>{await j.invalidateQueries({queryKey:["interactions",L.sessionId]})},onError:(x,L)=>{j.setQueryData(["interactions",L.sessionId],K=>(K??[]).map(Se=>Se.id===L.requestId?{...Se,status:"pending"}:Se)),$e(null),Fe(x instanceof Error?x.message:"无法提交确认回复")}}),ds=Gn({mutationFn:async x=>(await sn()).client.interruptSession(x),onMutate:async x=>{Fe(null),Ae(!0),de(!1),Ue.current&&(window.clearTimeout(Ue.current),Ue.current=null);const L=new Date().toISOString();Ts(K=>Ff(K,x,{run_state:"completed",run_state_changed_at:L,last_event_at:L})),j.setQueryData(["plan",x],null)},onSuccess:(x,L)=>{Ae(!1),j.invalidateQueries({queryKey:hs}),j.invalidateQueries({queryKey:["timeline",L]}),j.invalidateQueries({queryKey:["change-sets",L]})},onError:(x,L)=>{Ae(!1),de(!0),j.invalidateQueries({queryKey:hs}),j.invalidateQueries({queryKey:["plan",L]}),Fe(x instanceof Error?x.message:"无法中断会话")}});_.useEffect(()=>{!p||!ge||ce||ds.isPending||de(ge.run_state==="running")},[ds.isPending,ce,ge,ge==null?void 0:ge.run_state,p]);const Vn=Gn({mutationFn:async x=>(await cn({sessionId:x.sessionId})).client.updateSession(x)}),To=Gn({mutationFn:async x=>(await cn({projectId:x.projectId,agentId:x.agentId})).client.updateThread(x)}),ha=Gn({mutationFn:async x=>(await sn()).client.executeSessionGitAction({sessionId:p,action:x.action,path:x.path,branch:x.branch,message:x.message}),onMutate:async()=>{On(null)},onSuccess:(x,L)=>{j.setQueryData(["session-git-workspace",p],x.workspace),(L.action==="commit-all"||L.action==="switch-branch")&&j.invalidateQueries({queryKey:["session-git-history",p]})},onError:x=>{On(x instanceof Error?x.message:"无法执行 git 操作")}}),Mo=Gn({mutationFn:async x=>(await sn()).client.executeSessionTurnAction({sessionId:p,turnId:x.turnId,action:"rollback"}),onMutate:()=>{Kt(null)},onSuccess:x=>{Kt(null),us(L=>({...L,[x.turn_id]:!0})),j.setQueryData(["session-git-workspace",p],x.workspace)},onError:(x,L)=>{Kt({turnId:L.turnId,message:x instanceof Error?x.message:"无法回滚这轮改动"})}}),ci=Gn({mutationFn:async x=>(await sn()).client.saveSessionRunCommand({sessionId:p,action:x.action,commandId:x.commandId,command:x.command}),onMutate:()=>{Ot(null)},onSuccess:async({catalog:x})=>{await Eo(L=>({...L,command_catalog:x}))},onError:x=>{Ot(x instanceof Error?x.message:"无法保存项目命令。")}}),Xa=Gn({mutationFn:async x=>(await sn()).client.saveSessionRunWebsite({sessionId:p,action:x.action,websiteId:x.websiteId,website:x.website}),onMutate:()=>{Ot(null)},onSuccess:async({catalog:x})=>{await Eo(L=>({...L,website_catalog:x}))},onError:x=>{Ot(x instanceof Error?x.message:"无法保存项目网页。")}}),Uc=Gn({mutationFn:async()=>(await sn()).client.generateSessionRunCommand({sessionId:p,prompt:"",model:lp()}),onMutate:()=>{Ot(null),da(null)},onSuccess:async({generation:x,catalog:L})=>{await Eo(K=>({...K,command_catalog:L})),da(x.reason)},onError:x=>{Ot(x instanceof Error?x.message:"无法一键生成项目命令。")}}),Ci=Gn({mutationFn:async()=>(await sn()).client.generateSessionRunWebsite({sessionId:p,prompt:"",model:lp()}),onMutate:()=>{Ot(null),In(null)},onSuccess:async({generation:x,catalog:L})=>{await Eo(K=>({...K,website_catalog:L})),In(x.reason)},onError:x=>{Ot(x instanceof Error?x.message:"无法一键生成项目网页。")}}),ms=Gn({mutationFn:async x=>(await sn()).client.executeSessionTerminalAction({sessionId:p,action:x.action,commandId:x.commandId,terminalId:x.terminalId}),onMutate:()=>{Ot(null)},onSuccess:async(x,L)=>{j.setQueryData(["session-run-workbench",p],K=>K&&{...K,terminal_snapshot:x.snapshot}),(L.action==="run-command"||L.action==="run-kill-command")&&x.terminal&&(Sn(!1),ns("terminal"),await pl(x.terminal.id,{force:!0})),L.action==="focus"&&L.terminalId&&await pl(L.terminalId),L.action==="close"&&L.terminalId&&Os(K=>{const Se={...K};return delete Se[L.terminalId],Se})},onError:x=>{Ot(x instanceof Error?x.message:"无法执行终端操作。")}}),Gi=ko.data??[],zc=ge&&_D(Sa.data)!=="tail"?HD(ge):!1,Ro=_.useMemo(()=>FD(_l,{projectPath:ta==null?void 0:ta.path,compactCompletedTurns:zc}),[zc,ta==null?void 0:ta.path,_l]),Ti=_.useMemo(()=>GD(Ro.blocks,Gi),[Ro.blocks,Gi]),Sr=_.useMemo(()=>{const x=Sa.data,L=Gm(x),K=Math.max(0,Math.min(Lx,Fi)),Se=Math.max(0,Math.min(1,K/l_));return{hasEarlierEntries:L,canLoadEarlierEntries:L,isPulling:Wi,pullDistance:K,isReadyToLoad:K>=l_,isLoadingFull:Ma,indicatorOffset:Ma?u0:Math.min(u0,K*.75),indicatorRotation:Ma?Px:Math.round(Se*Px),triggerSource:Qa}},[Ma,Wi,Qa,Fi,Sa.data]),jr=[...Ti].reverse().find(x=>x.kind==="turn"&&!x.turn.completion)??null;_.useEffect(()=>{var Se;if(typeof window>"u")return;const x=window,L=(Se=x.requestIdleCallback)==null?void 0:Se.call(x,()=>{d0()},{timeout:1500}),K=L===void 0?window.setTimeout(()=>{d0()},320):null;return()=>{var Ge;L!==void 0&&((Ge=x.cancelIdleCallback)==null||Ge.call(x,L)),K!==null&&window.clearTimeout(K)}},[]);const Ao=!!(ge&&(ta||xo)),wr=!!p&&k.isPending&&!ge;ge??(ge=UI),ta??(ta=LI);const Rd=!!p&&Zt.sessionId!==p,Ad=!!p&&!Ao&&(Zt.pending||Rd||wr),zh=Ad?"正在载入会话…":k.error instanceof Error?k.error.message:Zt.error?Zt.error:"没有找到这个会话。",Id=ge.capability.can_send_input&&!ce,Dd=Id&&(i===void 0||i==="online"),Bc=(Co.data??[]).filter(x=>x.status==="pending"||x.status==="submitting"),Od=(ge.run_state==="running"||q)&&!ce||ds.isPending,Io=Id&&Bc.length===0&&!Od&&!Qi.isPending,Do=(gn==null?void 0:gn.id)??ge.agent_id,Aa=_.useCallback((x,L)=>{st(K=>{if(!L.trim()){if(!(x in K))return K;const Se={...K};return delete Se[x],Se}return{...K,[x]:L}})},[]),Oo=_.useCallback((x,L)=>{const K=L.trim();!K||!Io||Qi.mutate({sessionId:ge.id,input:K,attachments:[],model:Gt,reasoningEffort:Ft,serviceTier:dt?"fast":void 0,planMode:$t,yoloMode:Nn,clearComposer:!1,proposedPlanEntryId:x})},[Io,dt,$t,Nn,Gt,Ft,Qi,ge.id]),ja=_.useCallback(x=>{Mo.mutate({turnId:x})},[Mo]),Nr=Mo.isPending?((eu=Mo.variables)==null?void 0:eu.turnId)??null:null,Ld=_.useMemo(()=>a.jsx(ZD,{sessionId:ge.id,sessions:vr,sessionRunState:ge.run_state,isDesktopSidebar:r?!!o:ue,projectPath:ta.path,renderedBlocks:Ti,lastToolGroupId:Ro.lastToolGroupId,sessionChangeSets:Gi,isSubagentTimelinePending:Md,isInitialTimelinePending:!!p&&_l.length===0&&(Zt.pending||Rd),hasTimeline:_l.length>0,proposedPlanReplyDrafts:rt,pendingProposedPlanReplyEntryId:Dt,canRespondToProposedPlan:Io,onProposedPlanReplyDraftChange:Aa,onSubmitProposedPlanReply:Oo,onPreviewImage:Ze,changeSetDiffs:Cs,changeSetDiffErrors:qs,loadingChangeSetDiffKeys:Ks,onLoadSessionChangeSets:Dh,onLoadChangeSetFileDiff:Cd,onLoadFullTimeline:()=>{No()},timelineLoadState:Sr,canRollbackChangeSets:xa,pendingRollbackTurnId:Nr,rollbackTurnError:Ss,rolledBackTurnIds:Zs,onRollbackTurn:ja},ge.id),[xa,Io,qs,Cs,Aa,Oo,r,ue,o,Md,Dh,Cd,No,Ks,ja,Dt,ta.path,rt,Ti,Ro.lastToolGroupId,Nr,Ss,Zs,ge.id,ge.run_state,Gi,vr,_l.length,Sr]),ui=_.useCallback(async(x,L,K)=>{var Se;Fe(null),we(!1),L==="pin"||L==="unpin"?ra.flushSync(()=>{Ts(Ge=>Pp(Ge,x,{pinned:L==="pin"}))}):L==="rename"&&(K!=null&&K.trim())&&Ts(Ge=>Pp(Ge,x,{title:K.trim()}));try{const Ge=await Vn.mutateAsync({sessionId:x,action:L,name:K}),bt=(Se=Ge.affectedSessionIds)!=null&&Se.length?Ge.affectedSessionIds:[x];if(L==="delete"){Ts(ze=>p3(ze,bt)),Z();for(const ze of bt)j.removeQueries({queryKey:["timeline",ze],exact:!0}),j.removeQueries({queryKey:ic(ze),exact:!0}),j.removeQueries({queryKey:["change-sets",ze],exact:!0}),ct(ze)}else Ts(ze=>m3(ze,bt,{...L==="rename"&&(K!=null&&K.trim())?{title:K.trim()}:{pinned:L==="pin"}}));if(x===ge.id&&L==="delete"){const ze=Ge.nextSessionId;ze?await ri(ze):await yr()}}catch(Ge){j.invalidateQueries({queryKey:hs}),Fe(Ge instanceof Error?Ge.message:"无法更新会话")}},[yr,ri,j,Z,ct,ge.id,Vn]),$c=_.useCallback(async(x,L,K)=>{var Ge,bt;Fe(null),we(!1);const Se=(Ge=K==null?void 0:K.name)==null?void 0:Ge.trim();L==="pin"||L==="unpin"?ra.flushSync(()=>{Ts(ze=>Wu(ze,x,{pinned:L==="pin"}))}):L==="rename"&&Se?Ts(ze=>Wu(ze,x,{display_name:Se})):L==="reorder"&&((bt=K==null?void 0:K.orderedProjectIds)!=null&&bt.length)?Ts(ze=>Up(ze,K.orderedProjectIds??[])):L==="remove"||L==="archive"?(Ts(ze=>zp(ze,x)),Z()):L==="unarchive"&&(Z(),j.invalidateQueries({queryKey:hs}));try{const ze=await To.mutateAsync({projectId:x,agentId:(gn==null?void 0:gn.id)??ge.agent_id,action:L,name:K==null?void 0:K.name,orderedProjectIds:K==null?void 0:K.orderedProjectIds});if(L==="remove"||L==="archive"||L==="unarchive"){const xt=ze.nextSessionId;xt?await ri(xt):await yr()}}catch(ze){j.invalidateQueries({queryKey:hs}),Fe(ze instanceof Error?ze.message:"无法更新线程")}},[yr,ri,j,Z,To]),Hc=_.useCallback(async x=>{Do&&(fr(Do),Ea(null),sl(null),Hu(x),await N({to:"/"}))},[Do,N]),kr=((tu=Ki.data)==null?void 0:tu.steps.some(x=>x.status==="pending"||x.status==="in_progress"))??!1,Pd=ge.run_state==="running"||q,Fc=!!((Tl=Ki.data)!=null&&Tl.updated_at&&Date.now()-new Date(Ki.data.updated_at).getTime()<=TI),vl=Ki.data&&(kr||Pd&&Fc)?Ki.data:null,Za=ge.context_usage,ma=Za?Math.round(Za.percent_used):0,Ud=Math.max(0,100-ma),Mi=Za?{"--usage-progress":`${Math.max(0,Math.min(100,Za.percent_used))}%`}:void 0,Bh=Ke.state==="connected"&&At.state==="idle"&&Pd&&!ce&&!ds.isPending&&!(jr!=null&&jr.turn.completion),qc=!!Pn||Td.length>0;_.useEffect(()=>{p&&(Je.current+=1,mn({state:"idle"}))},[p]),_.useEffect(()=>{if(!Ee)return;(Co.data??[]).some(L=>L.id===Ee&&L.status==="submitting")||$e(null)},[Co.data,Ee]),_.useEffect(()=>{var x;!p||!Ao||ge.run_state==="running"||Qi.isPending||ds.isPending||jr||(x=Ki.data)!=null&&x.is_active||(Ue.current&&(window.clearTimeout(Ue.current),Ue.current=null),de(!1))},[jr,Ao,ds.isPending,(Ml=Ki.data)==null?void 0:Ml.is_active,Qi.isPending,ge,ge==null?void 0:ge.run_state,p]);const Ls=ue?0:YD(),zd=ue||X,Bd=ue?0:Pe??(X?Ls:0),$d=Re&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"sheet-wrap sheet-wrap--centered",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"sheet-wrap__scrim",onClick:()=>{te(!1),V(ge.title)},"aria-label":"关闭重命名会话面板"}),a.jsx("div",{className:"sheet-wrap__center",children:a.jsxs("div",{className:"sheet-panel sheet-panel--form sheet-panel--centered",children:[a.jsx("div",{className:"sheet-panel__title",children:"重命名会话"}),a.jsx("input",{className:"sheet-panel__input",value:ve,onChange:x=>V(x.target.value),placeholder:"输入会话名称",autoFocus:!0}),a.jsxs("div",{className:"sheet-panel__actions",children:[a.jsx("button",{type:"button",className:"sheet-panel__button",onClick:()=>{te(!1),V(ge.title)},children:"取消"}),a.jsx("button",{type:"button",className:"sheet-panel__button is-primary",disabled:!ve.trim()||Vn.isPending&&((Vd=Vn.variables)==null?void 0:Vd.sessionId)===ge.id,onClick:()=>{ui(ge.id,"rename",ve.trim()),te(!1)},children:"保存"})]})]})})]}),document.body):null,$h=!(r?o:ue)&&re&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"picker-sheet-wrap",role:"dialog","aria-modal":"true",children:[a.jsx("button",{type:"button",className:"picker-sheet__scrim",onClick:()=>we(!1),"aria-label":"关闭会话操作菜单"}),a.jsxs("div",{className:"picker-sheet",children:[a.jsx("div",{className:"picker-sheet__header",children:a.jsx("strong",{children:ge.title})}),a.jsxs("div",{className:"picker-sheet__list",children:[a.jsx("button",{type:"button",className:"picker-sheet__item",disabled:Vn.isPending&&((Xd=Vn.variables)==null?void 0:Xd.sessionId)===ge.id,onClick:()=>void ui(ge.id,ge.pinned?"unpin":"pin"),children:a.jsx("span",{children:ge.pinned?"取消置顶会话":"置顶会话"})}),a.jsx("button",{type:"button",className:"picker-sheet__item",disabled:Vn.isPending&&((Dr=Vn.variables)==null?void 0:Dr.sessionId)===ge.id,onClick:()=>{we(!1),te(!0)},children:a.jsx("span",{children:"重命名会话"})}),a.jsx("button",{type:"button",className:"picker-sheet__item is-danger",disabled:Vn.isPending&&((Fo=Vn.variables)==null?void 0:Fo.sessionId)===ge.id,onClick:()=>void ui(ge.id,"delete"),children:a.jsx("span",{children:"删除会话"})})]})]})]}),document.body):null,Ia=ue?1:Ls>0?Bd/Ls:0,Er=!ue&&Pe!==null,bl=ue?{"--desktop-sidebar-width":`${D}px`}:void 0,Ms=r?!!o:ue,Cr=r?u:Bd,pa=r?d:Er,Da=ha.isPending?ha.variables??null:null,Yi=oa??(li.error instanceof Error?li.error.message:null),di=oi.error instanceof Error?oi.error.message:null,wa=Ln??(Ei.error instanceof Error?Ei.error.message:null),ps=Ei.data??null,Ja=(ps==null?void 0:ps.terminal_snapshot)??null,Ri=(ps==null?void 0:ps.command_catalog.commands)??[],Wc=(ps==null?void 0:ps.website_catalog.websites)??[],Kc=Fp(lp(),Et),bs=(Ja==null?void 0:Ja.terminals.find(x=>x.id===Ja.active_terminal_id))??(Ja==null?void 0:Ja.terminals[0])??null,Un=na&&hn==="terminal",en=xa&&hn==="git",ga=Ms&&Un&&Xs,Oa=en&&Ms,Tr=(Un||en)&&Ms&&!ga,Vi=(Un||en)&&!Ms,Hd=ms.isPending&&((Zd=ms.variables)==null?void 0:Zd.action)==="run-command"?ms.variables.commandId??null:null,Hh=ms.isPending&&((nu=ms.variables)==null?void 0:nu.action)==="run-kill-command"?ms.variables.commandId??null:null,Mr=ci.isPending&&((su=ci.variables)==null?void 0:su.action)==="delete"?ci.variables.commandId??null:null,Xi=Xa.isPending&&((_a=Xa.variables)==null?void 0:_a.action)==="delete"?Xa.variables.websiteId??null:null;_.useEffect(()=>{!Ms&&Xs&&$s(!1)},[Xs,Ms]);const fi=x=>{Nt.current=x,ht(x)},xl=(x,L,K)=>(Kn.current={mode:X?"close":"open",startX:x,startY:L,axis:"pending",pointerId:K},!0),Qc=(x,L)=>{const K=Kn.current;if(!K)return!1;const Se=x-K.startX,Ge=L-K.startY;if(K.axis==="pending"){if(Math.abs(Se)<8&&Math.abs(Ge)<8)return!1;if(K.axis=Math.abs(Se)>Math.abs(Ge)?"x":"y",K.axis==="y")return Kn.current=null,fi(null),!1}const bt=K.mode==="open"?Math.max(0,Math.min(Ls,Se)):Math.max(0,Math.min(Ls,Ls+Se));return fi(bt),!0},Zi=(x,L)=>{const K=Kn.current;if(!K)return;const Se=x-K.startX,Ge=L-K.startY;if(K.axis==="pending"&&Math.abs(Ge)>48){Kn.current=null,fi(null);return}const ze=(K.axis==="x"?Nt.current??(K.mode==="open"?Math.max(0,Math.min(Ls,Se)):Math.max(0,Math.min(Ls,Ls+Se))):X?Ls:0)>=Ls*kI;le(ze),Kn.current=null,fi(null)},hi=_.useCallback(()=>{if(r){m==null||m();return}le(!0)},[r,m]),Ji=_.useCallback(()=>{Ne(x=>!x)},[]),Ai=_.useCallback(()=>{Fe(null)},[]),Fd=_.useCallback(()=>{rn(x=>!x)},[]),qd=_.useCallback(x=>{ri(x)},[ri]),Rr=_.useCallback(x=>{const L=new Date().toISOString();if(Et.length===0){Bt({panel_id:`${o_}${Date.now()}`,session_id:ge.id,command_name:"model",command_text:x,title:"选择模型",description:"选择后会更新当前会话后续发送时使用的模型。",status:"completed",body:"当前没有可选模型,请先去设置页维护模型列表。",submitted_at:L,updated_at:L,input_type:"none",options:[],input_placeholder:null,submit_label:null,effect:null});return}Bt({panel_id:`${o_}${Date.now()}`,session_id:ge.id,command_name:"model",command_text:x,title:"选择模型",description:"选择后会更新当前会话后续发送时使用的模型。",status:"awaiting_input",body:"在下面选择一个模型。",submitted_at:L,updated_at:L,input_type:"choice",options:Et.map(K=>({id:K.value,label:K.label,description:K.description??null})),input_placeholder:null,submit_label:null,effect:null})},[Et,ge.id]),Gc=_.useCallback(()=>{if(Dd){if(hy(be)){if(se.length>0){Fe("命令暂不支持附件,请先移除附件后再执行。");return}if(uD(be)==="model"){Fe(null),De(""),Rr(be);return}Pc.mutate({sessionId:ge.id,input:be});return}Qi.mutate({sessionId:ge.id,input:be.trim(),attachments:se,model:Gt,reasoningEffort:Ft,serviceTier:dt?"fast":void 0,planMode:$t,yoloMode:Nn})}},[Dd,be,dt,$t,Nn,Pc,Rr,se,Gt,Ft,Qi,ge.id]),Ar=_.useCallback(()=>{Bt(null)},[]),Ps=_.useCallback(x=>{if(kt){if(kt.panel_id.startsWith(o_)){Xt(x),Bt(L=>L&&{...L,status:"completed",body:`后续消息将优先使用 ${Fp(x,Et)}。`,updated_at:new Date().toISOString(),input_type:"none",options:[]});return}yl.mutate({sessionId:ge.id,panelId:kt.panel_id,optionId:x})}},[kt,yl,Et,ge.id]),Yc=_.useCallback(x=>{kt&&yl.mutate({sessionId:ge.id,panelId:kt.panel_id,text:x})},[kt,yl,ge.id]),Fh=_.useCallback(x=>{Uh.mutate({sessionId:ge.id,requestId:x.requestId,optionId:x.optionId??null,text:x.text??null,answers:x.answers})},[Uh,ge.id]),ig=_.useCallback(x=>{const L=[...x];L.length!==0&&(Fe(null),Promise.all(L.map(K=>cy(K))).then(K=>{pe(Se=>[...Se,...K])}).catch(K=>{Fe(K instanceof Error?K.message:"无法读取附件")}))},[]),rg=_.useCallback(x=>{pe(L=>L.filter(K=>K.id!==x))},[]),lg=_.useCallback(()=>{ds.isPending||ce||ds.mutate(ge.id)},[ds,ce,ge.id]),gs=_.useCallback(()=>{tn(x=>!x)},[]),er=_.useCallback(x=>{x==="git"&&!xa||x==="terminal"&&!na||(On(null),Ot(null),Sn(!1),js(!1),$s(!1),ns(x))},[xa,na]);_.useEffect(()=>{if(!Tr)return;const x=L=>{var Se,Ge;const K=L.target;K instanceof Node&&((Se=Ce.current)!=null&&Se.contains(K)||(Ge=R.current)!=null&&Ge.contains(K)||er("code"))};return window.addEventListener("pointerdown",x),()=>{window.removeEventListener("pointerdown",x)}},[er,Tr]);const Lo=_.useCallback(()=>{On(null),li.refetch()},[li]),Po=_.useCallback(()=>{oi.refetch()},[oi]),Wd=_.useCallback(()=>{oi.data||oi.isFetching||oi.refetch()},[oi]),Sl=_.useCallback(x=>{ha.mutate({action:"discard-file",path:x})},[ha]),jl=_.useCallback(()=>{ha.mutate({action:"discard-all"})},[ha]),og=_.useCallback(x=>{ha.mutate({action:"commit-all",message:x})},[ha]),qh=_.useCallback(async(x,L)=>{On(null);const K=(L==null?void 0:L.trim())??"";K&&await ha.mutateAsync({action:"commit-all",message:K}),await ha.mutateAsync({action:"switch-branch",branch:x})},[ha]),cg=_.useCallback(()=>{ha.mutate({action:"push"})},[ha]),Wh=_.useCallback(async(x,L,K)=>(await sn()).client.getSessionGitHistoryFileDiff(ge.id,{commitOid:x,path:L,previousPath:K}),[sn,ge.id]),Ir=_.useCallback(async(x,L)=>(await sn()).client.getSessionGitWorkspaceFileDiff(ge.id,{path:x,previousPath:L}),[sn,ge.id]),Vc=_.useCallback(x=>{ms.mutate({action:"run-command",commandId:x})},[ms]),Uo=_.useCallback(async()=>{if(!(Ri.length===0||Hs||Fs)){ca(!0);try{for(const x of Ri)await ms.mutateAsync({action:"run-command",commandId:x.id})}finally{ca(!1)}}},[Hs,Fs,Ri,ms]),Kd=_.useCallback(async()=>{if(Hs||Fs)return;const x=Ri.filter(L=>!!L.kill_command);if(x.length!==0){Js(!0);try{for(const L of x)await ms.mutateAsync({action:"run-kill-command",commandId:L.id})}finally{Js(!1)}}},[Hs,Fs,Ri,ms]),wl=_.useCallback(x=>{ms.mutate({action:"run-kill-command",commandId:x})},[ms]),Xc=_.useCallback(x=>{ci.mutate({action:x.commandId?"update":"create",commandId:x.commandId,command:x.draft})},[ci]),zo=_.useCallback(x=>{ci.mutate({action:"delete",commandId:x})},[ci]),Bo=_.useCallback(()=>{Uc.mutate()},[Uc]),Qd=_.useCallback(x=>{Xa.mutate({action:x.websiteId?"update":"create",websiteId:x.websiteId,website:x.draft})},[Xa]),Gd=_.useCallback(x=>{Xa.mutate({action:"delete",websiteId:x})},[Xa]),tr=_.useCallback(()=>{Ci.mutate()},[Ci]),nr=_.useCallback(()=>{js(!1)},[]),Kh=_.useCallback(x=>{ms.mutate({action:"focus",terminalId:x}),ns("terminal")},[ms]),Qh=_.useCallback(x=>{ms.mutate({action:"close",terminalId:x})},[ms]),Nl=_.useCallback(()=>{!Ms||!na||(ns("terminal"),$s(x=>!x))},[na,Ms]),kl=_.useMemo(()=>{var x,L,K;return a.jsxs("div",{className:"conversation-topbar__title-actions",children:[a.jsx("button",{type:"button",className:"conversation-topbar__more",onClick:()=>we(Se=>!Se),"aria-label":"更多会话选项",children:a.jsx($I,{})}),re&&Ms?a.jsxs("div",{className:"topbar-menu",role:"menu",children:[a.jsx("button",{type:"button",className:"topbar-menu__item",disabled:Vn.isPending&&((x=Vn.variables)==null?void 0:x.sessionId)===ge.id,onClick:()=>void ui(ge.id,ge.pinned?"unpin":"pin"),children:ge.pinned?"取消置顶会话":"置顶会话"}),a.jsx("button",{type:"button",className:"topbar-menu__item",disabled:Vn.isPending&&((L=Vn.variables)==null?void 0:L.sessionId)===ge.id,onClick:()=>{we(!1),te(!0)},children:"重命名会话"}),a.jsx("button",{type:"button",className:"topbar-menu__item is-danger",disabled:Vn.isPending&&((K=Vn.variables)==null?void 0:K.sessionId)===ge.id,onClick:()=>void ui(ge.id,"delete"),children:"删除会话"})]}):null]})},[ui,re,Ms,ge.id,ge.pinned,Vn.isPending,(Na=Vn.variables)==null?void 0:Na.sessionId]),$o=_.useMemo(()=>na||xa?a.jsxs("div",{className:"conversation-topbar__actions",children:[na?a.jsxs("div",{className:"conversation-topbar__run-group",children:[a.jsx("button",{type:"button",className:`conversation-topbar__run-button ${Wn?"is-active":""}`,onClick:()=>{js(!1),Sn(x=>!x)},"aria-expanded":Wn,"aria-haspopup":"dialog","aria-label":"打开项目命令列表",children:a.jsx(KI,{})}),Wn?a.jsx("div",{className:"conversation-run-popover",role:"dialog","aria-label":"项目命令列表",children:a.jsx(oI,{commands:Ri,nodeRuntime:(ps==null?void 0:ps.node_runtime)??null,error:wa,pendingRunCommandId:Hd,pendingKillCommandId:Hh,pendingDeleteCommandId:Mr,isSaving:ci.isPending,isGenerating:Uc.isPending,isStartingAll:Hs,isStoppingAll:Fs,generationReason:ua,executionModelLabel:Kc,onRun:Vc,onRunAll:Uo,onRunAllKill:Kd,onRunKill:wl,onSave:Xc,onDelete:zo,onGenerate:Bo})}):null]}):null,na?a.jsxs("div",{className:"conversation-topbar__run-group",children:[a.jsx("button",{type:"button",className:`conversation-topbar__run-button ${Jn?"is-active":""}`,onClick:()=>{Sn(!1),js(x=>!x)},"aria-expanded":Jn,"aria-haspopup":"dialog","aria-label":"打开项目网页列表",children:a.jsx(QI,{})}),Jn?a.jsx("div",{className:"conversation-run-popover",role:"dialog","aria-label":"项目网页列表",children:a.jsx(mI,{websites:Wc,error:wa,pendingDeleteWebsiteId:Xi,isSaving:Xa.isPending,isGenerating:Ci.isPending,generationReason:fa,executionModelLabel:Kc,onOpen:nr,onSave:Qd,onDelete:Gd,onGenerate:tr})}):null]}):null,na||xa?a.jsxs("div",{ref:R,className:"conversation-topbar__view-toggle","aria-label":"切换工作台面板",children:[a.jsx("button",{type:"button",className:`conversation-topbar__view-button ${hn==="code"?"is-active":""}`,onClick:()=>er("code"),"aria-pressed":hn==="code","aria-label":"切换到代码会话视图",children:a.jsx(FI,{})}),na?a.jsx("button",{type:"button",className:`conversation-topbar__view-button ${hn==="terminal"?"is-active":""}`,onClick:()=>er("terminal"),"aria-pressed":hn==="terminal","aria-label":"切换到终端视图",children:a.jsx(WI,{})}):null,xa?a.jsx("button",{type:"button",className:`conversation-topbar__view-button ${hn==="git"?"is-active":""}`,onClick:()=>er("git"),"aria-pressed":hn==="git","aria-label":"切换到 git 视图",children:a.jsx(qI,{})}):null]}):null]}):null,[hn,xa,na,ua,fa,Hs,Fs,Kc,Uc.isPending,Ci.isPending,zo,Bo,Gd,tr,nr,Vc,Uo,Kd,Xc,Qd,er,Wn,Jn,Mr,Xi,Hd,Ri,Wc,wa,ci.isPending,Xa.isPending]),Ho=a.jsx(sI,{workspace:li.data??null,history:oi.data??null,isLoading:li.isPending,isHistoryLoading:oi.isFetching,error:Yi,historyError:di,onRefresh:Lo,onRefreshHistory:Po,onRequestHistory:Wd,onDiscardFile:Sl,onDiscardAll:jl,onCommitAll:og,onSwitchBranch:qh,onPush:cg,onLoadWorkspaceFileDiff:Ir,onLoadHistoryFileDiff:Wh,pendingAction:Da,compact:Oa}),Zc=a.jsx(jI,{terminals:(Ja==null?void 0:Ja.terminals)??[],activeTerminalId:(bs==null?void 0:bs.id)??null,outputs:ws,error:wa,compact:Tr||ga,canToggleFullscreen:Ms,isFullscreen:ga,onSelectTerminal:Kh,onCloseTerminal:Qh,onToggleFullscreen:Nl}),Gh=a.jsx(p5,{isDesktopSidebar:Ms,sidebarShift:Cr,isSidebarDragging:pa,composerError:zt,onDismissComposerError:Ai,interactionRequests:Bc,pendingInteractionRequestId:Ee,onRespondInteraction:Fh,parentSession:Pn,backgroundAgentSessions:Td,isBackgroundAgentsOpen:Le,planSnapshot:vl,onToggleBackgroundAgents:Fd,onOpenSession:qd,getBackgroundAgentStatusLabel:ED,getBackgroundAgentAccent:wD,formatBackgroundAgentsLabel:vD,hasBackgroundAgentStrip:qc,commandPanel:kt,isCommandPanelPending:Pc.isPending||yl.isPending,onDismissCommandPanel:Ar,onCommandPanelOptionSelect:Ps,onCommandPanelTextSubmit:Yc,projectId:ge.project_id,agentId:(gn==null?void 0:gn.id)??ge.agent_id,draft:be,pendingAttachments:se,canSendInput:Id,canSubmitInput:Dd,isInputLocked:Bc.length>0,readOnlyPlaceholder:Bc.length>0?"请先处理上方确认请求":void 0,onDraftChange:De,onUploadFiles:ig,onRemoveAttachment:rg,onSubmit:Gc,showStopIcon:Od,isSendPending:Qi.isPending||Pc.isPending||yl.isPending,onInterrupt:lg,isFastModeEnabled:dt,isPlanModeEnabled:$t,isYoloModeEnabled:Nn,onToggleFastMode:()=>un(x=>!x),onTogglePlanMode:()=>An(x=>!x),onToggleYoloMode:()=>Tt(x=>!x),showModeBadges:!0,selectedModel:Gt,modelOptions:Et,selectedReasoning:Ft,onSelectModel:Xt,onSelectReasoning:x=>qe(x),contextUsage:Za,isContextUsageOpen:Xe,onToggleContextUsage:gs,contextUsageRingStyle:Mi,usedPercent:ma,remainingPercent:Ud,usedTokensLabel:qx((Za==null?void 0:Za.used_tokens)??0),totalTokensLabel:qx((Za==null?void 0:Za.total_tokens)??0),showJumpToBottom:ee,onJumpToBottom:ki}),sr=Un?Zc:Ho,Yd=Vi||ga,Ii=Yd?a.jsxs("div",{ref:he,className:`conversation-main ${Ms?"has-desktop-sidebar":""} ${ga?"is-terminal-fullscreen":""}`,style:{transform:`translateX(${Cr}px)`,transition:pa?"none":void 0},children:[a.jsxs("div",{className:"conversation-topbar",children:[Ms?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:hi,"aria-label":"打开侧边栏",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]}),a.jsx("div",{className:"conversation-topbar__meta",children:a.jsxs("div",{className:"conversation-topbar__title-row",children:[a.jsx("h1",{children:ge.title}),kl]})}),$o]}),a.jsx("div",{ref:ne,className:`conversation-scroll ${Yd?"conversation-scroll--workbench":""}`,children:a.jsx("div",{className:`session-workbench-surface ${ga?"is-terminal-fullscreen":""}`,children:sr})})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:`session-detail-workspace ${Tr?"has-workbench-panel":""}`,children:[a.jsx(wI,{conversationMainRef:he,conversationScrollRef:ne,isDesktopSidebar:Ms,sidebarShift:Cr,isSidebarDragging:pa,title:ge.title,titleActions:kl,topbarActions:$o,onOpenSidebar:hi,threadContent:Ld,connectionStatus:Ke,sessionRecoveryStatus:At,isConnectionDetailOpen:U,onToggleConnectionDetail:Ji,showThinkingStatus:Bh}),Tr?a.jsx("aside",{ref:Ce,className:"session-workbench-rail",children:sr}):null]}),ga?null:Gh]}),El=a.jsxs(a.Fragment,{children:[$d,$h,ke&&typeof document<"u"?ra.createPortal(a.jsxs("div",{className:"attachment-lightbox",role:"dialog","aria-modal":"true","aria-label":`预览 ${ke.label}`,children:[a.jsx("button",{type:"button",className:"attachment-lightbox__scrim",onClick:()=>Ze(null),"aria-label":"关闭图片预览"}),a.jsxs("div",{className:"attachment-lightbox__panel",children:[a.jsx("button",{type:"button",className:"attachment-lightbox__close",onClick:()=>Ze(null),"aria-label":"关闭图片预览",children:a.jsx(HI,{})}),a.jsx("div",{className:"attachment-lightbox__frame",children:a.jsx("img",{src:ke.src,alt:ke.label,className:"attachment-lightbox__image"})}),a.jsxs("div",{className:"attachment-lightbox__meta",children:[a.jsx("div",{className:"attachment-lightbox__title",children:ke.label}),a.jsx("div",{className:"attachment-lightbox__hint",children:ke.meta})]})]})]}),document.body):null]});if(!Ao){const x=a.jsx("div",{className:"conversation-main conversation-main--empty",children:Ad?a.jsxs("div",{className:"empty-panel empty-panel--loading",role:"status","aria-live":"polite","aria-busy":"true",children:[a.jsxs("span",{className:"empty-panel__loading-dots","aria-hidden":"true",children:[a.jsx("span",{className:"empty-panel__loading-dot"}),a.jsx("span",{className:"empty-panel__loading-dot"}),a.jsx("span",{className:"empty-panel__loading-dot"})]}),a.jsx("span",{className:"sr-only",children:"正在加载会话"})]}):a.jsx("div",{className:"empty-panel",children:zh})});return r?a.jsxs(a.Fragment,{children:[x,El]}):a.jsxs("div",{className:"conversation-page",children:[x,El]})}return r?a.jsxs(a.Fragment,{children:[Ii,El]}):a.jsxs("div",{ref:ae,className:`conversation-page ${ue?"has-desktop-sidebar":""}`,style:bl,onPointerDown:x=>{ue||x.pointerType!=="touch"&&(x.pointerType==="mouse"&&x.button!==0||jo(x.target)||(xl(x.clientX,x.clientY,x.pointerId),x.currentTarget.setPointerCapture(x.pointerId)))},onPointerMove:x=>{if(ue||x.pointerType==="touch")return;const L=Kn.current;!L||L.pointerId!==x.pointerId||!Qc(x.clientX,x.clientY)||x.preventDefault()},onPointerUp:x=>{if(ue||x.pointerType==="touch")return;const L=Kn.current;!L||L.pointerId!==x.pointerId||Zi(x.clientX,x.clientY)},onPointerCancel:x=>{if(ue||x.pointerType==="touch")return;const L=Kn.current;!L||L.pointerId!==x.pointerId||(Kn.current=null,fi(null))},children:[a.jsx(a5,{open:zd,progress:Ia,isDragging:Er,desktopPinned:ue,isDesktopResizing:je,onClose:()=>{ue||(le(!1),fi(null))},onDesktopResizeStart:x=>{ii.current=Ra.current,Ya.current={startX:x,startWidth:Ra.current},z(!0)},currentAgent:gn??void 0,agentIndicatorState:gn?i??(gn.status==="online"?"online":"offline"):void 0,projects:sg,sessions:vr,projectStats:ag,historySessionsByProject:Object.fromEntries(Object.entries(O).map(([x,L])=>[x,L.sessions])),archivedSessionsByProject:Object.fromEntries(Object.entries(Q).map(([x,L])=>[x,L.sessions])),chatHistorySessions:Rh.sessions,chatArchivedSessions:Ah.sessions,historyPageStateByProject:O,archivedPageStateByProject:Q,chatHistoryPageState:Rh,chatArchivedPageState:Ah,activeSessionId:ge.id,onCreateSession:x=>{Hc(x)},onCreateChat:()=>{Hc(Gr)},onSessionAction:ui,onThreadAction:$c,onLoadMoreHistory:x=>{J(x)},onLoadMoreChatHistory:()=>{F()},onLoadMoreArchived:x=>{B(x)},onLoadMoreChatArchived:()=>{G()},pendingSessionActionId:Vn.isPending?((Li=Vn.variables)==null?void 0:Li.sessionId)??null:null,pendingThreadActionId:To.isPending?((au=To.variables)==null?void 0:au.projectId)??null:null}),Ii,El]})},eO=({mode:e,agentName:t,agentStatus:i,onOpenNodes:r,onCreateThread:o})=>{if(e==="node")return a.jsxs("section",{className:"session-empty-state is-node-mode",children:[a.jsx("div",{className:"session-empty-state__eyebrow",children:"Panda Workspace"}),a.jsx("div",{className:"session-empty-state__actions",children:a.jsx("button",{type:"button",className:"session-empty-state__button is-primary",onClick:r,children:"选择节点"})})]});const u=i==="online";return a.jsxs("section",{className:"session-empty-state is-session-mode",children:[a.jsxs("div",{className:"session-empty-state__status-row",children:[a.jsx("span",{className:`session-empty-state__status-dot is-${u?"online":"offline"}`,"aria-hidden":"true"}),a.jsxs("div",{className:"session-empty-state__eyebrow",children:["节点 · ",t??"当前节点"]})]}),a.jsxs("div",{className:"session-empty-state__actions",children:[o?a.jsx("button",{type:"button",className:"session-empty-state__button is-primary",onClick:o,children:"新建会话"}):null,a.jsx("button",{type:"button",className:"session-empty-state__button",onClick:r,children:"切换节点"})]})]})},Yx=1100,D5="panda:desktop-sidebar-width",Qf="panda:desktop-sidebar-width-version",Gf="2026-03-24-narrow",tO=300,O5=232,Ou=O5,nO=460,f_=.4,sO=56,aO=56,iO=160,Vx=5,rO=_.lazy(async()=>({default:(await cl(()=>import("./session-file-preview-page-DbdsZil_.js").then(t=>t.s),__vite__mapDeps([2,1]))).SessionFilePreviewPage})),Xx=e=>{const t=new Date((e==null?void 0:e.generated_at)??"").getTime();return Number.isFinite(t)?t:0},lO=(e,t)=>{var r;if(!t)return;let i;for(const[,o]of e)!o||!(((r=o.agent)==null?void 0:r.id)===t||o.projects.some(d=>d.agent_id===t)||o.sessions.some(d=>d.agent_id===t))||(!i||Xx(o)>Xx(i))&&(i=o);return i},oO=()=>typeof window>"u"?248:Math.max(0,Math.min(248,window.innerWidth-84)),cO=()=>typeof window>"u"?0:Math.max(window.innerWidth,0),p0=e=>Math.max(O5,Math.min(nO,e)),uO=()=>{if(typeof window>"u")return Ou;try{const e=window.localStorage.getItem(D5),t=window.localStorage.getItem(Qf);if(!e)return window.localStorage.setItem(Qf,Gf),Ou;const i=Number(e);if(!Number.isFinite(i))return window.localStorage.setItem(Qf,Gf),Ou;const o=t!==Gf||i===tO||i>Ou?Ou:i;return window.localStorage.setItem(Qf,Gf),p0(o)}catch{return Ou}},L5=()=>{var ws,Os;const e=qa(ee=>ee.openSettingsOverlay),{agentId:t}=Mc({strict:!1}),i=Hi(),r=Ka(),o=_.useRef(null),[u,d]=_.useState(()=>vo()),[m,y]=_.useState(()=>SE()??Rp()),[g,b]=_.useState(()=>jE()),[p,v]=_.useState(()=>wE()?"directory-picker":"composer"),[w,N]=_.useState(!1),[j,T]=_.useState(!1),[M,P]=_.useState(()=>typeof window<"u"&&window.innerWidth>=Yx),[I,k]=_.useState(()=>uO()),[O,Q]=_.useState(!1),[J,F]=_.useState({state:"connected",attempt:0,maxAttempts:Vx}),[B,G]=_.useState(null),[Z,ae]=_.useState(null),he=_.useRef(null),ne=_.useRef(null),Ce=_.useRef(null),R=_.useRef(null),X=_.useRef(null),le=_.useRef(I),ue=_.useRef(null),ye=_.useRef(null),D=_.useRef(null),oe=_.useRef(0),je=_.useRef(null),z=_.useRef(!1),be=_.useRef(!1),De=_.useRef(!1),se=_.useRef(null),pe=_.useRef(null),ke=t??u??null,Ze=ke?{agentId:ke}:void 0,Fe=r.getQueryData(s0({scope:Ze}))??lO(r.getQueriesData({queryKey:hs}),ke),kt=m&&!(Fe!=null&&Fe.sessions.some(ee=>ee.id===m))?m:null,Bt=_.useRef({agentId:ke,selectedSessionIdHint:kt});kh(ke);const Gt=oy({enabled:!1}),Xt=Gt.data,Ft=e5({scope:Ze,selectedSessionId:kt,enabled:!!ke}),qe=Ft.data??Fe,{historyState:dt,archivedState:un,loadMoreHistory:$t,loadMoreProjectlessHistory:An,loadMoreArchived:Nn,loadMoreProjectlessArchived:Tt,reset:lt}=n5({scope:Ze,selectedSessionId:m??null}),Et=[...Object.values(dt).flatMap(ee=>ee.sessions),...Object.values(un).flatMap(ee=>ee.sessions)];_.useEffect(()=>{t&&(d(t),fr(t),y(null))},[t]),_.useEffect(()=>{qe&&(d(ee=>{var Be;return ee&&(((Be=qe.agent)==null?void 0:Be.id)===ee||Xt!=null&&Xt.agents.some(Ke=>Ke.id===ee))?ee:null}),y(ee=>ee&&(qe.sessions.some(Be=>Be.id===ee)||Et.some(Be=>Be.id===ee)||Ft.isPending||Ft.isFetching||Ft.isError)?ee:null))},[Xt==null?void 0:Xt.agents,Et,qe,Ft.isError,Ft.isFetching,Ft.isPending]),_.useEffect(()=>{t||u||(A6(),i({to:"/nodes",replace:!0}))},[i,t,u]),_.useEffect(()=>{if(!qe||t||!u||m)return;const ee=Rp(),Be=qe.sessions.find(Ke=>Ke.id===ee)??null;Be&&(y(Be.id),Ea(Be.id))},[t,u,m,qe]);const rt=(ke?(Xt==null?void 0:Xt.agents.find(ee=>ee.id===ke))??null:null)??null,st=_.useMemo(()=>{const ee=(qe==null?void 0:qe.agent)??(rt?{id:rt.id,name:rt.name,display_name:rt.display_name,status:rt.status}:null);if(!ee)return null;const Be=(rt==null?void 0:rt.status)??ee.status,Ke=(rt==null?void 0:rt.name)??ee.name,Lt=(rt==null?void 0:rt.display_name)??ee.display_name;return ee.status===Be&&ee.name===Ke&&ee.display_name===Lt?ee:{...ee,name:Ke,display_name:Lt,status:Be}},[rt,qe==null?void 0:qe.agent]),Dt=st?XM(st.status,J.state):void 0,an=(qe==null?void 0:qe.projects)??[],re=(qe==null?void 0:qe.sessions)??[],we=(qe==null?void 0:qe.project_stats)??[],Re=dt[gh]??al,te=un[gh]??al,ve=m?re.find(ee=>ee.id===m)??null:null,V=ve?an.find(ee=>ee.id===ve.project_id)??null:null,q=!!(ve&&V);_.useEffect(()=>{T(!1),ae(null),ne.current=null},[ve==null?void 0:ve.id,V==null?void 0:V.id]);const de=!!ke&&!st&&(Gt.isPending||Gt.isFetching||Ft.isPending||Ft.isFetching),ce=!!m&&!re.some(ee=>ee.id===m)&&(Ft.isPending||Ft.isFetching),Ae=de||ce,Ee=(ve==null?void 0:ve.id)??(Ae?m??null:null);Bt.current={agentId:(st==null?void 0:st.id)??ke,selectedSessionIdHint:kt},_.useEffect(()=>{const ee=(rt==null?void 0:rt.status)??null,Be=se.current;se.current=ee;const Ke=(ke==null?void 0:ke.trim())??"";if(!Ke||ee!=="online"){ee!=="online"&&(pe.current=null);return}if(!(Be!=="online"||!qe))return;const Zt=`${Ke}:${Be!=="online"?"online":"missing"}:${kt??""}`;pe.current!==Zt&&(pe.current=Zt,qf(r,{scope:{agentId:Ke},selectedSessionId:kt}))},[ke,rt==null?void 0:rt.status,r,qe,kt]),_.useEffect(()=>{var Zt;if(!Bt.current.agentId){je.current!==null&&(clearTimeout(je.current),je.current=null),(Zt=D.current)==null||Zt.stream.close(),D.current=null,z.current=!1,be.current=!1,De.current=!1;return}let ee=!1;const Be=++oe.current,Ke=()=>{je.current!==null&&(clearTimeout(je.current),je.current=null)},Lt=Pt=>{const At=(Pt==null?void 0:Pt.includeHubDirectory)??!1;Ke(),je.current=setTimeout(()=>{je.current=null;const mn=Bt.current,jn=[qf(r,{scope:mn.agentId?{agentId:mn.agentId}:void 0,selectedSessionId:mn.selectedSessionIdHint})];At&&jn.unshift(y3(r)),Promise.allSettled(jn)},iO)};return cn({agentId:Bt.current.agentId}).then(Pt=>{var jn,kn;if(ee||oe.current!==Be)return;const At=Pt.client.getConnectionKey();if(((jn=D.current)==null?void 0:jn.key)===At)return;(kn=D.current)==null||kn.stream.close(),z.current=!1,be.current=!1,De.current=!1;const mn=Pt.client.createEventStream(pn=>{var Ue,Qe,at,Je,vt,ot;const U=typeof((Ue=pn.payload)==null?void 0:Ue.sessionId)=="string"?pn.payload.sessionId:null,Ne=typeof((Qe=pn.payload)==null?void 0:Qe.projectId)=="string"?pn.payload.projectId:null;if(pn.type==="agent.online"){if(De.current){De.current=!1;return}lt(),Lt({includeHubDirectory:!0});return}if(pn.type==="thread.updated"&&Ne){const nn=typeof((at=pn.payload)==null?void 0:at.action)=="string"?pn.payload.action:"",Jt=(Je=pn.payload)!=null&&Je.projectPatch&&typeof pn.payload.projectPatch=="object"?pn.payload.projectPatch:null,qt=Array.isArray((vt=pn.payload)==null?void 0:vt.orderedProjectIds)?pn.payload.orderedProjectIds.filter(St=>typeof St=="string"&&St.trim().length>0):[];if((nn==="pin"||nn==="unpin"||nn==="rename")&&Jt){r.setQueriesData({queryKey:hs},St=>Wu(St,Ne,Jt));return}if(nn==="reorder"&&qt.length>0){r.setQueriesData({queryKey:hs},St=>Up(St,qt));return}if(nn==="remove"||nn==="archive"){lt(),r.setQueriesData({queryKey:hs},St=>zp(St,Ne));return}if(nn==="unarchive"){lt();const St=Bt.current;qf(r,{scope:St.agentId?{agentId:St.agentId}:void 0,selectedSessionId:St.selectedSessionIdHint});return}}if(pn.type==="session.updated"&&U){const nn=(ot=pn.payload)!=null&&ot.sessionPatch&&typeof pn.payload.sessionPatch=="object"?t0(pn.payload.sessionPatch):null,Jt=Bt.current,qt=r.getQueryData(s0({scope:Jt.agentId?{agentId:Jt.agentId}:void 0,selectedSessionId:Jt.selectedSessionIdHint})),St=Lp(qt,U);if(nn&&St){r.setQueriesData({queryKey:hs},En=>Ff(En,U,nn));return}if(St)return;qf(r,{scope:Jt.agentId?{agentId:Jt.agentId}:void 0,selectedSessionId:Jt.selectedSessionIdHint})}},{onStatus:pn=>{if(F(pn),pn.state==="connected"){De.current=!0,z.current&&be.current&&(be.current=!1,lt(),Lt({includeHubDirectory:Pt.mode==="hub"})),z.current=!0;return}z.current&&(be.current=!0)}});D.current={key:At,stream:mn}}).catch(Pt=>{ee||oe.current!==Be||F({state:"failed",attempt:0,maxAttempts:Vx,error:Pt instanceof Error?Pt.message:"无法建立节点工作区连接"})}),()=>{ee=!0}},[st==null?void 0:st.id,st==null?void 0:st.status,ke,r,lt]),_.useEffect(()=>()=>{var ee;oe.current+=1,je.current!==null&&(clearTimeout(je.current),je.current=null),(ee=D.current)==null||ee.stream.close(),D.current=null},[]),_.useEffect(()=>{le.current=I},[I]),_.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(D5,String(p0(I))),window.localStorage.setItem(Qf,Gf)}catch{}},[I]),_.useEffect(()=>{if(typeof window>"u")return;const ee=()=>{const Be=window.innerWidth>=Yx;P(Be),Be&&(N(!1),G(null))};return ee(),window.addEventListener("resize",ee),()=>{window.removeEventListener("resize",ee)}},[]),_.useEffect(()=>{if(!O)return;const ee=Ke=>{const Lt=X.current;if(!Lt)return;const Zt=Ke.clientX-Lt.startX,Pt=p0(Lt.startWidth+Zt);ue.current=Pt,ye.current===null&&(ye.current=window.requestAnimationFrame(()=>{ye.current=null;const At=ue.current;At!==null&&k(At)}))},Be=()=>{ye.current!==null&&(window.cancelAnimationFrame(ye.current),ye.current=null);const Ke=ue.current??le.current;ue.current=null,X.current=null,Q(!1),le.current=Ke,k(Ke)};return window.addEventListener("pointermove",ee),window.addEventListener("pointerup",Be),()=>{window.removeEventListener("pointermove",ee),window.removeEventListener("pointerup",Be)}},[O]),_.useEffect(()=>()=>{ye.current!==null&&window.cancelAnimationFrame(ye.current)},[]);const $e=Gn({mutationFn:async ee=>{const Be=tn(ee.sessionId);return(await cn({sessionId:ee.sessionId,agentId:(Be==null?void 0:Be.agent_id)??(st==null?void 0:st.id)??u??t})).client.updateSession(ee)}}),Pe=Gn({mutationFn:async ee=>(await cn({projectId:ee.projectId,agentId:ee.agentId})).client.updateThread(ee)}),ht=Gn({mutationFn:async ee=>(await cn({agentId:ee.agentId})).client.createImageSession({title:"新绘图"})}),Xe=ee=>{r.setQueriesData({queryKey:hs},ee)},tn=ee=>re.find(Be=>Be.id===ee)??Et.find(Be=>Be.id===ee)??((ve==null?void 0:ve.id)===ee?ve:null),Le=async(ee,Be,Ke)=>{var Pt;const Lt=await $e.mutateAsync({sessionId:ee,action:Be,name:Ke}),Zt=(Pt=Lt.affectedSessionIds)!=null&&Pt.length?Lt.affectedSessionIds:[ee];if(Be==="delete"?(Xe(At=>p3(At,Zt)),lt()):Xe(At=>m3(At,Zt,{...Be==="rename"&&(Ke!=null&&Ke.trim())?{title:Ke.trim()}:{pinned:Be==="pin"}})),Be==="delete"&&m===ee){const At=Lt.nextSessionId;At?(Ea(At),y(At)):(Ea(null),y(null))}},rn=async(ee,Be,Ke)=>{var Pt,At;const Lt=await Pe.mutateAsync({projectId:ee,agentId:(st==null?void 0:st.id)??u??t??"",action:Be,name:Ke==null?void 0:Ke.name,orderedProjectIds:Ke==null?void 0:Ke.orderedProjectIds}),Zt=(Pt=Ke==null?void 0:Ke.name)==null?void 0:Pt.trim();Be==="pin"||Be==="unpin"?Xe(mn=>Wu(mn,ee,{pinned:Be==="pin"})):Be==="rename"&&Zt?Xe(mn=>Wu(mn,ee,{display_name:Zt})):Be==="reorder"&&((At=Ke==null?void 0:Ke.orderedProjectIds)!=null&&At.length)?Xe(mn=>Up(mn,Ke.orderedProjectIds??[])):Be==="remove"||Be==="archive"?(Xe(mn=>zp(mn,ee)),lt()):Be==="unarchive"&&(lt(),r.invalidateQueries({queryKey:hs})),ve&&ve.project_id===ee&&(Be==="remove"||Be==="archive"||Be==="unarchive")&&(Lt.nextSessionId?(Ea(Lt.nextSessionId),y(Lt.nextSessionId)):(Ea(null),y(null)))},hn=async ee=>{st&&(fr(st.id),Ea(null),sl(null),Hf(!1),Hu(ee),b(ee),v("composer"),y(null),await i({to:"/"}))},ns=async()=>{st&&(M||(N(!1),Jn(null)),fr(st.id),Ea(null),sl(null),Hu(null),Hf(!0),b(null),v("directory-picker"),y(null),await i({to:"/"}))},Xs=async ee=>{await hn(ee)},$s=async()=>{const ee=(st==null?void 0:st.id)??ke;if(!ee)return;const Be=await ht.mutateAsync({agentId:ee});Xe(Ke=>Bp(Ke,Be.session)),await oa(Be.session.id)},oa=async ee=>{const Be=tn(ee);b(null),v("composer"),Hf(!1),Hu(null),sl(null),Be&&!re.some(Lt=>Lt.id===ee)&&Xe(Lt=>Bp(Lt,Be)),y(ee),Ea(ee);const Ke=(Be==null?void 0:Be.agent_id)??(st==null?void 0:st.id)??ke;Ke&&(d(Ke),fr(Ke)),t&&await i({to:"/",replace:!0})},On=M?0:oO(),Ss=M?0:cO(),Kt=M||w,Zs=M?0:B??(w?On:0),us=M?0:Z??(j?Ss:0),Ln=M?1:On>0?Zs/On:0,Ot=!M&&B!==null,Wn=!M&&Z!==null,Sn=M?{"--desktop-sidebar-width":`${I}px`}:{"--workspace-preview-shift":`${us}px`},Jn=ee=>{he.current=ee,G(ee)},js=ee=>{ne.current=ee,ae(ee)},Hs=ee=>ee instanceof Element&&!!ee.closest('button, textarea, input, a, [role="dialog"]'),ca=ee=>{if(!(ee instanceof Element))return!1;const Be=ee.closest(".conversation-markdown-code-block__pre, .conversation-markdown-table__scroll");return!!(Be&&Be.scrollWidth-Be.clientWidth>1)},Fs=ee=>Hs(ee)||ca(ee),Js=(ee,Be,Ke)=>(R.current={target:"sidebar",mode:w?"close":"open",startX:ee,startY:Be,axis:"pending",pointerId:Ke},!0),ua=(ee,Be,Ke)=>q?(R.current={target:"preview",mode:"open",startX:ee,startY:Be,axis:"pending",pointerId:Ke},!0):!1,da=(ee,Be)=>{const Ke=R.current;if(!Ke)return!1;const Lt=ee-Ke.startX,Zt=Be-Ke.startY;if(Ke.axis==="pending"){if(Math.abs(Lt)<8&&Math.abs(Zt)<8)return!1;if(Ke.axis=Math.abs(Lt)>Math.abs(Zt)?"x":"y",Ke.axis==="y")return R.current=null,Jn(null),!1}if(Ke.target==="preview"){const At=Math.max(0,Math.min(Ss,-Lt));return js(At),!0}const Pt=Ke.mode==="open"?Math.max(0,Math.min(On,Lt)):Math.max(0,Math.min(On,On+Lt));return Jn(Pt),!0},fa=(ee,Be)=>{const Ke=R.current;if(!Ke)return;const Lt=ee-Ke.startX,Zt=Be-Ke.startY;if(Ke.axis==="pending"&&Math.abs(Zt)>48){R.current=null,Jn(null);return}if(Ke.target==="preview"){const jn=(Ke.axis==="x"?ne.current??Math.max(0,Math.min(Ss,-Lt)):j?Ss:0)>=Math.min(aO,Ss*f_);T(jn),jn&&(N(!1),Jn(null)),R.current=null,js(null);return}const Pt=Ke.axis==="x"?he.current??(Ke.mode==="open"?Math.max(0,Math.min(On,Lt)):Math.max(0,Math.min(On,On+Lt))):w?On:0,At=Ke.mode==="open"?Pt>=Math.min(sO,On*f_):Pt>=On*f_;N(At),R.current=null,Jn(null)};_.useEffect(()=>{const ee=o.current;if(!ee||M)return;const Be=Pt=>{if(j)return;const At=Pt.touches[0];Pt.touches.length!==1||!At||Fs(Pt.target)||(Ce.current={startX:At.clientX,startY:At.clientY})},Ke=Pt=>{if(Pt.touches.length!==1)return;const At=Pt.touches[0];if(!R.current){const jn=Ce.current;if(!jn)return;const kn=At.clientX-jn.startX,pn=At.clientY-jn.startY;if(Math.abs(kn)<8&&Math.abs(pn)<8)return;if(Math.abs(kn)<=Math.abs(pn)){Ce.current=null;return}const U=w&&kn<0,Ne=!j&&!w&&kn>0,Ue=!w&&!j&&kn<0&&q,Qe=U||Ne?Js(jn.startX,jn.startY):Ue?ua(jn.startX,jn.startY):!1;if(Ce.current=null,!Qe)return}da(At.clientX,At.clientY)&&Pt.cancelable&&Pt.preventDefault()},Lt=Pt=>{if(Ce.current=null,!R.current)return;const At=Pt.changedTouches[0];if(!At){R.current=null,Jn(null),js(null);return}fa(At.clientX,At.clientY)},Zt=()=>{Ce.current=null,R.current=null,Jn(null),js(null)};return ee.addEventListener("touchstart",Be,{passive:!0,capture:!0}),ee.addEventListener("touchmove",Ke,{passive:!1,capture:!0}),ee.addEventListener("touchend",Lt,{capture:!0}),ee.addEventListener("touchcancel",Zt,{capture:!0}),()=>{ee.removeEventListener("touchstart",Be,{capture:!0}),ee.removeEventListener("touchmove",Ke,{capture:!0}),ee.removeEventListener("touchend",Lt,{capture:!0}),ee.removeEventListener("touchcancel",Zt,{capture:!0})}},[q,M,j,w]);const In=()=>a.jsx(a.Fragment,{children:a.jsxs("div",{className:`conversation-main ${M?"has-desktop-sidebar":""}`,style:{transform:`translateX(${Zs}px)`,transition:Ot?"none":void 0},children:[a.jsx("div",{className:"conversation-topbar",children:M?null:a.jsxs("button",{type:"button",className:"conversation-menu",onClick:()=>N(!0),"aria-label":"打开侧边栏",children:[a.jsx("span",{}),a.jsx("span",{className:"short"})]})}),a.jsx("div",{className:"conversation-scroll conversation-scroll--empty",children:a.jsx("div",{className:"conversation-thread conversation-thread--empty",children:a.jsx(eO,{mode:"node",agentName:st?Cc(st):void 0,agentStatus:(st==null?void 0:st.status)??null,onOpenNodes:()=>{i({to:"/nodes"})}})})})]})});return a.jsxs("div",{ref:o,className:`conversation-page ${M?"has-desktop-sidebar":""}`,style:Sn,onPointerDown:ee=>{M||j||ee.pointerType!=="touch"&&(ee.pointerType==="mouse"&&ee.button!==0||Fs(ee.target)||(Js(ee.clientX,ee.clientY,ee.pointerId),ee.currentTarget.setPointerCapture(ee.pointerId)))},onPointerMove:ee=>{if(M||ee.pointerType==="touch")return;const Be=R.current;!Be||Be.pointerId!==ee.pointerId||!da(ee.clientX,ee.clientY)||ee.preventDefault()},onPointerUp:ee=>{if(M||ee.pointerType==="touch")return;const Be=R.current;!Be||Be.pointerId!==ee.pointerId||fa(ee.clientX,ee.clientY)},onPointerCancel:ee=>{if(M||ee.pointerType==="touch")return;const Be=R.current;!Be||Be.pointerId!==ee.pointerId||(R.current=null,Jn(null),js(null))},children:[a.jsx(a5,{open:Kt,progress:Ln,isDragging:Ot,desktopPinned:M,isDesktopResizing:O,onClose:()=>{M||(N(!1),Jn(null))},onDesktopResizeStart:ee=>{ue.current=le.current,X.current={startX:ee,startWidth:le.current},Q(!0)},currentAgent:st??void 0,agentIndicatorState:Dt,projects:an,sessions:re,projectStats:we,historySessionsByProject:Object.fromEntries(Object.entries(dt).map(([ee,Be])=>[ee,Be.sessions])),archivedSessionsByProject:Object.fromEntries(Object.entries(un).map(([ee,Be])=>[ee,Be.sessions])),chatHistorySessions:Re.sessions,chatArchivedSessions:te.sessions,historyPageStateByProject:dt,archivedPageStateByProject:un,chatHistoryPageState:Re,chatArchivedPageState:te,activeSessionId:ve==null?void 0:ve.id,onCreateSession:ee=>{Xs(ee)},onCreateChat:()=>{Xs(Gr)},onCreateImageSession:()=>{$s()},onCreateDirectoryThread:()=>{ns()},onSelectSession:ee=>{oa(ee)},onSessionAction:Le,onThreadAction:rn,onOpenSettings:e,onLoadMoreHistory:ee=>{$t(ee)},onLoadMoreChatHistory:()=>{An()},onLoadMoreArchived:ee=>{Nn(ee)},onLoadMoreChatArchived:()=>{Tt()},pendingSessionActionId:$e.isPending?((ws=$e.variables)==null?void 0:ws.sessionId)??null:null,pendingThreadActionId:Pe.isPending?((Os=Pe.variables)==null?void 0:Os.projectId)??null:null}),a.jsxs("div",{className:`conversation-workspace-stack ${j||Wn?"is-preview-open":""} ${Wn?"is-dragging":""}`,children:[a.jsx("div",{className:"conversation-workspace-stack__page is-primary",children:Ee?(ve==null?void 0:ve.provider)==="image"?a.jsx(HR,{sessionId:Ee,workspaceDirectorySnapshot:qe??null,workspaceAgentIndicatorState:Dt,embedded:!0,isDesktopSidebar:M,sidebarOffset:Zs,isSidebarDragging:Ot,onOpenSidebar:()=>{T(!1),N(!0)}}):a.jsx(JD,{sessionId:Ee,workspaceDirectorySnapshot:qe??null,workspaceAgentIndicatorState:Dt,embedded:!0,isDesktopSidebar:M,sidebarOffset:Zs,isSidebarDragging:Ot,onOpenSidebar:()=>{T(!1),N(!0)},onSelectSession:ee=>{ee&&oa(ee)},onExitToNodes:()=>{sl(null),Ea(null),y(null),i({to:"/nodes"})}}):st?ve?null:a.jsx(RA,{currentAgent:st,projects:an,sessions:re,initialProjectId:g,entryView:p,isDesktopSidebar:M,sidebarOffset:Zs,isSidebarDragging:Ot,onOpenSidebar:()=>{T(!1),N(!0)},onProjectSelected:ee=>{b(ee),v("composer"),Hf(!1)},onSessionCreated:ee=>{oa(ee)}}):In()}),a.jsx("div",{className:"conversation-workspace-stack__page is-preview",children:a.jsx("div",{className:"session-file-preview-pane",children:ve&&V&&(j||Z!==null)?a.jsx(_.Suspense,{fallback:a.jsx("div",{className:"session-file-preview-pane__fallback",children:"正在载入预览页…"}),children:a.jsx(rO,{agentId:(st==null?void 0:st.id)??ke,sessionId:ve.id,projectName:V.display_name||V.name,projectPath:V.path,isActive:j,onBack:()=>{T(!1),js(null)}},ve.id)}):null})})]})]})},dO=24,fO=32,hO=72,Zx="panda:native-safe-area-change",yy=e=>{const t=Number(e);if(!Number.isFinite(t))return 0;const i=typeof window<"u"&&Number.isFinite(window.devicePixelRatio)&&window.devicePixelRatio>0?window.devicePixelRatio:1;return Math.max(0,t/i)},h_=e=>`${Math.round(yy(e)*100)/100}px`,mO=e=>`${Math.round(e*100)/100}px`,pO=e=>{const t=yy(e);if(!Yp())return`${Math.round(t*100)/100}px`;const i=Math.min(fO,Math.max(dO,t+1));return`${Math.round(i*100)/100}px`},gO=()=>{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},_O=e=>{var o;if(!ba())return"0px";const t=gO(),i=yy((o=e==null?void 0:e.getKeyboardInsetPx)==null?void 0:o.call(e)),r=t>0?t:i;return r<hO?"0px":mO(r)},yO=()=>{var i,r,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",pO((i=e.getTopInsetPx)==null?void 0:i.call(e))),t.setProperty("--native-safe-area-right",h_((r=e.getRightInsetPx)==null?void 0:r.call(e))),t.setProperty("--native-safe-area-bottom",h_((o=e.getBottomInsetPx)==null?void 0:o.call(e))),t.setProperty("--native-safe-area-left",h_((u=e.getLeftInsetPx)==null?void 0:u.call(e)))),t.setProperty("--native-keyboard-inset-bottom",_O(e))},vO=()=>{var u,d;if(typeof window>"u"||typeof document>"u")return()=>{};const e=()=>{yO()},t=new Set,i=m=>{const y=window.setTimeout(()=>{t.delete(y),e()},m);t.add(y)},r=()=>{e(),i(120),i(280)};let o=null;return e(),i(0),i(250),i(800),window.addEventListener("load",e,{once:!0}),window.addEventListener("resize",e),window.addEventListener("orientationchange",e),window.addEventListener(Zx,e),document.addEventListener("visibilitychange",e),document.addEventListener("focusin",r,!0),document.addEventListener("focusout",r,!0),(u=window.visualViewport)==null||u.addEventListener("resize",e),(d=window.visualViewport)==null||d.addEventListener("scroll",e),w3.addListener("resume",e).then(m=>{o=()=>{m.remove()}}).catch(()=>{}),()=>{var m,y;window.removeEventListener("resize",e),window.removeEventListener("orientationchange",e),window.removeEventListener(Zx,e),document.removeEventListener("visibilitychange",e),document.removeEventListener("focusin",r,!0),document.removeEventListener("focusout",r,!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()}},m_=new OS,bO=async()=>{},xO=_.lazy(async()=>({default:(await cl(()=>import("./diagnostics-page-4wwMLeXa.js"),__vite__mapDeps([3,4]))).DiagnosticsPage})),SO=()=>a.jsx(_.Suspense,{fallback:a.jsx("main",{className:"diagnostics-page",children:a.jsx("div",{className:"diagnostics-shell",children:a.jsx("section",{className:"diagnostics-card",children:a.jsx("p",{children:"正在载入诊断页…"})})})}),children:a.jsx(xO,{})}),Ic=L7({component:FM}),jO=Rc({getParentRoute:()=>Ic,path:"/",component:L5}),wO=Rc({getParentRoute:()=>Ic,path:"/nodes",component:QM}),NO=Rc({getParentRoute:()=>Ic,path:"/session/$sessionId",component:VM}),kO=Rc({getParentRoute:()=>Ic,path:"/new-thread/$agentId",component:L5}),EO=Rc({getParentRoute:()=>Ic,path:"/settings",component:J3}),CO=Rc({getParentRoute:()=>Ic,path:"/diagnostics",component:SO}),TO=Ic.addChildren([jO,wO,NO,kO,EO,CO]),MO=q7({routeTree:TO,defaultPreload:"intent"});typeof document<"u"&&(G3(Q3()),vO());bO().catch(()=>{}).then(async()=>{await DE(),await fC(m_),mC(m_)}).finally(()=>{nS.createRoot(document.getElementById("root")).render(a.jsx(LS,{client:m_,children:a.jsx(Q7,{router:MO})}))});export{Ub as B,QC as C,id as E,L_ as L,ES as Q,vd as S,q2 as W,hh as X,cl as _,h2 as a,Ka as b,PS as c,BS as d,qS as e,$S as f,HS as g,zs as h,KS as i,a as j,ob as k,FS as l,la as m,Bs as n,cn as o,cs as p,IO as q,_ as r,up as s,Z0 as t,Hi as u,Q9 as v,O1 as w};
|