@evandu/super-pi 0.1.302 → 0.1.303
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/.super-pi-check-inputs.json +2 -2
- package/dist/client/.super-pi-client-sources.json +16 -15
- package/dist/client/assets/{CodeMirrorEditor-BeVgHVpR.js → CodeMirrorEditor-DlcBTysV.js} +1 -1
- package/dist/client/assets/{GitDiffEditor-D3hvVjdf.js → GitDiffEditor-CyDiA4rj.js} +1 -1
- package/dist/client/assets/index-DBuR5Y3G.css +1 -0
- package/dist/client/assets/{index-BAq4p4ug.js → index-DDvvcuuS.js} +16 -16
- package/dist/client/index.html +2 -2
- package/dist/server/application/catalog-service.js +2 -8
- package/dist/server/application/group-chat-service.js +13 -3
- package/dist/server/application/rsi-repairs.js +2 -2
- package/dist/server/application/rsi-service.js +13 -13
- package/dist/server/application/run-service.js +2 -0
- package/dist/server/index.js +8 -2
- package/dist/server/model-filter.d.ts +15 -0
- package/dist/server/model-filter.js +24 -0
- package/dist/server/rsi-http.js +11 -1
- package/dist/server/store.d.ts +1 -0
- package/dist/server/store.js +7 -0
- package/dist/server/types.d.ts +1 -0
- package/dist/shared/rsi.d.ts +7 -2
- package/package.json +1 -1
- package/dist/client/assets/index-BzYJAyfI.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-DP4hrTBF.js","assets/rolldown-runtime-XKyaHtl9.js","assets/dist-D978o95T.js","assets/dist-DTIPfQj7.js","assets/dist-Cus6_oaF.js","assets/dist-699T9mBC.js","assets/dist-BXAOrsjq.js","assets/dist-BUY8ZNeZ.js","assets/dist-BJHpSQV1.js","assets/dist-Dfhu-vbV.js","assets/dist-BqSTJyq9.js","assets/dist-CVPY8uK1.js","assets/dist-DLNOWOmk.js","assets/dist-Jg3fJuzH.js","assets/dist-B2l9cUU9.js","assets/dist-BX5MJasK.js","assets/dist-dybF9Ag8.js","assets/dist-BXqtlD7O.js","assets/dist-CAlPBcem.js","assets/dist-X4BHLQqs.js","assets/dist-gDvn1xVj.js","assets/dist-S5ntGzJB.js","assets/dist-Qjm1p8SR.js","assets/CodeMirrorEditor-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-DP4hrTBF.js","assets/rolldown-runtime-XKyaHtl9.js","assets/dist-D978o95T.js","assets/dist-DTIPfQj7.js","assets/dist-Cus6_oaF.js","assets/dist-699T9mBC.js","assets/dist-BXAOrsjq.js","assets/dist-BUY8ZNeZ.js","assets/dist-BJHpSQV1.js","assets/dist-Dfhu-vbV.js","assets/dist-BqSTJyq9.js","assets/dist-CVPY8uK1.js","assets/dist-DLNOWOmk.js","assets/dist-Jg3fJuzH.js","assets/dist-B2l9cUU9.js","assets/dist-BX5MJasK.js","assets/dist-dybF9Ag8.js","assets/dist-BXqtlD7O.js","assets/dist-CAlPBcem.js","assets/dist-X4BHLQqs.js","assets/dist-gDvn1xVj.js","assets/dist-S5ntGzJB.js","assets/dist-Qjm1p8SR.js","assets/CodeMirrorEditor-DlcBTysV.js","assets/CodeMirrorEditor-C8sidScW.css","assets/GitDiffEditor-CyDiA4rj.js","assets/GitDiffEditor-DUY8YwXS.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{r as e,t}from"./rolldown-runtime-XKyaHtl9.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var n=t((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.for(`react.view_transition`),m=Symbol.iterator;function h(e){return typeof e!=`object`||!e?null:(e=m&&e[m]||e[`@@iterator`],typeof e==`function`?e:null)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},_=Object.assign,v={};function y(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}y.prototype.isReactComponent={},y.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},y.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function b(){}b.prototype=y.prototype;function x(e,t,n){this.props=e,this.context=t,this.refs=v,this.updater=n||g}var S=x.prototype=new b;S.constructor=x,_(S,y.prototype),S.isPureReactComponent=!0;var C=Array.isArray;function w(){}var T={H:null,A:null,T:null,S:null},E=Object.prototype.hasOwnProperty;function D(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function O(e,t){return D(e.type,t,e.props)}function k(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function A(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var j=/\/+/g;function ee(e,t){return typeof e==`object`&&e&&e.key!=null?A(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(w,w):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ee(e,0):a,C(o)?(i=``,c!=null&&(i=c.replace(j,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(k(o)&&(o=O(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(j,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(C(e))for(var u=0;u<e.length;u++)a=e[u],s=l+ee(a,u),c+=N(a,r,i,s,o);else if(u=h(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+ee(a,u++),c+=N(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return N(M(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function P(e,t,n){if(e==null)return e;var r=[],i=0;return N(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function F(e){if(e._status===-1){var t=e._result,n=t();n.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t,n.status===void 0&&(n.status=`fulfilled`,n.value=t))},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t,n.status===void 0&&(n.status=`rejected`,n.reason=t))}),e._status===-1&&(e._status=0,e._result=n)}if(e._status===1)return e._result.default;throw e._result}var I=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)};function te(e){var t=T.T,n={};n.types=t===null?null:t.types,T.T=n;try{var r=e(),i=T.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(w,I)}catch(e){I(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),T.T=t}}function ne(e){var t=T.T;if(t!==null){var n=t.types;n===null?t.types=[e]:n.indexOf(e)===-1&&n.push(e)}else te(ne.bind(null,e))}var re={map:P,forEach:function(e,t,n){P(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return P(e,function(){t++}),t},toArray:function(e){return P(e,function(e){return e})||[]},only:function(e){if(!k(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=re,e.Component=y,e.Fragment=r,e.Profiler=a,e.PureComponent=x,e.StrictMode=i,e.Suspense=l,e.ViewTransition=p,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return T.H.useMemoCache(e)}},e.addTransitionType=ne,e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=_({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!E.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return D(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)E.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return D(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=k,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:F}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=te,e.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},e.use=function(e){return T.H.use(e)},e.useActionState=function(e,t,n){return T.H.useActionState(e,t,n)},e.useCallback=function(e,t){return T.H.useCallback(e,t)},e.useContext=function(e){return T.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return T.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return T.H.useEffect(e,t)},e.useEffectEvent=function(e){return T.H.useEffectEvent(e)},e.useId=function(){return T.H.useId()},e.useImperativeHandle=function(e,t,n){return T.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return T.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return T.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return T.H.useMemo(e,t)},e.useOptimistic=function(e,t){return T.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return T.H.useReducer(e,t,n)},e.useRef=function(e){return T.H.useRef(e)},e.useState=function(e){return T.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return T.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return T.H.useTransition()},e.version=`19.3.1`})),r=t(((e,t)=>{t.exports=n()})),i=t((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&j(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-T<w)}function D(){if(g=!1,S){var t=e.unstable_now();T=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&j(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var k=new MessageChannel,A=k.port2;k.port1.onmessage=D,O=function(){A.postMessage(null)}}else O=function(){_(D,0)};function j(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,j(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),a=t(((e,t)=>{t.exports=i()})),o=t((e=>{var t=r();function n(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function i(){}var a={d:{f:i,r:function(){throw Error(n(522))},D:i,C:i,L:i,m:i,X:i,S:i,M:i},p:0,findDOMNode:null},o=Symbol.for(`react.portal`),s=Symbol.for(`react.recoverable`),c=Symbol.for(`react.optimistic_key`);function l(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:o,key:r==null?null:r===c?c:``+r,children:e,containerInfo:t,implementation:n}}var u=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function d(e,t){if(e===`font`)return``;if(typeof t==`string`)return t===`use-credentials`?t:``}e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=a,e.browser=function(e){return{$$typeof:s,_reason:e}},e.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)throw Error(n(299));return l(e,t,null,r)},e.flushSync=function(e){var t=u.T,n=a.p;try{if(u.T=null,a.p=2,e)return e()}finally{u.T=t,a.p=n,a.d.f()}},e.preconnect=function(e,t){typeof e==`string`&&(t?(t=t.crossOrigin,t=typeof t==`string`?t===`use-credentials`?t:``:void 0):t=null,a.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&a.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=d(n,t.crossOrigin),i=typeof t.integrity==`string`?t.integrity:void 0,o=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?a.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:i,fetchPriority:o}):n===`script`&&a.d.X(e,{crossOrigin:r,integrity:i,fetchPriority:o,nonce:typeof t.nonce==`string`?t.nonce:void 0})}},e.preinitModule=function(e,t){if(typeof e==`string`){if(typeof t==`object`&&t){if(t.as==null||t.as===`script`){var n=d(t.as,t.crossOrigin);a.d.M(e,{crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0})}}else t??a.d.M(e)}},e.preload=function(e,t){if(typeof e==`string`&&typeof t==`object`&&t&&typeof t.as==`string`){var n=t.as,r=d(n,t.crossOrigin);a.d.L(e,n,{crossOrigin:r,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,type:typeof t.type==`string`?t.type:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0,referrerPolicy:typeof t.referrerPolicy==`string`?t.referrerPolicy:void 0,imageSrcSet:typeof t.imageSrcSet==`string`?t.imageSrcSet:void 0,imageSizes:typeof t.imageSizes==`string`?t.imageSizes:void 0,media:typeof t.media==`string`?t.media:void 0})}},e.preloadModule=function(e,t){if(typeof e==`string`){if(t){var n=d(t.as,t.crossOrigin);a.d.m(e,{as:typeof t.as==`string`&&t.as!==`script`?t.as:void 0,crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0})}else a.d.m(e)}},e.requestFormReset=function(e){a.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return u.H.useFormState(e,t,n)},e.useFormStatus=function(){return u.H.useHostTransitionStatus()},e.version=`19.3.1`})),s=t(((e,t)=>{function n(){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE==`function`)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=o()})),c=t((e=>{var t=a(),n=r(),i=s();function o(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function c(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function l(e){for(var t=e,n=t;n&&!n.alternate;)t=n,t.flags&4098&&(e=t.return),n=t.return;for(;t.return;)t=t.return;return t.tag===3?e:null}function u(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function d(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function f(e){if(l(e)!==e)throw Error(o(188))}function p(e){var t=e.alternate;if(!t){if(t=l(e),t===null)throw Error(o(188));return t===e?e:null}for(var n=e,r=t;;){var i=n.return;if(i===null)break;var a=i.alternate;if(a===null){if(r=i.return,r!==null){n=r;continue}break}if(i.child===a.child){for(a=i.child;a;){if(a===n)return f(i),e;if(a===r)return f(i),t;a=a.sibling}throw Error(o(188))}if(n.return!==r.return)n=i,r=a;else{for(var s=!1,c=i.child;c;){if(c===n){s=!0,n=i,r=a;break}if(c===r){s=!0,r=i,n=a;break}c=c.sibling}if(!s){for(c=a.child;c;){if(c===n){s=!0,n=a,r=i;break}if(c===r){s=!0,r=a,n=i;break}c=c.sibling}if(!s)throw Error(o(189))}}if(n.alternate!==r)throw Error(o(190))}if(n.tag!==3)throw Error(o(188));return n.stateNode.current===n?e:t}function m(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=m(e),t!==null)return t;e=e.sibling}return null}function h(e,t,n,r,i,a){for(;e!==null;){if((e.tag===5||e.tag===27||e.tag===6)&&n(e,r,i,a)||(e.tag!==22||e.memoizedState===null)&&(t||e.tag!==5&&e.tag!==27)&&h(e.child,t,n,r,i,a))return!0;e=e.sibling}return!1}function g(e){for(e=e.return;e!==null;){if(e.tag===3||e.tag===5||e.tag===27)return e;e=e.return}return null}function _(e){var t=!1;for(e=e.return;e!==null&&(e.tag===4&&(t=!0),e.tag!==3&&e.tag!==5&&e.tag!==27);)e=e.return;return t}function v(e){var t=[null,null],n=g(e);return n===null||y(t,e,n.child,{foundSelf:!1}),t}function y(e,t,n,r){for(;n!==null;){if(n===t)r.foundSelf=!0;else if(n.tag===5||n.tag===27||n.tag===6){if(r.foundSelf)return e[1]=n,!0;e[0]=n}else if((n.tag!==22||n.memoizedState===null)&&y(e,t,n.child,r))return!0;n=n.sibling}return!1}function b(e){switch(e.tag){case 5:case 27:case 6:return e.stateNode;case 3:return e.stateNode.containerInfo;default:throw Error(o(559))}}var x=null,S=null;function C(e,t,n){return e===n||e===t&&(x=e,!0)}function w(e,t,n){return e===n?(S=e,!1):e===t&&(S!==null&&(x=e),!0)}function T(e){if(e===null)return null;do e=e===null?null:e.return;while(e&&e.tag!==5&&e.tag!==27&&e.tag!==3);return e||null}function E(e,t,n){for(var r=0,i=e;i;i=n(i))r++;i=0;for(var a=t;a;a=n(a))i++;for(;0<r-i;)e=n(e),r--;for(;0<i-r;)t=n(t),i--;for(;r--;){if(e===t||t!==null&&e===t.alternate)return e;e=n(e),t=n(t)}return null}var D=Object.assign,O=Symbol.for(`react.element`),k=Symbol.for(`react.transitional.element`),A=Symbol.for(`react.portal`),j=Symbol.for(`react.fragment`),ee=Symbol.for(`react.strict_mode`),M=Symbol.for(`react.profiler`),N=Symbol.for(`react.consumer`),P=Symbol.for(`react.context`),F=Symbol.for(`react.forward_ref`),I=Symbol.for(`react.suspense`),te=Symbol.for(`react.suspense_list`),ne=Symbol.for(`react.memo`),re=Symbol.for(`react.lazy`),ie=Symbol.for(`react.activity`),ae=Symbol.for(`react.legacy_hidden`),oe=Symbol.for(`react.memo_cache_sentinel`),se=Symbol.for(`react.view_transition`),ce=Symbol.for(`react.recoverable`),le=Symbol.iterator;function ue(e){return typeof e!=`object`||!e?null:(e=le&&e[le]||e[`@@iterator`],typeof e==`function`?e:null)}var de=Symbol.for(`react.client.reference`);function fe(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===de?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case j:return`Fragment`;case M:return`Profiler`;case ee:return`StrictMode`;case I:return`Suspense`;case te:return`SuspenseList`;case ie:return`Activity`;case se:return`ViewTransition`}if(typeof e==`object`)switch(e.$$typeof){case A:return`Portal`;case P:return e.displayName||`Context`;case N:return(e._context.displayName||`Context`)+`.Consumer`;case F:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case ne:return t=e.displayName||null,t===null?fe(e.type)||`Memo`:t;case re:t=e._payload,e=e._init;try{return fe(e(t))}catch{}}return null}var pe=Array.isArray,L=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,me=i.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,he={pending:!1,data:null,method:null,action:null},ge=[],_e=-1;function ve(e){return{current:e}}function ye(e){0>_e||(e.current=ge[_e],ge[_e]=null,_e--)}function be(e,t){_e++,ge[_e]=e.current,e.current=t}var xe=ve(null),Se=ve(null),Ce=ve(null),we=ve(null);function Te(e,t){switch(be(Ce,t),be(Se,e),be(xe,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?dp(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=dp(t),e=fp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ye(xe),be(xe,e)}function Ee(){ye(xe),ye(Se),ye(Ce)}function De(e){var t=e.memoizedState;t!==null&&(ch._currentValue=t.memoizedState,be(we,e)),t=xe.current;var n=fp(t,e.type);t!==n&&(be(Se,e),be(xe,n))}function Oe(e){Se.current===e&&(ye(xe),ye(Se)),we.current===e&&(ye(we),ch._currentValue=he)}var ke,Ae;function je(e){if(ke===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);ke=t&&t[1]||``,Ae=-1<e.stack.indexOf(`
|
|
3
3
|
at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
|
|
4
4
|
`+ke+e+Ae}var Me=!1;function Ne(e,t){if(!e||Me)return``;Me=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}n=!1;try{var i=Object.getOwnPropertyDescriptor(e.prototype,`props`);Object.defineProperty(e.prototype,"props",{configurable:!0,set:function(){throw Error()}}),n=!0,new e}finally{n&&(i===void 0?delete e.prototype.props:Object.defineProperty(e.prototype,"props",i))}}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
|
|
@@ -284,13 +284,13 @@ ${h}.`);break;case m:switch(t){case`xml`:break;case``:e.fail(`the default namesp
|
|
|
284
284
|
`&&(s+=1),n.length===500&&s<e.length-1))return{rows:n,clipped:!0}}else i+=c}return(i||r.length)&&(r.length<50?r.push(i):o=!0,n.push(r)),{rows:n,clipped:o}}function Cp({workspaceId:e,cwd:t,path:n,name:r,kind:i,content:a,source:o,version:s,sourceRequest:c,external:l,navigation:u,assetTicket:d,onReload:f}){let[h,g]=(0,p.useState)(c!==void 0),[_,v]=(0,p.useState)(),[y,b]=(0,p.useState)(!1),x=(r,i)=>d?xp(r,e,t,d,i):bp(r,e,t,n,i),S=x(`asset`,{v:s}),C=x(`asset`,{download:`1`}),w=x(`document`);(0,p.useEffect)(()=>{c!==void 0&&g(!0)},[c]),(0,p.useEffect)(()=>{b(!1)},[S]),(0,p.useEffect)(()=>{if(i!==`document`)return;let e=new AbortController;return Ie(w,{signal:e.signal}).then(async e=>{let t=await e.json();if(!e.ok)throw Error(t.error??`无法读取文档。`);v(t)}).catch(t=>{e.signal.aborted||v({error:String(t.message??t)})}),()=>e.abort()},[w,i,s]);let T=(0,p.useMemo)(()=>i===`table`&&!h?Sp(a,/\.tsv$/i.test(n)?` `:`,`):void 0,[i,a,n,h]);return(0,m.jsxs)(`section`,{className:`workspace-file-preview`,"aria-label":`预览 ${r}`,"data-workspace-file-preview":i,"data-file-readonly":d?`1`:void 0,children:[(0,m.jsxs)(`div`,{className:`workspace-file-preview-head`,children:[u,(0,m.jsxs)(`div`,{className:`workspace-file-preview-actions`,children:[d&&(0,m.jsx)(`span`,{children:`外部文件 · 只读`}),d&&f&&(0,m.jsx)(`button`,{type:`button`,onClick:f,children:`重新读取`}),o&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>g(e=>!e),children:h?`查看表格`:d?`查看原文`:`编辑原文`}),(0,m.jsxs)(`a`,{href:C,download:r,children:[(0,m.jsx)(Ri,{name:`download`}),`下载`]})]})]}),l&&!h&&(0,m.jsx)(`p`,{role:`status`,children:o?`磁盘上的文件已变化,请打开原文查看。`:`磁盘上的文件已移走或无法读取。`}),h?o:y?(0,m.jsx)(`p`,{role:`status`,children:`预览无法打开,可以下载文件。`}):(0,m.jsxs)(m.Fragment,{children:[i===`download`&&(0,m.jsx)(`p`,{children:`此文件可以下载。`}),i===`presentation`&&(d?(0,m.jsx)(`p`,{children:`外部演示稿可通过上方按钮下载。`}):(0,m.jsx)(yp,{workspaceId:e,cwd:t,path:n,version:s})),i===`image`&&(0,m.jsx)(`img`,{src:S,alt:r,onError:()=>b(!0)}),i===`pdf`&&(0,m.jsx)(`iframe`,{src:S,title:r}),i===`audio`&&(0,m.jsx)(`audio`,{src:S,controls:!0,preload:`metadata`,onError:()=>b(!0)}),i===`video`&&(0,m.jsx)(`video`,{src:S,controls:!0,preload:`metadata`,onError:()=>b(!0)}),i===`document`&&(_?.error?(0,m.jsx)(`p`,{role:`alert`,children:_.error}):_?(0,m.jsxs)(m.Fragment,{children:[_.warnings?.map(e=>(0,m.jsx)(`p`,{children:e},e)),(0,m.jsx)(`pre`,{children:_.text||`此文档没有可显示的文字。`})]}):(0,m.jsx)(`p`,{children:`正在读取文档…`})),T&&(T.rows.length?(0,m.jsx)(`div`,{className:`workspace-file-table`,children:(0,m.jsx)(`table`,{children:(0,m.jsx)(`tbody`,{children:T.rows.map((e,t)=>(0,m.jsxs)(`tr`,{children:[(0,m.jsx)(`th`,{scope:`row`,children:t+1}),e.map((e,t)=>(0,m.jsx)(`td`,{children:e},t))]},t))})})}):(0,m.jsx)(`p`,{children:`文件为空。`})),T?.clipped&&(0,m.jsx)(`p`,{className:`workspace-file-preview-limit`,children:`表格超出预览范围。完整内容可在原文中查看。`})]})]})}var wp={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,pdf:`application/pdf`,mp3:`audio/mpeg`,wav:`audio/wav`,ogg:`audio/ogg`,m4a:`audio/mp4`,mp4:`video/mp4`,webm:`video/webm`,ogv:`video/ogg`};function Tp(e){return/\.([^./]+)$/.exec(e)?.[1].toLowerCase()??``}function Ep(e){let t=Tp(e);return Object.hasOwn(wp,t)?wp[t]:void 0}function Dp(e){let t=Ep(e);if(t===`application/pdf`)return`pdf`;if(t?.startsWith(`image/`))return`image`;if(t?.startsWith(`audio/`))return`audio`;if(t?.startsWith(`video/`))return`video`;if(/\.(csv|tsv)$/i.test(e))return`table`;if(/\.docx$/i.test(e))return`document`;if(/\.pptx$/i.test(e))return`presentation`}var Op=e=>e.slice(0,Math.max(0,e.lastIndexOf(`/`))),kp=(e,t)=>!t||e===t||e.startsWith(`${t}/`),Ap=e=>e.split(`/`).at(-1)??e;function jp(e){if(!(e instanceof Element))return;let t=e.closest(`[data-file-dir], [data-file-entry], [data-file-hit]`);if(!t)return;let n=t.dataset.fileDir??t.dataset.fileEntry??t.dataset.fileHit;if(n!==void 0)return{path:n,directory:t.dataset.fileDir!==void 0,linked:t.dataset.linked===`true`||t.dataset.fileOutside!==void 0}}function Mp({title:e,cancel:t,children:n}){let r=(0,p.useRef)(null);return(0,p.useEffect)(()=>{let e=r.current,t=document.activeElement;return e?.showModal(),()=>{e?.close(),t?.isConnected&&t.focus()}},[]),(0,m.jsx)(`dialog`,{ref:r,className:`file-explorer-dialog`,"aria-label":e,onCancel:e=>{e.preventDefault(),t()},onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`file-explorer-dialog-body`,children:[(0,m.jsx)(`h2`,{children:e}),n]})})}function Np({target:e,label:t,initial:n,busy:r,error:i,depth:a,submit:o,close:s}){let c=(0,p.useRef)(null);return(0,p.useLayoutEffect)(()=>{let t=c.current;if(!t)return;t.focus();let r=n.lastIndexOf(`.`);t.setSelectionRange(0,!e.directory&&r>0?r:n.length)},[n,e.directory]),(0,m.jsxs)(`form`,{className:`file-inline-edit`,"data-file-inline-edit":e.path,"aria-label":t,style:{paddingInlineStart:23+a*15},onSubmit:o,onKeyDown:e=>{e.key===`Escape`&&!r&&(e.preventDefault(),e.stopPropagation(),s())},children:[(0,m.jsxs)(`div`,{className:`file-inline-row`,children:[(0,m.jsx)(Kr,{path:e.path,category:e.directory?`folder`:void 0}),(0,m.jsx)(`input`,{ref:c,name:`name`,required:!0,defaultValue:n,placeholder:t,"aria-label":t,"aria-invalid":!!i,readOnly:r,autoComplete:`off`,spellCheck:!1}),(0,m.jsx)(`button`,{className:`explorer-icon-button`,type:`submit`,title:t,"aria-label":t,disabled:r,children:(0,m.jsx)(Ri,{name:`right`})}),(0,m.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,onClick:s,disabled:r,title:`取消`,"aria-label":`取消`,children:(0,m.jsx)(Ri,{name:`close`})})]}),i&&(0,m.jsx)(`p`,{className:`file-inline-error`,role:`alert`,children:i})]})}function Pp({files:e,source:t,scopeName:n}){let[r,i]=(0,p.useState)(Op(t.path)),a=e.listings[r],o=e.loadDirectory;(0,p.useEffect)(()=>{a||o(r)},[r,a,o]);let s=a&&`entries`in a?a.entries.filter(e=>e.kind===`directory`&&!e.symlink&&!(t.directory&&kp(e.path,t.path))):[];return(0,m.jsxs)(`div`,{className:`file-move-picker`,children:[(0,m.jsx)(`input`,{type:`hidden`,name:`parent`,value:r}),(0,m.jsxs)(`div`,{className:`file-move-location`,children:[(0,m.jsx)(`button`,{type:`button`,disabled:!r,"aria-label":`上一级`,onClick:()=>i(Op(r)),children:`↑`}),(0,m.jsx)(`span`,{title:r||n,children:r||n})]}),(0,m.jsx)(`ul`,{"aria-label":`目标文件夹`,children:s.map(e=>(0,m.jsx)(`li`,{children:(0,m.jsxs)(`button`,{type:`button`,onClick:()=>i(e.path),children:[(0,m.jsx)(Kr,{category:`folder`}),(0,m.jsx)(`span`,{children:e.name}),(0,m.jsx)(Ri,{name:`right`})]})},e.path))}),!s.length&&(0,m.jsx)(`p`,{children:a?`error`in a?a.error.message:`此处没有子文件夹。`:`正在读取文件夹…`})]})}function Fp({workspaceId:e,scopeName:t,cwd:n,files:r,onOpen:i,onReference:a,onMoved:o,onSearchFolder:s}){let[c,l]=(0,p.useState)(),[u,d]=(0,p.useState)(),[f,h]=(0,p.useState)(),[g,_]=(0,p.useState)(!1),[v,y]=(0,p.useState)(``),[b,x]=(0,p.useState)(),S=(0,p.useRef)(null),C=(0,p.useRef)(``),w=(0,p.useRef)(void 0),T=(0,p.useRef)(void 0);(0,p.useEffect)(()=>{let e={controller:new AbortController};return T.current=e,l(void 0),d(void 0),h(void 0),x(void 0),_(!1),y(``),()=>{e.controller.abort(),T.current===e&&(T.current=void 0)}},[e,n]);let E=(t,r=``,i)=>bp(t,e??``,n,r,i);async function D(e,t){let n=await Ie(e,{...t,signal:T.current?.controller.signal}),r=await n.json();if(!n.ok)throw Error(r.error??`操作失败(${n.status})`);return r}function O(e,t){c?.anchor.origin===t.origin&&c.target.path===e.path?l(void 0):l({target:e,anchor:t})}function k(e){l(void 0),e&&c?.anchor.origin.isConnected&&c.anchor.origin.focus({preventScroll:!0})}function A(e,t,n,i){w.current=i??c?.anchor.origin??(document.activeElement instanceof HTMLElement?document.activeElement:void 0),l(void 0),y(``),d({action:e,target:t,move:n}),e===`create-file`||e===`create-directory`?t.path?r.revealPath(`${t.path}/`):r.setQuery(``):e===`move`&&!n&&r.revealPath(t.path)}function j(){d(void 0);let e=w.current;requestAnimationFrame(()=>{e?.isConnected&&e.offsetParent?e.focus({preventScroll:!0}):u?.target.path&&r.locatePath(u.target.path,u.target.directory)})}async function ee(t){let a=T.current;_(!0),y(``);try{let s=await D(E(`tree`),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)});if(T.current!==a)return;if(s.previousPath&&s.previousPath!==s.path?(r.movePath(s.previousPath,s.path,s.text),o?.(s.previousPath,s.path)):s.removed||r.revealPath(s.path),r.invalidateTree(e??``,[s.path,...s.previousPath?[s.previousPath]:[]].map(e=>n?`${n}/${e}`:e)),s.removed){for(let e of r.open)kp(e.path,s.path)&&!e.dirty&&r.closeFile(e.path);r.locatePath(Op(s.path),!0)}d(void 0),t.action===`restore`&&h(e=>e?.filter(e=>e.id!==t.id)),t.action===`create-file`&&s.text!==!1&&i({path:s.path,name:Ap(s.path),text:!0},!0),t.action!==`restore`&&!s.removed&&r.locatePath(s.path,!!s.directory),r.setNotice(s.removed?`已移到回收站:${s.path}`:t.action===`restore`?`已恢复:${s.path}`:``)}catch(e){if(T.current===a){let t=e instanceof Error?e.message:String(e);y(t),u||r.setNotice(t)}}finally{T.current===a&&_(!1)}}function M(e){if(e.preventDefault(),!u||g)return;let{action:t,target:n}=u;if((t===`move`||t===`trash`)&&Object.entries(r.saves).some(([e,t])=>kp(e,n.path)&&t.state===`saving`)){y(`文件正在保存,等保存结束后再操作。`);return}if(t===`trash`&&r.open.some(e=>e.dirty&&kp(e.path,n.path))){y(`这里有未保存的草稿,请先保存。`);return}let i=new FormData(e.currentTarget),a=String(i.get(`name`)??Ap(n.path));if(t===`move`&&!n.directory&&Tp(n.path)!==Tp(a)&&r.open.some(e=>e.path===n.path&&e.dirty)){y(`更换文件扩展名之前,请先保存草稿。`);return}let o=String(i.get(`parent`)??(t===`move`?Op(n.path):n.path));u.move&&o===Op(n.path)?y(`请选择另一个文件夹。`):ee({action:t,path:n.path,parent:o,name:a})}async function N(){let e=T.current;l(void 0),y(``);try{let t=await D(E(`tree`));T.current===e&&h(t.entries)}catch(t){T.current===e&&r.setNotice(String(t.message))}}function P(e){C.current=e,k(!0),S.current?.click()}async function F(t,i,a){let o=T.current;if(!e||!o||!i.length||g)return;_(!0),y(``),x(void 0);let s=[],c=[],l=[];try{for(let e of i){if(o!==T.current)return;try{let n=a?.find(t=>t.file===e)?.etag;if(!a){let n=await D(E(`upload-check`,t,{name:e.name}));if(n.exists){!n.replaceable||!n.meta?c.push(`${e.name}:同名目录或链接`):s.push({file:e,etag:n.meta.etag});continue}}let r=await D(E(`upload`,t,{name:e.name}),{method:`POST`,headers:{"content-type":`application/octet-stream`,...n?{"if-match":n}:{}},body:e});l.push(r.path)}catch(t){c.push(`${e.name}:${t.message}`)}}if(T.current!==o)return;l[0]&&r.revealPath(l[0]),l.length&&r.invalidateTree(e,l.map(e=>n?`${n}/${e}`:e)),s.length&&x({parent:t,items:s}),r.setNotice([l.length?`已上传 ${l.length} 个文件`:``,...c].filter(Boolean).join(`。`))}finally{T.current===o&&_(!1)}}function I(e,t){l(void 0),a?.(e||`.`,t)}function te(e){k(!0),Hi(e||`.`).then(t=>r.setNotice(t?`已复制相对路径。`:`相对路径:${e||`.`}`))}let ne=u?.action===`create-file`?`新建文件`:u?.action===`create-directory`?`新建文件夹`:u?.action===`trash`?`移到回收站`:u?.move?`移动到文件夹`:`重命名`,re={path:``,directory:!0},ie=u?.action===`create-file`||u?.action===`create-directory`,ae=u?.action===`move`&&!u.move,oe=(e,t,n)=>!u||u.target.path!==e||(t===`child`?!ie:!ae)?null:(0,m.jsx)(Np,{target:{...u.target,directory:ie?u.action===`create-directory`:u.target.directory},label:ne,initial:ae?Ap(e):``,busy:g,error:v,depth:n,submit:M,close:j},`${u.action}:${e}`),se=(e,t)=>{g||e.linked||e.directory&&kp(t,e.path)||t===Op(e.path)||(Object.entries(r.saves).some(([t,n])=>kp(t,e.path)&&n.state===`saving`)?r.setNotice(`文件正在保存,等保存结束后再移动。`):ee({action:`move`,path:e.path,parent:t,name:Ap(e.path)}))},ce=(0,m.jsxs)(`div`,{className:`file-explorer-toolbar`,role:`group`,"aria-label":`文件操作`,children:[(0,m.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-explorer-command":`new-file`,title:`新建文件`,"aria-label":`新建文件`,onClick:e=>A(`create-file`,re,!1,e.currentTarget),disabled:!e||g,children:(0,m.jsx)(Ri,{name:`file`})}),(0,m.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-explorer-command":`new-directory`,title:`新建文件夹`,"aria-label":`新建文件夹`,onClick:e=>A(`create-directory`,re,!1,e.currentTarget),disabled:!e||g,children:(0,m.jsx)(Ri,{name:`folder`})}),(0,m.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-file-refresh":`1`,title:`刷新目录`,"aria-label":`刷新目录`,onClick:r.refreshTree,disabled:!e,children:(0,m.jsx)(Ri,{name:`refresh`})}),(0,m.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-file-collapse-all":`1`,title:`折叠所有文件夹`,"aria-label":`折叠所有文件夹`,onClick:r.collapseDirectories,disabled:!r.expanded.size,children:(0,m.jsx)(Ri,{name:`collapse`})}),(0,m.jsx)(`button`,{className:`explorer-icon-button`,type:`button`,"data-explorer-command":`root-menu`,"aria-haspopup":`menu`,"aria-expanded":c?.target.path===``,onClick:e=>O(re,zi(e.currentTarget)),title:`更多文件操作`,"aria-label":`更多文件操作`,disabled:!e||g,children:(0,m.jsx)(Ri,{name:`more`})})]}),le=(e,t,n,r,i)=>(0,m.jsxs)(`button`,{type:`button`,role:`menuitem`,tabIndex:-1,className:`file-context-item`,"data-explorer-command":r,onClick:n,children:[(0,m.jsx)(Ri,{name:t}),(0,m.jsx)(`span`,{children:e}),i&&(0,m.jsx)(`kbd`,{children:i})]});return{controls:(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`input`,{ref:S,type:`file`,multiple:!0,hidden:!0,"aria-label":`上传工作区文件`,onChange:e=>{let t=Array.from(e.currentTarget.files??[]);e.currentTarget.value=``,F(C.current,t)}}),c&&(0,m.jsxs)(Bi,{label:c.target.path||t,anchor:c.anchor,close:k,children:[c.target.directory&&!c.target.linked&&(0,m.jsxs)(m.Fragment,{children:[s&&le(`在此文件夹中搜索`,`search`,()=>{let e=c.target.path;k(!1),s(e)},`search-folder`),le(`新建文件`,`file`,()=>A(`create-file`,c.target),`new-file`),le(`新建文件夹`,`folder`,()=>A(`create-directory`,c.target),`new-directory`),le(`上传到此处`,`upload`,()=>P(c.target.path),`upload`),(0,m.jsx)(`div`,{role:`separator`})]}),c.target.path&&!c.target.linked&&(0,m.jsxs)(m.Fragment,{children:[le(`重命名`,`rename`,()=>A(`move`,c.target),`rename`,`F2`),le(`移动到文件夹`,`move`,()=>A(`move`,c.target,!0),`move`),(0,m.jsx)(`div`,{role:`separator`})]}),!c.target.linked&&a&&le(`引用到会话`,`reference`,()=>I(c.target.path,c.target.directory),`reference`),le(`复制相对路径`,`copy`,()=>te(c.target.path)),!c.target.directory&&!c.target.linked&&(0,m.jsxs)(`a`,{role:`menuitem`,tabIndex:-1,className:`file-context-item`,href:E(`asset`,c.target.path,{download:`1`}),download:Ap(c.target.path),onClick:()=>k(!0),children:[(0,m.jsx)(Ri,{name:`download`}),(0,m.jsx)(`span`,{children:`下载`})]}),!c.target.path&&le(`打开回收站`,`trash`,()=>void N(),`trash-list`),!!c.target.path&&!c.target.linked&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`div`,{role:`separator`}),le(`移到回收站`,`trash`,()=>A(`trash`,c.target),`trash`,`Delete`)]})]}),u&&!ie&&!ae&&(0,m.jsx)(Mp,{title:ne,cancel:()=>{g||j()},children:(0,m.jsxs)(`form`,{onSubmit:M,className:`file-explorer-form`,children:[u.action===`trash`?(0,m.jsxs)(`p`,{children:[`将「`,u.target.path,`」移到回收站?`]}):(0,m.jsx)(Pp,{files:r,source:u.target,scopeName:t}),v&&(0,m.jsx)(`p`,{role:`alert`,children:v}),(0,m.jsxs)(`div`,{className:`file-explorer-form-buttons`,children:[(0,m.jsx)(`button`,{type:`button`,disabled:g,onClick:j,children:`取消`}),(0,m.jsx)(`button`,{type:`submit`,disabled:g,children:u.move?`移动到此处`:ne})]})]})}),f&&(0,m.jsxs)(Mp,{title:`回收站`,cancel:()=>{g||h(void 0)},children:[v&&(0,m.jsx)(`p`,{role:`alert`,children:v}),f.length?(0,m.jsx)(`ul`,{className:`file-explorer-trash`,children:f.map(e=>(0,m.jsxs)(`li`,{children:[(0,m.jsx)(`span`,{children:e.path}),(0,m.jsx)(`button`,{type:`button`,"data-explorer-restore":e.path,disabled:g,onClick:()=>void ee({action:`restore`,id:e.id}),children:`还原`})]},e.id))}):(0,m.jsx)(`p`,{children:`回收站为空。`}),(0,m.jsx)(`button`,{type:`button`,disabled:g,onClick:()=>h(void 0),children:`关闭`})]}),b&&(0,m.jsxs)(Mp,{title:`同名文件`,cancel:()=>x(void 0),children:[(0,m.jsx)(`p`,{children:`以下文件已经存在。替换前会再次检查磁盘版本。`}),(0,m.jsx)(`ul`,{children:b.items.map(e=>(0,m.jsx)(`li`,{children:e.file.name},e.file.name))}),(0,m.jsxs)(`div`,{className:`file-explorer-form-buttons`,children:[(0,m.jsx)(`button`,{type:`button`,onClick:()=>{r.setNotice(`已跳过 ${b.items.length} 个同名文件。`),x(void 0)},children:`跳过`}),(0,m.jsx)(`button`,{type:`button`,"data-file-replace-upload":`1`,onClick:()=>void F(b.parent,b.items.map(e=>e.file),b.items),children:`替换`})]})]})]}),toolbar:ce,inline:oe,editing:ie||ae,busy:g,openMenu:O,showAction:A,upload:F,moveTo:se}}var Ip=[{id:`path`,label:`文件名 / 路径`,shortcut:`Ctrl+P`},{id:`content`,label:`文件内容`,shortcut:`Ctrl+Shift+F`},{id:`session`,label:`会话消息`}];function Lp({mode:e,query:t,onClose:n,onMode:r,children:i,presentation:a}){let o=e===`path`?{"data-quick-open":`1`}:e===`content`?{"data-content-search":`1`}:{"data-session-search":`1`},s=(0,m.jsx)(`div`,{className:`workbench-search-modes`,role:`group`,"aria-label":`搜索范围`,children:Ip.map(n=>(0,m.jsx)(`button`,{type:`button`,"data-workbench-search-mode":n.id,"aria-pressed":n.id===e,title:n.label+` · `+n.shortcut,onClick:()=>{n.id!==e&&r(n.id,t)},children:n.label},n.id))});return a===`sidebar`?(0,m.jsxs)(`div`,{className:`workbench-search-embedded`,...o,children:[s,i]}):(0,m.jsx)(`div`,{className:`quick-open-backdrop`,...o,role:`presentation`,onMouseDown:n,children:(0,m.jsxs)(`div`,{className:e===`path`?`quick-open`:`quick-open content-search`,role:`dialog`,"aria-modal":`true`,"aria-label":Ip.find(t=>t.id===e)?.label,onMouseDown:e=>e.stopPropagation(),onKeyDown:e=>{e.key===`Escape`&&!e.nativeEvent.isComposing&&(e.preventDefault(),n())},children:[s,i]})})}function Rp({workspaceId:e,initialQuery:t=``,onClose:n,onMode:r,onOpen:i,presentation:a}){let[o,s]=(0,p.useState)(t),[c,l]=(0,p.useState)(),[u,d]=(0,p.useState)(``),[f,h]=(0,p.useState)(0),[g,_]=(0,p.useState)(!1),v=(0,p.useRef)(null),y=(0,p.useRef)(null);return(0,p.useEffect)(()=>{v.current?.focus()},[]),(0,p.useEffect)(()=>{y.current?.scrollIntoView({block:`nearest`})},[f]),(0,p.useEffect)(()=>{let t=o.trim();if(l(void 0),h(0),d(``),_(!1),!e||!t)return;if(t.length>256){d(`搜索词不能超过 256 个字符。`);return}let n=new AbortController;_(!0);let r=setTimeout(()=>{Ie(`/api/session-search?${new URLSearchParams({workspaceId:e,q:t})}`,{signal:n.signal}).then(async e=>{if(!e.ok)throw Error(`会话搜索没有完成。`);return await e.json()}).then(e=>{n.signal.aborted||l(e)}).catch(e=>{n.signal.aborted||d(zr(e,`会话搜索没有完成。`))}).finally(()=>{n.signal.aborted||_(!1)})},180);return()=>{clearTimeout(r),n.abort()}},[o,e]),(0,m.jsxs)(Lp,{mode:`session`,query:o,onMode:r,onClose:n,presentation:a,children:[(0,m.jsx)(`input`,{ref:v,className:`quick-open-input`,"data-session-search-input":!0,value:o,"aria-label":`搜索会话消息`,placeholder:`输入要在会话消息中查找的文字`,onChange:e=>s(e.target.value),onKeyDown:e=>{if(!e.nativeEvent.isComposing&&(e.key===`ArrowDown`&&(e.preventDefault(),h(e=>Math.min(e+1,Math.max(0,(c?.hits.length??0)-1)))),e.key===`ArrowUp`&&(e.preventDefault(),h(e=>Math.max(0,e-1))),e.key===`Enter`)){e.preventDefault();let t=c?.hits[f];t&&i(t)}}}),(0,m.jsx)(`p`,{className:`quick-open-status`,role:`status`,"data-session-search-status":!0,children:u||(g?`搜索中…`:e?c?c.truncated?`显示前 60 条命中`:`${c.hits.length} 条命中`:`当前工作区的未归档会话 · 用户和 Agent 消息`:`请选择工作区`)}),(0,m.jsx)(`ul`,{className:`quick-open-results content-search-results`,"aria-label":`会话搜索结果`,children:c?.hits.map((e,t)=>(0,m.jsx)(`li`,{children:(0,m.jsxs)(`button`,{ref:t===f?y:void 0,type:`button`,"data-session-search-result":e.messageId,className:`quick-open-result content-search-result${f===t?` quick-open-result-active`:``}`,onMouseEnter:()=>h(t),onClick:()=>i(e),children:[(0,m.jsxs)(`span`,{children:[e.title,` · `,e.role===`user`?`用户`:`Agent`]}),(0,m.jsxs)(`small`,{children:[e.before,(0,m.jsx)(`mark`,{children:e.match}),e.after]})]})},`${e.conversationId}:${e.messageId}`))})]})}var zp={caseSensitive:`区分大小写`,wholeWord:`全词匹配`,regexp:`正则表达式`},Bp={c:`caseSensitive`,w:`wholeWord`,r:`regexp`};function Vp(e){return e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&!e.isComposing?Bp[e.key.toLowerCase()]:void 0}function Hp(e,t,n){e.classList.add(`find-controls`);let r=new Map,i=(t,i)=>{let a=document.createElement(`button`);if(a.type=`button`,a.dataset.findOption=t,t===`expanded`)a.dataset.editorSearchOptions=``,a.innerHTML=`<svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true"><path d="m6 3 5 5-5 5" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>`;else{let e=document.createElement(`span`);e.setAttribute(`aria-hidden`,`true`),e.textContent=i,t===`wholeWord`&&(e.className=`search-whole-word`),a.append(e)}a.onclick=()=>n(t),e.append(a),r.set(t,a)};t.expanded!==void 0&&i(`expanded`,``),i(`caseSensitive`,`Aa`),i(`wholeWord`,`ab`),i(`regexp`,`.*`);let a=e=>{for(let[t,n]of r)if(t===`expanded`){let t=e.expanded?`收起查找选项`:`展开查找选项`;n.setAttribute(`aria-expanded`,String(e.expanded)),n.setAttribute(`aria-label`,t),n.title=t}else{n.setAttribute(`aria-label`,zp[t]),n.setAttribute(`aria-pressed`,String(e[t]));let r=t===`caseSensitive`?e[t]?`已开启,只匹配相同大小写`:`已关闭,忽略大小写`:t===`wholeWord`?e[t]?`已开启,只匹配完整单词`:`已关闭,也匹配单词的一部分`:e[t]?`已开启`:`已关闭`;n.title=`${t===`wholeWord`?`整词匹配`:zp[t]}:${r}(Alt+${t===`caseSensitive`?`C`:t===`wholeWord`?`W`:`R`})`}};return a(t),{update:a,destroy(){for(let e of r.values())e.remove();e.classList.remove(`find-controls`)}}}function Up({value:e,onToggle:t}){let n=(0,p.useRef)(null),r=(0,p.useRef)(t);r.current=t;let i=(0,p.useRef)(void 0);return(0,p.useLayoutEffect)(()=>{if(!n.current)return;let t=Hp(n.current,e,e=>r.current(e));return i.current=t,()=>{t.destroy(),i.current=void 0}},[]),(0,p.useLayoutEffect)(()=>i.current?.update(e),[e.caseSensitive,e.wholeWord,e.regexp,e.expanded]),(0,m.jsx)(`span`,{ref:n,"data-find-controls":!0})}var Wp=class extends p.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){console.error(`[SuperPi ErrorBoundary captured error]:`,e,t)}reset=()=>{this.setState({error:null})};render(){let{error:e}=this.state;return e?this.props.fallback?this.props.fallback(e,this.reset):(0,m.jsxs)(`div`,{className:`error-boundary-card`,"data-error-boundary":`1`,children:[(0,m.jsxs)(`div`,{className:`error-boundary-head`,children:[(0,m.jsx)(`span`,{className:`error-boundary-icon`,"aria-hidden":`true`,children:`⚠️`}),(0,m.jsx)(`strong`,{children:`视图渲染遇到异常`})]}),(0,m.jsx)(`p`,{className:`error-boundary-msg`,children:e.message||`未知组件错误`}),(0,m.jsx)(`button`,{type:`button`,className:`error-boundary-retry`,onClick:this.reset,children:`重试`})]}):this.props.children}},Gp=`super-pi.editor.preferences.v1`,Kp={fontSize:13,tabSize:4,indent:`spaces`,wrap:!1,whitespace:!1},qp=(e,t,n,r)=>typeof e==`number`&&Number.isInteger(e)&&e>=n&&e<=r?e:t;function Jp(){try{let e=JSON.parse(localStorage.getItem(Gp)??`{}`);return{fontSize:qp(e.fontSize,13,10,28),tabSize:qp(e.tabSize,4,1,8),indent:e.indent===`tabs`?`tabs`:`spaces`,wrap:e.wrap===!0,whitespace:e.whitespace===!0}}catch{return{...Kp}}}var Yp=Jp(),Xp=new Set;function Zp(){typeof document<`u`&&(document.documentElement.style.setProperty(`--editor-user-font-size`,`${Yp.fontSize}px`),document.documentElement.dataset.editorWrap=String(Yp.wrap));for(let e of Xp)e()}Zp();var Qp=()=>Yp;function $p(e){return Xp.add(e),()=>{Xp.delete(e)}}function em(e){let t={...Yp,...e};t.fontSize=qp(t.fontSize,Yp.fontSize,10,28),t.tabSize=qp(t.tabSize,Yp.tabSize,1,8),Yp=t;try{localStorage.setItem(Gp,JSON.stringify(Yp))}catch{}Zp()}typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key===Gp&&(Yp=Jp(),Zp())});var tm=[[`undo`,`撤销`,`Ctrl/⌘+Z`,!0],[`redo`,`重做`,`Ctrl/⌘+Shift+Z`,!0],[`selectAll`,`全选`,`Ctrl/⌘+A`,!1],[`next`,`选中下一个相同文本`,`Ctrl/⌘+D`,!1],[`all`,`选中所有相同文本`,`Ctrl/⌘+Shift+L`,!1],[`comment`,`切换行注释`,`Ctrl/⌘+/`,!0],[`foldAll`,`折叠全部`,``,!1],[`unfoldAll`,`展开全部`,``,!1]];function nm({view:e,label:t=`编辑与显示`}){let[n,r]=(0,p.useState)(!1),i=(0,p.useRef)(null),a=(0,p.useSyncExternalStore)($p,Qp),[o,s]=(0,p.useState)(String(a.fontSize)),[c,l]=(0,p.useState)(String(a.tabSize)),[u,d]=(0,p.useState)(``),f=(e,t)=>{let n=/^\d+$/.test(t)?Number(t):NaN,r=e===`fontSize`?10:1,i=e===`fontSize`?28:8;!Number.isInteger(n)||n<r||n>i?d(`请输入 ${r}–${i} 之间的整数。`):(d(``),em({[e]:n}))},h=async t=>{if(!e||!e.dom.isConnected||e.state.readOnly&&tm.some(e=>e[0]===t&&e[3]))return;let[n,i,a]=await Promise.all([kn(()=>import(`./dist-S5ntGzJB.js`),__vite__mapDeps([21,2,1,3,4,0])),kn(()=>import(`./dist-Qjm1p8SR.js`),__vite__mapDeps([22,2,1,3])),kn(()=>import(`./dist-DP4hrTBF.js`).then(e=>e.d),__vite__mapDeps([0,1,2,3,4]))]);if(!e.dom.isConnected)return;let o=t===`undo`?n.undo:t===`redo`?n.redo:t===`selectAll`?n.selectAll:t===`next`?i.selectNextOccurrence:t===`all`?i.selectSelectionMatches:t===`comment`?n.toggleComment:t===`foldAll`?a.foldAll:a.unfoldAll;r(!1),o(e),e.focus()};return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`button`,{ref:i,type:`button`,"data-editor-actions":!0,"aria-label":t,"aria-expanded":n,onClick:()=>{s(String(a.fontSize)),l(String(a.tabSize)),r(e=>!e)},children:t}),n&&(0,m.jsxs)(He,{anchor:i.current,label:`编辑器操作与偏好`,className:`editor-actions-menu`,onClose:()=>r(!1),children:[(0,m.jsxs)(`header`,{children:[(0,m.jsx)(`strong`,{children:`编辑器`}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`关闭编辑器操作`,onClick:()=>r(!1),children:`×`})]}),(0,m.jsx)(`div`,{className:`editor-command-list`,children:tm.map(([t,n,r,i])=>(0,m.jsxs)(`button`,{type:`button`,"data-editor-command":t,disabled:!e||i&&e.state.readOnly,onClick:()=>void h(t),children:[(0,m.jsx)(`span`,{children:n}),(0,m.jsx)(`small`,{children:r})]},t))}),(0,m.jsxs)(`fieldset`,{children:[(0,m.jsx)(`legend`,{children:`所有文件与会话共用`}),(0,m.jsxs)(`label`,{children:[`字号`,(0,m.jsx)(`input`,{"aria-label":`编辑器字号`,inputMode:`numeric`,value:o,onChange:e=>s(e.target.value),onBlur:()=>f(`fontSize`,o),onKeyDown:e=>{e.key===`Enter`&&e.currentTarget.blur()}})]}),(0,m.jsxs)(`label`,{children:[`缩进宽度`,(0,m.jsx)(`input`,{"aria-label":`编辑器缩进宽度`,inputMode:`numeric`,value:c,onChange:e=>l(e.target.value),onBlur:()=>f(`tabSize`,c),onKeyDown:e=>{e.key===`Enter`&&e.currentTarget.blur()}})]}),(0,m.jsxs)(`label`,{children:[`缩进方式`,(0,m.jsxs)(`select`,{"aria-label":`编辑器缩进方式`,value:a.indent,onChange:e=>em({indent:e.target.value}),children:[(0,m.jsx)(`option`,{value:`spaces`,children:`空格`}),(0,m.jsx)(`option`,{value:`tabs`,children:`Tab`})]})]}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{"aria-label":`自动换行`,type:`checkbox`,checked:a.wrap,onChange:e=>em({wrap:e.target.checked})}),`自动换行 `,(0,m.jsx)(`small`,{children:`Alt+Z`})]}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{"aria-label":`显示空白字符`,type:`checkbox`,checked:a.whitespace,onChange:e=>em({whitespace:e.target.checked})}),`显示空白字符`]})]}),u&&(0,m.jsx)(`p`,{role:`alert`,children:u})]})]})}function rm(){}rm.prototype={diff:function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.callback;typeof n==`function`&&(r=n,n={}),this.options=n;var i=this;function a(e){return r?(setTimeout(function(){r(void 0,e)},0),!0):e}e=this.castInput(e),t=this.castInput(t),e=this.removeEmpty(this.tokenize(e)),t=this.removeEmpty(this.tokenize(t));var o=t.length,s=e.length,c=1,l=o+s;n.maxEditLength&&(l=Math.min(l,n.maxEditLength));var u=n.timeout??1/0,d=Date.now()+u,f=[{oldPos:-1,lastComponent:void 0}],p=this.extractCommon(f[0],t,e,0);if(f[0].oldPos+1>=s&&p+1>=o)return a([{value:this.join(t),count:t.length}]);var m=-1/0,h=1/0;function g(){for(var n=Math.max(m,-c);n<=Math.min(h,c);n+=2){var r=void 0,l=f[n-1],u=f[n+1];l&&(f[n-1]=void 0);var d=!1;if(u){var g=u.oldPos-n;d=u&&0<=g&&g<o}var _=l&&l.oldPos+1<s;if(!d&&!_)f[n]=void 0;else{if(r=!_||d&&l.oldPos+1<u.oldPos?i.addToPath(u,!0,void 0,0):i.addToPath(l,void 0,!0,1),p=i.extractCommon(r,t,e,n),r.oldPos+1>=s&&p+1>=o)return a(im(i,r.lastComponent,t,e,i.useLongestToken));f[n]=r,r.oldPos+1>=s&&(h=Math.min(h,n-1)),p+1>=o&&(m=Math.max(m,n+1))}}c++}if(r)(function e(){setTimeout(function(){if(c>l||Date.now()>d)return r();g()||e()},0)})();else for(;c<=l&&Date.now()<=d;){var _=g();if(_)return _}},addToPath:function(e,t,n,r){var i=e.lastComponent;return i&&i.added===t&&i.removed===n?{oldPos:e.oldPos+r,lastComponent:{count:i.count+1,added:t,removed:n,previousComponent:i.previousComponent}}:{oldPos:e.oldPos+r,lastComponent:{count:1,added:t,removed:n,previousComponent:i}}},extractCommon:function(e,t,n,r){for(var i=t.length,a=n.length,o=e.oldPos,s=o-r,c=0;s+1<i&&o+1<a&&this.equals(t[s+1],n[o+1]);)s++,o++,c++;return c&&(e.lastComponent={count:c,previousComponent:e.lastComponent}),e.oldPos=o,s},equals:function(e,t){return this.options.comparator?this.options.comparator(e,t):e===t||this.options.ignoreCase&&e.toLowerCase()===t.toLowerCase()},removeEmpty:function(e){for(var t=[],n=0;n<e.length;n++)e[n]&&t.push(e[n]);return t},castInput:function(e){return e},tokenize:function(e){return e.split(``)},join:function(e){return e.join(``)}};function im(e,t,n,r,i){for(var a=[],o;t;)a.push(t),o=t.previousComponent,delete t.previousComponent,t=o;a.reverse();for(var s=0,c=a.length,l=0,u=0;s<c;s++){var d=a[s];if(!d.removed){if(!d.added&&i){var f=n.slice(l,l+d.count);f=f.map(function(e,t){var n=r[u+t];return n.length>e.length?n:e}),d.value=e.join(f)}else d.value=e.join(n.slice(l,l+d.count));l+=d.count,d.added||(u+=d.count)}else if(d.value=e.join(r.slice(u,u+d.count)),u+=d.count,s&&a[s-1].added){var p=a[s-1];a[s-1]=a[s],a[s]=p}}var m=a[c-1];return c>1&&typeof m.value==`string`&&(m.added||m.removed)&&e.equals(``,m.value)&&(a[c-2].value+=m.value,a.pop()),a}new rm;var am=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,om=/\S/,sm=new rm;sm.equals=function(e,t){return this.options.ignoreCase&&(e=e.toLowerCase(),t=t.toLowerCase()),e===t||this.options.ignoreWhitespace&&!om.test(e)&&!om.test(t)},sm.tokenize=function(e){for(var t=e.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<t.length-1;n++)!t[n+1]&&t[n+2]&&am.test(t[n])&&am.test(t[n+2])&&(t[n]+=t[n+2],t.splice(n+1,2),n--);return t};var cm=new rm;cm.tokenize=function(e){this.options.stripTrailingCr&&(e=e.replace(/\r\n/g,`
|
|
285
285
|
`));var t=[],n=e.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var i=n[r];r%2&&!this.options.newlineIsToken?t[t.length-1]+=i:(this.options.ignoreWhitespace&&(i=i.trim()),t.push(i))}return t};function lm(e,t,n){return cm.diff(e,t,n)}var um=new rm;um.tokenize=function(e){return e.split(/(\S.+?[.!?])(?=\s+|$)/)};var dm=new rm;dm.tokenize=function(e){return e.split(/([{}:;,]|\s+)/)};function fm(e){"@babel/helpers - typeof";return fm=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},fm(e)}var pm=Object.prototype.toString,mm=new rm;mm.useLongestToken=!0,mm.tokenize=cm.tokenize,mm.castInput=function(e){var t=this.options,n=t.undefinedReplacement,r=t.stringifyReplacer,i=r===void 0?function(e,t){return t===void 0?n:t}:r;return typeof e==`string`?e:JSON.stringify(hm(e,null,null,i),i,` `)},mm.equals=function(e,t){return rm.prototype.equals.call(mm,e.replace(/,([\r\n])/g,`$1`),t.replace(/,([\r\n])/g,`$1`))};function hm(e,t,n,r,i){t||=[],n||=[],r&&(e=r(i,e));for(var a=0;a<t.length;a+=1)if(t[a]===e)return n[a];var o;if(pm.call(e)===`[object Array]`){for(t.push(e),o=Array(e.length),n.push(o),a=0;a<e.length;a+=1)o[a]=hm(e[a],t,n,r,i);return t.pop(),n.pop(),o}if(e&&e.toJSON&&(e=e.toJSON()),fm(e)===`object`&&e!==null){t.push(e),o={},n.push(o);var s=[],c;for(c in e)e.hasOwnProperty(c)&&s.push(c);for(s.sort(),a=0;a<s.length;a+=1)c=s[a],o[c]=hm(e[c],t,n,r,c);t.pop(),n.pop()}else o=e;return o}var gm=new rm;gm.tokenize=function(e){return e.slice()},gm.join=gm.removeEmpty=function(e){return e};function _m(e,t){let n=lm(e??``,t??``),r=[],i=0,a=0,o=1,s=1;for(let e of n){let t=e.value.split(`
|
|
286
286
|
`),n=t.length>0&&t[t.length-1]===``;n&&t.pop();for(let c=0;c<t.length;c+=1){let l=t[c],u=c===t.length-1&&!n;e.added?(r.push({kind:`added`,text:l,newLine:s,noNewline:u}),s+=1,i+=1):e.removed?(r.push({kind:`removed`,text:l,oldLine:o,noNewline:u}),o+=1,a+=1):(r.push({kind:`same`,text:l,oldLine:o,newLine:s,noNewline:u}),o+=1,s+=1)}}return{lines:r,added:i,removed:a,identical:i===0&&a===0}}function vm(e,t=3){let n=new Set;e.lines.forEach((r,i)=>{if(r.kind!==`same`)for(let r=-t;r<=t;r+=1){let t=i+r;t>=0&&t<e.lines.length&&n.add(t)}});let r=[],i=0,a=!1;return e.lines.forEach((e,t)=>{n.has(t)?(a&&=(r.push({kind:`fold`,text:`⋯ 省略未改动的行`}),!1),r.push(e)):a||(a=!0,i+=1)}),a&&r.push({kind:`fold`,text:`⋯ 省略未改动的行`}),{lines:r,folded:i}}var ym=`super-pi.outbox.v1.`,bm=e=>ym+JSON.stringify([e.conversationId,e.clientId]);function xm(){try{let e=[];for(let t of Object.keys(window.localStorage).filter(e=>e.startsWith(ym)))try{let n=JSON.parse(window.localStorage.getItem(t)??`null`),r=n?.send;r?.type===`message.send`&&typeof r.conversationId==`string`&&/^message_[0-9a-f-]{36}$/.test(r.clientId)&&typeof r.content==`string`&&t===bm(r)&&e.push(n)}catch{}return e.sort((e,t)=>e.queuedAt-t.queuedAt).map(e=>e.send)}catch{return[]}}function Sm(e){try{return window.localStorage.setItem(bm(e),JSON.stringify({queuedAt:Date.now(),send:e})),!0}catch{return!1}}function Cm(e,t){try{window.localStorage.removeItem(bm({conversationId:e,clientId:t}))}catch{}}function wm(e){return v(y(e.conversationId).server,e.clientId)}function Tm(e,t,n){let r=e.conversations.find(e=>e.id===t.conversationId),i=wm(t);if(!r||r.messages.some(e=>e.id===i))return e;let a=r.status===`running`||r.status===`waiting`;return{...e,conversations:e.conversations.map(e=>e===r?{...e,...a?{}:{status:`waiting`,updatedAt:n},messages:[...e.messages,{id:i,role:`user`,content:t.content,createdAt:n,...t.images?.length?{images:t.images}:{},...t.attachments?.length?{attachments:t.attachments}:{},...a?{delivery:`waiting`}:{}}]}:e)}}function Em(e,t){try{return JSON.parse(Gn(e)??`null`)??t}catch{return t}}function Dm(e,t){try{return Kn(e,JSON.stringify(t)),!0}catch{return!1}}var Om=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.name=`BlameApiError`,this.status=e,this.body=t}},km=class extends Error{constructor(){super(`Blame 请求已取消`),this.name=`BlameCancelledError`}},Am=(e,t,n=``)=>`/api/git?workspaceId=${encodeURIComponent(e)}&op=blame&path=${encodeURIComponent(t)}${n?`&cwd=${encodeURIComponent(n)}`:``}`;async function jm(e,t,n={}){if(n.signal?.aborted)throw new km;let r=n.timeoutMs??15e3,i=new AbortController,a=!1,o=setTimeout(()=>{a=!0,i.abort()},r),s=()=>i.abort();n.signal?.addEventListener(`abort`,s,{once:!0});try{let r=await Ie(Am(e,t,n.cwd),{signal:i.signal}),a;try{a=await r.json()}catch{a=void 0}if(!r.ok){let e=a??{};throw new Om(r.status,{error:e.error||`HTTP ${r.status}`,...e.code?{code:e.code}:{}})}return a}catch(e){throw n.signal?.aborted?new km:a?new Om(408,{error:`请求超时:${Math.round(r/1e3)} 秒内服务端没有响应`,code:`timeout`}):e}finally{clearTimeout(o),n.signal?.removeEventListener(`abort`,s)}}var Mm=`\0`,Nm=(e,t,n)=>[e,t,n??``].join(Mm),Pm=24,Fm=new Map;function Im(e){let t=Fm.get(e);if(t)return Fm.delete(e),Fm.set(e,t),t}function Lm(e,t){for(Fm.delete(e),Fm.set(e,t);Fm.size>Pm;){let e=Fm.keys().next();if(e.done)break;Fm.delete(e.value)}}var Rm={untracked:`这个文件尚未被 Git 跟踪`,binary:`二进制文件不支持 Blame`,too_large:`文件过大,未显示 Blame`,no_head:`仓库还没有提交`,not_in_revision:`这个版本里没有这个文件`},zm=`此工作区不是 Git 仓库`;function Bm(e){return e&&Rm[e]?{code:e,text:Rm[e]}:{code:`unsupported`,text:`这个文件暂时不能显示 Blame`}}function Vm(e){return e instanceof Om&&e.body.code===`not_a_repo`?{state:`unsupported`,note:{code:`not_a_repo`,text:zm}}:{state:`error`,note:{code:`error`,text:`读取 Blame 失败:${e instanceof Error&&e.message?e.message:`未知错误`}`}}}var Hm=`${Mm}uncommitted`;function Um(e){let t=new Map,n=0;for(let r of e.lines)t.has(r.line)||t.set(r.line,r),r.line>n&&(n=r.line);let r=[],i=null,a=0;for(let e=1;e<=n;e+=1){let n=t.get(e);if(!n){r.push({line:e,kind:`missing`,data:null}),i=null,a=e;continue}let o=n.isUncommitted?Hm:n.commit??`${Mm}none`,s=o===i&&e===a+1?`continuation`:n.isUncommitted?`uncommitted`:`commit`;r.push({line:e,kind:s,data:n}),i=o,a=e}if(e.truncated)for(let t=n+1;t<=e.totalLines;t+=1)r.push({line:t,kind:`truncated`,data:null});return r}function Wm(e){let t=0;for(let n of e.lines)n.line>t&&(t=n.line);return t}function Gm(e){switch(e.kind){case`commit`:{let t=e.data,n=t?.shortCommit??t?.commit?.slice(0,8)??`?`,r=t?.author?.trim();return r?`${n} · ${r}`:n}case`continuation`:return`│`;case`uncommitted`:return`● 未提交`;case`missing`:return`?`;case`truncated`:return`…`;default:return``}}function Km(e){if(e.kind===`uncommitted`||e.data?.isUncommitted)return[`未提交`,`这行尚不属于任何 Git 提交`];if(e.kind===`missing`)return[`没有 Blame 信息`,`这一行没有对应的提交记录`];if(e.kind===`truncated`)return[`Blame 数据已截断`,`文件太长,只显示了前面一部分的提交信息`];let t=e.data;if(!t)return[`没有 Blame 信息`];let n=t.shortCommit??t.commit?.slice(0,8)??`未知提交`,r=t.author?.trim()||`未知作者`;return[n,t.authorEmail?`${r} <${t.authorEmail}>`:r,qm(t.date),t.summary?.trim()||`(没有提交摘要)`]}function qm(e){if(!e)return`不详`;let t=new Date(e);if(!Number.isFinite(t.getTime()))return e;let n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function Jm(e){if(e.length===0)return 0;let t=1;for(let n=0;n<e.length;n+=1)e.charCodeAt(n)===10&&(t+=1);return e.charCodeAt(e.length-1)===10&&--t,t}function Ym(e,t,n=!1){return!t||!t.supported?!1:n||Jm(e)!==t.totalLines}var Xm=new WeakMap;function Zm(e){let t=Xm.get(e);if(t)return t;let n={response:e,models:Um(e),covered:Wm(e)};return Xm.set(e,n),n}function Qm(e,t){if(!e||t<1)return null;let n=e.models[t-1];return n&&n.line===t?n:null}var $m=`a1b2c3d · Author`;async function eh(){let[e,t]=await Promise.all([kn(()=>import(`./dist-D978o95T.js`).then(e=>e.S),__vite__mapDeps([2,1])),kn(()=>import(`./dist-DTIPfQj7.js`).then(e=>e.s),__vite__mapDeps([3,1,2]))]),n=e.StateEffect.define(),r=e.StateField.define({create:()=>null,update:(e,t)=>{for(let e of t.effects)if(e.is(n))return e.value;return e}}),i=e.StateEffect.define(),a=e.StateField.define({create:()=>null,update:(e,t)=>{for(let e of t.effects)if(e.is(i))return e.value;return e}}),o=t.GutterMarker;class s extends o{model;constructor(e){super(),this.model=e}eq(e){let t=e.model;return t?t.line===this.model.line&&t.kind===this.model.kind&&t.data?.commit===this.model.data?.commit&&t.data?.summary===this.model.data?.summary&&t.data?.author===this.model.data?.author:!1}toDOM(){let e=document.createElement(`span`);e.className=`cm-blame-marker cm-blame-${this.model.kind}`,e.setAttribute(`data-file-blame-line`,String(this.model.line)),e.setAttribute(`data-file-blame-kind`,this.model.kind),this.model.data?.commit&&e.setAttribute(`data-file-blame-commit`,this.model.data.commit);let t=Km(this.model);return e.setAttribute(`title`,t.join(`
|
|
287
|
-
`)),e.setAttribute(`aria-label`,t.join(` · `)),e.textContent=Gm(this.model),e}}class c extends o{eq(){return!0}toDOM(){let e=document.createElement(`span`);return e.className=`cm-blame-marker cm-blame-spacer`,e.textContent=$m,e}}let l=t.gutter({class:`cm-blame-gutter`,initialSpacer:()=>new c,lineMarker:(e,t)=>{let n=e.state.field(r);if(!n)return null;let i=e.state.doc.lineAt(t.from).number,a=Qm(n,i);return new s(a??{line:i,kind:`missing`,data:null})},lineMarkerChange:e=>e.startState.field(r)!==e.state.field(r)}),u=t.ViewPlugin.fromClass(class{line=null;editorView;constructor(e){this.editorView=e,this.editorView.dom.addEventListener(`mousemove`,this.onMove),this.editorView.dom.addEventListener(`mouseleave`,this.onLeave)}destroy(){this.editorView.dom.removeEventListener(`mousemove`,this.onMove),this.editorView.dom.removeEventListener(`mouseleave`,this.onLeave)}update(e){e.startState.field(r)!==e.state.field(r)&&this.line!==null&&(this.line=null,this.editorView.dispatch({effects:i.of(null)}))}onMove=e=>{let t=this.lineAt(e);if(t===this.line)return;if(this.line=t,t===null){this.editorView.dispatch({effects:i.of(null)});return}let n=Qm(this.editorView.state.field(r),t);if(!n){this.editorView.dispatch({effects:i.of(null)});return}let a=this.editorView.state.doc,o=a.line(Math.min(t,a.lines));this.editorView.dispatch({effects:i.of({pos:o.from,above:!0,create:()=>({dom:th(n)})})})};onLeave=()=>{this.line=null,this.editorView.dispatch({effects:i.of(null)})};lineAt(e){let t=e.target,n=t?.closest?.(`[data-file-blame-line]`);if(n){let e=Number(n.getAttribute(`data-file-blame-line`));return Number.isInteger(e)&&e>0?e:null}if(t?.closest?.(`.cm-blame-gutter`))return null;let r=this.editorView.posAtCoords({x:e.clientX,y:e.clientY});return r==null?null:this.editorView.state.doc.lineAt(r).number}});return{field:r,setBlame:n,base:[r,a,t.showTooltip.from(a),u],gutter:l}}function th(e){let t=document.createElement(`div`);t.className=`cm-blame-tooltip`,t.setAttribute(`data-file-blame-tooltip`,`1`),t.setAttribute(`data-file-blame-kind`,e.kind),e.data?.commit&&t.setAttribute(`data-file-blame-commit`,e.data.commit);for(let n of Km(e)){let e=document.createElement(`div`);e.className=`cm-blame-tooltip-row`,e.textContent=n,t.appendChild(e)}return t}function nh(e,t){let n=(0,p.useRef)(null),r=(0,p.useRef)(void 0);return(0,p.useLayoutEffect)(()=>{let e=r.current;r.current=void 0;let i=n.current;if(!i||!e)return;let a=i.querySelectorAll(t)[e.index];a&&(i.scrollTop+=a.getBoundingClientRect().top-i.getBoundingClientRect().top-e.offset)},[e,t]),{scrollBox:n,capture:()=>{let e=n.current;if(!e)return;let i=e.getBoundingClientRect().top,a;e.querySelectorAll(t).forEach((e,t)=>{let n=e.getBoundingClientRect().top-i;(!a||Math.abs(n)<Math.abs(a.offset))&&(a={index:t,offset:n})}),r.current=a}}}var rh=`super-pi.diff-layout.v1`,ih=`super-pi-diff-layout`;function ah(){try{return localStorage.getItem(rh)===`split`}catch{return!1}}function oh(e){let t=t=>{(t.key===rh||t.key===null)&&e()};return window.addEventListener(ih,e),window.addEventListener(`storage`,t),()=>{window.removeEventListener(ih,e),window.removeEventListener(`storage`,t)}}var sh;function ch(){return sh??ah()}function lh(){return[(0,p.useSyncExternalStore)(oh,ch,()=>!1),e=>{sh=e;try{localStorage.setItem(rh,e?`split`:`inline`),sh=void 0}catch{}window.dispatchEvent(new Event(ih))}]}var uh=4e3,dh=(0,p.lazy)(()=>kn(()=>import(`./CodeMirrorEditor-BeVgHVpR.js`).then(e=>({default:e.CodeMirrorEditor})),__vite__mapDeps([23,1,24]))),fh=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.status=e,this.body=t,this.name=`ApiError`}},ph=15e3,mh=e=>new fh(408,{error:`请求超时:${ph/1e3} 秒内服务端没有响应`,code:`timeout`,details:{path:e}});async function hh(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),ph);try{let r=t?.signal?AbortSignal.any([t.signal,n.signal]):n.signal,i=await Ie(e,{...t,signal:r}),a;try{a=await i.json()}catch{a=void 0}if(!i.ok)throw new fh(i.status,a??{error:`HTTP ${i.status}`});return a}catch(t){throw n.signal.aborted?mh(e):t}finally{clearTimeout(r)}}var gh=e=>e instanceof fh?e:new fh(0,{error:e instanceof Error?e.message:`读取失败`}),_h=e=>encodeURIComponent(e),vh=e=>e?`&cwd=${_h(e)}`:``,yh=(e,t,n)=>`/api/files?workspaceId=${_h(e)}&path=${_h(t)}${vh(n)}`,bh=`//workspace/`,xh=e=>e.startsWith(bh)?e.slice(12):void 0,Sh=(e,t,n)=>{let r=xh(t);return`/api/file?workspaceId=${_h(e)}&path=${_h(r??t)}${vh(r?``:n)}`},Ch=(e,t,n)=>Sh(e,t,n)+`&meta=1`,wh=(e,t,n)=>`/api/files?workspaceId=${_h(e)}&q=${_h(t)}${vh(n)}`;async function Th(e,t,n){let r=t.current;if(!r)return t.current=hh(e+`&refresh=1`,{cache:`no-store`}),t.current;if(await r.catch(()=>{}),n())return hh(e,{cache:`no-store`})}function Eh(e){let t=e.trim();if(/^(["']).*\1$/u.test(t)&&(t=t.slice(1,-1)),!/^file:\/\//iu.test(t))return t;try{let e=new URL(t);return e.hostname||e.search||e.hash?t:decodeURIComponent(e.pathname).replace(/^\/(?=[a-z]:[\\/])/iu,``)}catch{return t}}function Dh(e){return{path:e,name:e.split(/[\\/]/).at(-1)||e,text:null,openLink:!0}}function Oh(e){let t=Eh(e);if(/^(?:\/|[a-z]:[\\/]|\\\\)/iu.test(t))return Dh(t)}function kh(e){return Eh(e).replaceAll(`\\`,`/`).replace(/^\.\//u,``)}async function Ah(e,t,n){let r=xh(n.path),i=await hh(`/api/files/open?workspaceId=${_h(e)}${vh(r===void 0?t:``)}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({path:r??n.path})}),{path:a,name:o,text:s,ticket:c,content:l,meta:u}=i,d=Dp(i.targetName??a),f=s===!1&&d===`table`?`download`:d??(s===!1?`download`:void 0);return{path:r===void 0?a:n.path,name:o,content:l??``,etag:u.etag,dirty:!1,view:f,assetTicket:c}}var jh=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:new Date(e).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`})};function Mh({workspaceId:e,entryPath:t,name:n,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d,linked:f,presentation:h}){let g=r[t],_=i.has(t);(0,p.useEffect)(()=>{_&&g===void 0&&o(t)},[_,t,g,o]);let v=h.inline(t,`entry`,d),y=h.inline(t,`child`,d+1);return(0,m.jsxs)(`li`,{className:`file-node`,"data-file-dir":t,"data-linked":f,"data-file-dir-changed":c.has(t)?`1`:`0`,children:[(0,m.jsxs)(`div`,{className:`file-explorer-row`,"data-file-drop-target":h.dropPath===t?`1`:void 0,hidden:!!v,style:{"--file-depth":d},children:[(0,m.jsxs)(`button`,{type:`button`,className:`file-row file-row-dir`,"data-file-dir-toggle":t,"aria-expanded":_,tabIndex:-1,draggable:!f,title:c.has(t)?`${t} 里有 agent 改过的文件`:t,onClick:()=>a(t),children:[(0,m.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`,children:(0,m.jsx)(Ri,{name:_?`down`:`right`})}),(0,m.jsx)(Kr,{category:_?`folder-open`:`folder`}),(0,m.jsx)(`span`,{className:`file-name`,children:n}),c.has(t)&&(0,m.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-dir-changed-badge":t,title:`里面有 agent 改过的文件`,children:`✎`})]}),(0,m.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,tabIndex:-1,"aria-haspopup":`menu`,"aria-label":`${n} 的文件操作`,children:(0,m.jsx)(Ri,{name:`more`})})]}),v,_&&(0,m.jsxs)(`ul`,{className:`file-children`,children:[y&&(0,m.jsx)(`li`,{children:y}),g===void 0?(0,m.jsx)(`li`,{className:`file-row-loading`,"data-file-loading":t,children:`读取中…`}):`error`in g?(0,m.jsx)(`li`,{className:`file-row-error`,"data-file-error":t,title:Br(g.error.message),children:zr(g.error.message,`这个目录读取失败。`)}):g.entries.length===0?(0,m.jsx)(`li`,{className:`file-row-empty`,"data-file-empty":t,children:`空目录`}):(0,m.jsxs)(m.Fragment,{children:[g.truncated&&(0,m.jsx)(`li`,{className:`file-row-empty`,"data-file-truncated":t,children:`条目过多,只显示前一部分`}),g.entries.map(t=>t.kind===`directory`?(0,m.jsx)(Mh,{workspaceId:e,entryPath:t.path,name:t.name,linked:t.symlink,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d+1,presentation:h},t.path):(0,m.jsx)(Nh,{entry:t,depth:d+1,openPaths:s,changedPaths:l,onOpen:u,presentation:h},t.path))]})]})]})}function Nh({entry:e,depth:t,openPaths:n,changedPaths:r,onOpen:i,presentation:a}){let o={"--file-depth":t};if(e.kind===`symlink`&&!e.openLink)return(0,m.jsx)(`li`,{className:`file-node file-explorer-row`,"data-file-entry":e.path,"data-file-outside":e.path,style:o,children:(0,m.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,disabled:!0,title:`${e.path} 的目标目录在当前工作区之外,或目标文件不可用`,tabIndex:-1,children:[(0,m.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:`file-name`,children:e.name}),(0,m.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`})]})});let s=n.has(e.path),c=r.has(e.path),l=Dp(e.path),u=!!(e.outside&&e.openLink||e.text||l),d=a.currentPath===e.path,f=a.inline(e.path,`entry`,t);return(0,m.jsxs)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-linked":e.symlink,"data-file-outside":e.outside?e.path:void 0,"data-file-row-open":s?`1`:`0`,"data-file-row-changed":c?`1`:`0`,children:[(0,m.jsxs)(`div`,{className:`file-explorer-row`,"data-file-current":d?`1`:void 0,hidden:!!f,style:o,children:[(0,m.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-open":e.path,"aria-disabled":!u||void 0,title:u?e.path:`${e.name} 可以通过文件操作菜单下载`,tabIndex:-1,"aria-current":d?`true`:void 0,draggable:!e.symlink,onClick:t=>{u&&i(e.openLink&&!e.outside?{...e,openLink:void 0}:e,t.detail>1)},children:[(0,m.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,m.jsx)(Kr,{path:e.path}),(0,m.jsx)(`span`,{className:`file-name`,children:e.name}),s&&(0,m.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`}),c&&(0,m.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed":e.path,title:`agent 改过这个文件`,children:`✎ 已改`}),e.document&&(0,m.jsx)(`span`,{className:`file-badge`,"data-file-document":`1`,"aria-label":`文档文件`,children:`文档`}),e.outside&&(0,m.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`}),!u&&!e.document&&(0,m.jsx)(`span`,{className:`file-badge`,"data-file-binary":`1`,"aria-label":`不支持的文件类型`,children:`不支持`})]}),!e.outside&&(0,m.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,"aria-haspopup":`menu`,tabIndex:-1,"aria-label":`${e.name} 的文件操作`,children:(0,m.jsx)(Ri,{name:`more`})})]}),f]})}function Ph({file:e,state:t,message:n,external:r,jumpToLine:i,onChange:a,onSave:o,onReload:s,onOverwrite:c,workspaceId:l,cwd:u=``,navigation:d,embedded:f=!1,onPosition:h,languageOverride:g}){let[_,v]=(0,p.useState)(!0),[y,b]=(0,p.useState)(),x=(0,p.useRef)(null),[S,C]=(0,p.useState)({}),[w,T]=(0,p.useState)(null),E=(0,p.useRef)(0),D=!!e.assetTicket,O=!D&&S[e.path]===!0&&!!l,k=l?u?`${l}:${u}`:l:``;(0,p.useEffect)(()=>{let t=++E.current;if(!O||!l){T(null);return}let n=new AbortController,i=Nm(k,e.path,e.etag),a=r?void 0:Im(i);if(a){T({state:a.supported?`ready`:`unsupported`,response:a,path:e.path,workspaceId:k,note:a.supported?null:Bm(a.reason)});return}T({state:`loading`,response:null,path:e.path,workspaceId:k,note:null});let o=xh(e.path);return jm(l,o??e.path,{signal:n.signal,cwd:o?``:u}).then(n=>{t===E.current&&(r||Lm(i,n),T({state:n.supported?`ready`:`unsupported`,response:n,path:e.path,workspaceId:k,note:n.supported?null:Bm(n.reason)}))}).catch(n=>{if(t!==E.current||n instanceof km)return;let r=Vm(n);T({state:r.state,response:null,path:e.path,workspaceId:k,note:r.note})}),()=>{n.abort()}},[O,l,u,k,e.path,e.etag,r]);let A=w&&w.path===e.path&&w.workspaceId===k?w:null,j=O?A?.state??`loading`:`off`,ee=j===`ready`&&Ym(e.content,A?.response??null,e.dirty||r),M=[];A?.note&&M.push(A.note),j===`ready`&&A?.response?.truncated&&M.push({code:`truncated`,text:`Blame 数据已截断,只显示了前面一部分(共 ${A.response.totalLines} 行)`}),ee&&M.push({code:`stale`,text:`内容已改动,Blame 对应的是磁盘上的版本`});let N=j===`loading`?`⌛ Blame`:j===`ready`?`✓ Blame`:j===`off`?`Blame`:`! Blame`;(0,p.useEffect)(()=>{i&&v(!1)},[e.path,i]),(0,p.useEffect)(()=>{let e=x.current;if(!i||!e)return;let t=Math.min(i.line,e.value.split(`
|
|
287
|
+
`)),e.setAttribute(`aria-label`,t.join(` · `)),e.textContent=Gm(this.model),e}}class c extends o{eq(){return!0}toDOM(){let e=document.createElement(`span`);return e.className=`cm-blame-marker cm-blame-spacer`,e.textContent=$m,e}}let l=t.gutter({class:`cm-blame-gutter`,initialSpacer:()=>new c,lineMarker:(e,t)=>{let n=e.state.field(r);if(!n)return null;let i=e.state.doc.lineAt(t.from).number,a=Qm(n,i);return new s(a??{line:i,kind:`missing`,data:null})},lineMarkerChange:e=>e.startState.field(r)!==e.state.field(r)}),u=t.ViewPlugin.fromClass(class{line=null;editorView;constructor(e){this.editorView=e,this.editorView.dom.addEventListener(`mousemove`,this.onMove),this.editorView.dom.addEventListener(`mouseleave`,this.onLeave)}destroy(){this.editorView.dom.removeEventListener(`mousemove`,this.onMove),this.editorView.dom.removeEventListener(`mouseleave`,this.onLeave)}update(e){e.startState.field(r)!==e.state.field(r)&&this.line!==null&&(this.line=null,this.editorView.dispatch({effects:i.of(null)}))}onMove=e=>{let t=this.lineAt(e);if(t===this.line)return;if(this.line=t,t===null){this.editorView.dispatch({effects:i.of(null)});return}let n=Qm(this.editorView.state.field(r),t);if(!n){this.editorView.dispatch({effects:i.of(null)});return}let a=this.editorView.state.doc,o=a.line(Math.min(t,a.lines));this.editorView.dispatch({effects:i.of({pos:o.from,above:!0,create:()=>({dom:th(n)})})})};onLeave=()=>{this.line=null,this.editorView.dispatch({effects:i.of(null)})};lineAt(e){let t=e.target,n=t?.closest?.(`[data-file-blame-line]`);if(n){let e=Number(n.getAttribute(`data-file-blame-line`));return Number.isInteger(e)&&e>0?e:null}if(t?.closest?.(`.cm-blame-gutter`))return null;let r=this.editorView.posAtCoords({x:e.clientX,y:e.clientY});return r==null?null:this.editorView.state.doc.lineAt(r).number}});return{field:r,setBlame:n,base:[r,a,t.showTooltip.from(a),u],gutter:l}}function th(e){let t=document.createElement(`div`);t.className=`cm-blame-tooltip`,t.setAttribute(`data-file-blame-tooltip`,`1`),t.setAttribute(`data-file-blame-kind`,e.kind),e.data?.commit&&t.setAttribute(`data-file-blame-commit`,e.data.commit);for(let n of Km(e)){let e=document.createElement(`div`);e.className=`cm-blame-tooltip-row`,e.textContent=n,t.appendChild(e)}return t}function nh(e,t){let n=(0,p.useRef)(null),r=(0,p.useRef)(void 0);return(0,p.useLayoutEffect)(()=>{let e=r.current;r.current=void 0;let i=n.current;if(!i||!e)return;let a=i.querySelectorAll(t)[e.index];a&&(i.scrollTop+=a.getBoundingClientRect().top-i.getBoundingClientRect().top-e.offset)},[e,t]),{scrollBox:n,capture:()=>{let e=n.current;if(!e)return;let i=e.getBoundingClientRect().top,a;e.querySelectorAll(t).forEach((e,t)=>{let n=e.getBoundingClientRect().top-i;(!a||Math.abs(n)<Math.abs(a.offset))&&(a={index:t,offset:n})}),r.current=a}}}var rh=`super-pi.diff-layout.v1`,ih=`super-pi-diff-layout`;function ah(){try{return localStorage.getItem(rh)===`split`}catch{return!1}}function oh(e){let t=t=>{(t.key===rh||t.key===null)&&e()};return window.addEventListener(ih,e),window.addEventListener(`storage`,t),()=>{window.removeEventListener(ih,e),window.removeEventListener(`storage`,t)}}var sh;function ch(){return sh??ah()}function lh(){return[(0,p.useSyncExternalStore)(oh,ch,()=>!1),e=>{sh=e;try{localStorage.setItem(rh,e?`split`:`inline`),sh=void 0}catch{}window.dispatchEvent(new Event(ih))}]}var uh=4e3,dh=(0,p.lazy)(()=>kn(()=>import(`./CodeMirrorEditor-DlcBTysV.js`).then(e=>({default:e.CodeMirrorEditor})),__vite__mapDeps([23,1,24]))),fh=class extends Error{status;body;constructor(e,t){super(t.error||`HTTP ${e}`),this.status=e,this.body=t,this.name=`ApiError`}},ph=15e3,mh=e=>new fh(408,{error:`请求超时:${ph/1e3} 秒内服务端没有响应`,code:`timeout`,details:{path:e}});async function hh(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),ph);try{let r=t?.signal?AbortSignal.any([t.signal,n.signal]):n.signal,i=await Ie(e,{...t,signal:r}),a;try{a=await i.json()}catch{a=void 0}if(!i.ok)throw new fh(i.status,a??{error:`HTTP ${i.status}`});return a}catch(t){throw n.signal.aborted?mh(e):t}finally{clearTimeout(r)}}var gh=e=>e instanceof fh?e:new fh(0,{error:e instanceof Error?e.message:`读取失败`}),_h=e=>encodeURIComponent(e),vh=e=>e?`&cwd=${_h(e)}`:``,yh=(e,t,n)=>`/api/files?workspaceId=${_h(e)}&path=${_h(t)}${vh(n)}`,bh=`//workspace/`,xh=e=>e.startsWith(bh)?e.slice(12):void 0,Sh=(e,t,n)=>{let r=xh(t);return`/api/file?workspaceId=${_h(e)}&path=${_h(r??t)}${vh(r?``:n)}`},Ch=(e,t,n)=>Sh(e,t,n)+`&meta=1`,wh=(e,t,n)=>`/api/files?workspaceId=${_h(e)}&q=${_h(t)}${vh(n)}`;async function Th(e,t,n){let r=t.current;if(!r)return t.current=hh(e+`&refresh=1`,{cache:`no-store`}),t.current;if(await r.catch(()=>{}),n())return hh(e,{cache:`no-store`})}function Eh(e){let t=e.trim();if(/^(["']).*\1$/u.test(t)&&(t=t.slice(1,-1)),!/^file:\/\//iu.test(t))return t;try{let e=new URL(t);return e.hostname||e.search||e.hash?t:decodeURIComponent(e.pathname).replace(/^\/(?=[a-z]:[\\/])/iu,``)}catch{return t}}function Dh(e){return{path:e,name:e.split(/[\\/]/).at(-1)||e,text:null,openLink:!0}}function Oh(e){let t=Eh(e);if(/^(?:\/|[a-z]:[\\/]|\\\\)/iu.test(t))return Dh(t)}function kh(e){return Eh(e).replaceAll(`\\`,`/`).replace(/^\.\//u,``)}async function Ah(e,t,n){let r=xh(n.path),i=await hh(`/api/files/open?workspaceId=${_h(e)}${vh(r===void 0?t:``)}`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({path:r??n.path})}),{path:a,name:o,text:s,ticket:c,content:l,meta:u}=i,d=Dp(i.targetName??a),f=s===!1&&d===`table`?`download`:d??(s===!1?`download`:void 0);return{path:r===void 0?a:n.path,name:o,content:l??``,etag:u.etag,dirty:!1,view:f,assetTicket:c}}var jh=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:new Date(e).toLocaleTimeString(`zh-CN`,{hour:`2-digit`,minute:`2-digit`})};function Mh({workspaceId:e,entryPath:t,name:n,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d,linked:f,presentation:h}){let g=r[t],_=i.has(t);(0,p.useEffect)(()=>{_&&g===void 0&&o(t)},[_,t,g,o]);let v=h.inline(t,`entry`,d),y=h.inline(t,`child`,d+1);return(0,m.jsxs)(`li`,{className:`file-node`,"data-file-dir":t,"data-linked":f,"data-file-dir-changed":c.has(t)?`1`:`0`,children:[(0,m.jsxs)(`div`,{className:`file-explorer-row`,"data-file-drop-target":h.dropPath===t?`1`:void 0,hidden:!!v,style:{"--file-depth":d},children:[(0,m.jsxs)(`button`,{type:`button`,className:`file-row file-row-dir`,"data-file-dir-toggle":t,"aria-expanded":_,tabIndex:-1,draggable:!f,title:c.has(t)?`${t} 里有 agent 改过的文件`:t,onClick:()=>a(t),children:[(0,m.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`,children:(0,m.jsx)(Ri,{name:_?`down`:`right`})}),(0,m.jsx)(Kr,{category:_?`folder-open`:`folder`}),(0,m.jsx)(`span`,{className:`file-name`,children:n}),c.has(t)&&(0,m.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-dir-changed-badge":t,title:`里面有 agent 改过的文件`,children:`✎`})]}),(0,m.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,tabIndex:-1,"aria-haspopup":`menu`,"aria-label":`${n} 的文件操作`,children:(0,m.jsx)(Ri,{name:`more`})})]}),v,_&&(0,m.jsxs)(`ul`,{className:`file-children`,children:[y&&(0,m.jsx)(`li`,{children:y}),g===void 0?(0,m.jsx)(`li`,{className:`file-row-loading`,"data-file-loading":t,children:`读取中…`}):`error`in g?(0,m.jsx)(`li`,{className:`file-row-error`,"data-file-error":t,title:Br(g.error.message),children:zr(g.error.message,`这个目录读取失败。`)}):g.entries.length===0?(0,m.jsx)(`li`,{className:`file-row-empty`,"data-file-empty":t,children:`空目录`}):(0,m.jsxs)(m.Fragment,{children:[g.truncated&&(0,m.jsx)(`li`,{className:`file-row-empty`,"data-file-truncated":t,children:`条目过多,只显示前一部分`}),g.entries.map(t=>t.kind===`directory`?(0,m.jsx)(Mh,{workspaceId:e,entryPath:t.path,name:t.name,linked:t.symlink,listings:r,expanded:i,toggle:a,loadDirectory:o,openPaths:s,changedDirs:c,changedPaths:l,onOpen:u,depth:d+1,presentation:h},t.path):(0,m.jsx)(Nh,{entry:t,depth:d+1,openPaths:s,changedPaths:l,onOpen:u,presentation:h},t.path))]})]})]})}function Nh({entry:e,depth:t,openPaths:n,changedPaths:r,onOpen:i,presentation:a}){let o={"--file-depth":t};if(e.kind===`symlink`&&!e.openLink)return(0,m.jsx)(`li`,{className:`file-node file-explorer-row`,"data-file-entry":e.path,"data-file-outside":e.path,style:o,children:(0,m.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,disabled:!0,title:`${e.path} 的目标目录在当前工作区之外,或目标文件不可用`,tabIndex:-1,children:[(0,m.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:`file-name`,children:e.name}),(0,m.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`})]})});let s=n.has(e.path),c=r.has(e.path),l=Dp(e.path),u=!!(e.outside&&e.openLink||e.text||l),d=a.currentPath===e.path,f=a.inline(e.path,`entry`,t);return(0,m.jsxs)(`li`,{className:`file-node`,"data-file-entry":e.path,"data-linked":e.symlink,"data-file-outside":e.outside?e.path:void 0,"data-file-row-open":s?`1`:`0`,"data-file-row-changed":c?`1`:`0`,children:[(0,m.jsxs)(`div`,{className:`file-explorer-row`,"data-file-current":d?`1`:void 0,hidden:!!f,style:o,children:[(0,m.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-open":e.path,"aria-disabled":!u||void 0,title:u?e.path:`${e.name} 可以通过文件操作菜单下载`,tabIndex:-1,"aria-current":d?`true`:void 0,draggable:!e.symlink,onClick:t=>{u&&i(e.openLink&&!e.outside?{...e,openLink:void 0}:e,t.detail>1)},children:[(0,m.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,m.jsx)(Kr,{path:e.path}),(0,m.jsx)(`span`,{className:`file-name`,children:e.name}),s&&(0,m.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`}),c&&(0,m.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed":e.path,title:`agent 改过这个文件`,children:`✎ 已改`}),e.document&&(0,m.jsx)(`span`,{className:`file-badge`,"data-file-document":`1`,"aria-label":`文档文件`,children:`文档`}),e.outside&&(0,m.jsx)(`span`,{className:`file-badge`,"data-file-outside-badge":`1`,children:`外部链接`}),!u&&!e.document&&(0,m.jsx)(`span`,{className:`file-badge`,"data-file-binary":`1`,"aria-label":`不支持的文件类型`,children:`不支持`})]}),!e.outside&&(0,m.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,"aria-haspopup":`menu`,tabIndex:-1,"aria-label":`${e.name} 的文件操作`,children:(0,m.jsx)(Ri,{name:`more`})})]}),f]})}function Ph({file:e,state:t,message:n,external:r,jumpToLine:i,onChange:a,onSave:o,onReload:s,onOverwrite:c,workspaceId:l,cwd:u=``,navigation:d,embedded:f=!1,onPosition:h,languageOverride:g}){let[_,v]=(0,p.useState)(!0),[y,b]=(0,p.useState)(),x=(0,p.useRef)(null),[S,C]=(0,p.useState)({}),[w,T]=(0,p.useState)(null),E=(0,p.useRef)(0),D=!!e.assetTicket,O=!D&&S[e.path]===!0&&!!l,k=l?u?`${l}:${u}`:l:``;(0,p.useEffect)(()=>{let t=++E.current;if(!O||!l){T(null);return}let n=new AbortController,i=Nm(k,e.path,e.etag),a=r?void 0:Im(i);if(a){T({state:a.supported?`ready`:`unsupported`,response:a,path:e.path,workspaceId:k,note:a.supported?null:Bm(a.reason)});return}T({state:`loading`,response:null,path:e.path,workspaceId:k,note:null});let o=xh(e.path);return jm(l,o??e.path,{signal:n.signal,cwd:o?``:u}).then(n=>{t===E.current&&(r||Lm(i,n),T({state:n.supported?`ready`:`unsupported`,response:n,path:e.path,workspaceId:k,note:n.supported?null:Bm(n.reason)}))}).catch(n=>{if(t!==E.current||n instanceof km)return;let r=Vm(n);T({state:r.state,response:null,path:e.path,workspaceId:k,note:r.note})}),()=>{n.abort()}},[O,l,u,k,e.path,e.etag,r]);let A=w&&w.path===e.path&&w.workspaceId===k?w:null,j=O?A?.state??`loading`:`off`,ee=j===`ready`&&Ym(e.content,A?.response??null,e.dirty||r),M=[];A?.note&&M.push(A.note),j===`ready`&&A?.response?.truncated&&M.push({code:`truncated`,text:`Blame 数据已截断,只显示了前面一部分(共 ${A.response.totalLines} 行)`}),ee&&M.push({code:`stale`,text:`内容已改动,Blame 对应的是磁盘上的版本`});let N=j===`loading`?`⌛ Blame`:j===`ready`?`✓ Blame`:j===`off`?`Blame`:`! Blame`;(0,p.useEffect)(()=>{i&&v(!1)},[e.path,i]),(0,p.useEffect)(()=>{let e=x.current;if(!i||!e)return;let t=Math.min(i.line,e.value.split(`
|
|
288
288
|
`).length),n=e.value.split(`
|
|
289
289
|
`),r=n.slice(0,t-1).reduce((e,t)=>e+t.length+1,0),a=n[t-1].length;e.focus(),e.setSelectionRange(r+Math.min(a,(i.column??1)-1),r+a);let o=parseFloat(getComputedStyle(e).lineHeight);e.scrollTop=Math.max(0,(t-1)*o-e.clientHeight/2),e.scrollLeft=0;let s=e.previousElementSibling;s instanceof HTMLElement&&(s.scrollTop=e.scrollTop,s.scrollLeft=0)},[e.path,i,_]);let P=/\.md$/i.test(e.path);return(0,m.jsxs)(`div`,{className:`file-editor`,"data-file-editor":e.path,"data-save-state":t,"data-file-readonly":D?`1`:void 0,children:[(0,m.jsxs)(`div`,{className:`file-editor-head`,children:[d??(!f&&(0,m.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path})),(0,m.jsxs)(`span`,{className:`file-editor-flags`,children:[(0,m.jsx)(nm,{view:y}),P&&(0,m.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,onClick:()=>v(e=>!e),children:_?`原文`:`预览`}),e.assetTicket&&l&&!f&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{children:`外部文件 · 只读`}),(0,m.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,onClick:s,children:`重新读取`}),(0,m.jsx)(`a`,{className:`file-preview-toggle`,href:xp(`asset`,l,xh(e.path)===void 0?u:``,e.assetTicket,{download:`1`}),download:e.name,children:`下载`})]}),!D&&(0,m.jsx)(`button`,{type:`button`,className:`file-blame-toggle`,"data-file-blame-toggle":e.path,"data-file-blame-state":j,"aria-pressed":O,"aria-label":O?`关闭 Git Blame`:`显示 Git Blame`,onClick:()=>C(t=>({...t,[e.path]:t[e.path]!==!0})),children:N}),e.dirty&&(0,m.jsx)(`span`,{className:`file-dirty`,"data-file-dirty":`1`,children:`未保存`}),!D&&(0,m.jsxs)(`button`,{type:`button`,className:`file-save`,"data-file-save":e.path,onClick:o,title:`保存文件 (Ctrl+S)`,disabled:t===`saving`,children:[(0,m.jsx)(Ri,{name:`save`}),t===`saving`?`保存中…`:`保存`]})]})]}),M.length>0&&(0,m.jsx)(`p`,{className:`file-blame-note`,"data-file-blame-reason":M.map(e=>e.code).join(` `),role:`status`,children:M.map(e=>e.text).join(`;`)}),r&&t!==`conflict`&&(0,m.jsxs)(`div`,{className:`file-conflict`,"data-file-external":e.path,role:`alert`,children:[(0,m.jsx)(`p`,{children:`这个文件在磁盘上已经被改过了,你的修改还没有覆盖它。`}),(0,m.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,m.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,m.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),t===`conflict`&&(0,m.jsxs)(`div`,{className:`file-conflict`,"data-file-conflict":e.path,role:`alert`,children:[(0,m.jsx)(`p`,{children:`保存被拒绝:这个文件在磁盘上已经被改过了,覆盖会丢掉对方的改动。`}),(0,m.jsxs)(`div`,{className:`file-conflict-actions`,children:[(0,m.jsx)(`button`,{type:`button`,"data-file-reload":e.path,onClick:s,children:`丢掉我的修改,读磁盘版本`}),(0,m.jsx)(`button`,{type:`button`,"data-file-overwrite":e.path,onClick:c,children:`仍然覆盖磁盘`})]})]}),n&&t!==`conflict`&&!r&&(0,m.jsx)(`p`,{className:`file-editor-message file-message-${t}`,"data-file-message":t,role:`status`,children:n}),P&&_?(0,m.jsx)(`div`,{className:`file-markdown-preview`,"data-file-preview":`markdown`,children:(0,m.jsx)(ep,{source:e.content})}):(0,m.jsx)(Wp,{fallback:(t,n)=>(0,m.jsxs)(`div`,{className:`file-editor-fallback`,"data-file-editor-fallback":`1`,children:[(0,m.jsxs)(`div`,{className:`file-editor-fallback-bar`,children:[(0,m.jsxs)(`span`,{children:[`⚠️ 高级编辑器加载异常(`,t.message||`未知错误`,`),已自动降级为安全模式`]}),(0,m.jsx)(`button`,{type:`button`,onClick:n,children:`重新加载`})]}),(0,m.jsx)(`textarea`,{className:`file-textarea`,readOnly:D,value:e.content,onChange:e=>a(e.target.value),onKeyDown:e=>{(e.ctrlKey||e.metaKey)&&e.key===`s`&&(e.preventDefault(),o())}})]}),children:(0,m.jsx)(p.Suspense,{fallback:(0,m.jsx)(`div`,{className:`file-cm-wrap`,"data-file-text":e.path,"data-file-content":e.content,"data-file-selection":`0,0`,"data-file-editor-ready":`0`,children:(0,m.jsx)(`span`,{className:`file-cm-status`,"data-file-editor-loading":`1`,children:`⌛ 正在加载编辑器…`})}),children:(0,m.jsx)(dh,{path:e.path,languageOverride:g,value:e.content,onChange:a,jumpToLine:i,onSave:o,readOnly:D,workspaceId:l,cwd:u,onPosition:h,onView:b,blame:O&&A&&!ee?{state:A.state,response:A.response,path:A.path,workspaceId:l??``}:void 0})})})]})}function Fh({line:e}){if(e.kind===`fold`)return(0,m.jsx)(`div`,{className:`file-diff-line file-diff-fold`,"data-diff-kind":`fold`,children:e.text});let t=e.kind===`added`?`+`:e.kind===`removed`?`-`:` `;return(0,m.jsxs)(`div`,{className:`file-diff-line file-diff-${e.kind}`,"data-diff-kind":e.kind,"data-diff-no-newline":e.noNewline?`1`:void 0,children:[(0,m.jsx)(`span`,{className:`file-diff-mark`,"aria-hidden":`true`,children:t}),(0,m.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.oldLine??``}),(0,m.jsx)(`span`,{className:`file-diff-number`,"aria-hidden":`true`,children:e.newLine??``}),(0,m.jsx)(`span`,{className:`file-diff-text`,children:e.text}),e.noNewline&&(0,m.jsx)(`span`,{className:`file-diff-no-newline`,title:`这个版本的末尾没有换行`,children:`(末尾无换行)`})]})}function Ih(e){let t=[];for(let n=0;n<e.length;){let r=e[n];if(r.kind===`same`||r.kind===`fold`){t.push({before:r,after:r}),n++;continue}let i=[],a=[];for(;n<e.length&&[`removed`,`added`].includes(e[n].kind);){let t=e[n++];(t.kind===`removed`?i:a).push(t)}for(let e=0;e<Math.max(i.length,a.length);e++)t.push({before:i[e],after:a[e]})}return t}function Lh({diff:e,loading:t,error:n,bufferContent:r,mode:i,onMode:a}){let[o,s]=(0,p.useState)(),[c,l]=lh(),u=JSON.stringify([e?.path,i]),d=o===u,{scrollBox:f,capture:h}=nh(d,`.file-diff-added, .file-diff-removed`);if(t)return(0,m.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`loading`,children:(0,m.jsx)(`p`,{className:`rail-empty`,"data-file-diff-loading":`1`,children:`正在读取差异…`})});if(n)return(0,m.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`error`,children:(0,m.jsx)(`p`,{className:`rail-empty`,"data-file-diff-error":`1`,title:Br(n),children:zr(n,`这个文件的差异读取失败。`)})});if(!e)return(0,m.jsx)(`div`,{className:`file-diff`,"data-file-diff-state":`empty`,children:(0,m.jsx)(`p`,{className:`rail-empty`,"data-file-diff-empty":`1`,children:`没有选中的差异。`})});let g=typeof r==`string`,_=i===`buffer`&&g,v=_?e.after:e.before,y=_?r:e.after,b=_?`我未保存的修改`:e.label,x=_?`buffer`:e.baseline,S=g&&e.baseline!==`none`?(0,m.jsxs)(`span`,{className:`file-diff-switch`,"data-file-diff-switch":`1`,children:[(0,m.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${_?``:` file-diff-switch-active`}`,"data-file-diff-base":`server`,"aria-pressed":!_,onClick:()=>a(`server`),children:`agent 的改动`}),(0,m.jsx)(`button`,{type:`button`,className:`file-diff-switch-btn${_?` file-diff-switch-active`:``}`,"data-file-diff-base":`buffer`,"aria-pressed":_,onClick:()=>a(`buffer`),children:`我的修改`})]}):null;if(x===`none`)return(0,m.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`none`,"data-file-diff-baseline":x,children:[(0,m.jsxs)(`div`,{className:`file-editor-head`,children:[(0,m.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,m.jsx)(`span`,{className:`file-editor-flags`,children:S})]}),(0,m.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-nobaseline":`1`,children:b})]});let C=_m(v,y),w=vm(C),T=d?C.lines:w.lines,E=c?Ih(T):[];return(0,m.jsxs)(`div`,{className:`file-diff`,"data-file-diff-state":`ready`,"data-file-diff-baseline":x,"data-file-diff-added":C.added,"data-file-diff-removed":C.removed,"data-file-diff-layout":c?`split`:`inline`,children:[(0,m.jsxs)(`div`,{className:`file-editor-head`,children:[(0,m.jsx)(`span`,{className:`file-editor-path`,title:e.path,children:e.path}),(0,m.jsxs)(`span`,{className:`file-editor-flags`,children:[S,(0,m.jsx)(`span`,{className:`file-diff-baseline`,"data-file-diff-label":`1`,children:b}),(0,m.jsxs)(`span`,{className:`file-diff-count`,"data-file-diff-count":`1`,children:[`+`,C.added,` / -`,C.removed]}),(0,m.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,"data-file-diff-layout-button":!0,onClick:()=>l(!c),title:c?`切换为全局内联视图`:`切换为全局分栏视图`,children:c?`内联`:`分栏`}),!C.identical&&w.folded>0&&(0,m.jsx)(`button`,{type:`button`,className:`file-preview-toggle`,"data-file-diff-context":!0,"aria-pressed":d,onClick:()=>{h(),s(d?void 0:u)},children:d?`折叠未改动行`:`显示全文`})]})]}),e.beforeUnknown&&!_&&(0,m.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-before-unknown":`1`,role:`status`,children:`读不到改动前的版本(文件太大或无法读取),这里只显示现在的内容。`}),e.before===null&&!e.beforeUnknown&&!_&&(0,m.jsx)(`p`,{className:`file-diff-warning`,"data-file-diff-is-new":`1`,role:`status`,children:`这个文件是新建的,下面是它的全部内容。`}),C.identical?(0,m.jsx)(`p`,{className:`file-diff-nobaseline`,"data-file-diff-identical":`1`,children:`两个版本没有区别。`}):(0,m.jsx)(`div`,{ref:f,className:`file-diff-body`,"data-file-diff-body":`1`,"data-file-diff-context-mode":d?`full`:`compact`,children:c?(0,m.jsx)(`div`,{className:`file-diff-split-grid`,children:[`before`,`after`].map(e=>(0,m.jsx)(`div`,{"data-diff-side":e,"aria-label":e===`before`?`修改前`:`修改后`,children:E.map((t,n)=>t[e]?(0,m.jsx)(Fh,{line:t[e]},n):(0,m.jsx)(`div`,{className:`file-diff-line`,"aria-hidden":`true`,children:`\xA0`},n))},e))}):T.map((e,t)=>(0,m.jsx)(Fh,{line:e},t))})]})}function Rh({error:e}){let t=e.body.code,n=typeof e.body.details?.path==`string`?e.body.details.path:``,r=t===`workspace_missing`?`missing`:t===`timeout`?`timeout`:`failed`;return(0,m.jsxs)(`div`,{className:`rail-empty file-problem`,"data-file-root-error":`1`,"data-file-error-kind":r,role:`alert`,children:[r===`missing`&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`工作区路径不存在,无法读取文件。`}),(0,m.jsx)(`p`,{className:`file-problem-hint`,children:`请确认这个路径是写错了,还是目录被移动或删除了:`}),(0,m.jsx)(`code`,{className:`file-problem-path`,"data-file-error-path":`1`,children:n||zr(e.message,`路径未知`)})]}),r===`timeout`&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取超时,服务端没有回应。`}),(0,m.jsxs)(`p`,{className:`file-problem-hint`,children:[`已经等了 `,ph/1e3,` 秒。如果这个工作区在网络盘上,请检查它是否已连接,然后点上面的 ↻ 重试。`]})]}),r===`failed`&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{className:`file-problem-title`,"data-file-error-title":`1`,children:`读取失败。`}),(0,m.jsx)(`p`,{className:`file-problem-hint`,title:Br(e.message),children:zr(e.message,`读取失败,请稍后重试。`)})]})]})}function zh(e,t=``,{navigation:n,showingFile:r=!1,splitFilePath:i}={}){let a=t.trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``),o=e?a?`${e}:${a}`:e:void 0,s=(0,p.useRef)(o);s.current=o;let[c,l]=(0,p.useState)([]),[u,d]=(0,p.useState)(e),f=(0,p.useRef)(c);f.current=c;let[h,g]=(0,p.useState)(),[_,v]=(0,p.useState)(``),[y,b]=(0,p.useState)({}),[x,S]=(0,p.useState)({}),[C,w]=(0,p.useState)({}),[T,E]=(0,p.useState)(()=>new Set),[D,O]=(0,p.useState)(),k=(0,p.useRef)(T);k.current=T;let A=(0,p.useRef)(new Map),j=(0,p.useRef)(new Map),[ee,M]=(0,p.useState)(0),[N,P]=(0,p.useState)(``),[F,I]=(0,p.useState)(null),[te,ne]=(0,p.useState)(null),[re,ie]=(0,p.useState)(!1),[ae,oe]=(0,p.useState)({});(0,p.useEffect)(()=>{if(d(e),A.current=new Map,l([]),g(void 0),v(``),b({}),S({}),w({}),E(new Set),O(void 0),I(null),ne(null),P(``),ie(!1),!e)return;let t=!0;return hh(yh(e,``,a)).then(e=>{t&&w({"":e})}).catch(e=>{t&&w({"":{error:gh(e)}})}),()=>{if(t=!1,o&&s.current!==o){let e=f.current.filter(e=>e.dirty);e.length?j.current.set(o,e):j.current.delete(o),Dm(`super-pi.file-drafts.v1.`+o,e),Uh(o)}}},[e,a,o]);let[se,ce]=(0,p.useState)(),[le,ue]=(0,p.useState)(void 0);(0,p.useEffect)(()=>{if(!e||!o)return;let t=!0;ue(void 0),ce(void 0);let r=Vh()[o]??{expanded:[],open:[]},i=e=>({path:e,name:e.split(/[\\/]/).at(-1)||e,text:!0,openLink:r.explicit?.includes(e)?!0:void 0}),a=Em(`super-pi.file-drafts.v1.`+o,[]),c=new Map((j.current.get(o)??a).map(e=>[e.path,e]));r.expanded.length&&E(new Set(r.expanded)),typeof r.listHeight==`number`&&I(r.listHeight);let u=new Set([...r.open,...c.keys()]);if(!u.size){ce(o);return}let d=r.active??[...c.keys()].at(-1),f=n?.current,p=()=>t&&n?.current===f;return(async()=>{let e,n=r.preview&&!c.has(r.preview)?r.preview:void 0;for(let r of u){if(r===n)continue;let a=c.get(r);a&&l(e=>e.some(e=>e.path===r)?e:[...e,a]);let u=a?.path??await Se(i(r),{activate:!1,isCurrent:()=>t});if(!t||s.current!==o)return;r===d&&(e=u)}if(n&&p()&&(e=await Se(i(n),{activate:!1,isCurrent:p})),e&&s.current===o&&p()){let t=e;r.preview===r.active&&l(e=>e.map(e=>e.path===t&&!e.dirty?{...e,preview:!0}:e)),g(t),ue(t)}})().finally(()=>{t&&s.current===o&&ce(o)}),()=>{t=!1}},[e,a,o,n]),(0,p.useEffect)(()=>{if(!e||!o)return;let t=setTimeout(()=>{let e=Vh();e[o]={open:c.map(e=>e.path),explicit:c.filter(e=>e.assetTicket).map(e=>e.path),expanded:[...T],...r&&h?{active:h}:{},...r&&h&&c.some(e=>e.path===h&&e.preview)?{preview:h}:{},...F===null?{}:{listHeight:F}},Hh(e)},400);return()=>{clearTimeout(t)}},[e,o,c,T,h,F,r]),(0,p.useEffect)(()=>{if(!o||se!==o)return;let e=()=>{if(s.current!==o)return;let e=f.current.filter(e=>e.dirty);return Dm(`super-pi.file-drafts.v1.`+o,e)||e.length===0},t=window.setTimeout(()=>{e()===!1&&v(`浏览器无法保存文件草稿,刷新前请先保存修改。`)},250);return window.addEventListener(`pagehide`,e),()=>{window.clearTimeout(t),window.removeEventListener(`pagehide`,e)}},[o,se,c]);let de=(0,p.useCallback)(async(t,n=!1)=>{if(!e)return;let r={},i=A.current;i.set(t,r);let c=()=>s.current===o&&A.current===i&&i.get(t)===r;await hh(yh(e,t,a)+(n?`&revalidate=1`:``)).then(e=>{c()&&w(n=>({...n,[t]:e}))}).catch(e=>{c()&&w(n=>({...n,[t]:{error:gh(e)}}))}).finally(()=>{c()&&i.delete(t)})},[e,a,o]),fe=(0,p.useCallback)(e=>{E(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),pe=(0,p.useCallback)(t=>{if(!e)return;let n=new Set([``,...k.current]),r=t&&new Set(t.map(Op)),i=e=>!r||r.has(e)||t.some(t=>kp(e,t));w(e=>Object.fromEntries(Object.entries(e).filter(([e])=>n.has(e)||!i(e))));for(let e of A.current.keys())!n.has(e)&&i(e)&&A.current.delete(e);Promise.all([...n].filter(i).map(e=>de(e,!t&&!e))).then(()=>{s.current===o&&M(e=>e+1)})},[e,o,de]),L=(0,p.useCallback)(()=>pe(),[pe]),me=(0,p.useRef)(void 0),he=(0,p.useRef)(new Set);(0,p.useEffect)(()=>()=>{clearTimeout(me.current),me.current=void 0,he.current=new Set},[o]);let ge=(0,p.useCallback)((t,n)=>{if(t!==e)return;let r=a?`${a}/`:``,i=n?.flatMap(e=>e.startsWith(r)?[e.slice(r.length)]:[]);if(i?.length===0){if(!n?.some(e=>kp(a,e)))return;he.current=null}else if(!i)he.current=null;else for(let e of i)he.current?.add(e);me.current||=setTimeout(()=>{me.current=void 0;let e=he.current;he.current=new Set,pe(e?[...e]:void 0)},100)},[e,a,pe]),_e=(0,p.useCallback)(e=>{let t=new Set;for(let n=Op(e);n;n=Op(n))t.add(n);P(``),E(e=>new Set([...e,...t]))},[]),ve=(0,p.useCallback)((e,t)=>{_e(t&&e?`${e}/`:e),O({path:e,directory:t})},[_e]),ye=(0,p.useCallback)(()=>E(new Set),[]),be=(0,p.useCallback)((e,t,n)=>{let r=n=>kp(n,e)?t+n.slice(e.length):n,i=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[r(e),t]));l(t=>t.map(t=>{let i=r(t.path);if(i===t.path)return t;let a=Dp(i),o=t.view&&t.view!==`table`&&(!a||a===`table`)||t.path===e&&n===!1&&!a?`download`:a;return{...t,path:i,view:o,name:i.split(`/`).at(-1)??t.name}})),g(e=>e&&r(e)),E(e=>new Set([...e].map(r))),b(i),S(i);for(let t of A.current.keys())kp(t,e)&&A.current.delete(t);w(t=>Object.fromEntries(Object.entries(t).filter(([t])=>!kp(t,e)))),_e(t)},[_e]),xe=(0,p.useRef)(void 0);(0,p.useEffect)(()=>{xe.current=void 0},[e,a]),(0,p.useEffect)(()=>{let t=kh(N);if(!e||!t||Oh(N)){xe.current=void 0,ne(null),ie(!1);return}let n=!0,r,i=async()=>{try{let o=await Th(wh(e,t,a),xe,()=>n);if(!n||!o)return;ne(o),ie(!1),o.indexed||(r=setTimeout(()=>void i(),400))}catch(e){if(!n)return;ne(null),ie(!1),v(zr(e,`文件查找没有完成`))}};return ie(!0),r=setTimeout(()=>void i(),80),()=>{n=!1,clearTimeout(r)}},[N,e,a,ee]);let Se=(0,p.useCallback)(async(t,{preview:n=!1,activate:r=!0,isCurrent:i,throwOnError:c,requireText:u}={})=>{if(!(!e||i&&!i())){v(``);try{let c=f.current.find(e=>e.path===t.path),d=c??await Ah(e,a,t);if(s.current!==o||i&&!i())return;if(u&&d.view&&d.view!==`table`)throw Error(`已找到匹配行,但此文件无法在文本编辑器中定位。可以在搜索结果中查看这一行。`);return c?(r&&g(t.path),t.path):(l(e=>e.some(e=>e.path===d.path)?e:[...e,{...d,...n?{preview:n}:{}}]),r&&g(d.path),S(e=>({...e,[d.path]:!1})),d.path)}catch(e){if(s.current!==o||i&&!i())return;if(c)throw e;v(`打不开「${t.name}」:${e instanceof Error?e.message:`未知错误`}`)}}},[e,a,o]),Ce=(0,p.useCallback)(e=>{o&&f.current.some(t=>t.path===e&&t.preview&&!t.dirty)&&Uh(o,e),l(t=>{let n=t.find(t=>t.path===e);if(n?.dirty&&!window.confirm(`「${n.name}」有未保存的修改,关掉就丢了。仍然关闭?`))return t;let r=t.findIndex(t=>t.path===e),i=t.filter(t=>t.path!==e);return e===h&&g(i.length===0?void 0:i[Math.min(r,i.length-1)]?.path),i})},[h,o]),we=(0,p.useCallback)(e=>{l(t=>t.map(t=>t.path===e&&t.preview?{...t,preview:!1}:t))},[]),Te=(0,p.useCallback)(e=>{l(t=>t.filter(t=>t.path!==e||!t.preview||t.dirty)),g(t=>t===e?void 0:t),o&&Uh(o,e)},[o]),Ee=(0,p.useCallback)((e,t)=>{l(n=>n.map(n=>n.path===e&&!n.assetTicket&&n.content!==t?{...n,content:t,dirty:!0,preview:!1}:n))},[]);(0,p.useEffect)(()=>{if(!e||c.length===0)return;let t=!0,n=setInterval(()=>{for(let{path:n,assetTicket:r}of f.current)r||hh(Ch(e,n,a)).then(r=>{if(!t)return;let i=f.current.find(e=>e.path===n);if(i?.view&&i.view!==`table`&&r.etag!==i.etag)l(e=>e.map(e=>e.path===n&&e.etag===i.etag?{...e,etag:r.etag}:e));else if(i&&r.etag!==i.etag){if(i.dirty){S(e=>({...e,[n]:!0}));return}let r=i;hh(Sh(e,n,a)).then(e=>{t&&l(t=>t.map(t=>t.path===n&&!t.dirty&&t.etag===r.etag&&t.content===r.content?{...t,content:e.content,etag:e.meta.etag}:t))}).catch(()=>{t&&S(e=>({...e,[n]:!0}))})}}).catch(e=>{t&&gh(e).status===404&&S(e=>({...e,[n]:!0}))})},uh);return()=>{t=!1,clearInterval(n)}},[e,a,c.length]);let De=(0,p.useCallback)(async(t,n)=>{if(!e)return;let r=c.find(e=>e.path===t);if(!r||r.assetTicket)return;b(e=>({...e,[t]:{state:`saving`,message:``}}));let i=r.etag;if(n)try{i=(await hh(Ch(e,t,a))).etag}catch(e){s.current===o&&b(n=>({...n,[t]:{state:`error`,message:`无法读取磁盘上的最新版本:${e instanceof Error?e.message:`未知错误`}`}}));return}let u=r.content;try{let n=await hh(Sh(e,t,a),{method:`PUT`,headers:{"content-type":`application/json`},body:JSON.stringify({path:xh(t)??t,content:u,baseEtag:i})});if(s.current!==o)return;let r=f.current.find(e=>e.path===t),c=r!==void 0&&r.content!==u;l(e=>e.map(e=>e.path===t?{...e,etag:n.meta.etag,dirty:e.content!==u}:e)),S(e=>({...e,[t]:!1})),b(e=>({...e,[t]:{state:`saved`,message:c?`已保存,但你又改了;最新修改仍未保存`:`已保存 ${jh(n.meta.modifiedAt)}`}}))}catch(e){if(s.current!==o)return;let n=e instanceof fh&&e.body.code===`stale`;b(r=>({...r,[t]:{state:n?`conflict`:`error`,message:e instanceof Error?e.message:`保存失败`}})),n&&S(e=>({...e,[t]:!0}))}},[e,a,o,c]),Oe=(0,p.useCallback)(async t=>{if(!e)return;let n=f.current.find(e=>e.path===t),r=n?.content;try{if(n?.assetTicket){let r=await Ah(e,a,{path:t,name:n.name,text:null,openLink:!0});if(!r.assetTicket||r.path!==t)throw Error(`链接目标已变化,请关闭后重新打开。`);s.current===o&&(l(e=>e.map(e=>e.path===t?{...r,preview:e.preview}:e)),b(e=>({...e,[t]:{state:`idle`,message:``}})));return}let i=await hh(Sh(e,t,a));if(s.current!==o)return;let c=f.current.find(e=>e.path===t),u=c!==void 0&&c.content!==r;l(e=>e.map(e=>e.path===t?{...e,content:u?e.content:i.content,etag:i.meta.etag,dirty:u}:e)),S(e=>({...e,[t]:!1})),b(e=>({...e,[t]:{state:`saved`,message:u?`已读取磁盘版本;你后来输入的修改仍未保存`:`已重新载入磁盘版本`}}))}catch(e){s.current===o&&b(n=>({...n,[t]:{state:`error`,message:e instanceof Error?e.message:`重新载入失败`}}))}},[e,a,o]),ke=c.find(e=>e.path===h),Ae=(0,p.useMemo)(()=>c.map(e=>({id:e.path,label:e.name,title:xh(e.path)??e.path,closable:!0,badge:e.dirty?(0,m.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[c]),je=(0,p.useMemo)(()=>new Set(c.map(e=>e.path)),[c]),Me=(0,p.useCallback)((e,t,n)=>{oe(r=>({...r,[e]:{changes:t,dropped:n}}))},[]),Ne=e?ae[e]:void 0,Pe=(0,p.useMemo)(()=>{let e=Ne?.changes??[];if(!a)return e;let t=`${a}/`;return e.flatMap(e=>e.path.startsWith(t)?[{...e,path:e.path.slice(t.length)}]:[])},[Ne,a]),Fe=Ne?.dropped??0,Ie=(0,p.useMemo)(()=>new Set(Pe.map(e=>e.path)),[Pe]),Le=(0,p.useMemo)(()=>{let e=new Set;for(let t of Pe){let n=t.path.split(`/`);for(let t=1;t<n.length;t++)e.add(n.slice(0,t).join(`/`))}return e},[Pe]);return{ownerWorkspaceId:u,open:c,activePath:h,visiblePath:r?h:i,location:D,active:ke,tabItems:Ae,openPaths:je,notice:_,setNotice:v,saves:y,external:x,restoringWorkbench:!!(o&&se!==o),openFile:Se,setActivePath:g,closeFile:Ce,pinFile:we,discardPreview:Te,updateBuffer:Ee,save:De,reload:Oe,listings:C,expanded:T,toggleDirectory:fe,loadDirectory:de,refreshTree:L,invalidateTree:ge,revealPath:_e,locatePath:ve,collapseDirectories:ye,movePath:be,listHeight:F,setListHeight:I,query:N,setQuery:P,hits:te,searching:re,changed:Pe,changedPaths:Ie,changedDirs:Le,changedDropped:Fe,setChangedFor:Me,restoredActive:le}}var Bh=`super-pi.file-workbench.v1`;function Vh(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.file-workbench.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){if(!r||typeof r!=`object`)continue;let e=r,i=Array.isArray(e.open)?e.open.filter(e=>typeof e==`string`):[],a=typeof e.preview==`string`?e.preview:void 0;a&&a!==e.active&&(i=i.filter(e=>e!==a));let o=Array.isArray(e.expanded)?e.expanded.filter(e=>typeof e==`string`):[],s=typeof e.listHeight==`number`&&Number.isFinite(e.listHeight)&&e.listHeight>0?Math.round(e.listHeight):void 0,c=Array.isArray(e.explicit)?e.explicit.filter(e=>typeof e==`string`):[];t[n]={open:i,expanded:o,explicit:c,...typeof e.active==`string`?{active:e.active}:{},...a&&a===e.active?{preview:a}:{},...s?{listHeight:s}:{}}}return t}catch{return{}}}function Hh(e){try{typeof window<`u`&&window.localStorage.setItem(Bh,JSON.stringify(e))}catch{}}function Uh(e,t){let n=Vh(),r=n[e];!r?.preview||t&&r.preview!==t||(n[e]={...r,open:r.open.filter(e=>e!==r.preview),active:void 0,preview:void 0},Hh(n))}function Wh({height:e,onHeight:t,panelRef:n,min:r=120}){let[i,a]=(0,p.useState)(!1),o=()=>{let e=n.current?.querySelector(`.files-tree`)??null;return{list:e,height:e?.getBoundingClientRect().height??0}},s=e=>{e.preventDefault(),e.currentTarget.focus();let n=e.clientY,{height:i}=o();a(!0);let s=document.body,c=s.style.cursor,l=s.style.userSelect;s.style.cursor=`row-resize`,s.style.userSelect=`none`;let u=e=>{let a=Math.round(i+(e.clientY-n));t(Math.max(r,a))},d=()=>{s.style.cursor=c,s.style.userSelect=l,a(!1),window.removeEventListener(`mousemove`,u),window.removeEventListener(`mouseup`,d)};window.addEventListener(`mousemove`,u),window.addEventListener(`mouseup`,d)},c=e=>e.shiftKey?96:24;return(0,m.jsx)(`div`,{className:`files-splitter${i?` files-splitter-dragging`:``}`,"data-file-splitter":`1`,"data-file-splitter-dragging":i?`true`:`false`,role:`separator`,"aria-orientation":`horizontal`,"aria-label":`调整文件列表高度`,"aria-valuenow":e??void 0,"aria-valuemin":r,tabIndex:0,onMouseDown:s,onKeyDown:e=>{let i=c(e);if(e.key===`ArrowDown`){e.preventDefault();let{height:n}=o();t(Math.max(r,Math.round(n)+i))}else if(e.key===`ArrowUp`){e.preventDefault();let{height:n}=o(),a=Math.round(n)-i;t(a<=r?null:a)}else if(e.key===`Home`)e.preventDefault(),t(null);else if(e.key===`End`){e.preventDefault();let i=n.current?.querySelector(`.files-tree`)?.parentElement?.clientHeight??0;t(Math.max(r,i))}}})}var Gh=()=>null,Kh=`application/x-super-pi-workspace-file`;function qh({workspaceId:e,workspaceName:t,cwd:n=``,files:r,onOpenFile:i,onOpenChanged:a,onReference:o,onMoved:s,onSearchFolder:c}){let{open:l,openPaths:u,notice:d,setNotice:f,openFile:h,listings:g,expanded:_,toggleDirectory:v,loadDirectory:y,refreshTree:b,listHeight:x,setListHeight:S,query:C,setQuery:w,hits:T,searching:E,changed:D,changedPaths:O,changedDirs:k,changedDropped:A}=r,j=(0,p.useCallback)((e,t)=>{i?i(e,t):h(e)},[i,h]),ee=ki(`file-tree`),M=ki(`file-changes`),N=n.split(`/`).at(-1)||t||`工作目录`,P=Fp({workspaceId:e,cwd:n,scopeName:N,files:r,onOpen:j,onReference:o,onMoved:s,onSearchFolder:c}),[F,I]=(0,p.useState)(),te=(0,p.useRef)(void 0),[ne,re]=(0,p.useState)(!1),ie=P.editing?P.inline:Gh,ae=(0,p.useMemo)(()=>({currentPath:r.visiblePath,dropPath:F,inline:ie}),[r.visiblePath,F,ie]);(0,p.useEffect)(()=>{if(!ee.visible)return;b();function e(){b()}return window.addEventListener(`focus`,e),()=>window.removeEventListener(`focus`,e)},[b,ee.visible]),(0,p.useEffect)(()=>{I(void 0),te.current=void 0,re(!1)},[e,n]);let oe=g[``],se=C.trim(),ce=e?Oh(C):void 0,le=(0,p.useRef)(null),ue=(0,p.useRef)(null),de=(0,p.useRef)(void 0);function fe(e){let t=ue.current;t&&(de.current&&de.current!==e&&(de.current.tabIndex=-1),de.current=e,t.tabIndex=e?-1:0,e&&(e.tabIndex=0))}let pe=(0,p.useRef)(void 0);(0,p.useEffect)(()=>{let{location:e}=r;if(!e||pe.current===e)return;let t=le.current?.querySelector(e.path?`[${e.directory?`data-file-dir-toggle`:`data-file-open`}="${CSS.escape(e.path)}"]`:`[data-explorer-root]`);t&&(pe.current=e,t.focus({preventScroll:!0}),t.scrollIntoView({block:`nearest`}))},[r.location,g,_,C]),(0,p.useEffect)(()=>{if(!F||_.has(F))return;let e=window.setTimeout(()=>v(F),650);return()=>window.clearTimeout(e)},[F,_,v]);let L=(0,p.useCallback)(e=>{let t=le.current;if(!t)return;let n=e.target?.closest(`.file-row`);if(!n)return;let r=jp(n);if(r&&!P.busy){if(e.key===`ContextMenu`||e.shiftKey&&e.key===`F10`){e.preventDefault(),P.openMenu(r,zi(n));return}if(!r.linked&&e.key===`F2`){e.preventDefault(),P.showAction(`move`,r,!1,n);return}if(!r.linked&&e.key===`Delete`){e.preventDefault(),P.showAction(`trash`,r,!1,n);return}}let i=[...(n.closest(`.files-tree, .files-changed`)??t).querySelectorAll(`.file-row:not(:disabled)`)].filter(e=>e.offsetParent!==null),a=i.indexOf(n);if(a<0)return;let o=e=>{let t=Math.max(0,Math.min(i.length-1,e));i[t]?.focus()};if(e.key===`ArrowDown`)e.preventDefault(),o(a+1);else if(e.key===`ArrowUp`)e.preventDefault(),o(a-1);else if(e.key===`Home`)e.preventDefault(),o(0);else if(e.key===`End`)e.preventDefault(),o(i.length-1);else if(e.key===`ArrowRight`){let t=n.getAttribute(`data-file-dir-toggle`);if(t&&n.getAttribute(`aria-expanded`)===`false`)e.preventDefault(),v(t);else if(t){let t=n.closest(`.file-node`)?.querySelector(`.file-children .file-row:not(:disabled)`);t&&(e.preventDefault(),t.focus())}}else if(e.key===`ArrowLeft`){let r=n.getAttribute(`data-file-dir-toggle`);if(r&&n.getAttribute(`aria-expanded`)===`true`){e.preventDefault(),v(r);return}let i=n.getAttribute(`data-file-open`)??n.getAttribute(`data-file-hit`)??r;if(i){e.preventDefault();let n=i.lastIndexOf(`/`),r=n<0?``:i.slice(0,n);(r?t.querySelector(`[data-file-dir-toggle="${CSS.escape(r)}"]`):null)?.focus()}}},[v,P]),[me,he]=(0,p.useState)(200);(0,p.useEffect)(()=>{he(200)},[se,e]);let ge=(0,p.useRef)(null);(0,p.useEffect)(()=>{if(se===``)return;let e=ge.current;if(!e||typeof IntersectionObserver>`u`)return;let t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&he(e=>e>=(T?.hits.length??0)?e:e+200)},{rootMargin:`200px`});return t.observe(e),()=>t.disconnect()},[se,T]);let _e=(0,p.useMemo)(()=>{if(ce)return(0,m.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-exact-path":ce.path,title:ce.path,onClick:()=>j(ce),children:[(0,m.jsx)(Kr,{path:ce.path}),(0,m.jsxs)(`span`,{className:`file-name`,children:[`打开 `,ce.name]})]});if(se){if(E)return(0,m.jsx)(`p`,{className:`rail-empty`,"data-file-searching":`1`,children:`搜索中…`});if(!T)return null;if(T.hits.length===0)return(0,m.jsx)(`p`,{className:`rail-empty`,"data-file-search-empty":`1`,children:T.indexed?`没有匹配「${se}」的文件。`:`正在建立索引…`});let e=T.hits.slice(0,me),t=[],n=new Map;for(let r of e){let e=n.get(r.directory);if(e)e.push(r);else{let e=[r];n.set(r.directory,e),t.push({directory:r.directory,hits:e})}}return(0,m.jsxs)(m.Fragment,{children:[t.map(e=>(0,m.jsxs)(`section`,{className:`file-group`,"data-file-search-group":e.directory,children:[(0,m.jsxs)(`h3`,{className:`file-group-head`,"data-file-search-group-head":e.directory,children:[(0,m.jsx)(`span`,{className:`file-group-name`,children:e.directory||`/`}),(0,m.jsx)(`span`,{className:`file-group-count`,children:e.hits.length})]}),(0,m.jsx)(`ul`,{className:`file-list`,children:e.hits.map(e=>(0,m.jsxs)(`li`,{className:`file-explorer-row`,"data-file-entry":e.path,"data-linked":e.openLink,"data-file-current":r.visiblePath===e.path?`1`:void 0,children:[(0,m.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-hit":e.path,tabIndex:-1,"aria-current":r.visiblePath===e.path?`true`:void 0,"data-file-hit-open":u.has(e.path)?`1`:`0`,onClick:()=>j({...e,text:!0}),children:[(0,m.jsx)(`span`,{className:`file-caret`,"aria-hidden":`true`}),(0,m.jsx)(Kr,{path:e.path}),(0,m.jsx)(`span`,{className:`file-name`,children:e.name}),u.has(e.path)&&(0,m.jsx)(`span`,{className:`file-open-mark`,"data-file-open-mark":e.path,title:`已经打开`,"aria-label":`已经打开`,children:`●`})]}),!e.openLink&&(0,m.jsx)(`button`,{type:`button`,className:`file-explorer-more explorer-icon-button`,"data-explorer-action":`1`,tabIndex:-1,"aria-haspopup":`menu`,"aria-label":`${e.name} 的文件操作`,children:(0,m.jsx)(Ri,{name:`more`})})]},e.path))})]},e.directory||`/`)),e.length<T.hits.length&&(0,m.jsx)(`div`,{ref:ge,className:`file-sentinel`,"data-file-search-more":`1`,children:`正在载入更多…`})]})}return e?oe===void 0?(0,m.jsx)(`p`,{className:`rail-empty`,"data-file-root-loading":`1`,children:`读取工作区…`}):`error`in oe?(0,m.jsx)(Rh,{error:oe.error}):(0,m.jsxs)(m.Fragment,{children:[oe.truncated&&(0,m.jsx)(`p`,{className:`file-search-note`,"data-file-truncated-root":`1`,children:`条目过多,只显示前一部分。`}),oe.entries.length===0?(0,m.jsx)(`p`,{className:`rail-empty`,"data-file-root-empty":`1`,children:`这个工作区是空的,没有文件也没有子目录。`}):(0,m.jsx)(`ul`,{className:`file-list`,children:oe.entries.map(t=>t.kind===`directory`?(0,m.jsx)(Mh,{workspaceId:e,entryPath:t.path,name:t.name,linked:t.symlink,listings:g,expanded:_,toggle:v,loadDirectory:y,openPaths:u,changedDirs:k,changedPaths:O,onOpen:j,depth:0,presentation:ae},t.path):(0,m.jsx)(Nh,{entry:t,depth:0,openPaths:u,changedPaths:O,onOpen:j,presentation:ae},t.path))})]}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-file-no-workspace":`1`,children:`先在左侧选一个工作区,这里会显示它的文件。`})},[ce,se,E,T,me,e,oe,g,_,v,y,j,u,k,O,ae,r.visiblePath]),ve=e=>{let t=jp(e);if(!t?.linked)return t?t.directory?t.path:Op(t.path):``},ye=(e,t)=>e!==Op(t.path)&&!(t.directory&&kp(e,t.path));(0,p.useLayoutEffect)(()=>{let e=ue.current;if(!e)return;let t=[...e.querySelectorAll(`.file-row:not(:disabled)`)].filter(e=>e.offsetParent!==null),n=de.current;fe(n&&t.includes(n)?n:t.find(e=>e.hasAttribute(`aria-current`))??t[0])},[_e,P.editing]);let be=t=>(0,m.jsx)(`div`,{className:`files-panel`,"data-files-panel":`1`,"data-files-open-count":l.length,"data-files-changed-count":D.length,ref:le,onKeyDown:L,onClick:e=>{let t=e.target instanceof Element?e.target.closest(`[data-explorer-action]`):void 0,n=jp(t??null);t&&n&&!P.busy&&P.openMenu(n,zi(t))},onContextMenu:e=>{let t=jp(e.target),n=e.target instanceof Element?e.target.closest(`.file-row, [data-explorer-action]`):void 0;t&&n&&!P.busy&&(e.preventDefault(),P.openMenu(t,{x:e.clientX,y:e.clientY,origin:n}))},onDragStart:e=>{let t=jp(e.target instanceof Element?e.target.closest(`.file-row[draggable=true]`):null);!t||t.linked||P.busy||se||(te.current=t,e.dataTransfer.setData(Kh,t.path),e.dataTransfer.effectAllowed=`move`)},onDragEnd:()=>{te.current=void 0,I(void 0)},onDragLeave:e=>{(!(e.relatedTarget instanceof Node)||!e.currentTarget.contains(e.relatedTarget))&&I(void 0)},onDragOver:t=>{let n=t.dataTransfer.types.includes(`Files`),r=te.current&&t.dataTransfer.types.includes(Kh)?te.current:void 0;if(!e||P.busy||!n&&!r)return;t.preventDefault();let i=ve(t.target),a=i!==void 0&&(!r||ye(i,r));t.dataTransfer.dropEffect=a?r?`move`:`copy`:`none`,I(a?i:void 0)},onDrop:t=>{I(void 0);let n=t.dataTransfer.types.includes(Kh)?te.current:void 0;if(te.current=void 0,!e||P.busy||!n&&!t.dataTransfer.types.includes(`Files`))return;t.preventDefault();let r=ve(t.target);if(r===void 0){f(`请选择工作区里的普通文件夹。`);return}if(n){ye(r,n)&&P.moveTo(n,r);return}let i=Array.from(t.dataTransfer.items).filter(e=>!e.webkitGetAsEntry?.()?.isDirectory).map(e=>e.getAsFile()).filter(e=>e!==null);i.length?P.upload(r,i):t.dataTransfer.files.length&&!t.dataTransfer.items.length?P.upload(r,Array.from(t.dataTransfer.files)):f(`请选择要上传的文件。`)},children:t}),xe=(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`header`,{className:`file-explorer-header`,"data-file-drop-target":F===``?`1`:void 0,children:[(0,m.jsxs)(`div`,{className:`file-explorer-scope`,"data-explorer-root":`1`,tabIndex:-1,title:n?`${t??`工作区`}/${n}`:N,children:[(0,m.jsx)(Kr,{category:`folder-open`}),(0,m.jsx)(Ni,{id:`file-tree`,children:N})]}),P.toolbar,(0,m.jsx)(Pi,{id:`file-tree`})]}),(0,m.jsxs)(`div`,{className:`files-search`,children:[(0,m.jsx)(`span`,{className:`files-search-icon`,"aria-hidden":`true`,children:(0,m.jsx)(Ri,{name:`search`})}),(0,m.jsx)(`input`,{type:`search`,className:`files-search-input`,"data-file-search-input":`1`,value:C,placeholder:`筛选文件或输入绝对路径`,"aria-label":`按文件名搜索`,onKeyDown:e=>{e.key===`Escape`?(e.preventDefault(),w(``)):e.key===`Enter`&&ce&&(e.preventDefault(),j(ce))},onChange:e=>w(e.target.value)}),(0,m.jsx)(`button`,{type:`button`,className:`explorer-icon-button`,disabled:!r.activePath||!!xh(r.activePath)||!!(r.active?.assetTicket&&Oh(r.activePath)),onClick:()=>{r.activePath&&r.locatePath(r.activePath,!1)},title:`定位打开的文件`,"aria-label":`在文件树中定位当前文件`,children:(0,m.jsx)(Ri,{name:`locate`})})]}),P.controls,!ce&&se&&T&&!E&&(0,m.jsxs)(`p`,{className:`files-count`,"data-file-search-count":`1`,role:`status`,children:[(0,m.jsx)(`b`,{children:T.total.toLocaleString(`zh-CN`)}),` 个结果`,T.indexed===!1&&(0,m.jsx)(`span`,{className:`files-count-note`,"data-file-search-indexing":`1`,children:`正在建立索引…`}),T.indexed&&T.incomplete&&(0,m.jsx)(`span`,{className:`files-count-note`,children:`索引不完整`})]}),d&&(0,m.jsx)(`p`,{className:`rail-empty file-explorer-notice`,"data-file-notice":`1`,role:`status`,children:d}),P.busy&&(0,m.jsx)(`p`,{className:`file-explorer-notice`,role:`status`,children:`正在处理文件…`}),(0,m.jsx)(`div`,{className:`files-tree`,ref:ue,"data-file-tree":se?`search`:`browse`,tabIndex:0,"aria-label":`文件树`,onFocus:e=>{e.target instanceof HTMLElement&&e.target.matches(`.file-row:not(:disabled)`)&&fe(e.target)},style:x===null?void 0:{height:`${x}px`,flex:`0 0 auto`},children:(0,m.jsxs)(`div`,{className:`files-tree-body`,children:[P.inline(``,`child`,0),_e]})})]}),Se=(0,m.jsx)(Mi,{id:`file-changes`,header:!1,children:(0,m.jsxs)(`div`,{className:`files-changed`,"data-file-changed-list":`1`,children:[(0,m.jsxs)(`div`,{className:`file-changes-heading`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`files-changed-head`,"data-file-changed-head":`1`,"aria-expanded":ne,onClick:()=>re(e=>!e),children:[(0,m.jsx)(Ri,{name:ne?`down`:`right`}),(0,m.jsx)(Ri,{name:`changes`}),(0,m.jsx)(Ni,{id:`file-changes`,children:`改动`}),(0,m.jsx)(`span`,{className:`files-change-count`,children:D.length})]}),(0,m.jsx)(Pi,{id:`file-changes`})]}),ne&&(0,m.jsxs)(`div`,{className:`files-change-list`,children:[A>0&&(0,m.jsxs)(`p`,{className:`file-search-note`,"data-file-changed-dropped":`1`,children:[`还有 `,A,` 个改动没有记录(超过保留上限)。`]}),!D.length&&(0,m.jsx)(`p`,{className:`file-row-empty`,children:`没有 agent 改动。`}),(0,m.jsx)(`ul`,{className:`file-list`,children:D.map(e=>(0,m.jsx)(`li`,{children:(0,m.jsxs)(`button`,{type:`button`,className:`file-row file-row-file`,"data-file-changed-open":e.path,title:`${e.path}(点击查看改动)`,onClick:()=>a?.(e.path),children:[(0,m.jsx)(Kr,{path:e.path}),(0,m.jsx)(`span`,{className:`file-name`,children:e.path.split(`/`).pop()}),(0,m.jsx)(`span`,{className:`file-badge-path`,children:e.path.split(`/`).slice(0,-1).join(`/`)||`/`}),(0,m.jsx)(`span`,{className:`file-badge file-badge-changed`,"data-file-changed-kind":e.path,children:e.baseline===null&&!e.baselineUnknown?`新建`:`已改`})]})},e.path))})]})]})});return ee.embedded?be((0,m.jsxs)(m.Fragment,{children:[xe,M.embedded&&(0,m.jsx)(Wh,{height:x,onHeight:S,panelRef:le}),Se]})):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(Mi,{id:`file-tree`,header:!1,children:be(xe)}),Se]})}function Jh(e,t){let[n,r]=(0,p.useState)(!1),[i,a]=(0,p.useState)(``);return{choose:async(i,o,s)=>{if(i&&!n){r(!0),a(``);try{await e(i,o,s)&&t()}catch(e){a(zr(e,`文件无法打开`))}finally{r(!1)}}},openError:i,opening:n,setOpenError:a}}var Yh=200;async function Xh(e,t,n){let r=await Ie(e,{signal:t,cache:`no-store`});if(!r.ok)throw new fh(r.status,await r.json());if(!r.body)throw Error(`服务端没有返回搜索结果。`);let i=r.body.pipeThrough(new TextDecoderStream).getReader(),a=``,o=!1;try{for(;;){let e=await i.read();if(e.done)break;let t=(a+e.value).split(`
|
|
290
290
|
`);a=t.pop();for(let e of t){if(!e)continue;let t=JSON.parse(e);if(t.type===`error`)throw Error(t.error);n(t),t.type===`done`&&(o=!0)}}if(!o)throw Error(`搜索连接提前断开,结果可能不完整。`)}finally{await i.cancel().catch(()=>void 0),i.releaseLock()}}function Zh(e,t){return{path:t?e.startsWith(t+`/`)?e.slice(t.length+1):bh+e:e,name:e.split(`/`).at(-1)??e,text:!0}}function Qh(e,t,n){return{...Zh(t?t+`/`+e.path:e.path,n),name:e.name}}var $h=new Map;function eg({workspaceId:e,cwd:t=``,directory:n,initialQuery:r=``,initialReplace:i=!1,onOpen:a,onClose:o,onMode:s,presentation:c,dirtyPaths:l=[]}){let u=JSON.stringify([e,t,n??``]),[d]=(0,p.useState)(()=>{let e=$h.get(u);return e&&(!r||r===e.query)?e:void 0}),f=(0,p.useRef)(!!d),[h,g]=(0,p.useState)(r||d?.query||``),[_,v]=(0,p.useState)(d?.root??n??``),[y,b]=(0,p.useState)(d?.include??``),[x,S]=(0,p.useState)(d?.exclude??``),[C,w]=(0,p.useState)(d?.ignore??!0),[T,E]=(0,p.useState)(d?.caseSensitive??!1),[D,O]=(0,p.useState)(d?.wholeWord??!1),[k,A]=(0,p.useState)(d?.regexp??!1),[j,ee]=(0,p.useState)(0),[M,N]=(0,p.useState)(i||d?.replaceOpen||!1),[P,F]=(0,p.useState)(d?.replacement??``),[I,te]=(0,p.useState)(d?.preserveCase??!1),[ne,re]=(0,p.useState)(!1),[ie,ae]=(0,p.useState)(),[oe,se]=(0,p.useState)([]),[ce,le]=(0,p.useState)(``),[ue,de]=(0,p.useState)(d?.hits??[]),[fe,pe]=(0,p.useState)(d?.summary),[L,me]=(0,p.useState)(d?.visible??Yh),[he,ge]=(0,p.useState)(d?.error??``),[_e,ve]=(0,p.useState)(!1),[ye,be]=(0,p.useState)(!1),[xe,Se]=(0,p.useState)(d?.selected??0),{choose:Ce,openError:we,opening:Te,setOpenError:Ee}=Jh(a,o),De=!!Oh(h),Oe=(0,p.useRef)(null),ke=(0,p.useRef)(null),Ae=(0,p.useRef)(void 0),je=(0,p.useId)(),Me=(0,p.useRef)(null),Ne=(0,p.useRef)(d?.scrollTop??0);(0,p.useEffect)(()=>{i&&N(!0)},[i]),(0,p.useEffect)(()=>{let e=e=>{!e.altKey||e.ctrlKey||e.metaKey||e.isComposing||!Me.current?.closest(`[data-content-search]`)?.contains(document.activeElement)||(e.key.toLowerCase()===`c`?(e.preventDefault(),E(e=>!e)):e.key.toLowerCase()===`w`?(e.preventDefault(),O(e=>!e)):e.key.toLowerCase()===`r`&&(e.preventDefault(),A(e=>!e)))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]),(0,p.useEffect)(()=>{Oe.current?.focus(),Oe.current?.select()},[]),(0,p.useEffect)(()=>{ke.current?.scrollIntoView({block:`nearest`})},[xe]),(0,p.useEffect)(()=>{if(f.current){f.current=!1;return}let t=h,n=new AbortController;if(Ae.current=n,de([]),pe(void 0),ge(``),be(!1),me(Yh),Se(0),!e||!t){ve(!1);return}if(t.length>4096){ge(`搜索词不能超过 4096 个字符。`),ve(!1);return}let r=new URLSearchParams({workspaceId:e,q:t,stream:`1`,ignore:C?`1`:`0`});r.set(`case`,T?`1`:`0`),r.set(`word`,D?`1`:`0`),r.set(`regex`,k?`1`:`0`),_&&r.set(`cwd`,_),y.trim()&&r.set(`include`,y.trim()),x.trim()&&r.set(`exclude`,x.trim()),ve(!0);let i=setTimeout(()=>{n.signal.aborted||Xh(`/api/files/search?`+r,n.signal,e=>{n.signal.aborted||(e.type===`matches`?de(t=>[...t,...e.hits]):e.type===`done`&&pe(e.summary))}).catch(e=>{n.signal.aborted||ge(zr(e,`搜索没有完成`))}).finally(()=>{n.signal.aborted||ve(!1)})},220);return()=>{n.abort(),clearTimeout(i)}},[h,e,_,y,x,C,T,D,k,j]),(0,p.useEffect)(()=>{$h.delete(u),$h.set(u,{query:h,root:_,include:y,exclude:x,ignore:C,caseSensitive:T,wholeWord:D,regexp:k,replacement:P,replaceOpen:M,preserveCase:I,hits:ue,summary:fe,visible:L,selected:xe,error:he,scrollTop:Ne.current}),$h.size>12&&$h.delete($h.keys().next().value)},[u,h,_,y,x,C,T,D,k,P,M,I,ue,fe,L,xe,he]),(0,p.useEffect)(()=>{let e=requestAnimationFrame(()=>{Me.current&&(Me.current.scrollTop=Ne.current)});return()=>cancelAnimationFrame(e)},[]);let Pe=(0,p.useMemo)(()=>{let e=new Map;return ue.slice(0,L).forEach((t,n)=>{let r=e.get(t.path);r?r.push({hit:t,row:n}):e.set(t.path,[{hit:t,row:n}])}),[...e]},[ue,L]),Fe=e=>{e&&Ce(Qh(e,_,t),e.line,e.column)},Ie=fe?.complete===!1;(0,p.useEffect)(()=>{ae(void 0),le(``)},[h,_,y,x,C,T,D,k,P,I]);let Le=async t=>{let n=new URLSearchParams({workspaceId:e});return _&&n.set(`cwd`,_),hh(`/api/files/replace?`+n,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})},Re=async()=>{if(e&&!ne){re(!0),ge(``),le(``);try{let e=await Le({action:`preview`,query:h,replacement:P,include:y,exclude:x,ignore:C,caseSensitive:T,wholeWord:D,regexp:k,preserveCase:I});ae(e),se(e.files.flatMap(e=>e.matches.map(e=>e.id)))}catch(e){ge(zr(e,`替换预览失败`))}finally{re(!1)}}},ze=async e=>{if(!ie||ne||!e.length)return;let n=ie.files.filter(n=>n.matches.some(t=>e.includes(t.id))&&l.includes(Qh({path:n.path,name:n.path,line:1,column:1,text:``},_,t).path));if(n.length)ge(`这些文件有未保存编辑,请先保存或排除:${n.map(e=>e.path).join(`、`)}`);else{re(!0),ge(``);try{let t=await Le({action:`apply`,id:ie.id,selected:e});ae(void 0),le(`已替换 ${t.applied.length} 个文件`),t.failed.length&&ge(t.failed.map(e=>`${e.path}:${e.error}`).join(`;`)),ee(e=>e+1)}catch(e){ge(zr(e,`替换失败,请重新预览`))}finally{re(!1)}}},Be={time:`搜索超时`,results:`达到全局结果上限`,line:`部分行太长`,encoding:`部分文件的编码无法读取`,unreadable:`部分文件无法读取`};return(0,m.jsxs)(Lp,{mode:`content`,query:h,onMode:s,onClose:o,presentation:c,children:[(0,m.jsx)(`textarea`,{ref:Oe,rows:Math.min(4,h.split(`
|
|
291
291
|
`).length),className:`quick-open-input`,"data-content-search-input":`1`,value:h,readOnly:Te,placeholder:`搜索文件内容(Ctrl+Enter 换行)`,role:`combobox`,"aria-label":`内容搜索`,"aria-autocomplete":`list`,"aria-controls":je,"aria-expanded":ue.length>0,"aria-activedescendant":ue[xe]?`${je}-${xe}`:void 0,onChange:e=>{g(e.target.value),Ee(``)},onKeyDown:e=>{if(!e.nativeEvent.isComposing){if(e.key===`Enter`&&(e.ctrlKey||e.metaKey)){e.preventDefault();let t=e.currentTarget.selectionStart,n=e.currentTarget.selectionEnd;g(e=>e.slice(0,t)+`
|
|
292
292
|
`+e.slice(n)),requestAnimationFrame(()=>Oe.current?.setSelectionRange(t+1,t+1))}else e.key===`ArrowDown`?(e.preventDefault(),Se(e=>Math.min(e+1,Math.max(0,Math.min(L,ue.length)-1)))):e.key===`ArrowUp`?(e.preventDefault(),Se(e=>Math.max(0,e-1))):e.key===`Enter`&&(e.preventDefault(),Fe(ue[xe]))}}}),(0,m.jsxs)(`div`,{className:`content-search-controls`,children:[(0,m.jsx)(Up,{value:{caseSensitive:T,wholeWord:D,regexp:k},onToggle:e=>{e===`caseSensitive`&&E(e=>!e),e===`wholeWord`&&O(e=>!e),e===`regexp`&&A(e=>!e)}}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`刷新搜索结果`,disabled:_e||!h.trim(),onClick:()=>ee(e=>e+1),children:`刷新`}),(0,m.jsx)(`button`,{type:`button`,"data-content-replace-toggle":!0,"aria-expanded":M,onClick:()=>N(e=>!e),children:`替换`}),(0,m.jsxs)(`label`,{children:[`范围 `,(0,m.jsxs)(`select`,{value:_,"aria-label":`搜索范围`,onChange:e=>v(e.target.value),children:[(0,m.jsx)(`option`,{value:``,children:`整个工作区`}),t&&(0,m.jsxs)(`option`,{value:t,children:[`当前目录 · `,t]}),n&&n!==t&&(0,m.jsxs)(`option`,{value:n,children:[`文件夹 · `,n]})]})]}),_e&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>{Ae.current?.abort(),Oe.current?.focus(),ve(!1),be(!0)},children:`取消搜索`})]}),M&&(0,m.jsxs)(`div`,{className:`content-replace-controls`,children:[(0,m.jsx)(`textarea`,{rows:Math.min(4,P.split(`
|
|
293
|
-
`).length),"aria-label":`替换为`,value:P,placeholder:`替换为(留空表示删除匹配内容)`,onChange:e=>F(e.target.value),disabled:ne}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:I,onChange:e=>te(e.target.checked)}),`保留大小写`]}),(0,m.jsx)(`button`,{type:`button`,"data-content-replace-preview":!0,disabled:!h||ne||_e,onClick:()=>void Re(),children:ne?`处理中…`:`预览替换`})]}),ce&&(0,m.jsx)(`p`,{role:`status`,children:ce}),ie&&(0,m.jsxs)(`section`,{className:`content-replace-preview`,"aria-label":`替换预览`,children:[(0,m.jsxs)(`header`,{children:[(0,m.jsxs)(`strong`,{children:[ie.count,` 处匹配 · `,ie.files.length,` 个文件`]}),(0,m.jsxs)(`button`,{type:`button`,"data-content-replace-apply":`selected`,disabled:ne||!oe.length,onClick:()=>void ze(oe),children:[`替换选中 (`,oe.length,`)`]}),(0,m.jsx)(`button`,{type:`button`,"data-content-replace-apply":`all`,disabled:ne||!ie.count,onClick:()=>void ze(ie.files.flatMap(e=>e.matches.map(e=>e.id))),children:`替换全部`})]}),ie.files.map(e=>(0,m.jsxs)(`details`,{children:[(0,m.jsxs)(`summary`,{title:e.path,children:[e.path,` · `,e.matches.length,` 处 `,(0,m.jsx)(`button`,{type:`button`,disabled:ne,onClick:t=>{t.preventDefault(),ze(e.matches.map(e=>e.id))},children:`替换此文件`})]}),e.matches.map(e=>(0,m.jsxs)(`div`,{className:`content-replace-match`,children:[(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:oe.includes(e.id),onChange:t=>se(n=>t.target.checked?[...n,e.id]:n.filter(t=>t!==e.id))}),e.line,`:`,e.column]}),(0,m.jsxs)(`code`,{children:[(0,m.jsx)(`del`,{children:e.before||`(空匹配)`}),(0,m.jsx)(`ins`,{children:e.after||`(删除)`})]}),(0,m.jsx)(`button`,{type:`button`,disabled:ne,onClick:()=>void ze([e.id]),children:`替换此项`})]},e.id))]},e.path))]}),(0,m.jsxs)(`details`,{className:`content-search-filters`,children:[(0,m.jsx)(`summary`,{children:`文件筛选`}),(0,m.jsxs)(`label`,{children:[`包含 `,(0,m.jsx)(`input`,{"aria-label":`包含文件`,value:y,onChange:e=>b(e.target.value),placeholder:`例如 src/, **/*.{cpp,h}`})]}),(0,m.jsxs)(`label`,{children:[`排除 `,(0,m.jsx)(`input`,{"aria-label":`排除文件`,value:x,onChange:e=>S(e.target.value),placeholder:`例如 **/generated/**, **/*.min.js`})]}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),` 遵循忽略文件和默认排除`]})]}),(0,m.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"data-content-search-status":he?`error`:_e?`searching`:ye?`cancelled`:Ie?`partial`:`complete`,children:[he?`搜索失败:`+he:_e?`搜索中…`:ye?`已取消`:e?Ie?`结果不完整`:fe?`搜索完成`:`输入要搜索的内容`:`请先选择工作区`,(ue.length>0||fe)&&` · ${ue.length} 条命中`]}),De&&(0,m.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,onClick:()=>s(`path`,h),children:`按文件路径打开`}),Ie&&(0,m.jsx)(`p`,{className:`quick-open-status`,"data-content-search-partial":`1`,children:fe.reasons.map(e=>Be[e]??e).join(`;`)}),fe?.complete&&!ue.length&&(0,m.jsx)(`p`,{className:`quick-open-status`,"data-content-search-empty":`1`,children:`没有匹配的行`}),we&&(0,m.jsx)(`p`,{className:`quick-open-status`,role:`alert`,children:we}),(0,m.jsx)(`ul`,{ref:Me,onScroll:e=>{Ne.current=e.currentTarget.scrollTop;let t=$h.get(u);t&&(t.scrollTop=Ne.current)},id:je,className:`quick-open-results content-search-results`,role:`listbox`,"aria-label":`正文搜索结果`,children:Pe.map(([e,t])=>(0,m.jsxs)(`li`,{className:`content-search-group`,role:`presentation`,children:[(0,m.jsx)(`div`,{className:`content-search-file`,title:e,children:e}),t.map(({hit:e,row:t})=>(0,m.jsxs)(`button`,{id:`${je}-${t}`,ref:t===xe?ke:void 0,type:`button`,role:`option`,tabIndex:-1,"data-content-search-result":`${e.path}:${e.line}`,className:`quick-open-result content-search-result${xe===t?` quick-open-result-active`:``}`,"aria-selected":xe===t,"aria-label":`${e.path}:${e.line}:${e.column} ${e.text}`,onMouseEnter:()=>Se(t),onClick:()=>Fe(e),children:[(0,m.jsxs)(`span`,{title:`${e.path}:${e.line}:${e.column}`,className:`content-search-result-position`,children:[e.line,`:`,e.column]}),(0,m.jsx)(`small`,{title:e.text,children:e.text})]},e.line))]},e))}),ue.length>L&&(0,m.jsxs)(`button`,{className:`workbench-search-path-link`,type:`button`,"data-content-search-more":`1`,onClick:()=>{L+Yh>=ue.length&&Oe.current?.focus(),me(e=>e+Yh)},children:[`显示更多结果(已显示 `,L,` / `,ue.length,`)`]})]})}function tg({workspaceId:e,cwd:t=``,connected:n,initialQuery:r=``,onOpen:i,onClose:a,onMode:o,presentation:s}){let[c,l]=(0,p.useState)(r),[u,d]=(0,p.useState)(0),[f,h]=(0,p.useState)(0),[g,_]=(0,p.useState)(),v=(0,p.useRef)(void 0),y=(0,p.useRef)(void 0),{choose:b,openError:x,opening:S,setOpenError:C}=Jh(i,a),w=(0,p.useRef)(null),T=(0,p.useRef)(null),E=kh(c),D=e?Oh(c):void 0,O=!!D;(0,p.useEffect)(()=>{if(!n||!e)return;let r=new AbortController,i=wh(e,``,t)+`&quick=1&refresh=1`;return v.current=hh(i,{cache:`no-store`,signal:r.signal}).catch(()=>void 0),()=>{r.abort(),v.current=void 0}},[n,e,t]),(0,p.useEffect)(()=>{if(!n||!e||O)return;let r=new AbortController,i=r.signal,a=wh(e,E,t)+`&quick=1&page=${f}`,o,s=async e=>{try{let t=e?await v.current:void 0;if(i.aborted)return;let n=e&&!E&&t?t:await hh(a,{cache:`no-store`,signal:i});if(i.aborted)return;_({query:E,page:f,response:n}),n.indexed||(o=setTimeout(()=>void s(!1),350))}catch(e){i.aborted||_({query:E,page:f,error:zr(e,`文件查找没有完成`)})}};return o=setTimeout(()=>void s(!0),E?120:0),()=>{r.abort(),clearTimeout(o)}},[n,e,t,E,O,f]);let k=g?.query===E&&g.page===f?g:void 0,A=k?.response,j=(0,p.useMemo)(()=>{if(D)return[D];let t=A?.hits.map(e=>({...e,text:null}))??[];return f>0||e&&E.includes(`/`)&&!E.endsWith(`/`)&&!E.split(`/`).includes(`..`)&&!t.some(e=>e.path.toLowerCase()===E.toLowerCase())&&(A?.total?t.push(Dh(E)):t.unshift(Dh(E))),t},[D,E,A,f,e]),ee=e=>{y.current=void 0,h(e),_(void 0),d(0),C(``),w.current?.focus()},M=!O&&!(!e||k?.error||A?.indexed);return(0,p.useEffect)(()=>{let e=y.current;e===void 0||M||(y.current=void 0,b(j[Math.min(e,j.length-1)]))},[M,j,b]),(0,p.useEffect)(()=>{w.current?.focus()},[]),(0,p.useEffect)(()=>{T.current?.scrollIntoView({block:`nearest`})},[u]),(0,m.jsxs)(Lp,{mode:`path`,query:c,onMode:o,onClose:a,presentation:s,children:[(0,m.jsx)(`input`,{ref:w,className:`quick-open-input`,"data-quick-open-input":`1`,value:c,readOnly:S,placeholder:`快速打开:输入文件名或路径`,"aria-label":`快速打开文件路径`,onChange:e=>{let t=e.target.value;y.current=void 0,(kh(t)!==E||f!==0)&&_(void 0),l(t),h(0),d(0),C(``)},onKeyDown:e=>{if(!e.nativeEvent.isComposing){if(e.key===`ArrowDown`)e.preventDefault(),d(e=>Math.min(e+1,Math.max(0,j.length-1)));else if(e.key===`ArrowUp`)e.preventDefault(),d(e=>Math.max(e-1,0));else if(e.key===`Enter`){e.preventDefault();let t=j[Math.min(u,j.length-1)],n=A?.hits.some(e=>e.path===t?.path&&[e.name,e.path].some(e=>e.toLowerCase()===E.toLowerCase()));M&&!n?y.current=u:b(t)}}}}),(0,m.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"aria-live":`polite`,"data-quick-open-status":O||A?.indexed&&!A.incomplete?`complete`:`partial`,children:[O?`按 Enter 打开指定文件`:e?n?k?.error||(M?`正在检查文件索引…`:E?A?.incomplete?`索引不完整 · ${A.total} 条命中`:A?.total?`${A.total} 条命中${f?` · 第 ${f+1} 页`:``}`:j.length?`近似路径`:`没有匹配的文件名或路径`:`输入文件名或路径以查找当前目录中的文件`):`等待连接…`:`请先选择工作区`,` · Esc 关闭`]}),x&&(0,m.jsx)(`p`,{className:`quick-open-status`,role:`alert`,children:x}),(0,m.jsx)(`ul`,{className:`quick-open-results`,role:`listbox`,children:j.map((e,t)=>(0,m.jsx)(`li`,{children:(0,m.jsxs)(`button`,{ref:t===u?T:void 0,type:`button`,"data-quick-open-result":e.path,className:t===u?`quick-open-result quick-open-result-active`:`quick-open-result`,"aria-selected":t===u,onMouseMove:()=>d(t),onClick:()=>{y.current=void 0,b(e)},children:[(0,m.jsx)(`span`,{title:e.name,children:e.name}),(0,m.jsx)(`small`,{title:e.path,children:e.path})]})},e.path))}),E&&A?.indexed&&(f>0||A.truncated)&&(0,m.jsxs)(`div`,{className:`quick-open-pages`,"aria-label":`文件搜索翻页`,children:[f>0&&(0,m.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,onClick:()=>ee(f-1),children:`上一页`}),A.truncated&&(0,m.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,"data-quick-open-next-page":!0,onClick:()=>ee(f+1),children:`下一页`})]})]})}function ng({workspaceId:e,workspaceName:t,cwd:n,connected:r,onOpen:i,onSession:a,active:o=!0,dirtyPaths:s=[]}){let[c,l]=(0,p.useState)(`content`),[u,d]=(0,p.useState)(``),f=(0,p.useRef)(null);(0,p.useEffect)(()=>{if(!o)return;let e=requestAnimationFrame(()=>f.current?.parentElement?.querySelector(`[data-content-search-input], [data-quick-open-input], [data-session-search-input]`)?.focus());return()=>cancelAnimationFrame(e)},[o,c]);let h={workspaceId:e,cwd:n,initialQuery:u,presentation:`sidebar`,onClose:()=>{},onMode:(e,t)=>{d(t),l(e)}};return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{ref:f,className:`workbench-search-heading`,children:[(0,m.jsx)(Ni,{id:`search`,children:`搜索`}),(0,m.jsx)(`span`,{title:t,children:t??`请选择工作区`}),(0,m.jsx)(Pi,{id:`search`})]}),c===`content`?(0,m.jsx)(eg,{...h,onOpen:i,dirtyPaths:s}):c===`path`?(0,m.jsx)(tg,{...h,connected:r,onOpen:i}):(0,m.jsx)(Rp,{...h,onOpen:a})]})}function rg(e,t,n){if(!t)return[];let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=new RegExp(n.regexp?t:r,n.caseSensitive?`gmu`:`gmiu`),a=/[\p{L}\p{N}\p{M}\p{Pc}]/u,o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),s=[];for(;o.nextNode();){let e=o.currentNode,t=e.parentElement;if(!t||!e.data||t.closest(`script,style,textarea,input,select,[hidden],[aria-hidden="true"],.katex-mathml,button:not([data-message-source-link])`))continue;let n=t.closest(`details:not([open])`);if(n&&!n.querySelector(`summary`)?.contains(t))continue;let r=t.closest(`.diff-line-syntax-raw,p,pre,li,td,th,h1,h2,h3,h4,h5,h6,summary,[data-transcript-key]`);if(!r)continue;let i=s.at(-1);(!i||i.block!==r)&&(i={block:r,nodes:[],text:``},s.push(i)),i.nodes.push(e),i.text+=e.data}let c=[];for(let e of s){let t=0,r=0;for(let o of e.text.matchAll(i)){let i=o.index,s=i+o[0].length;if(i===s)continue;let l=Array.from(e.text.slice(Math.max(0,i-2),i)).at(-1),u=Array.from(e.text.slice(s,s+2))[0],d=Array.from(o[0])[0],f=Array.from(o[0]).at(-1);if(n.wholeWord&&(l&&a.test(l)&&a.test(d)||u&&a.test(u)&&a.test(f)))continue;for(;t<e.nodes.length-1&&i>=r+e.nodes[t].length;)r+=e.nodes[t++].length;let p=document.createRange();p.setStart(e.nodes[t],i-r);let m=t,h=r;for(;m<e.nodes.length-1&&s>h+e.nodes[m].length;)h+=e.nodes[m++].length;p.setEnd(e.nodes[m],s-h),p.getClientRects().length&&c.push(p)}}return c}var ig=new Map;function ag(e,t,n){if(typeof Highlight>`u`||!CSS.highlights)return;let r=ig.get(e)??new Map;n?r.set(t,n):r.delete(t),r.size?(ig.set(e,r),CSS.highlights.set(e,new Highlight(...[...r.values()].flatMap(e=>e.matches))),CSS.highlights.set(e+`-current`,new Highlight(...[...r.values()].flatMap(e=>e.current?[e.current]:[])))):(ig.delete(e),CSS.highlights.delete(e),CSS.highlights.delete(e+`-current`))}function og(e,t,n){if(!n||!t.length)return 0;let r=new Map,i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),a=0;for(;i.nextNode();)r.set(i.currentNode,a),a+=i.currentNode.textContent?.length??0;let o=(t,n)=>{let i=r.get(t);if(i!==void 0)return i+n;let a=document.createRange();return a.selectNodeContents(e),a.setEnd(t,n),a.toString().length},s=n.range,c=s&&e.contains(s.startContainer)?o(s.startContainer,s.startOffset):void 0,l=e.getBoundingClientRect(),u=0,d=1/0;return t.forEach((t,r)=>{let i=c===void 0?0:o(t.startContainer,t.startOffset),a=c===void 0?0:o(t.endContainer,t.endOffset),s=c===void 0?Math.abs(t.getBoundingClientRect().top-l.top+e.scrollTop-n.top):c>=a?c-a+1:Math.max(i-c,0);s<d&&(u=r,d=s)}),u}function sg({container:e,onNavigate:t,mode:n=`transcript`}){let r=n===`diff`?`diff-find`:`transcript-find`,i=(0,p.useRef)(Symbol(`find`)),a=n===`diff`?`当前差异`:`当前会话`,[o,s]=(0,p.useState)(!1),[c,l]=(0,p.useState)(``),[u,d]=(0,p.useState)(!1),[f,h]=(0,p.useState)(!1),[g,_]=(0,p.useState)(!1),[v,y]=(0,p.useState)(``),[b,x]=(0,p.useState)([]),[S,C]=(0,p.useState)(0),[w,T]=(0,p.useState)({top:0,right:0,width:0}),E=(0,p.useRef)(null),D=(0,p.useRef)(null),O=(0,p.useRef)(null),k=(0,p.useRef)(void 0),A=(0,p.useRef)(void 0),[j,ee]=(0,p.useState)(0),M=(0,p.useRef)(t);M.current=t;let N=(0,p.useCallback)(()=>{s(!1),D.current?.isConnected&&D.current.focus({preventScroll:!0})},[]);(0,p.useEffect)(()=>{let t=t=>{if(t.defaultPrevented||t.isComposing||t.altKey)return;let r=e.current,i=t.target;if(r?.getClientRects().length&&(!i.closest(`.transcript-find`)||O.current?.contains(i))&&(n!==`transcript`||!i.closest(`.messages`)||r.contains(i))){if(n===`diff`){let e=r?.closest(`.git-diff-editor`),n=t.target;if(!e||!r?.getClientRects().length||!e.contains(n)&&!e.closest(`.chat[data-main-view="diff"]`)||!e.contains(n)&&n.closest(`input,textarea,[contenteditable="true"],.messages,.chat-file-view`))return}if((t.ctrlKey||t.metaKey)&&!t.shiftKey&&t.key.toLowerCase()===`f`){if(t.target?.closest(`.cm-editor,.workbench-editor-search,.xterm,[role="dialog"],.modal`))return;t.preventDefault();let e=window.getSelection();if(!r)return;let n=e&&e.rangeCount>0&&r.contains(e.anchorNode)&&r.contains(e.focusNode);(n||!o)&&(A.current={range:n?e.getRangeAt(0).cloneRange():void 0,top:r.scrollTop+r.clientHeight/3},x([]),k.current=void 0,ee(e=>e+1)),n&&!e.isCollapsed&&l(e.toString()),o||(D.current=document.activeElement),s(!0),requestAnimationFrame(()=>{E.current?.focus(),E.current?.select()})}else o&&t.key===`Escape`&&(t.preventDefault(),N())}};return window.addEventListener(`keydown`,t,n===`diff`),()=>window.removeEventListener(`keydown`,t,n===`diff`)},[N,o,n]),(0,p.useLayoutEffect)(()=>{let t=e.current;if(!o||!t)return;let n=()=>{let e=t.getBoundingClientRect();T({top:e.top+8,right:window.innerWidth-e.right+12,width:Math.max(0,e.width-24)})};n();let r=new ResizeObserver(n);return r.observe(t),window.addEventListener(`resize`,n),()=>{r.disconnect(),window.removeEventListener(`resize`,n)}},[e,o]),(0,p.useEffect)(()=>{let t=e.current;if(!o||!t){x([]);return}let n,r=()=>{try{let e=rg(t,c,{caseSensitive:u,wholeWord:f,regexp:g});y(``),x(e),C(og(t,e,A.current))}catch{y(`正则表达式无效`),x([]),C(0)}};r();let i=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(r,100)});return i.observe(t,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`open`,`hidden`]}),()=>{clearTimeout(n),i.disconnect()}},[e,o,c,u,f,g,j]);let P=b.length?Math.min(S,b.length-1):0;if((0,p.useEffect)(()=>{let e=i.current;return ag(r,e,o?{matches:b,current:b[P]}:void 0),()=>ag(r,e)},[o,b,P,r]),(0,p.useEffect)(()=>{let t=e.current,n=b[P];if(!o||!t||!n){k.current=void 0;return}let r=k.current;if(r?.node===n.startContainer&&r.offset===n.startOffset&&r.end===n.endOffset)return;k.current={node:n.startContainer,offset:n.startOffset,end:n.endOffset},A.current={range:n.cloneRange(),top:t.scrollTop+t.clientHeight/3};let i=n.getBoundingClientRect(),a=t.getBoundingClientRect();t.scrollTop+=i.top-a.top-a.height/3,M.current(t)},[e,o,b,P]),!o)return null;let F=e=>C((P+e+b.length)%(b.length||1));return(0,m.jsxs)(`div`,{ref:O,className:`transcript-find`,role:`search`,"aria-label":`${a}页内查找`,style:{top:w.top,right:w.right,maxWidth:w.width},onKeyDown:e=>{let t=Vp(e.nativeEvent);t&&(e.preventDefault(),e.stopPropagation(),t===`caseSensitive`&&d(e=>!e),t===`wholeWord`&&h(e=>!e),t===`regexp`&&_(e=>!e)),e.key===`F3`&&(e.preventDefault(),e.stopPropagation(),F(e.shiftKey?-1:1))},children:[(0,m.jsx)(`input`,{ref:E,"aria-label":`查找${a}`,placeholder:`查找${a}…`,value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),F(e.shiftKey?-1:1))}}),(0,m.jsx)(Up,{value:{caseSensitive:u,wholeWord:f,regexp:g},onToggle:e=>{e===`caseSensitive`&&d(e=>!e),e===`wholeWord`&&h(e=>!e),e===`regexp`&&_(e=>!e)}}),(0,m.jsx)(`output`,{"aria-live":`polite`,"data-transcript-find-count":!0,children:c?b.length?`${P+1} / ${b.length}`:`无结果`:`0 / 0`}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`上一个匹配`,title:`上一个匹配(Shift+Enter)`,disabled:!b.length,onClick:()=>F(-1),children:`↑`}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`下一个匹配`,title:`下一个匹配(Enter)`,disabled:!b.length,onClick:()=>F(1),children:`↓`}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`关闭页内查找`,title:`关闭(Esc)`,onClick:N,children:`×`}),v&&(0,m.jsx)(`output`,{className:`transcript-find-error`,role:`alert`,"data-find-error":!0,children:v})]})}function cg(e,t,n,r,i){let a=Number.isFinite(t)&&t>0?t:n,o=e.map(e=>({id:e.id,width:Math.min(a,Math.max(Math.min(n,a),Number.isFinite(e.width)?e.width:n))}));if(o.every(e=>e.width<=i.width)){let t=[];for(let n=0;n<e.length;n+=Math.max(1,i.perRow))t.push({ids:e.slice(n,n+Math.max(1,i.perRow)).map(e=>e.id),width:Math.min(a,i.width)});return t}let s=[],c=[],l=0,u=()=>{c.length&&(s.push({ids:c.map(e=>e.id),width:Math.min(a/c.length,Math.max(r,l))}),c=[],l=0)};for(let e of o)c.length&&Math.max(l,e.width)*(c.length+1)>a+.1&&u(),c.push(e),l=Math.max(l,e.width);return u(),s}function lg(e,t,n=88,r=200){let i=Math.max(0,Math.floor(e));if(!Number.isFinite(t)||t<=0)return{perRow:Math.max(1,i),width:n};if(i===0)return{perRow:1,width:n};if(i===1)return{perRow:1,width:Math.min(r,t)};let a=t/i;if(a>=n)return{perRow:i,width:Math.min(a,r)};for(let e=2;e<=i;e+=1){let a=Math.ceil(i/e),o=t/a;if(o>=n)return{perRow:a,width:Math.min(o,r)}}return{perRow:1,width:n}}function ug(e,t,n=88,r=200){let[i,a]=(0,p.useState)(()=>lg(e,0,n,r)),[o,s]=(0,p.useState)(null),c=(0,p.useCallback)(()=>{let i=lg(e,t,n,r);s({count:e,containerWidth:t}),a(e=>e.perRow===i.perRow&&e.width===i.width?e:i)},[e,t,n,r]),l=(0,p.useRef)(t);(0,p.useLayoutEffect)(()=>{t<=0||l.current!==t&&(l.current=t,c())},[t,c]);let u=(0,p.useRef)(null);return(0,p.useLayoutEffect)(()=>{let t=u.current;u.current=e,t!==null&&e>t&&c()},[e,c]),{layout:i,frozen:o!==null&&o.count!==e,recompute:c}}function dg({tabs:e,activeId:t,onSelect:n,onClose:r,onActivate:i,ariaLabel:a,minWidth:o=88,maxWidth:s=200,prefix:c=`workspace-tab`,idPrefix:l=c,className:u}){let d=(0,p.useRef)(null),[f,h]=(0,p.useState)(0),{layout:g,frozen:_,recompute:v}=ug(e.length,f,o,s);(0,p.useLayoutEffect)(()=>{let e=d.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.clientWidth;t>0&&h(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let[y,b]=(0,p.useState)({}),[x,S]=(0,p.useState)([]),C=JSON.stringify(e.map(e=>[e.id,e.label]));(0,p.useLayoutEffect)(()=>{let e=d.current;if(!e)return;let t=()=>{let t={};for(let n of e.querySelectorAll(`[role=tab]`)){let e=n.querySelector(`.workspace-tab-label`),r=n.id.slice(l.length+1);if(!e||!r)continue;let i=document.createRange();i.selectNodeContents(e);let a=n.getBoundingClientRect().width-e.getBoundingClientRect().width;t[r]=Math.ceil(i.getBoundingClientRect().width+a+2)}b(e=>JSON.stringify(e)===JSON.stringify(t)?e:t)};return t(),document.fonts?.addEventListener(`loadingdone`,t),()=>document.fonts?.removeEventListener(`loadingdone`,t)},[C,f,l]);let w=cg(e.map(e=>({id:e.id,width:y[e.id]??o})),f,o,s,g),T=JSON.stringify(w);(0,p.useLayoutEffect)(()=>{_||S(e=>JSON.stringify(e)===T?e:w)},[_,T]);let E=x.length&&e.every(e=>x.some(t=>t.ids.includes(e.id)))?x:w,D=0,O=E.map(t=>{let n=_?e.slice(D,D+=t.ids.length):t.ids.flatMap(t=>{let n=e.find(e=>e.id===t);return n?[n]:[]});return{...t,tabs:n}}).filter(e=>e.tabs.length),k=O.map(e=>e.tabs),A=O.map(e=>e.width),j=(e,t)=>t===void 0?{}:{[`data-${c}-${e}`]:t},ee=e.filter(e=>e.kind===`file`).length,M=e.filter(e=>e.kind===`session`||!e.kind).length,N=t=>({[`data-${t}-strip`]:`1`,..._?{[`data-${t}-frozen`]:`1`}:{},[`data-${t}-count`]:t===`file-tab`?ee:t===`session-tab`?M:e.length,[`data-${t}-min`]:o,[`data-${t}-max`]:s,[`data-${t}-per-row`]:k[0]?.length??g.perRow,[`data-${t}-width`]:Math.round((A[0]??g.width)*100)/100}),P=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&v()},F=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&v()};(0,p.useEffect)(()=>{if(!_)return;let e=d.current;if(!e)return;let t=t=>{let n=e.getBoundingClientRect();t.clientX>=n.left&&t.clientX<=n.right&&t.clientY>=n.top&&t.clientY<=n.bottom||v()};return document.addEventListener(`mousemove`,t,!0),()=>document.removeEventListener(`mousemove`,t,!0)},[_,v]);let I=[`${c}-strip`,`workspace-tab-strip`,`session-tab-strip`,`file-tab-strip`,u].filter(Boolean).join(` `);return(0,m.jsx)(`div`,{ref:d,className:I,role:`tablist`,"aria-label":a??`工作区标签页`,...j(`strip`,`1`),...N(`workspace-tab`),...N(`session-tab`),...N(`file-tab`),style:{"--tab-w":`${g.width}px`},onMouseEnter:P,onMouseLeave:F,children:k.map((a,o)=>(0,m.jsx)(`div`,{className:`${c}-row workspace-tab-row session-tab-row file-tab-row`,role:`presentation`,...j(`row`,o),"data-tab-row-width":A[o],children:a.map(a=>{let s={width:A[o]},u=a.id===t||a.rawId!==void 0&&a.rawId===t,d=a.title?a.title.includes(a.label)?a.title:`${a.label}\n${a.title}`:a.label,f=a.kind,p=a.rawId??a.id,h=e.findIndex(e=>e.id===a.id),g=[c,u?`${c}-active`:``,`workspace-tab`,u?`workspace-tab-active`:``,f?`${f}-tab`:``,f&&u?`${f}-tab-active`:``,a.preview?`${c}-preview`:``,a.preview?`workspace-tab-preview`:``,a.preview&&f?`${f}-tab-preview`:``].filter(Boolean).join(` `);return(0,m.jsxs)(`div`,{role:`tab`,id:`${l}-${a.id}`,"aria-selected":u,"aria-controls":`${l}-panel-${a.id}`,tabIndex:u?0:-1,className:g,...j(`id`,p),...j(`index`,h),...u?j(`active`,`1`):{},...j(`closable`,a.closable===!1?`0`:`1`),...f?{"data-tab-kind":f}:{},...a.preview?{"data-tab-preview":`1`}:{},...f===`session`||!f?{"data-session-tab-id":p,"data-session-tab-index":h,...u?{"data-session-tab-active":`1`}:{},"data-session-tab-closable":a.closable===!1?`0`:`1`,...a.preview?{"data-session-tab-preview":`1`}:{}}:{},...f===`file`?{"data-file-tab-id":p,"data-file-tab-index":h,...u?{"data-file-tab-active":`1`}:{},"data-file-tab-closable":a.closable===!1?`0`:`1`}:{},...f===`diff`?{"data-diff-tab-id":p,"data-diff-tab-index":h,...u?{"data-diff-tab-active":`1`}:{},"data-diff-tab-closable":a.closable===!1?`0`:`1`}:{},title:d,style:{width:s.width,boxSizing:`border-box`},onClick:()=>n?.(a.id),onDoubleClick:i?()=>i(a.id):void 0,onAuxClick:e=>{e.button===1&&(e.preventDefault(),e.stopPropagation(),a.closable!==!1&&r&&r(a.id))},onMouseDown:e=>{e.button===1&&e.preventDefault()},onKeyDown:t=>{if(t.key!==`ArrowLeft`&&t.key!==`ArrowRight`)return;t.preventDefault();let r=t.key===`ArrowRight`?1:-1,i=e[(e.findIndex(e=>e.id===a.id)+r+e.length)%e.length];i&&(document.getElementById(`${l}-${i.id}`)?.focus(),n?.(i.id))},children:[a.icon&&(0,m.jsx)(`span`,{className:`${c}-icon workspace-tab-icon`,children:a.icon}),a.badge,(0,m.jsx)(`span`,{className:`${c}-label workspace-tab-label ${f?`${f}-tab-label`:``}`,title:d,...j(`label`,p),...f===`session`||!f?{"data-session-tab-label":p}:{},...f===`file`?{"data-file-tab-label":p}:{},...f===`diff`?{"data-diff-tab-label":p}:{},children:a.label}),a.closable!==!1&&r&&(0,m.jsx)(`button`,{type:`button`,className:`${c}-close workspace-tab-close ${f?`${f}-tab-close`:``}`,...j(`close`,p),...f===`session`||!f?{"data-session-tab-close":p}:{},...f===`file`?{"data-file-tab-close":p}:{},...f===`diff`?{"data-diff-tab-close":p}:{},onClick:e=>{e.stopPropagation(),r(a.id)},onDoubleClick:e=>{e.stopPropagation()},title:`关闭 ${d}`,"aria-label":`关闭 ${d}`,children:`×`})]},a.id)})},`row_${o}`))})}var fg=25,pg=75;function mg({share:e,onShare:t}){let n=(0,p.useRef)(null),[r,i]=(0,p.useState)(!1),a=e=>t(Math.round(Math.min(pg,Math.max(fg,e))));return(0,p.useLayoutEffect)(()=>{let e=n.current?.parentElement;if(!e)return;let t=()=>i(getComputedStyle(e).flexDirection===`column`);t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[]),(0,m.jsx)(`div`,{ref:n,className:`workbench-split-divider`,"data-workbench-split-divider":!0,role:`separator`,"aria-label":`调整拆分大小`,"aria-orientation":r?`horizontal`:`vertical`,"aria-valuenow":e,"aria-valuemin":fg,"aria-valuemax":pg,tabIndex:0,onPointerDown:e=>{e.button===0&&(e.currentTarget.focus(),e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{if(!e.currentTarget.hasPointerCapture(e.pointerId))return;let t=e.currentTarget.parentElement?.getBoundingClientRect();t&&a(r?(e.clientY-t.top)/t.height*100:(e.clientX-t.left)/t.width*100)},onKeyDown:t=>{let n=t.key===(r?`ArrowDown`:`ArrowRight`),i=t.key===(r?`ArrowUp`:`ArrowLeft`);if(n||i)a(e+(n?5:-5));else if(t.key===`Home`)a(fg);else if(t.key===`End`)a(pg);else return;t.preventDefault()}})}function hg({tabs:e,selected:t,onSelect:n,onPin:r,onCloseTab:i,onClose:a,children:o}){let s=e.find(e=>e.id===t);return(0,m.jsxs)(`section`,{className:`workbench-split-pane`,"data-workbench-split-pane":!0,"aria-label":`拆分区`,children:[(0,m.jsxs)(`div`,{className:`workbench-split-bar`,children:[(0,m.jsxs)(`select`,{"aria-label":`拆分区标签页`,"data-workbench-split-tabs":!0,value:t??``,onChange:e=>n(e.target.value),title:s?.title,"data-workbench-split-preview":s?.preview||void 0,children:[(0,m.jsx)(`option`,{value:``,disabled:!0,children:`选择文件或差异`}),e.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.label},e.id))]}),t&&s?.preview&&(0,m.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,title:`固定标签页`,"aria-label":`固定拆分区标签页`,onClick:()=>r(t),children:(0,m.jsx)(vi,{name:`pin`})}),t&&(0,m.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,title:`关闭此标签页`,"aria-label":`关闭拆分区标签页`,onClick:()=>i(t),children:(0,m.jsx)(vi,{name:`close`})}),(0,m.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,"data-close-workbench-split":!0,title:`合并主区`,"aria-label":`合并主区`,onClick:a,children:(0,m.jsx)(vi,{name:`split`})})]}),o??(0,m.jsx)(`p`,{className:`rail-empty`,children:`从文件或 Git 面板打开一个文件或差异。`})]})}function gg(e,t){return!!e&&!!t&&e.key===t.key&&e.position?.line===t.position?.line&&e.position?.column===t.position?.column}function _g(e,t){let n=e.entries[e.index];if(gg(n,t))return e;if(n?.key===t.key&&(!t.position||!n.position||!t.explicitPosition&&Math.abs(t.position.line-n.position.line)<5)){if(!t.position)return e;let n=[...e.entries];return n[e.index]=t,{entries:n,index:e.index}}let r=[...e.entries.slice(0,e.index+1),t].slice(-100);return{entries:r,index:r.length-1}}function vg(e,t,n,r){for(let i=t+n;i>=0&&i<e.entries.length;i+=n)if(r(e.entries[i]))return i;return-1}var yg={pending:`未开始`,running:`运行中`,completed:`已完成`,failed:`失败`,skipped:`已跳过`,stopped:`已停止`},bg={running:`运行中`,completed:`全部完成`,failed:`中途失败`,stopped:`已停止`},xg={pending:`○`,running:`◐`,completed:`✓`,failed:`✕`,skipped:`→`,stopped:`■`},Sg={stop:`失败即停`,skip:`失败跳过`,"retry:1":`失败重试 1 次`,"retry:2":`失败重试 2 次`,"retry:3":`失败重试 3 次`};function Cg(e){let t=Math.max(0,Math.round(e/1e3)),n=t%60,r=Math.floor(t/60)%60,i=Math.floor(t/3600),a=e=>String(e).padStart(2,`0`);return i>0?`${i}h ${a(r)}:${a(n)}`:`${r}:${a(n)}`}function wg(e){let t=e.status===`running`,[n,r]=(0,p.useState)(0);(0,p.useEffect)(()=>{if(!t)return;r(Date.now());let e=window.setInterval(()=>r(Date.now()),200);return()=>window.clearInterval(e)},[t,e.startedAt]);let i=Date.parse(e.startedAt);if(Number.isFinite(i)){if(!t){let t=Date.parse(e.finishedAt??``);return Number.isFinite(t)?t-i:void 0}return n>0?n-i:void 0}}function Tg({step:e,names:t}){let n=e.attempts.length,r=e.attempts[n-1],i=t.get(e.agentId)||e.agentId,a=e.label?.trim()||i;return(0,m.jsxs)(`li`,{className:`workflow-step workflow-step-${e.status}`,"data-workflow-step":e.index+1,"data-workflow-step-status":e.status,"data-workflow-step-agent":e.agentId,"data-workflow-step-attempts":n,children:[(0,m.jsx)(`span`,{className:`workflow-step-mark`,"aria-hidden":`true`,children:xg[e.status]}),(0,m.jsxs)(`span`,{className:`workflow-step-n`,"data-workflow-step-n":e.index+1,children:[`第 `,e.index+1,` 步`]}),(0,m.jsx)(`strong`,{className:`workflow-step-name`,"data-workflow-step-name":e.index+1,children:a}),(0,m.jsx)(`span`,{className:`workflow-step-agent`,"data-workflow-step-agent-name":e.index+1,children:i}),n>1&&(0,m.jsxs)(`span`,{className:`workflow-step-tries`,"data-workflow-step-retried":e.index+1,children:[`尝试 `,n,` 次`]}),(0,m.jsx)(`span`,{className:`workflow-step-status`,"data-workflow-step-status-text":e.index+1,children:yg[e.status]}),e.status===`failed`&&r?.error&&(0,m.jsx)(`span`,{className:`workflow-step-why`,"data-workflow-step-error":e.index+1,title:Br(r.error),children:zr(r.error,`这一步没有完成。`)})]})}function Eg({nodes:e,steps:t,names:n}){return(0,m.jsx)(`ol`,{className:`workflow-steps`,children:e.map((e,r)=>{if(e.kind===`step`){let r=t[e.stepIndex];return r?(0,m.jsx)(Tg,{step:r,names:n},`step-${e.stepIndex}`):null}return e.kind===`loop`?(0,m.jsxs)(`li`,{className:`workflow-node workflow-loop`,"data-workflow-loop":!0,"data-workflow-loop-rounds":e.rounds.length,"data-workflow-loop-max":e.max,"data-workflow-until":e.until,children:[(0,m.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`↻`}),(0,m.jsx)(`strong`,{children:`循环`}),(0,m.jsxs)(`span`,{children:[`直到「`,e.until,`」`]}),(0,m.jsxs)(`span`,{"data-workflow-loop-progress":!0,children:[`已跑 `,e.rounds.length,`/`,e.max,` 轮`]})]}),e.rounds.map(e=>(0,m.jsxs)(`section`,{className:`workflow-round`,"data-workflow-round":e.n,"data-workflow-round-met":e.untilMet?`true`:`false`,children:[(0,m.jsxs)(`div`,{className:`workflow-round-head`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:e.untilMet?`✓`:`○`}),`第 `,e.n,` 轮 · `,e.untilMet?`条件满足`:`条件未满足`]}),(0,m.jsx)(Eg,{nodes:e.nodes,steps:t,names:n})]},e.n))]},`loop-${r}`):(0,m.jsxs)(`li`,{className:`workflow-node workflow-foreach`,"data-workflow-foreach":!0,"data-workflow-foreach-count":e.items.length,children:[(0,m.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`≡`}),(0,m.jsx)(`strong`,{children:`逐项执行`}),(0,m.jsxs)(`span`,{children:[e.items.length,` 个由 primary 给出的项目`]})]}),e.iterations.map((e,r)=>(0,m.jsxs)(`section`,{className:`workflow-item`,"data-workflow-item":r+1,"data-workflow-item-value":e.item,children:[(0,m.jsxs)(`div`,{className:`workflow-item-head`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),`第 `,r+1,` 项 · `,e.item]}),(0,m.jsx)(Eg,{nodes:e.nodes,steps:t,names:n})]},`${r}-${e.item}`))]},`foreach-${r}`)})})}function Dg({workflow:e,names:t,onStop:n,stopping:r}){let i=e.status===`running`,a=wg(e),o=e.steps.filter(e=>e.status===`completed`||e.status===`skipped`).length;return(0,m.jsxs)(`article`,{className:`workflow-card workflow-${e.status}`,"data-workflow-card":e.id,"data-workflow-status":e.status,"data-workflow-steps":e.steps.length,"data-workflow-current":e.currentIndex+1,children:[(0,m.jsxs)(`div`,{className:`workflow-head`,children:[(0,m.jsx)(`span`,{className:`workflow-badge`,children:`编排`}),(0,m.jsx)(`strong`,{className:`workflow-summary`,"data-workflow-summary":e.id,children:e.summary}),(0,m.jsxs)(`span`,{className:`workflow-progress`,"data-workflow-progress":e.id,children:[o,`/`,e.steps.length]}),(0,m.jsx)(`span`,{className:`workflow-status`,"data-workflow-status-text":e.id,children:bg[e.status]??`未知状态`}),(0,m.jsx)(`span`,{className:`workflow-policy`,"data-workflow-policy":e.onFailure,children:Sg[e.onFailure]??e.onFailure}),a!==void 0&&(0,m.jsxs)(`span`,{className:`workflow-clock`,"data-workflow-elapsed":e.id,children:[i?`已运行 `:`用时 `,Cg(a)]}),i&&(0,m.jsx)(`button`,{type:`button`,className:`workflow-stop`,"data-workflow-stop":e.id,disabled:r,onClick:n,children:`停止`})]}),e.nodes?(0,m.jsx)(Eg,{nodes:e.nodes,steps:e.steps,names:t}):(0,m.jsx)(`ol`,{className:`workflow-steps`,"data-workflow-step-count":e.steps.length,children:e.steps.map(e=>(0,m.jsx)(Tg,{step:e,names:t},e.index))})]})}var Og=[{id:`agents`,label:`智能体与创建`,icon:`🤖`,title:`Agent 智能体系统与创建指南`,description:`了解 Super Pi 的角色设定机制,以及如何一步步创建你自己的自定义 Agent。`},{id:`workspace`,label:`工作区与会话`,icon:`🗂️`,title:`工作区与多会话管理`,description:`高效管理本地代码仓库、独立会话标签页与多模态图文输入。`},{id:`subagents`,label:`子任务与编排`,icon:`⚡`,title:`子智能体委托与顺序编排使用指南`,description:`让主 Agent 安排分工、交接结果,并查看进度、处理失败与停止任务。`},{id:`model-policy`,label:`模型使用规则`,icon:`🔒`,title:`模型过滤规则(按工作区限制可用模型)`,description:`用正则规则限定哪些工作区只能用哪些模型,防止敏感代码被发到不该用的模型上。`},{id:`memory`,label:`主动记忆`,icon:`🧠`,title:`主动记忆与技能经验`,description:`让 Super Pi 在得到明确证据后保存长期事实、用户偏好和可复用工作方法。`},{id:`knowledge`,label:`知识库`,icon:`📚`,title:`工作区知识库`,description:`导入规范与设计文档,让 Agent 检索原文作答,而不是凭记忆编造。`},{id:`feishu`,label:`飞书`,icon:`📄`,title:`飞书云文档的读写`,description:`让 Agent 读一篇飞书文档、写回结论。接入方式、连接步骤与常见问题。`},{id:`tools`,label:`侧边栏工具`,icon:`🧩`,title:`全局工具:开发、导出与导入`,description:`让 Agent 写一个工具,用一个文件分享给别人,导入前先看清它会做什么。`},{id:`cli`,label:`指令与快捷键`,icon:`⌨️`,title:`Pi 终端命令与键盘快捷操作`,description:`利用 Pi 终端斜杠指令控制服务生命周期,掌握常用快捷键提升效率。`},{id:`themes`,label:`外观与主题`,icon:`🎨`,title:`界面主题与个性化显示`,description:`内置 4 款专业高对比度主题,针对不同环境提供舒适体验。`}];function kg({onClose:e}){let[t,n]=(0,p.useState)(`agents`);(0,p.useEffect)(()=>{let t=t=>{t.key===`Escape`&&!t.defaultPrevented&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let r=Og.find(e=>e.id===t)??Og[0];return(0,m.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,m.jsxs)(`div`,{className:`picker settings-window help-window`,"data-help-window":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-labelledby":`help-window-title`,children:[(0,m.jsxs)(`div`,{className:`settings-window-head help-window-head`,children:[(0,m.jsxs)(`div`,{className:`help-head-title`,children:[(0,m.jsx)(`h2`,{id:`help-window-title`,children:`使用指南与帮助`}),(0,m.jsx)(`span`,{className:`help-badge`,children:`v0.1.x`})]}),(0,m.jsx)(`button`,{type:`button`,className:`help-close-button`,"aria-label":`关闭指南`,onClick:e,children:`✕`})]}),(0,m.jsxs)(`div`,{className:`settings-window-body help-window-body`,children:[(0,m.jsxs)(`nav`,{className:`settings-nav help-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`使用指南分类`,children:[(0,m.jsx)(`div`,{className:`settings-nav-label`,children:`目录`}),Og.map(e=>(0,m.jsxs)(`button`,{type:`button`,id:`help-tab-${e.id}`,className:`settings-category help-category`,role:`tab`,"aria-selected":e.id===r.id,"aria-controls":`help-panel`,tabIndex:e.id===r.id?0:-1,onClick:()=>n(e.id),children:[(0,m.jsx)(`span`,{className:`help-tab-icon`,"aria-hidden":`true`,children:e.icon}),(0,m.jsx)(`span`,{children:e.label})]},e.id))]}),(0,m.jsxs)(`div`,{id:`help-panel`,className:`settings-panel help-panel`,role:`tabpanel`,"aria-labelledby":`help-tab-${r.id}`,children:[(0,m.jsxs)(`div`,{className:`help-panel-header`,children:[(0,m.jsx)(`h3`,{className:`help-panel-title`,children:r.title}),(0,m.jsx)(`p`,{className:`help-panel-desc`,children:r.description})]}),(0,m.jsxs)(`div`,{className:`help-panel-content`,children:[r.id===`agents`&&(0,m.jsx)(Mg,{}),r.id===`workspace`&&(0,m.jsx)(Ng,{}),r.id===`subagents`&&(0,m.jsx)(Fg,{}),r.id===`model-policy`&&(0,m.jsx)(Pg,{}),r.id===`memory`&&(0,m.jsx)(Ag,{}),r.id===`knowledge`&&(0,m.jsx)(jg,{}),r.id===`feishu`&&(0,m.jsx)(Ig,{}),r.id===`tools`&&(0,m.jsx)(Lg,{}),r.id===`cli`&&(0,m.jsx)(Rg,{}),r.id===`themes`&&(0,m.jsx)(zg,{})]}),(0,m.jsx)(`div`,{className:`picker-actions help-actions`,children:(0,m.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e,children:`关闭`})})]})]})]})})}function Ag(){return(0,m.jsxs)(`div`,{className:`help-section-group`,children:[(0,m.jsxs)(`div`,{className:`help-card highlight`,children:[(0,m.jsx)(`h4`,{children:`🧠 它会记住什么?`}),(0,m.jsx)(`p`,{children:`用户档案保存跨工作区的长期偏好;工作区事实保存环境与项目约定;技能保存已经验证过的步骤、命令和坑。临时结果、秘密和未验证的失败不会保存。`})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`主动保存与后台复盘`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsxs)(`li`,{children:[`主 Agent 可以使用 `,(0,m.jsx)(`code`,{children:`memory`}),` 和 `,(0,m.jsx)(`code`,{children:`skill_manage`}),` 工具主动保存;说“记住了”本身不会写入。`]}),(0,m.jsx)(`li`,{children:`每隔若干回合,系统会在独立会话中复盘最近证据。复盘不能读写工作区文件、执行命令或派发任务。`}),(0,m.jsx)(`li`,{children:`读取记忆和历史只返回带来源的参考数据,不能把记忆中的文字当作新的指令。`})]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`权限与审批`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsx)(`li`,{children:`子 Agent 可以读取相关记忆,但没有写入权限。`}),(0,m.jsx)(`li`,{children:`后台复盘新增记忆可以直接保存;修改或删除旧条目会进入设置中的待审批列表。`}),(0,m.jsx)(`li`,{children:`在“设置 → 主动记忆”可以开关功能、调整复盘间隔、编辑条目和批准提案。`})]})]})]})}function jg(){return(0,m.jsxs)(`div`,{className:`help-section-group`,children:[(0,m.jsxs)(`div`,{className:`help-card highlight`,children:[(0,m.jsx)(`h4`,{children:`📚 它解决什么问题?`}),(0,m.jsx)(`p`,{children:`Agent 默认靠训练时的记忆回答项目里的问题。知识库让你把规范、设计稿、会议纪要导入工作区,Agent 在回答前检索这些文档的原文片段,而不是凭印象编造。它与“主动记忆”不同:记忆是 Agent 自己沉淀的事实和技能,知识库的内容来自工作区里真实存在的文档。`})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`怎么用`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsxs)(`li`,{children:[`在“设置 → 知识库”里点“浏览工作区文件…”,在弹出的浏览器里挑一个 Markdown 或文本文件,挑完即导入。也可以直接粘贴正文、手动填写相对路径,或者直接对 Agent 说“把某某文件加入知识库”——它会用 `,(0,m.jsx)(`code`,{children:`knowledge_import`}),` 导入,走的是同一条服务端校验。`]}),(0,m.jsx)(`li`,{children:`同一个文件内容改了再导入就是更新,不会留下旧版本;同样的内容换个标题再导入也不会变成两篇。`}),(0,m.jsx)(`li`,{children:`面板里的“试检索”会用和 Agent 相同的检索器回答,方便你在交给 Agent 之前先确认它找得到。`}),(0,m.jsxs)(`li`,{children:[`从下一条消息开始生效。Agent 使用 `,(0,m.jsx)(`code`,{children:`knowledge_search`}),` 检索,只拿得到片段和来源,拿不到整篇文档。`]})]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`语义检索是内置的`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsxs)(`li`,{children:[`关键词检索始终可用。语义检索让“撤销购买”也能找到写着“取消订单”的段落,它靠一个`,(0,m.jsx)(`strong`,{children:`随安装包一起分发`}),`的中文模型在本机运行,不需要额外下载、不需要联网、也不会把文档发到任何服务。`]}),(0,m.jsxs)(`li`,{children:[`第一次检索时加载模型(约一秒),之后一直可用。设 `,(0,m.jsx)(`code`,{children:`SUPER_PI_KNOWLEDGE_EMBEDDINGS=0`}),` 可以彻底关闭语义检索,只保留关键词检索。`]})]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`它不知道的事`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsx)(`li`,{children:`知识库只会检索它有的东西。文档里没写的,它检索出来也不会有——所以导入什么,直接决定它能回答什么。`}),(0,m.jsx)(`li`,{children:`语义检索总会返回“最接近的那一段”,即使这一段其实并不回答问题。检索结果带一个分数,低分意味着这可能只是最像的一条,Agent 会被要求先核对再使用。`}),(0,m.jsxs)(`li`,{children:[`Agent 可以按你的要求把工作区文件导入知识库(`,(0,m.jsx)(`code`,{children:`knowledge_import`}),`,只接受文本类文件),但`,(0,m.jsx)(`strong`,{children:`不能删除`}),`——删除文档只有你能在“设置 → 知识库”里做。`]})]})]})]})}function Mg(){return(0,m.jsxs)(`div`,{className:`help-section-group`,children:[(0,m.jsxs)(`div`,{className:`help-card highlight`,children:[(0,m.jsx)(`h4`,{children:`💡 Agent 是什么?`}),(0,m.jsxs)(`p`,{children:[`在 Super Pi 中,`,(0,m.jsx)(`strong`,{children:`Agent(智能体)`}),` 是一套独立的「角色提示词设定与能力配置」。 通过切换 Agent,模型将扮演专精工程师、系统架构师、代码审查员或规划专家等不同角色,遵循指定的原则来协助你完成任务。`]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`📁 Agent 文件存放在哪里?`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsxs)(`li`,{children:[(0,m.jsx)(`strong`,{children:`内置 Agent 目录:`}),`项目根目录下的 `,(0,m.jsx)(`code`,{children:`agents/`}),` 文件夹,例如 `,(0,m.jsx)(`code`,{children:`agents/coder.md`}),`、`,(0,m.jsx)(`code`,{children:`agents/planner.md`}),`、`,(0,m.jsx)(`code`,{children:`agents/reviewer.md`}),` 等。`]}),(0,m.jsxs)(`li`,{children:[(0,m.jsx)(`strong`,{children:`用户自定义持久化目录:`}),`用户主目录下的 `,(0,m.jsx)(`code`,{children:`~/.super-pi/agents/`}),`,放入此目录的文件在所有项目和更新中均持久有效。`]})]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`🚀 如何创建一个全新的自定义 Agent?`}),(0,m.jsxs)(`div`,{className:`help-steps`,children:[(0,m.jsxs)(`div`,{className:`help-step`,children:[(0,m.jsx)(`span`,{className:`step-num`,children:`1`}),(0,m.jsxs)(`div`,{className:`step-body`,children:[(0,m.jsx)(`strong`,{children:`创建 Markdown 文件`}),(0,m.jsxs)(`p`,{children:[`在 `,(0,m.jsx)(`code`,{children:`agents/`}),` 或 `,(0,m.jsx)(`code`,{children:`~/.super-pi/agents/`}),` 目录下新建文件,例如 `,(0,m.jsx)(`code`,{children:`architect.md`}),`。`]})]})]}),(0,m.jsxs)(`div`,{className:`help-step`,children:[(0,m.jsx)(`span`,{className:`step-num`,children:`2`}),(0,m.jsxs)(`div`,{className:`step-body`,children:[(0,m.jsx)(`strong`,{children:`编写元数据与系统提示词`}),(0,m.jsx)(`p`,{children:`文件开头使用 YAML Frontmatter 声明名称和描述,正文编写设定提示词:`}),(0,m.jsx)(`pre`,{className:`help-code-block`,children:(0,m.jsx)(`code`,{children:`---
|
|
293
|
+
`).length),"aria-label":`替换为`,value:P,placeholder:`替换为(留空表示删除匹配内容)`,onChange:e=>F(e.target.value),disabled:ne}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:I,onChange:e=>te(e.target.checked)}),`保留大小写`]}),(0,m.jsx)(`button`,{type:`button`,"data-content-replace-preview":!0,disabled:!h||ne||_e,onClick:()=>void Re(),children:ne?`处理中…`:`预览替换`})]}),ce&&(0,m.jsx)(`p`,{role:`status`,children:ce}),ie&&(0,m.jsxs)(`section`,{className:`content-replace-preview`,"aria-label":`替换预览`,children:[(0,m.jsxs)(`header`,{children:[(0,m.jsxs)(`strong`,{children:[ie.count,` 处匹配 · `,ie.files.length,` 个文件`]}),(0,m.jsxs)(`button`,{type:`button`,"data-content-replace-apply":`selected`,disabled:ne||!oe.length,onClick:()=>void ze(oe),children:[`替换选中 (`,oe.length,`)`]}),(0,m.jsx)(`button`,{type:`button`,"data-content-replace-apply":`all`,disabled:ne||!ie.count,onClick:()=>void ze(ie.files.flatMap(e=>e.matches.map(e=>e.id))),children:`替换全部`})]}),ie.files.map(e=>(0,m.jsxs)(`details`,{children:[(0,m.jsxs)(`summary`,{title:e.path,children:[e.path,` · `,e.matches.length,` 处 `,(0,m.jsx)(`button`,{type:`button`,disabled:ne,onClick:t=>{t.preventDefault(),ze(e.matches.map(e=>e.id))},children:`替换此文件`})]}),e.matches.map(e=>(0,m.jsxs)(`div`,{className:`content-replace-match`,children:[(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:oe.includes(e.id),onChange:t=>se(n=>t.target.checked?[...n,e.id]:n.filter(t=>t!==e.id))}),e.line,`:`,e.column]}),(0,m.jsxs)(`code`,{children:[(0,m.jsx)(`del`,{children:e.before||`(空匹配)`}),(0,m.jsx)(`ins`,{children:e.after||`(删除)`})]}),(0,m.jsx)(`button`,{type:`button`,disabled:ne,onClick:()=>void ze([e.id]),children:`替换此项`})]},e.id))]},e.path))]}),(0,m.jsxs)(`details`,{className:`content-search-filters`,children:[(0,m.jsx)(`summary`,{children:`文件筛选`}),(0,m.jsxs)(`label`,{children:[`包含 `,(0,m.jsx)(`input`,{"aria-label":`包含文件`,value:y,onChange:e=>b(e.target.value),placeholder:`例如 src/, **/*.{cpp,h}`})]}),(0,m.jsxs)(`label`,{children:[`排除 `,(0,m.jsx)(`input`,{"aria-label":`排除文件`,value:x,onChange:e=>S(e.target.value),placeholder:`例如 **/generated/**, **/*.min.js`})]}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:C,onChange:e=>w(e.target.checked)}),` 遵循忽略文件和默认排除`]})]}),(0,m.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"data-content-search-status":he?`error`:_e?`searching`:ye?`cancelled`:Ie?`partial`:`complete`,children:[he?`搜索失败:`+he:_e?`搜索中…`:ye?`已取消`:e?Ie?`结果不完整`:fe?`搜索完成`:`输入要搜索的内容`:`请先选择工作区`,(ue.length>0||fe)&&` · ${ue.length} 条命中`]}),De&&(0,m.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,onClick:()=>s(`path`,h),children:`按文件路径打开`}),Ie&&(0,m.jsx)(`p`,{className:`quick-open-status`,"data-content-search-partial":`1`,children:fe.reasons.map(e=>Be[e]??e).join(`;`)}),fe?.complete&&!ue.length&&(0,m.jsx)(`p`,{className:`quick-open-status`,"data-content-search-empty":`1`,children:`没有匹配的行`}),we&&(0,m.jsx)(`p`,{className:`quick-open-status`,role:`alert`,children:we}),(0,m.jsx)(`ul`,{ref:Me,onScroll:e=>{Ne.current=e.currentTarget.scrollTop;let t=$h.get(u);t&&(t.scrollTop=Ne.current)},id:je,className:`quick-open-results content-search-results`,role:`listbox`,"aria-label":`正文搜索结果`,children:Pe.map(([e,t])=>(0,m.jsxs)(`li`,{className:`content-search-group`,role:`presentation`,children:[(0,m.jsx)(`div`,{className:`content-search-file`,title:e,children:e}),t.map(({hit:e,row:t})=>(0,m.jsxs)(`button`,{id:`${je}-${t}`,ref:t===xe?ke:void 0,type:`button`,role:`option`,tabIndex:-1,"data-content-search-result":`${e.path}:${e.line}`,className:`quick-open-result content-search-result${xe===t?` quick-open-result-active`:``}`,"aria-selected":xe===t,"aria-label":`${e.path}:${e.line}:${e.column} ${e.text}`,onMouseEnter:()=>Se(t),onClick:()=>Fe(e),children:[(0,m.jsxs)(`span`,{title:`${e.path}:${e.line}:${e.column}`,className:`content-search-result-position`,children:[e.line,`:`,e.column]}),(0,m.jsx)(`small`,{title:e.text,children:e.text})]},e.line))]},e))}),ue.length>L&&(0,m.jsxs)(`button`,{className:`workbench-search-path-link`,type:`button`,"data-content-search-more":`1`,onClick:()=>{L+Yh>=ue.length&&Oe.current?.focus(),me(e=>e+Yh)},children:[`显示更多结果(已显示 `,L,` / `,ue.length,`)`]})]})}function tg({workspaceId:e,cwd:t=``,connected:n,initialQuery:r=``,onOpen:i,onClose:a,onMode:o,presentation:s}){let[c,l]=(0,p.useState)(r),[u,d]=(0,p.useState)(0),[f,h]=(0,p.useState)(0),[g,_]=(0,p.useState)(),v=(0,p.useRef)(void 0),y=(0,p.useRef)(void 0),{choose:b,openError:x,opening:S,setOpenError:C}=Jh(i,a),w=(0,p.useRef)(null),T=(0,p.useRef)(null),E=kh(c),D=e?Oh(c):void 0,O=!!D;(0,p.useEffect)(()=>{if(!n||!e)return;let r=new AbortController,i=wh(e,``,t)+`&quick=1&refresh=1`;return v.current=hh(i,{cache:`no-store`,signal:r.signal}).catch(()=>void 0),()=>{r.abort(),v.current=void 0}},[n,e,t]),(0,p.useEffect)(()=>{if(!n||!e||O)return;let r=new AbortController,i=r.signal,a=wh(e,E,t)+`&quick=1&page=${f}`,o,s=async e=>{try{let t=e?await v.current:void 0;if(i.aborted)return;let n=e&&!E&&t?t:await hh(a,{cache:`no-store`,signal:i});if(i.aborted)return;_({query:E,page:f,response:n}),n.indexed||(o=setTimeout(()=>void s(!1),350))}catch(e){i.aborted||_({query:E,page:f,error:zr(e,`文件查找没有完成`)})}};return o=setTimeout(()=>void s(!0),E?120:0),()=>{r.abort(),clearTimeout(o)}},[n,e,t,E,O,f]);let k=g?.query===E&&g.page===f?g:void 0,A=k?.response,j=(0,p.useMemo)(()=>{if(D)return[D];let t=A?.hits.map(e=>({...e,text:null}))??[];return f>0||e&&E.includes(`/`)&&!E.endsWith(`/`)&&!E.split(`/`).includes(`..`)&&!t.some(e=>e.path.toLowerCase()===E.toLowerCase())&&(A?.total?t.push(Dh(E)):t.unshift(Dh(E))),t},[D,E,A,f,e]),ee=e=>{y.current=void 0,h(e),_(void 0),d(0),C(``),w.current?.focus()},M=!O&&!(!e||k?.error||A?.indexed);return(0,p.useEffect)(()=>{let e=y.current;e===void 0||M||(y.current=void 0,b(j[Math.min(e,j.length-1)]))},[M,j,b]),(0,p.useEffect)(()=>{w.current?.focus()},[]),(0,p.useEffect)(()=>{T.current?.scrollIntoView({block:`nearest`})},[u]),(0,m.jsxs)(Lp,{mode:`path`,query:c,onMode:o,onClose:a,presentation:s,children:[(0,m.jsx)(`input`,{ref:w,className:`quick-open-input`,"data-quick-open-input":`1`,value:c,readOnly:S,placeholder:`快速打开:输入文件名或路径`,"aria-label":`快速打开文件路径`,onChange:e=>{let t=e.target.value;y.current=void 0,(kh(t)!==E||f!==0)&&_(void 0),l(t),h(0),d(0),C(``)},onKeyDown:e=>{if(!e.nativeEvent.isComposing){if(e.key===`ArrowDown`)e.preventDefault(),d(e=>Math.min(e+1,Math.max(0,j.length-1)));else if(e.key===`ArrowUp`)e.preventDefault(),d(e=>Math.max(e-1,0));else if(e.key===`Enter`){e.preventDefault();let t=j[Math.min(u,j.length-1)],n=A?.hits.some(e=>e.path===t?.path&&[e.name,e.path].some(e=>e.toLowerCase()===E.toLowerCase()));M&&!n?y.current=u:b(t)}}}}),(0,m.jsxs)(`p`,{className:`quick-open-status`,role:`status`,"aria-live":`polite`,"data-quick-open-status":O||A?.indexed&&!A.incomplete?`complete`:`partial`,children:[O?`按 Enter 打开指定文件`:e?n?k?.error||(M?`正在检查文件索引…`:E?A?.incomplete?`索引不完整 · ${A.total} 条命中`:A?.total?`${A.total} 条命中${f?` · 第 ${f+1} 页`:``}`:j.length?`近似路径`:`没有匹配的文件名或路径`:`输入文件名或路径以查找当前目录中的文件`):`等待连接…`:`请先选择工作区`,` · Esc 关闭`]}),x&&(0,m.jsx)(`p`,{className:`quick-open-status`,role:`alert`,children:x}),(0,m.jsx)(`ul`,{className:`quick-open-results`,role:`listbox`,children:j.map((e,t)=>(0,m.jsx)(`li`,{children:(0,m.jsxs)(`button`,{ref:t===u?T:void 0,type:`button`,"data-quick-open-result":e.path,className:t===u?`quick-open-result quick-open-result-active`:`quick-open-result`,"aria-selected":t===u,onMouseMove:()=>d(t),onClick:()=>{y.current=void 0,b(e)},children:[(0,m.jsx)(`span`,{title:e.name,children:e.name}),(0,m.jsx)(`small`,{title:e.path,children:e.path})]})},e.path))}),E&&A?.indexed&&(f>0||A.truncated)&&(0,m.jsxs)(`div`,{className:`quick-open-pages`,"aria-label":`文件搜索翻页`,children:[f>0&&(0,m.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,onClick:()=>ee(f-1),children:`上一页`}),A.truncated&&(0,m.jsx)(`button`,{className:`workbench-search-path-link`,type:`button`,"data-quick-open-next-page":!0,onClick:()=>ee(f+1),children:`下一页`})]})]})}function ng({workspaceId:e,workspaceName:t,cwd:n,connected:r,onOpen:i,onSession:a,dirtyPaths:o=[]}){let{visible:s}=ki(`search`),[c,l]=(0,p.useState)(`content`),[u,d]=(0,p.useState)(``),f=(0,p.useRef)(null);(0,p.useEffect)(()=>{if(!s)return;let e=requestAnimationFrame(()=>f.current?.parentElement?.querySelector(`[data-content-search-input], [data-quick-open-input], [data-session-search-input]`)?.focus());return()=>cancelAnimationFrame(e)},[s,c]);let h={workspaceId:e,cwd:n,initialQuery:u,presentation:`sidebar`,onClose:()=>{},onMode:(e,t)=>{d(t),l(e)}};return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{ref:f,className:`workbench-search-heading`,children:[(0,m.jsx)(Ni,{id:`search`,children:`搜索`}),(0,m.jsx)(`span`,{title:t,children:t??`请选择工作区`}),(0,m.jsx)(Pi,{id:`search`})]}),c===`content`?(0,m.jsx)(eg,{...h,onOpen:i,dirtyPaths:o}):c===`path`?(0,m.jsx)(tg,{...h,connected:r,onOpen:i}):(0,m.jsx)(Rp,{...h,onOpen:a})]})}function rg(e,t,n){if(!t)return[];let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=new RegExp(n.regexp?t:r,n.caseSensitive?`gmu`:`gmiu`),a=/[\p{L}\p{N}\p{M}\p{Pc}]/u,o=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),s=[];for(;o.nextNode();){let e=o.currentNode,t=e.parentElement;if(!t||!e.data||t.closest(`script,style,textarea,input,select,[hidden],[aria-hidden="true"],.katex-mathml,button:not([data-message-source-link])`))continue;let n=t.closest(`details:not([open])`);if(n&&!n.querySelector(`summary`)?.contains(t))continue;let r=t.closest(`.diff-line-syntax-raw,p,pre,li,td,th,h1,h2,h3,h4,h5,h6,summary,[data-transcript-key]`);if(!r)continue;let i=s.at(-1);(!i||i.block!==r)&&(i={block:r,nodes:[],text:``},s.push(i)),i.nodes.push(e),i.text+=e.data}let c=[];for(let e of s){let t=0,r=0;for(let o of e.text.matchAll(i)){let i=o.index,s=i+o[0].length;if(i===s)continue;let l=Array.from(e.text.slice(Math.max(0,i-2),i)).at(-1),u=Array.from(e.text.slice(s,s+2))[0],d=Array.from(o[0])[0],f=Array.from(o[0]).at(-1);if(n.wholeWord&&(l&&a.test(l)&&a.test(d)||u&&a.test(u)&&a.test(f)))continue;for(;t<e.nodes.length-1&&i>=r+e.nodes[t].length;)r+=e.nodes[t++].length;let p=document.createRange();p.setStart(e.nodes[t],i-r);let m=t,h=r;for(;m<e.nodes.length-1&&s>h+e.nodes[m].length;)h+=e.nodes[m++].length;p.setEnd(e.nodes[m],s-h),p.getClientRects().length&&c.push(p)}}return c}var ig=new Map;function ag(e,t,n){if(typeof Highlight>`u`||!CSS.highlights)return;let r=ig.get(e)??new Map;n?r.set(t,n):r.delete(t),r.size?(ig.set(e,r),CSS.highlights.set(e,new Highlight(...[...r.values()].flatMap(e=>e.matches))),CSS.highlights.set(e+`-current`,new Highlight(...[...r.values()].flatMap(e=>e.current?[e.current]:[])))):(ig.delete(e),CSS.highlights.delete(e),CSS.highlights.delete(e+`-current`))}function og(e,t,n){if(!n||!t.length)return 0;let r=new Map,i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),a=0;for(;i.nextNode();)r.set(i.currentNode,a),a+=i.currentNode.textContent?.length??0;let o=(t,n)=>{let i=r.get(t);if(i!==void 0)return i+n;let a=document.createRange();return a.selectNodeContents(e),a.setEnd(t,n),a.toString().length},s=n.range,c=s&&e.contains(s.startContainer)?o(s.startContainer,s.startOffset):void 0,l=e.getBoundingClientRect(),u=0,d=1/0;return t.forEach((t,r)=>{let i=c===void 0?0:o(t.startContainer,t.startOffset),a=c===void 0?0:o(t.endContainer,t.endOffset),s=c===void 0?Math.abs(t.getBoundingClientRect().top-l.top+e.scrollTop-n.top):c>=a?c-a+1:Math.max(i-c,0);s<d&&(u=r,d=s)}),u}function sg({container:e,onNavigate:t,mode:n=`transcript`}){let r=n===`diff`?`diff-find`:`transcript-find`,i=(0,p.useRef)(Symbol(`find`)),a=n===`diff`?`当前差异`:`当前会话`,[o,s]=(0,p.useState)(!1),[c,l]=(0,p.useState)(``),[u,d]=(0,p.useState)(!1),[f,h]=(0,p.useState)(!1),[g,_]=(0,p.useState)(!1),[v,y]=(0,p.useState)(``),[b,x]=(0,p.useState)([]),[S,C]=(0,p.useState)(0),[w,T]=(0,p.useState)({top:0,right:0,width:0}),E=(0,p.useRef)(null),D=(0,p.useRef)(null),O=(0,p.useRef)(null),k=(0,p.useRef)(void 0),A=(0,p.useRef)(void 0),[j,ee]=(0,p.useState)(0),M=(0,p.useRef)(t);M.current=t;let N=(0,p.useCallback)(()=>{s(!1),D.current?.isConnected&&D.current.focus({preventScroll:!0})},[]);(0,p.useEffect)(()=>{let t=t=>{if(t.defaultPrevented||t.isComposing||t.altKey)return;let r=e.current,i=t.target;if(r?.getClientRects().length&&(!i.closest(`.transcript-find`)||O.current?.contains(i))&&(n!==`transcript`||!i.closest(`.messages`)||r.contains(i))){if(n===`diff`){let e=r?.closest(`.git-diff-editor`),n=t.target;if(!e||!r?.getClientRects().length||!e.contains(n)&&!e.closest(`.chat[data-main-view="diff"]`)||!e.contains(n)&&n.closest(`input,textarea,[contenteditable="true"],.messages,.chat-file-view`))return}if((t.ctrlKey||t.metaKey)&&!t.shiftKey&&t.key.toLowerCase()===`f`){if(t.target?.closest(`.cm-editor,.workbench-editor-search,.xterm,[role="dialog"],.modal`))return;t.preventDefault();let e=window.getSelection();if(!r)return;let n=e&&e.rangeCount>0&&r.contains(e.anchorNode)&&r.contains(e.focusNode);(n||!o)&&(A.current={range:n?e.getRangeAt(0).cloneRange():void 0,top:r.scrollTop+r.clientHeight/3},x([]),k.current=void 0,ee(e=>e+1)),n&&!e.isCollapsed&&l(e.toString()),o||(D.current=document.activeElement),s(!0),requestAnimationFrame(()=>{E.current?.focus(),E.current?.select()})}else o&&t.key===`Escape`&&(t.preventDefault(),N())}};return window.addEventListener(`keydown`,t,n===`diff`),()=>window.removeEventListener(`keydown`,t,n===`diff`)},[N,o,n]),(0,p.useLayoutEffect)(()=>{let t=e.current;if(!o||!t)return;let n=()=>{let e=t.getBoundingClientRect();T({top:e.top+8,right:window.innerWidth-e.right+12,width:Math.max(0,e.width-24)})};n();let r=new ResizeObserver(n);return r.observe(t),window.addEventListener(`resize`,n),()=>{r.disconnect(),window.removeEventListener(`resize`,n)}},[e,o]),(0,p.useEffect)(()=>{let t=e.current;if(!o||!t){x([]);return}let n,r=()=>{try{let e=rg(t,c,{caseSensitive:u,wholeWord:f,regexp:g});y(``),x(e),C(og(t,e,A.current))}catch{y(`正则表达式无效`),x([]),C(0)}};r();let i=new MutationObserver(()=>{clearTimeout(n),n=setTimeout(r,100)});return i.observe(t,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`open`,`hidden`]}),()=>{clearTimeout(n),i.disconnect()}},[e,o,c,u,f,g,j]);let P=b.length?Math.min(S,b.length-1):0;if((0,p.useEffect)(()=>{let e=i.current;return ag(r,e,o?{matches:b,current:b[P]}:void 0),()=>ag(r,e)},[o,b,P,r]),(0,p.useEffect)(()=>{let t=e.current,n=b[P];if(!o||!t||!n){k.current=void 0;return}let r=k.current;if(r?.node===n.startContainer&&r.offset===n.startOffset&&r.end===n.endOffset)return;k.current={node:n.startContainer,offset:n.startOffset,end:n.endOffset},A.current={range:n.cloneRange(),top:t.scrollTop+t.clientHeight/3};let i=n.getBoundingClientRect(),a=t.getBoundingClientRect();t.scrollTop+=i.top-a.top-a.height/3,M.current(t)},[e,o,b,P]),!o)return null;let F=e=>C((P+e+b.length)%(b.length||1));return(0,m.jsxs)(`div`,{ref:O,className:`transcript-find`,role:`search`,"aria-label":`${a}页内查找`,style:{top:w.top,right:w.right,maxWidth:w.width},onKeyDown:e=>{let t=Vp(e.nativeEvent);t&&(e.preventDefault(),e.stopPropagation(),t===`caseSensitive`&&d(e=>!e),t===`wholeWord`&&h(e=>!e),t===`regexp`&&_(e=>!e)),e.key===`F3`&&(e.preventDefault(),e.stopPropagation(),F(e.shiftKey?-1:1))},children:[(0,m.jsx)(`input`,{ref:E,"aria-label":`查找${a}`,placeholder:`查找${a}…`,value:c,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),F(e.shiftKey?-1:1))}}),(0,m.jsx)(Up,{value:{caseSensitive:u,wholeWord:f,regexp:g},onToggle:e=>{e===`caseSensitive`&&d(e=>!e),e===`wholeWord`&&h(e=>!e),e===`regexp`&&_(e=>!e)}}),(0,m.jsx)(`output`,{"aria-live":`polite`,"data-transcript-find-count":!0,children:c?b.length?`${P+1} / ${b.length}`:`无结果`:`0 / 0`}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`上一个匹配`,title:`上一个匹配(Shift+Enter)`,disabled:!b.length,onClick:()=>F(-1),children:`↑`}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`下一个匹配`,title:`下一个匹配(Enter)`,disabled:!b.length,onClick:()=>F(1),children:`↓`}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`关闭页内查找`,title:`关闭(Esc)`,onClick:N,children:`×`}),v&&(0,m.jsx)(`output`,{className:`transcript-find-error`,role:`alert`,"data-find-error":!0,children:v})]})}function cg(e,t,n,r,i){let a=Number.isFinite(t)&&t>0?t:n,o=e.map(e=>({id:e.id,width:Math.min(a,Math.max(Math.min(n,a),Number.isFinite(e.width)?e.width:n))}));if(o.every(e=>e.width<=i.width)){let t=[];for(let n=0;n<e.length;n+=Math.max(1,i.perRow))t.push({ids:e.slice(n,n+Math.max(1,i.perRow)).map(e=>e.id),width:Math.min(a,i.width)});return t}let s=[],c=[],l=0,u=()=>{c.length&&(s.push({ids:c.map(e=>e.id),width:Math.min(a/c.length,Math.max(r,l))}),c=[],l=0)};for(let e of o)c.length&&Math.max(l,e.width)*(c.length+1)>a+.1&&u(),c.push(e),l=Math.max(l,e.width);return u(),s}function lg(e,t,n=88,r=200){let i=Math.max(0,Math.floor(e));if(!Number.isFinite(t)||t<=0)return{perRow:Math.max(1,i),width:n};if(i===0)return{perRow:1,width:n};if(i===1)return{perRow:1,width:Math.min(r,t)};let a=t/i;if(a>=n)return{perRow:i,width:Math.min(a,r)};for(let e=2;e<=i;e+=1){let a=Math.ceil(i/e),o=t/a;if(o>=n)return{perRow:a,width:Math.min(o,r)}}return{perRow:1,width:n}}function ug(e,t,n=88,r=200){let[i,a]=(0,p.useState)(()=>lg(e,0,n,r)),[o,s]=(0,p.useState)(null),c=(0,p.useCallback)(()=>{let i=lg(e,t,n,r);s({count:e,containerWidth:t}),a(e=>e.perRow===i.perRow&&e.width===i.width?e:i)},[e,t,n,r]),l=(0,p.useRef)(t);(0,p.useLayoutEffect)(()=>{t<=0||l.current!==t&&(l.current=t,c())},[t,c]);let u=(0,p.useRef)(null);return(0,p.useLayoutEffect)(()=>{let t=u.current;u.current=e,t!==null&&e>t&&c()},[e,c]),{layout:i,frozen:o!==null&&o.count!==e,recompute:c}}function dg({tabs:e,activeId:t,onSelect:n,onClose:r,onActivate:i,ariaLabel:a,minWidth:o=88,maxWidth:s=200,prefix:c=`workspace-tab`,idPrefix:l=c,className:u}){let d=(0,p.useRef)(null),[f,h]=(0,p.useState)(0),{layout:g,frozen:_,recompute:v}=ug(e.length,f,o,s);(0,p.useLayoutEffect)(()=>{let e=d.current;if(!e||typeof ResizeObserver>`u`)return;let t=()=>{let t=e.clientWidth;t>0&&h(t)};t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let[y,b]=(0,p.useState)({}),[x,S]=(0,p.useState)([]),C=JSON.stringify(e.map(e=>[e.id,e.label]));(0,p.useLayoutEffect)(()=>{let e=d.current;if(!e)return;let t=()=>{let t={};for(let n of e.querySelectorAll(`[role=tab]`)){let e=n.querySelector(`.workspace-tab-label`),r=n.id.slice(l.length+1);if(!e||!r)continue;let i=document.createRange();i.selectNodeContents(e);let a=n.getBoundingClientRect().width-e.getBoundingClientRect().width;t[r]=Math.ceil(i.getBoundingClientRect().width+a+2)}b(e=>JSON.stringify(e)===JSON.stringify(t)?e:t)};return t(),document.fonts?.addEventListener(`loadingdone`,t),()=>document.fonts?.removeEventListener(`loadingdone`,t)},[C,f,l]);let w=cg(e.map(e=>({id:e.id,width:y[e.id]??o})),f,o,s,g),T=JSON.stringify(w);(0,p.useLayoutEffect)(()=>{_||S(e=>JSON.stringify(e)===T?e:w)},[_,T]);let E=x.length&&e.every(e=>x.some(t=>t.ids.includes(e.id)))?x:w,D=0,O=E.map(t=>{let n=_?e.slice(D,D+=t.ids.length):t.ids.flatMap(t=>{let n=e.find(e=>e.id===t);return n?[n]:[]});return{...t,tabs:n}}).filter(e=>e.tabs.length),k=O.map(e=>e.tabs),A=O.map(e=>e.width),j=(e,t)=>t===void 0?{}:{[`data-${c}-${e}`]:t},ee=e.filter(e=>e.kind===`file`).length,M=e.filter(e=>e.kind===`session`||!e.kind).length,N=t=>({[`data-${t}-strip`]:`1`,..._?{[`data-${t}-frozen`]:`1`}:{},[`data-${t}-count`]:t===`file-tab`?ee:t===`session-tab`?M:e.length,[`data-${t}-min`]:o,[`data-${t}-max`]:s,[`data-${t}-per-row`]:k[0]?.length??g.perRow,[`data-${t}-width`]:Math.round((A[0]??g.width)*100)/100}),P=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&v()},F=e=>{let t=e.relatedTarget;(!t||t.isConnected)&&v()};(0,p.useEffect)(()=>{if(!_)return;let e=d.current;if(!e)return;let t=t=>{let n=e.getBoundingClientRect();t.clientX>=n.left&&t.clientX<=n.right&&t.clientY>=n.top&&t.clientY<=n.bottom||v()};return document.addEventListener(`mousemove`,t,!0),()=>document.removeEventListener(`mousemove`,t,!0)},[_,v]);let I=[`${c}-strip`,`workspace-tab-strip`,`session-tab-strip`,`file-tab-strip`,u].filter(Boolean).join(` `);return(0,m.jsx)(`div`,{ref:d,className:I,role:`tablist`,"aria-label":a??`工作区标签页`,...j(`strip`,`1`),...N(`workspace-tab`),...N(`session-tab`),...N(`file-tab`),style:{"--tab-w":`${g.width}px`},onMouseEnter:P,onMouseLeave:F,children:k.map((a,o)=>(0,m.jsx)(`div`,{className:`${c}-row workspace-tab-row session-tab-row file-tab-row`,role:`presentation`,...j(`row`,o),"data-tab-row-width":A[o],children:a.map(a=>{let s={width:A[o]},u=a.id===t||a.rawId!==void 0&&a.rawId===t,d=a.title?a.title.includes(a.label)?a.title:`${a.label}\n${a.title}`:a.label,f=a.kind,p=a.rawId??a.id,h=e.findIndex(e=>e.id===a.id),g=[c,u?`${c}-active`:``,`workspace-tab`,u?`workspace-tab-active`:``,f?`${f}-tab`:``,f&&u?`${f}-tab-active`:``,a.preview?`${c}-preview`:``,a.preview?`workspace-tab-preview`:``,a.preview&&f?`${f}-tab-preview`:``].filter(Boolean).join(` `);return(0,m.jsxs)(`div`,{role:`tab`,id:`${l}-${a.id}`,"aria-selected":u,"aria-controls":`${l}-panel-${a.id}`,tabIndex:u?0:-1,className:g,...j(`id`,p),...j(`index`,h),...u?j(`active`,`1`):{},...j(`closable`,a.closable===!1?`0`:`1`),...f?{"data-tab-kind":f}:{},...a.preview?{"data-tab-preview":`1`}:{},...f===`session`||!f?{"data-session-tab-id":p,"data-session-tab-index":h,...u?{"data-session-tab-active":`1`}:{},"data-session-tab-closable":a.closable===!1?`0`:`1`,...a.preview?{"data-session-tab-preview":`1`}:{}}:{},...f===`file`?{"data-file-tab-id":p,"data-file-tab-index":h,...u?{"data-file-tab-active":`1`}:{},"data-file-tab-closable":a.closable===!1?`0`:`1`}:{},...f===`diff`?{"data-diff-tab-id":p,"data-diff-tab-index":h,...u?{"data-diff-tab-active":`1`}:{},"data-diff-tab-closable":a.closable===!1?`0`:`1`}:{},title:d,style:{width:s.width,boxSizing:`border-box`},onClick:()=>n?.(a.id),onDoubleClick:i?()=>i(a.id):void 0,onAuxClick:e=>{e.button===1&&(e.preventDefault(),e.stopPropagation(),a.closable!==!1&&r&&r(a.id))},onMouseDown:e=>{e.button===1&&e.preventDefault()},onKeyDown:t=>{if(t.key!==`ArrowLeft`&&t.key!==`ArrowRight`)return;t.preventDefault();let r=t.key===`ArrowRight`?1:-1,i=e[(e.findIndex(e=>e.id===a.id)+r+e.length)%e.length];i&&(document.getElementById(`${l}-${i.id}`)?.focus(),n?.(i.id))},children:[a.icon&&(0,m.jsx)(`span`,{className:`${c}-icon workspace-tab-icon`,children:a.icon}),a.badge,(0,m.jsx)(`span`,{className:`${c}-label workspace-tab-label ${f?`${f}-tab-label`:``}`,title:d,...j(`label`,p),...f===`session`||!f?{"data-session-tab-label":p}:{},...f===`file`?{"data-file-tab-label":p}:{},...f===`diff`?{"data-diff-tab-label":p}:{},children:a.label}),a.closable!==!1&&r&&(0,m.jsx)(`button`,{type:`button`,className:`${c}-close workspace-tab-close ${f?`${f}-tab-close`:``}`,...j(`close`,p),...f===`session`||!f?{"data-session-tab-close":p}:{},...f===`file`?{"data-file-tab-close":p}:{},...f===`diff`?{"data-diff-tab-close":p}:{},onClick:e=>{e.stopPropagation(),r(a.id)},onDoubleClick:e=>{e.stopPropagation()},title:`关闭 ${d}`,"aria-label":`关闭 ${d}`,children:`×`})]},a.id)})},`row_${o}`))})}var fg=25,pg=75;function mg({share:e,onShare:t}){let n=(0,p.useRef)(null),[r,i]=(0,p.useState)(!1),a=e=>t(Math.round(Math.min(pg,Math.max(fg,e))));return(0,p.useLayoutEffect)(()=>{let e=n.current?.parentElement;if(!e)return;let t=()=>i(getComputedStyle(e).flexDirection===`column`);t();let r=new ResizeObserver(t);return r.observe(e),()=>r.disconnect()},[]),(0,m.jsx)(`div`,{ref:n,className:`workbench-split-divider`,"data-workbench-split-divider":!0,role:`separator`,"aria-label":`调整拆分大小`,"aria-orientation":r?`horizontal`:`vertical`,"aria-valuenow":e,"aria-valuemin":fg,"aria-valuemax":pg,tabIndex:0,onPointerDown:e=>{e.button===0&&(e.currentTarget.focus(),e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{if(!e.currentTarget.hasPointerCapture(e.pointerId))return;let t=e.currentTarget.parentElement?.getBoundingClientRect();t&&a(r?(e.clientY-t.top)/t.height*100:(e.clientX-t.left)/t.width*100)},onKeyDown:t=>{let n=t.key===(r?`ArrowDown`:`ArrowRight`),i=t.key===(r?`ArrowUp`:`ArrowLeft`);if(n||i)a(e+(n?5:-5));else if(t.key===`Home`)a(fg);else if(t.key===`End`)a(pg);else return;t.preventDefault()}})}function hg({tabs:e,selected:t,onSelect:n,onPin:r,onCloseTab:i,onClose:a,children:o}){let s=e.find(e=>e.id===t);return(0,m.jsxs)(`section`,{className:`workbench-split-pane`,"data-workbench-split-pane":!0,"aria-label":`拆分区`,children:[(0,m.jsxs)(`div`,{className:`workbench-split-bar`,children:[(0,m.jsxs)(`select`,{"aria-label":`拆分区标签页`,"data-workbench-split-tabs":!0,value:t??``,onChange:e=>n(e.target.value),title:s?.title,"data-workbench-split-preview":s?.preview||void 0,children:[(0,m.jsx)(`option`,{value:``,disabled:!0,children:`选择文件或差异`}),e.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.label},e.id))]}),t&&s?.preview&&(0,m.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,title:`固定标签页`,"aria-label":`固定拆分区标签页`,onClick:()=>r(t),children:(0,m.jsx)(vi,{name:`pin`})}),t&&(0,m.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,title:`关闭此标签页`,"aria-label":`关闭拆分区标签页`,onClick:()=>i(t),children:(0,m.jsx)(vi,{name:`close`})}),(0,m.jsx)(`button`,{className:`workbench-icon-button`,type:`button`,"data-close-workbench-split":!0,title:`合并主区`,"aria-label":`合并主区`,onClick:a,children:(0,m.jsx)(vi,{name:`split`})})]}),o??(0,m.jsx)(`p`,{className:`rail-empty`,children:`从文件或 Git 面板打开一个文件或差异。`})]})}function gg(e,t){return!!e&&!!t&&e.key===t.key&&e.position?.line===t.position?.line&&e.position?.column===t.position?.column}function _g(e,t){let n=e.entries[e.index];if(gg(n,t))return e;if(n?.key===t.key&&(!t.position||!n.position||!t.explicitPosition&&Math.abs(t.position.line-n.position.line)<5)){if(!t.position)return e;let n=[...e.entries];return n[e.index]=t,{entries:n,index:e.index}}let r=[...e.entries.slice(0,e.index+1),t].slice(-100);return{entries:r,index:r.length-1}}function vg(e,t,n,r){for(let i=t+n;i>=0&&i<e.entries.length;i+=n)if(r(e.entries[i]))return i;return-1}var yg={pending:`未开始`,running:`运行中`,completed:`已完成`,failed:`失败`,skipped:`已跳过`,stopped:`已停止`},bg={running:`运行中`,completed:`全部完成`,failed:`中途失败`,stopped:`已停止`},xg={pending:`○`,running:`◐`,completed:`✓`,failed:`✕`,skipped:`→`,stopped:`■`},Sg={stop:`失败即停`,skip:`失败跳过`,"retry:1":`失败重试 1 次`,"retry:2":`失败重试 2 次`,"retry:3":`失败重试 3 次`};function Cg(e){let t=Math.max(0,Math.round(e/1e3)),n=t%60,r=Math.floor(t/60)%60,i=Math.floor(t/3600),a=e=>String(e).padStart(2,`0`);return i>0?`${i}h ${a(r)}:${a(n)}`:`${r}:${a(n)}`}function wg(e){let t=e.status===`running`,[n,r]=(0,p.useState)(0);(0,p.useEffect)(()=>{if(!t)return;r(Date.now());let e=window.setInterval(()=>r(Date.now()),200);return()=>window.clearInterval(e)},[t,e.startedAt]);let i=Date.parse(e.startedAt);if(Number.isFinite(i)){if(!t){let t=Date.parse(e.finishedAt??``);return Number.isFinite(t)?t-i:void 0}return n>0?n-i:void 0}}function Tg({step:e,names:t}){let n=e.attempts.length,r=e.attempts[n-1],i=t.get(e.agentId)||e.agentId,a=e.label?.trim()||i;return(0,m.jsxs)(`li`,{className:`workflow-step workflow-step-${e.status}`,"data-workflow-step":e.index+1,"data-workflow-step-status":e.status,"data-workflow-step-agent":e.agentId,"data-workflow-step-attempts":n,children:[(0,m.jsx)(`span`,{className:`workflow-step-mark`,"aria-hidden":`true`,children:xg[e.status]}),(0,m.jsxs)(`span`,{className:`workflow-step-n`,"data-workflow-step-n":e.index+1,children:[`第 `,e.index+1,` 步`]}),(0,m.jsx)(`strong`,{className:`workflow-step-name`,"data-workflow-step-name":e.index+1,children:a}),(0,m.jsx)(`span`,{className:`workflow-step-agent`,"data-workflow-step-agent-name":e.index+1,children:i}),n>1&&(0,m.jsxs)(`span`,{className:`workflow-step-tries`,"data-workflow-step-retried":e.index+1,children:[`尝试 `,n,` 次`]}),(0,m.jsx)(`span`,{className:`workflow-step-status`,"data-workflow-step-status-text":e.index+1,children:yg[e.status]}),e.status===`failed`&&r?.error&&(0,m.jsx)(`span`,{className:`workflow-step-why`,"data-workflow-step-error":e.index+1,title:Br(r.error),children:zr(r.error,`这一步没有完成。`)})]})}function Eg({nodes:e,steps:t,names:n}){return(0,m.jsx)(`ol`,{className:`workflow-steps`,children:e.map((e,r)=>{if(e.kind===`step`){let r=t[e.stepIndex];return r?(0,m.jsx)(Tg,{step:r,names:n},`step-${e.stepIndex}`):null}return e.kind===`loop`?(0,m.jsxs)(`li`,{className:`workflow-node workflow-loop`,"data-workflow-loop":!0,"data-workflow-loop-rounds":e.rounds.length,"data-workflow-loop-max":e.max,"data-workflow-until":e.until,children:[(0,m.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`↻`}),(0,m.jsx)(`strong`,{children:`循环`}),(0,m.jsxs)(`span`,{children:[`直到「`,e.until,`」`]}),(0,m.jsxs)(`span`,{"data-workflow-loop-progress":!0,children:[`已跑 `,e.rounds.length,`/`,e.max,` 轮`]})]}),e.rounds.map(e=>(0,m.jsxs)(`section`,{className:`workflow-round`,"data-workflow-round":e.n,"data-workflow-round-met":e.untilMet?`true`:`false`,children:[(0,m.jsxs)(`div`,{className:`workflow-round-head`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:e.untilMet?`✓`:`○`}),`第 `,e.n,` 轮 · `,e.untilMet?`条件满足`:`条件未满足`]}),(0,m.jsx)(Eg,{nodes:e.nodes,steps:t,names:n})]},e.n))]},`loop-${r}`):(0,m.jsxs)(`li`,{className:`workflow-node workflow-foreach`,"data-workflow-foreach":!0,"data-workflow-foreach-count":e.items.length,children:[(0,m.jsxs)(`div`,{className:`workflow-node-head`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`≡`}),(0,m.jsx)(`strong`,{children:`逐项执行`}),(0,m.jsxs)(`span`,{children:[e.items.length,` 个由 primary 给出的项目`]})]}),e.iterations.map((e,r)=>(0,m.jsxs)(`section`,{className:`workflow-item`,"data-workflow-item":r+1,"data-workflow-item-value":e.item,children:[(0,m.jsxs)(`div`,{className:`workflow-item-head`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`→`}),`第 `,r+1,` 项 · `,e.item]}),(0,m.jsx)(Eg,{nodes:e.nodes,steps:t,names:n})]},`${r}-${e.item}`))]},`foreach-${r}`)})})}function Dg({workflow:e,names:t,onStop:n,stopping:r}){let i=e.status===`running`,a=wg(e),o=e.steps.filter(e=>e.status===`completed`||e.status===`skipped`).length;return(0,m.jsxs)(`article`,{className:`workflow-card workflow-${e.status}`,"data-workflow-card":e.id,"data-workflow-status":e.status,"data-workflow-steps":e.steps.length,"data-workflow-current":e.currentIndex+1,children:[(0,m.jsxs)(`div`,{className:`workflow-head`,children:[(0,m.jsx)(`span`,{className:`workflow-badge`,children:`编排`}),(0,m.jsx)(`strong`,{className:`workflow-summary`,"data-workflow-summary":e.id,children:e.summary}),(0,m.jsxs)(`span`,{className:`workflow-progress`,"data-workflow-progress":e.id,children:[o,`/`,e.steps.length]}),(0,m.jsx)(`span`,{className:`workflow-status`,"data-workflow-status-text":e.id,children:bg[e.status]??`未知状态`}),(0,m.jsx)(`span`,{className:`workflow-policy`,"data-workflow-policy":e.onFailure,children:Sg[e.onFailure]??e.onFailure}),a!==void 0&&(0,m.jsxs)(`span`,{className:`workflow-clock`,"data-workflow-elapsed":e.id,children:[i?`已运行 `:`用时 `,Cg(a)]}),i&&(0,m.jsx)(`button`,{type:`button`,className:`workflow-stop`,"data-workflow-stop":e.id,disabled:r,onClick:n,children:`停止`})]}),e.nodes?(0,m.jsx)(Eg,{nodes:e.nodes,steps:e.steps,names:t}):(0,m.jsx)(`ol`,{className:`workflow-steps`,"data-workflow-step-count":e.steps.length,children:e.steps.map(e=>(0,m.jsx)(Tg,{step:e,names:t},e.index))})]})}var Og=[{id:`agents`,label:`智能体与创建`,icon:`🤖`,title:`Agent 智能体系统与创建指南`,description:`了解 Super Pi 的角色设定机制,以及如何一步步创建你自己的自定义 Agent。`},{id:`workspace`,label:`工作区与会话`,icon:`🗂️`,title:`工作区与多会话管理`,description:`高效管理本地代码仓库、独立会话标签页与多模态图文输入。`},{id:`subagents`,label:`子任务与编排`,icon:`⚡`,title:`子智能体委托与顺序编排使用指南`,description:`让主 Agent 安排分工、交接结果,并查看进度、处理失败与停止任务。`},{id:`model-policy`,label:`模型使用规则`,icon:`🔒`,title:`模型过滤规则(按工作区限制可用模型)`,description:`用正则规则限定哪些工作区只能用哪些模型,防止敏感代码被发到不该用的模型上。`},{id:`memory`,label:`主动记忆`,icon:`🧠`,title:`主动记忆与技能经验`,description:`让 Super Pi 在得到明确证据后保存长期事实、用户偏好和可复用工作方法。`},{id:`knowledge`,label:`知识库`,icon:`📚`,title:`工作区知识库`,description:`导入规范与设计文档,让 Agent 检索原文作答,而不是凭记忆编造。`},{id:`feishu`,label:`飞书`,icon:`📄`,title:`飞书云文档的读写`,description:`让 Agent 读一篇飞书文档、写回结论。接入方式、连接步骤与常见问题。`},{id:`tools`,label:`侧边栏工具`,icon:`🧩`,title:`全局工具:开发、导出与导入`,description:`让 Agent 写一个工具,用一个文件分享给别人,导入前先看清它会做什么。`},{id:`cli`,label:`指令与快捷键`,icon:`⌨️`,title:`Pi 终端命令与键盘快捷操作`,description:`利用 Pi 终端斜杠指令控制服务生命周期,掌握常用快捷键提升效率。`},{id:`themes`,label:`外观与主题`,icon:`🎨`,title:`界面主题与个性化显示`,description:`内置 4 款专业高对比度主题,针对不同环境提供舒适体验。`}];function kg({onClose:e}){let[t,n]=(0,p.useState)(`agents`);(0,p.useEffect)(()=>{let t=t=>{t.key===`Escape`&&!t.defaultPrevented&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let r=Og.find(e=>e.id===t)??Og[0];return(0,m.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,m.jsxs)(`div`,{className:`picker settings-window help-window`,"data-help-window":`1`,onClick:e=>e.stopPropagation(),role:`dialog`,"aria-modal":`true`,"aria-labelledby":`help-window-title`,children:[(0,m.jsxs)(`div`,{className:`settings-window-head help-window-head`,children:[(0,m.jsxs)(`div`,{className:`help-head-title`,children:[(0,m.jsx)(`h2`,{id:`help-window-title`,children:`使用指南与帮助`}),(0,m.jsx)(`span`,{className:`help-badge`,children:`v0.1.x`})]}),(0,m.jsx)(`button`,{type:`button`,className:`help-close-button`,"aria-label":`关闭指南`,onClick:e,children:`✕`})]}),(0,m.jsxs)(`div`,{className:`settings-window-body help-window-body`,children:[(0,m.jsxs)(`nav`,{className:`settings-nav help-nav`,role:`tablist`,"aria-orientation":`vertical`,"aria-label":`使用指南分类`,children:[(0,m.jsx)(`div`,{className:`settings-nav-label`,children:`目录`}),Og.map(e=>(0,m.jsxs)(`button`,{type:`button`,id:`help-tab-${e.id}`,className:`settings-category help-category`,role:`tab`,"aria-selected":e.id===r.id,"aria-controls":`help-panel`,tabIndex:e.id===r.id?0:-1,onClick:()=>n(e.id),children:[(0,m.jsx)(`span`,{className:`help-tab-icon`,"aria-hidden":`true`,children:e.icon}),(0,m.jsx)(`span`,{children:e.label})]},e.id))]}),(0,m.jsxs)(`div`,{id:`help-panel`,className:`settings-panel help-panel`,role:`tabpanel`,"aria-labelledby":`help-tab-${r.id}`,children:[(0,m.jsxs)(`div`,{className:`help-panel-header`,children:[(0,m.jsx)(`h3`,{className:`help-panel-title`,children:r.title}),(0,m.jsx)(`p`,{className:`help-panel-desc`,children:r.description})]}),(0,m.jsxs)(`div`,{className:`help-panel-content`,children:[r.id===`agents`&&(0,m.jsx)(Mg,{}),r.id===`workspace`&&(0,m.jsx)(Ng,{}),r.id===`subagents`&&(0,m.jsx)(Fg,{}),r.id===`model-policy`&&(0,m.jsx)(Pg,{}),r.id===`memory`&&(0,m.jsx)(Ag,{}),r.id===`knowledge`&&(0,m.jsx)(jg,{}),r.id===`feishu`&&(0,m.jsx)(Ig,{}),r.id===`tools`&&(0,m.jsx)(Lg,{}),r.id===`cli`&&(0,m.jsx)(Rg,{}),r.id===`themes`&&(0,m.jsx)(zg,{})]}),(0,m.jsx)(`div`,{className:`picker-actions help-actions`,children:(0,m.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:e,children:`关闭`})})]})]})]})})}function Ag(){return(0,m.jsxs)(`div`,{className:`help-section-group`,children:[(0,m.jsxs)(`div`,{className:`help-card highlight`,children:[(0,m.jsx)(`h4`,{children:`🧠 它会记住什么?`}),(0,m.jsx)(`p`,{children:`用户档案保存跨工作区的长期偏好;工作区事实保存环境与项目约定;技能保存已经验证过的步骤、命令和坑。临时结果、秘密和未验证的失败不会保存。`})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`主动保存与后台复盘`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsxs)(`li`,{children:[`主 Agent 可以使用 `,(0,m.jsx)(`code`,{children:`memory`}),` 和 `,(0,m.jsx)(`code`,{children:`skill_manage`}),` 工具主动保存;说“记住了”本身不会写入。`]}),(0,m.jsx)(`li`,{children:`每隔若干回合,系统会在独立会话中复盘最近证据。复盘不能读写工作区文件、执行命令或派发任务。`}),(0,m.jsx)(`li`,{children:`读取记忆和历史只返回带来源的参考数据,不能把记忆中的文字当作新的指令。`})]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`权限与审批`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsx)(`li`,{children:`子 Agent 可以读取相关记忆,但没有写入权限。`}),(0,m.jsx)(`li`,{children:`后台复盘新增记忆可以直接保存;修改或删除旧条目会进入设置中的待审批列表。`}),(0,m.jsx)(`li`,{children:`在“设置 → 主动记忆”可以开关功能、调整复盘间隔、编辑条目和批准提案。`})]})]})]})}function jg(){return(0,m.jsxs)(`div`,{className:`help-section-group`,children:[(0,m.jsxs)(`div`,{className:`help-card highlight`,children:[(0,m.jsx)(`h4`,{children:`📚 它解决什么问题?`}),(0,m.jsx)(`p`,{children:`Agent 默认靠训练时的记忆回答项目里的问题。知识库让你把规范、设计稿、会议纪要导入工作区,Agent 在回答前检索这些文档的原文片段,而不是凭印象编造。它与“主动记忆”不同:记忆是 Agent 自己沉淀的事实和技能,知识库的内容来自工作区里真实存在的文档。`})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`怎么用`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsxs)(`li`,{children:[`在“设置 → 知识库”里点“浏览工作区文件…”,在弹出的浏览器里挑一个 Markdown 或文本文件,挑完即导入。也可以直接粘贴正文、手动填写相对路径,或者直接对 Agent 说“把某某文件加入知识库”——它会用 `,(0,m.jsx)(`code`,{children:`knowledge_import`}),` 导入,走的是同一条服务端校验。`]}),(0,m.jsx)(`li`,{children:`同一个文件内容改了再导入就是更新,不会留下旧版本;同样的内容换个标题再导入也不会变成两篇。`}),(0,m.jsx)(`li`,{children:`面板里的“试检索”会用和 Agent 相同的检索器回答,方便你在交给 Agent 之前先确认它找得到。`}),(0,m.jsxs)(`li`,{children:[`从下一条消息开始生效。Agent 使用 `,(0,m.jsx)(`code`,{children:`knowledge_search`}),` 检索,只拿得到片段和来源,拿不到整篇文档。`]})]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`语义检索是内置的`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsxs)(`li`,{children:[`关键词检索始终可用。语义检索让“撤销购买”也能找到写着“取消订单”的段落,它靠一个`,(0,m.jsx)(`strong`,{children:`随安装包一起分发`}),`的中文模型在本机运行,不需要额外下载、不需要联网、也不会把文档发到任何服务。`]}),(0,m.jsxs)(`li`,{children:[`第一次检索时加载模型(约一秒),之后一直可用。设 `,(0,m.jsx)(`code`,{children:`SUPER_PI_KNOWLEDGE_EMBEDDINGS=0`}),` 可以彻底关闭语义检索,只保留关键词检索。`]})]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`它不知道的事`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsx)(`li`,{children:`知识库只会检索它有的东西。文档里没写的,它检索出来也不会有——所以导入什么,直接决定它能回答什么。`}),(0,m.jsx)(`li`,{children:`语义检索总会返回“最接近的那一段”,即使这一段其实并不回答问题。检索结果带一个分数,低分意味着这可能只是最像的一条,Agent 会被要求先核对再使用。`}),(0,m.jsxs)(`li`,{children:[`Agent 可以按你的要求把工作区文件导入知识库(`,(0,m.jsx)(`code`,{children:`knowledge_import`}),`,只接受文本类文件),但`,(0,m.jsx)(`strong`,{children:`不能删除`}),`——删除文档只有你能在“设置 → 知识库”里做。`]})]})]})]})}function Mg(){return(0,m.jsxs)(`div`,{className:`help-section-group`,children:[(0,m.jsxs)(`div`,{className:`help-card highlight`,children:[(0,m.jsx)(`h4`,{children:`💡 Agent 是什么?`}),(0,m.jsxs)(`p`,{children:[`在 Super Pi 中,`,(0,m.jsx)(`strong`,{children:`Agent(智能体)`}),` 是一套独立的「角色提示词设定与能力配置」。 通过切换 Agent,模型将扮演专精工程师、系统架构师、代码审查员或规划专家等不同角色,遵循指定的原则来协助你完成任务。`]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`📁 Agent 文件存放在哪里?`}),(0,m.jsxs)(`ul`,{className:`help-list`,children:[(0,m.jsxs)(`li`,{children:[(0,m.jsx)(`strong`,{children:`内置 Agent 目录:`}),`项目根目录下的 `,(0,m.jsx)(`code`,{children:`agents/`}),` 文件夹,例如 `,(0,m.jsx)(`code`,{children:`agents/coder.md`}),`、`,(0,m.jsx)(`code`,{children:`agents/planner.md`}),`、`,(0,m.jsx)(`code`,{children:`agents/reviewer.md`}),` 等。`]}),(0,m.jsxs)(`li`,{children:[(0,m.jsx)(`strong`,{children:`用户自定义持久化目录:`}),`用户主目录下的 `,(0,m.jsx)(`code`,{children:`~/.super-pi/agents/`}),`,放入此目录的文件在所有项目和更新中均持久有效。`]})]})]}),(0,m.jsxs)(`div`,{className:`help-card`,children:[(0,m.jsx)(`h4`,{children:`🚀 如何创建一个全新的自定义 Agent?`}),(0,m.jsxs)(`div`,{className:`help-steps`,children:[(0,m.jsxs)(`div`,{className:`help-step`,children:[(0,m.jsx)(`span`,{className:`step-num`,children:`1`}),(0,m.jsxs)(`div`,{className:`step-body`,children:[(0,m.jsx)(`strong`,{children:`创建 Markdown 文件`}),(0,m.jsxs)(`p`,{children:[`在 `,(0,m.jsx)(`code`,{children:`agents/`}),` 或 `,(0,m.jsx)(`code`,{children:`~/.super-pi/agents/`}),` 目录下新建文件,例如 `,(0,m.jsx)(`code`,{children:`architect.md`}),`。`]})]})]}),(0,m.jsxs)(`div`,{className:`help-step`,children:[(0,m.jsx)(`span`,{className:`step-num`,children:`2`}),(0,m.jsxs)(`div`,{className:`step-body`,children:[(0,m.jsx)(`strong`,{children:`编写元数据与系统提示词`}),(0,m.jsx)(`p`,{children:`文件开头使用 YAML Frontmatter 声明名称和描述,正文编写设定提示词:`}),(0,m.jsx)(`pre`,{className:`help-code-block`,children:(0,m.jsx)(`code`,{children:`---
|
|
294
294
|
name: 系统架构师
|
|
295
295
|
description: 专注于系统架构拆解、模块解耦与技术选型分析
|
|
296
296
|
---
|
|
@@ -330,25 +330,25 @@ WARNING: This link could potentially be dangerous`)){let e=window.open();if(e){t
|
|
|
330
330
|
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh()),YS&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r||!t?!1:this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!n||!r?!1:this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]<n[1]||t[1]===n[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<n[0]||t[1]<n[1]&&e[1]===n[1]&&e[0]<n[0]||t[1]<n[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=vC(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0):!1}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=NS(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-yC),yC),t/=yC,t/Math.abs(t)+Math.round(t*(bC-1)))}shouldForceSelection(e){return GS?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,!(e.button===2&&this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval(()=>this._dragScroll(),xC)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(GS&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd){this.refresh(!0);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(e),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]<n.lines.length){let e=n.lines.get(this._model.selectionEnd[1]);e&&e.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}(!t||t[0]!==this._model.selectionEnd[0]||t[1]!==this._model.selectionEnd[1])&&this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});let e=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<SC&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=iC(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!!e&&!!t&&(e[0]!==t[0]||e[1]!==t[1]);n?!e||!t||(!this._oldSelectionStart||!this._oldSelectionEnd||e[0]!==this._oldSelectionStart[0]||e[1]!==this._oldSelectionStart[1]||t[0]!==this._oldSelectionEnd[0]||t[1]!==this._oldSelectionEnd[1])&&this._fireOnSelectionChange(e,t,n):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim(e=>this._handleTrim(e))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c<o.length&&o.charAt(c+1)===` `;)c++}else{let t=e[0],n=e[0];a.getWidth(t)===0&&(u++,t--),a.getWidth(n)===2&&(d++,n++);let r=a.getString(n).length;for(r>1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n<a.length&&c+1<o.length&&!this._isCharWordSeparator(a.loadCell(n+1,this._workCell));){a.loadCell(n+1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===2?(d++,n++):e>1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=vC(n,this._bufferService.cols)}};wC=B_([V_(3,mv),V_(4,gv),V_(5,Ov),V_(6,bv),V_(7,kv),V_(8,Dv)],wC);var TC=class{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}},EC=class{constructor(){this._color=new TC,this._css=new TC}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}},DC=Object.freeze((()=>{let e=[tS.toColor(`#2e3436`),tS.toColor(`#cc0000`),tS.toColor(`#4e9a06`),tS.toColor(`#c4a000`),tS.toColor(`#3465a4`),tS.toColor(`#75507b`),tS.toColor(`#06989a`),tS.toColor(`#d3d7cf`),tS.toColor(`#555753`),tS.toColor(`#ef2929`),tS.toColor(`#8ae234`),tS.toColor(`#fce94f`),tS.toColor(`#729fcf`),tS.toColor(`#ad7fa8`),tS.toColor(`#34e2e2`),tS.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let r=t[n/36%6|0],i=t[n/6%6|0],a=t[n%6];e.push({css:$x.toCss(r,i,a),rgba:$x.toRgba(r,i,a)})}for(let t=0;t<24;t++){let n=8+t*10;e.push({css:$x.toCss(n,n,n),rgba:$x.toRgba(n,n,n)})}return e})()),OC=tS.toColor(`#ffffff`),kC=tS.toColor(`#000000`),AC=tS.toColor(`#ffffff`),jC=kC,MC={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},NC=OC,PC=class extends ry{constructor(e){super(),this._optionsService=e,this._contrastCache=new EC,this._halfContrastCache=new EC,this._onChangeColors=this._register(new Cy),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:OC,background:kC,cursor:AC,cursorAccent:jC,selectionForeground:void 0,selectionBackgroundTransparent:MC,selectionBackgroundOpaque:eS.blend(kC,MC),selectionInactiveBackgroundTransparent:MC,selectionInactiveBackgroundOpaque:eS.blend(kC,MC),scrollbarSliderBackground:eS.opacity(OC,.2),scrollbarSliderHoverBackground:eS.opacity(OC,.4),scrollbarSliderActiveBackground:eS.opacity(OC,.5),overviewRulerBorder:OC,ansi:DC.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,()=>this._contrastCache.clear())),this._register(this._optionsService.onSpecificOptionChange(`theme`,()=>this._setTheme(this._optionsService.rawOptions.theme)))}get colors(){return this._colors}_setTheme(e={}){let t=this._colors;if(t.foreground=FC(e.foreground,OC),t.background=FC(e.background,kC),t.cursor=eS.blend(t.background,FC(e.cursor,AC)),t.cursorAccent=eS.blend(t.background,FC(e.cursorAccent,jC)),t.selectionBackgroundTransparent=FC(e.selectionBackground,MC),t.selectionBackgroundOpaque=eS.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=FC(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=eS.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?FC(e.selectionForeground,Qx):void 0,t.selectionForeground===Qx&&(t.selectionForeground=void 0),eS.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=eS.opacity(t.selectionBackgroundTransparent,.3)),eS.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=eS.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=FC(e.scrollbarSliderBackground,eS.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=FC(e.scrollbarSliderHoverBackground,eS.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=FC(e.scrollbarSliderActiveBackground,eS.opacity(t.foreground,.5)),t.overviewRulerBorder=FC(e.overviewRulerBorder,NC),t.ansi=DC.slice(),t.ansi[0]=FC(e.black,DC[0]),t.ansi[1]=FC(e.red,DC[1]),t.ansi[2]=FC(e.green,DC[2]),t.ansi[3]=FC(e.yellow,DC[3]),t.ansi[4]=FC(e.blue,DC[4]),t.ansi[5]=FC(e.magenta,DC[5]),t.ansi[6]=FC(e.cyan,DC[6]),t.ansi[7]=FC(e.white,DC[7]),t.ansi[8]=FC(e.brightBlack,DC[8]),t.ansi[9]=FC(e.brightRed,DC[9]),t.ansi[10]=FC(e.brightGreen,DC[10]),t.ansi[11]=FC(e.brightYellow,DC[11]),t.ansi[12]=FC(e.brightBlue,DC[12]),t.ansi[13]=FC(e.brightMagenta,DC[13]),t.ansi[14]=FC(e.brightCyan,DC[14]),t.ansi[15]=FC(e.brightWhite,DC[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r<n;r++)t.ansi[r+16]=FC(e.extendedAnsi[r],DC[r+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(e){this._restoreColor(e),this._onChangeColors.fire(this.colors)}_restoreColor(e){if(e===void 0)for(let e=0;e<this._restoreColors.ansi.length;++e)this._colors.ansi[e]=this._restoreColors.ansi[e];else switch(e){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[e]=this._restoreColors.ansi[e]}}modifyColors(e){e(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};PC=B_([V_(0,bv)],PC);function FC(e,t){if(e!==void 0)try{return tS.toColor(e)}catch{}return t}var IC=class{constructor(...e){this._entries=new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}},LC=class{constructor(){this._services=new IC,this._services.set(vv,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=dv(e).sort((e,t)=>e.index-t.index),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let i=n.length>0?n[0].index:t.length;if(t.length!==i)throw Error(`[createInstance] First service dependency of ${e.name} at position ${i+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}},RC={trace:0,debug:1,info:2,warn:3,error:4,off:5},zC=`xterm.js: `,BC=class extends ry{constructor(e){super(),this._optionsService=e,this._logLevel=5,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,()=>this._updateLogLevel())),VC=this}get logLevel(){return this._logLevel}_updateLogLevel(){this._logLevel=RC[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t<e.length;t++)typeof e[t]==`function`&&(e[t]=e[t]())}_log(e,t,n){this._evalLazyOptionalParams(n),e.call(console,(this._optionsService.options.logger?``:zC)+t,...n)}trace(e,...t){this._logLevel<=0&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,e,t)}debug(e,...t){this._logLevel<=1&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,e,t)}info(e,...t){this._logLevel<=2&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,e,t)}warn(e,...t){this._logLevel<=3&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,e,t)}error(e,...t){this._logLevel<=4&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,e,t)}};BC=B_([V_(0,bv)],BC);var VC,HC=class extends ry{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new Cy),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new Cy),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new Cy),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;n<Math.min(e,this.length);n++)t[n]=this._array[this._getCyclicIndex(n)];this._array=t,this._maxLength=e,this._startIndex=0}get length(){return this._length}set length(e){if(e>this._length)for(let t=this._length;t<e;t++)this._array[t]=void 0;this._length=e}get(e){return this._array[this._getCyclicIndex(e)]}set(e,t){this._array[this._getCyclicIndex(e)]=t}push(e){this._array[this._getCyclicIndex(this._length)]=e,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw Error(`Can only recycle when the buffer is full`);return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(e,t,...n){if(t){for(let n=e;n<this._length-t;n++)this._array[this._getCyclicIndex(n)]=this._array[this._getCyclicIndex(n+t)];this._length-=t,this.onDeleteEmitter.fire({index:e,amount:t})}for(let t=this._length-1;t>=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;t<n.length;t++)this._array[this._getCyclicIndex(e+t)]=n[t];if(n.length&&this.onInsertEmitter.fire({index:e,amount:n.length}),this._length+n.length>this._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r<t;r++)this.set(e+r+n,this.get(e+r))}}_getCyclicIndex(e){return(this._startIndex+e)%this._maxLength}},UC=3,WC=Object.freeze(new av),GC=0,KC=2,qC=class e{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(e*UC);let r=t||sv.fromCharData([0,rv,1,0]);for(let t=0;t<e;++t)this.setCell(t,r);this.length=e}get(e){let t=this._data[e*UC+0],n=t&2097151;return[this._data[e*UC+1],t&2097152?this._combined[e]:n?$_(n):``,t>>22,t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[e*UC+1]=t[0],t[1].length>1?(this._combined[e]=t[1],this._data[e*UC+0]=e|2097152|t[2]<<22):this._data[e*UC+0]=t[1].charCodeAt(0)|t[2]<<22}getWidth(e){return this._data[e*UC+0]>>22}hasWidth(e){return this._data[e*UC+0]&12582912}getFg(e){return this._data[e*UC+1]}getBg(e){return this._data[e*UC+2]}hasContent(e){return this._data[e*UC+0]&4194303}getCodePoint(e){let t=this._data[e*UC+0];return t&2097152?this._combined[e].charCodeAt(this._combined[e].length-1):t&2097151}isCombined(e){return this._data[e*UC+0]&2097152}getString(e){let t=this._data[e*UC+0];return t&2097152?this._combined[e]:t&2097151?$_(t&2097151):``}isProtected(e){return this._data[e*UC+2]&536870912}loadCell(e,t){return GC=e*UC,t.content=this._data[GC+0],t.fg=this._data[GC+1],t.bg=this._data[GC+2],t.content&2097152&&(t.combinedData=this._combined[e]),t.bg&268435456&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){t.content&2097152&&(this._combined[e]=t.combinedData),t.bg&268435456&&(this._extendedAttrs[e]=t.extended),this._data[e*UC+0]=t.content,this._data[e*UC+1]=t.fg,this._data[e*UC+2]=t.bg}setCellFromCodepoint(e,t,n,r){r.bg&268435456&&(this._extendedAttrs[e]=r.extended),this._data[e*UC+0]=t|n<<22,this._data[e*UC+1]=r.fg,this._data[e*UC+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[e*UC+0];r&2097152?this._combined[e]+=$_(t):r&2097151?(this._combined[e]=$_(r&2097151)+$_(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[e*UC+0]=r}insertCells(e,t,n){if(e%=this.length,e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length-e){let r=new sv;for(let n=this.length-e-t-1;n>=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;r<t;++r)this.setCell(e+r,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,n)}deleteCells(e,t,n){if(e%=this.length,t<this.length-e){let r=new sv;for(let n=0;n<this.length-e-t;++n)this.setCell(e+n,this.loadCell(e+t+n,r));for(let e=this.length-t;e<this.length;++e)this.setCell(e,n)}else for(let t=e;t<this.length;++t)this.setCell(t,n);e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),this.getWidth(e)===0&&!this.hasContent(e)&&this.setCellFromCodepoint(e,0,1,n)}replaceCells(e,t,n,r=!1){if(r)for(e&&this.getWidth(e-1)===2&&!this.isProtected(e-1)&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&!this.isProtected(t)&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.isProtected(e)||this.setCell(e,n),e++;else for(e&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t<this.length&&this.getWidth(t-1)===2&&this.setCellFromCodepoint(t,0,1,n);e<t&&e<this.length;)this.setCell(e++,n)}resize(e,t){if(e===this.length)return this._data.length*4*KC<this._data.buffer.byteLength;let n=e*UC;if(e>this.length){if(this._data.buffer.byteLength>=n*4)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n<e;++n)this.setCell(n,t)}else{this._data=this._data.subarray(0,n);let t=Object.keys(this._combined);for(let n=0;n<t.length;n++){let r=parseInt(t[n],10);r>=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t<r.length;t++){let n=parseInt(r[t],10);n>=e&&delete this._extendedAttrs[n]}}return this.length=e,n*4*KC<this._data.buffer.byteLength}cleanupMemory(){if(this._data.length*4*KC<this._data.buffer.byteLength){let e=new Uint32Array(this._data.length);return e.set(this._data),this._data=e,1}return 0}fill(e,t=!1){if(t)for(let t=0;t<this.length;++t)this.isProtected(t)||this.setCell(t,e);else{this._combined={},this._extendedAttrs={};for(let t=0;t<this.length;++t)this.setCell(t,e)}}copyFrom(e){this.length===e.length?this._data.set(e._data):this._data=new Uint32Array(e._data),this.length=e.length,this._combined={};for(let t in e._combined)this._combined[t]=e._combined[t];this._extendedAttrs={};for(let t in e._extendedAttrs)this._extendedAttrs[t]=e._extendedAttrs[t];this.isWrapped=e.isWrapped}clone(){let t=new e(0);t._data=new Uint32Array(this._data),t.length=this.length;for(let e in this._combined)t._combined[e]=this._combined[e];for(let e in this._extendedAttrs)t._extendedAttrs[e]=this._extendedAttrs[e];return t.isWrapped=this.isWrapped,t}getTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*UC+0]&4194303)return e+(this._data[e*UC+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(this._data[e*UC+0]&4194303||this._data[e*UC+2]&50331648)return e+(this._data[e*UC+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<UC;e++)this._data[(n+i)*UC+e]=a[(t+i)*UC+e];a[(t+i)*UC+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i<r;i++){for(let e=0;e<UC;e++)this._data[(n+i)*UC+e]=a[(t+i)*UC+e];a[(t+i)*UC+2]&268435456&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}let o=Object.keys(e._combined);for(let r=0;r<o.length;r++){let i=parseInt(o[r],10);i>=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t<n;){let e=this._data[t*UC+0],n=e&2097151,a=e&2097152?this._combined[t]:n?$_(n):iv;if(i+=a,r)for(let e=0;e<a.length;++e)r.push(t);t+=e>>22||1}return r&&r.push(t),i}};function JC(e,t,n,r,i,a){let o=[];for(let s=0;s<e.length-1;s++){let c=s,l=e.get(++c);if(!l.isWrapped)continue;let u=[e.get(s)];for(;c<e.length&&l.isWrapped;)u.push(l),l=e.get(++c);if(!a&&r>=s&&r<c){s+=u.length-1;continue}let d=0,f=QC(u,d,t),p=1,m=0;for(;p<u.length;){let e=QC(u,p,t),r=e-m,a=n-f,o=Math.min(r,a);u[d].copyCellsFrom(u[p],m,f,o,!1),f+=o,f===n&&(d++,f=0),m+=o,m===e&&(p++,m=0),f===0&&d!==0&&u[d-1].getWidth(n-1)===2&&(u[d].copyCellsFrom(u[d-1],n-1,f++,1,!1),u[d-1].setCell(n-1,i))}u[d].replaceCells(f,n,i);let h=0;for(let e=u.length-1;e>0&&(e>d||u[e].getTrimmedLength()===0);e--)h++;h>0&&(o.push(s+u.length-h),o.push(h)),s+=u.length-1}return o}function YC(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;o<e.length;o++)if(i===o){let n=t[++r];e.onDeleteEmitter.fire({index:o-a,amount:n}),o+=n-1,a+=n,i=t[++r]}else n.push(o);return{layout:n,countRemoved:a}}function XC(e,t){let n=[];for(let r=0;r<t.length;r++)n.push(e.get(t[r]));for(let t=0;t<n.length;t++)e.set(t,n[t]);e.length=t.length}function ZC(e,t,n){let r=[],i=e.map((n,r)=>QC(e,r,t)).reduce((e,t)=>e+t),a=0,o=0,s=0;for(;s<i;){if(i-s<n){r.push(i-s);break}a+=n;let c=QC(e,o,t);a>c&&(a-=c,o++);let l=e[o].getWidth(a-1)===2;l&&a--;let u=l?n-1:n;r.push(u),s+=u}return r}function QC(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}var $C=class e{constructor(t){this.line=t,this.isDisposed=!1,this._disposables=[],this._id=e._nextId++,this._onDispose=this.register(new Cy),this.onDispose=this._onDispose.event}get id(){return this._id}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),Qv(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}};$C._nextId=1;var ew=$C,tw={},nw=tw.B;tw[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:``,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},tw.A={"#":`£`},tw.B=void 0,tw[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},tw.C=tw[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},tw.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},tw.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},tw.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},tw.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},tw.E=tw[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},tw.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},tw.H=tw[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},tw[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`};var rw=4294967295,iw=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=WC.clone(),this.savedCharset=nw,this.markers=[],this._nullCell=sv.fromCharData([0,rv,1,0]),this._whitespaceCell=sv.fromCharData([0,iv,1,32]),this._isClearing=!1,this._memoryCleanupQueue=new eC,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new HC(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new ov),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new ov),this._whitespaceCell}getBlankLine(e,t){return new qC(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&e<this._rows}_getCorrectBufferLength(e){if(!this._hasScrollback)return e;let t=e+this._optionsService.rawOptions.scrollback;return t>rw?rw:t}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=WC);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new HC(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(WC),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols<e)for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);let a=0;if(this._rows<t)for(let r=this._rows;r<t;r++)this.lines.length<t+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new qC(e,n)):this.ybase>0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new qC(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i<this.lines.maxLength){let e=this.lines.length-i;e>0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t<this.lines.length;t++)r+=+this.lines.get(t).resize(e,n);this._cols=e,this._rows=t,this._memoryCleanupQueue.clear(),r>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue(()=>this._batchedMemoryCleanup()))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition<this.lines.length;)if(t+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),t>100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=JC(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(WC),n);if(r.length>0){let n=YC(this.lines,r);XC(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(WC),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<t&&this.lines.push(new qC(e,r))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-n,0)}_reflowSmaller(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=this.getNullCell(WC),i=[],a=0;for(let o=this.lines.length-1;o>=0;o--){let s=this.lines.get(o);if(!s||!s.isWrapped&&s.getTrimmedLength()<=e)continue;let c=[s];for(;s.isWrapped&&o>0;)s=this.lines.get(--o),c.unshift(s);if(!n){let e=this.ybase+this.y;if(e>=o&&e<o+c.length)continue}let l=c[c.length-1].getTrimmedLength(),u=ZC(c,this._cols,e),d=u.length-c.length,f;f=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+d):Math.max(0,this.lines.length-this.lines.maxLength+d);let p=[];for(let e=0;e<d;e++){let e=this.getBlankLine(WC,!0);p.push(e)}p.length>0&&(i.push({start:o+c.length+a,newLines:p}),a+=p.length),c.push(...p);let m=u.length-1,h=u[m];h===0&&(m--,h=u[m]);let g=c.length-d-1,_=l;for(;g>=0;){let e=Math.min(_,h);if(c[m]===void 0)break;c[m].copyCellsFrom(c[g],_-e,h-e,e,!0),h-=e,h===0&&(m--,h=u[m]),_-=e,_===0&&(g--,_=QC(c,Math.max(g,0),this._cols))}for(let t=0;t<c.length;t++)u[t]<e&&c[t].setCell(u[t],r);let v=d-f;for(;v-->0;)this.ybase===0?this.y<t-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+a)-t&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+d,this.ybase+t-1)}if(i.length>0){let e=[],t=[];for(let e=0;e<this.lines.length;e++)t.push(this.lines.get(e));let n=this.lines.length,r=n-1,o=0,s=i[o];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+a);let c=0;for(let l=Math.min(this.lines.maxLength-1,n+a-1);l>=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+1<this.lines.length&&this.lines.get(n+1).isWrapped;)n++;return{first:t,last:n}}setupTabStops(e){for(e==null?(this.tabs={},e=0):this.tabs[e]||(e=this.prevStop(e));e<this._cols;e+=this._optionsService.rawOptions.tabStopWidth)this.tabs[e]=!0}prevStop(e){for(e??=this.x;!this.tabs[--e]&&e>0;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e<this._cols;);return e>=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t<this.markers.length;t++)this.markers[t].line===e&&(this.markers[t].dispose(),this.markers.splice(t--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let e=0;e<this.markers.length;e++)this.markers[e].dispose();this.markers.length=0,this._isClearing=!1}addMarker(e){let t=new ew(e);return this.markers.push(t),t.register(this.lines.onTrim(e=>{t.line-=e,t.line<0&&t.dispose()})),t.register(this.lines.onInsert(e=>{t.line>=e.index&&(t.line+=e.amount)})),t.register(this.lines.onDelete(e=>{t.line>=e.index&&t.line<e.index+e.amount&&t.dispose(),t.line>e.index&&(t.line-=e.amount)})),t.register(t.onDispose(()=>this._removeMarker(t))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}},aw=class extends ry{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new Cy),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,()=>this.resize(this._bufferService.cols,this._bufferService.rows))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,()=>this.setupTabStops()))}reset(){this._normal=new iw(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new iw(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}},ow=2,sw=1,cw=class extends ry{constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new Cy),this.onResize=this._onResize.event,this._onScroll=this._register(new Cy),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,ow),this.rows=Math.max(e.rawOptions.rows||0,sw),this.buffers=this._register(new aw(e,this)),this._register(this.buffers.onBufferActivate(e=>{this._onScroll.fire(e.activeBuffer.ydisp)}))}get buffer(){return this.buffers.active}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,(!r||r.length!==this.cols||r.getFg(0)!==e.fg||r.getBg(0)!==e.bg)&&(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};cw=B_([V_(0,bv)],cw);var lw={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:GS,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}},uw=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`],dw=class extends ry{constructor(e){super(),this._onOptionChange=this._register(new Cy),this.onOptionChange=this._onOptionChange.event;let t={...lw};for(let n in e)if(n in t)try{let r=e[n];t[n]=this._sanitizeAndValidateOption(n,r)}catch(e){console.error(e)}this.rawOptions=t,this.options={...t},this._setupOptions(),this._register(ey(()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null}))}onSpecificOptionChange(e,t){return this.onOptionChange(n=>{n===e&&t(this.rawOptions[e])})}onMultipleOptionChange(e,t){return this.onOptionChange(n=>{e.indexOf(n)!==-1&&t()})}_setupOptions(){let e=e=>{if(!(e in lw))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},t=(e,t)=>{if(!(e in lw))throw Error(`No option with key "${e}"`);t=this._sanitizeAndValidateOption(e,t),this.rawOptions[e]!==t&&(this.rawOptions[e]=t,this._onOptionChange.fire(e))};for(let n in this.rawOptions){let r={get:e.bind(this,n),set:t.bind(this,n)};Object.defineProperty(this.options,n,r)}}_sanitizeAndValidateOption(e,t){switch(e){case`cursorStyle`:if(t||=lw[e],!fw(t))throw Error(`"${t}" is not a valid value for ${e}`);break;case`wordSeparator`:t||=lw[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof t==`number`&&1<=t&&t<=1e3)break;t=uw.includes(t)?t:lw[e];break;case`cursorWidth`:t=Math.floor(t);case`lineHeight`:case`tabStopWidth`:if(t<1)throw Error(`${e} cannot be less than 1, value: ${t}`);break;case`minimumContrastRatio`:t=Math.max(1,Math.min(21,Math.round(t*10)/10));break;case`scrollback`:if(t=Math.min(t,4294967295),t<0)throw Error(`${e} cannot be less than 0, value: ${t}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(t<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${t}`);break;case`rows`:case`cols`:if(!t&&t!==0)throw Error(`${e} must be numeric, value: ${t}`);break;case`windowsPty`:t??={}}return t}};function fw(e){return e===`block`||e===`underline`||e===`bar`}function pw(e,t=5){if(typeof e!=`object`)return e;let n=Array.isArray(e)?[]:{};for(let r in e)n[r]=t<=1?e[r]:e[r]&&pw(e[r],t-1);return n}var mw=Object.freeze({insertMode:!1}),hw=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),gw=class extends ry{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new Cy),this.onData=this._onData.event,this._onUserInput=this._register(new Cy),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new Cy),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new Cy),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=pw(mw),this.decPrivateModes=pw(hw)}reset(){this.modes=pw(mw),this.decPrivateModes=pw(hw)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,()=>e.split(``).map(e=>e.charCodeAt(0))),this._onBinary.fire(e))}};gw=B_([V_(0,mv),V_(1,yv),V_(2,bv)],gw);var _w={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button===4||e.action!==1?!1:(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function vw(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=e.button&3,e.button&4&&(n|=64),e.button&8&&(n|=128),e.action===32?n|=32:e.action===0&&!t&&(n|=3)),n}var yw=String.fromCharCode,bw={DEFAULT:e=>{let t=[vw(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`\x1B[M${yw(t[0])}${yw(t[1])}${yw(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${vw(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`\x1B[<${vw(e,!0)};${e.x};${e.y}${t}`}},xw=class extends ry{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new Cy),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(_w))this.addProtocol(e,_w[e]);for(let e of Object.keys(bw))this.addEncoding(e,bw[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(e&1),up:!!(e&2),drag:!!(e&4),move:!!(e&8),wheel:!!(e&16)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};xw=B_([V_(0,mv),V_(1,gv),V_(2,bv)],xw);var Sw=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],Cw=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],ww;function Tw(e,t){let n=0,r=t.length-1,i;if(e<t[0][0]||e>t[r][1])return!1;for(;r>=n;)if(i=n+r>>1,e>t[i][1])n=i+1;else if(e<t[i][0])r=i-1;else return!0;return!1}var Ew=class{constructor(){if(this.version=`6`,!ww){ww=new Uint8Array(65536),ww.fill(1),ww[0]=0,ww.fill(0,1,32),ww.fill(0,127,160),ww.fill(2,4352,4448),ww[9001]=2,ww[9002]=2,ww.fill(2,11904,42192),ww[12351]=1,ww.fill(2,44032,55204),ww.fill(2,63744,64256),ww.fill(2,65040,65050),ww.fill(2,65072,65136),ww.fill(2,65280,65377),ww.fill(2,65504,65511);for(let e=0;e<Sw.length;++e)ww.fill(0,Sw[e][0],Sw[e][1]+1)}}wcwidth(e){return e<32?0:e<127?1:e<65536?ww[e]:Tw(e,Cw)?0:e>=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),r=n===0&&t!==0;if(r){let e=Dw.extractWidth(t);e===0?r=!1:e>n&&(n=e)}return Dw.createPropertyValue(0,n,r)}},Dw=class e{constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new Cy,this.onChange=this._onChange.event;let e=new Ew;this.register(e),this._active=e.version,this._activeProvider=e}static extractShouldJoin(e){return!!(e&1)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(e&16777215)<<3|(t&3)<<1|!!n}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(t){let n=0,r=0,i=t.length;for(let a=0;a<i;++a){let o=t.charCodeAt(a);if(55296<=o&&o<=56319){if(++a>=i)return n+this.wcwidth(o);let e=t.charCodeAt(a);56320<=e&&e<=57343?o=(o-55296)*1024+e-56320+65536:n+=this.wcwidth(e)}let s=this.charProperties(o,r),c=e.extractWidth(s);e.extractShouldJoin(s)&&(c-=e.extractWidth(r)),n+=c,r=s}return n}charProperties(e,t){return this._activeProvider.charProperties(e,t)}},Ow=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}};function kw(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[3]!==0&&t[3]!==32)}var Aw=2147483647,jw=256,Mw=class e{constructor(e=32,t=32){if(this.maxLength=e,this.maxSubParamsLength=t,t>jw)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}static fromArray(t){let n=new e;if(!t.length)return n;for(let e=+!!Array.isArray(t[0]);e<t.length;++e){let r=t[e];if(Array.isArray(r))for(let e=0;e<r.length;++e)n.addSubParam(r[e]);else n.addParam(r)}return n}clone(){let t=new e(this.maxLength,this.maxSubParamsLength);return t.params.set(this.params),t.length=this.length,t._subParams.set(this._subParams),t._subParamsLength=this._subParamsLength,t._subParamsIdx.set(this._subParamsIdx),t._rejectDigits=this._rejectDigits,t._rejectSubDigits=this._rejectSubDigits,t._digitIsSub=this._digitIsSub,t}toArray(){let e=[];for(let t=0;t<this.length;++t){e.push(this.params[t]);let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>Aw?Aw:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength){this._rejectSubDigits=!0;return}if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>Aw?Aw:e,this._subParamsIdx[this.length-1]++}}hasSubParams(e){return(this._subParamsIdx[e]&255)-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=this._subParamsIdx[e]&255;return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t<this.length;++t){let n=this._subParamsIdx[t]>>8,r=this._subParamsIdx[t]&255;r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let n=this._digitIsSub?this._subParams:this.params,r=n[t-1];n[t-1]=~r?Math.min(r*10+e,Aw):e}},Nw=[],Pw=class{constructor(){this._state=0,this._active=Nw,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Nw}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=Nw,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||Nw,!this._active.length)this._handlerFb(this._id,`START`);else for(let e=this._active.length-1;e>=0;e--)this._active[e].start()}_put(e,t,n){if(!this._active.length)this._handlerFb(this._id,`PUT`,ev(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t<n;){let n=e[t++];if(n===59){this._state=2,this._start();break}if(n<48||57<n){this._state=3;return}this._id===-1&&(this._id=0),this._id=this._id*10+n-48}this._state===2&&n-t>0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),!this._active.length)this._handlerFb(this._id,`END`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].end(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}}this._active=Nw,this._id=-1,this._state=0}}},Fw=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=ev(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then(e=>(this._data=``,this._hitLimit=!1,e));return this._data=``,this._hitLimit=!1,t}},Iw=[],Lw=class{constructor(){this._handlers=Object.create(null),this._active=Iw,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=Iw}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=Iw,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||Iw,!this._active.length)this._handlerFb(this._ident,`HOOK`,t);else for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t)}put(e,t,n){if(!this._active.length)this._handlerFb(this._ident,`PUT`,ev(e,t,n));else for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n)}unhook(e,t=!0){if(!this._active.length)this._handlerFb(this._ident,`UNHOOK`,e);else{let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&n===!1){for(;r>=0&&(n=this._active[r].unhook(e),n!==!0);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}this._active=Iw,this._ident=0}},Rw=new Mw;Rw.addParam(0);var zw=class{constructor(e){this._handler=e,this._data=``,this._params=Rw,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():Rw,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=ev(e,t,n),this._data.length>1e7&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then(e=>(this._params=Rw,this._data=``,this._hitLimit=!1,e));return this._params=Rw,this._data=``,this._hitLimit=!1,t}},Bw=class{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;i<e.length;i++)this.table[t<<8|e[i]]=n<<4|r}},Vw=160,Hw=function(){let e=new Bw(4095),t=Array.apply(null,Array(256)).map((e,t)=>t),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(Vw,0,2,0),e.add(Vw,8,5,8),e.add(Vw,6,0,6),e.add(Vw,11,0,11),e.add(Vw,13,13,13),e}(),Uw=class extends ry{constructor(e=Hw){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new Mw,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register(ey(()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)})),this._oscParser=this._register(new Pw),this._dcsParser=this._register(new Lw),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},()=>!0)}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;t<e.intermediates.length;++t){let r=e.intermediates.charCodeAt(t);if(32>r||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(e&255)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r=0,i=0,a=0,o;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,a=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,i=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](this._params),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 4:if(n===!1&&i>-1){for(;i>=0&&(o=t[i](),o!==!0);i--)if(o instanceof Promise)return this._parseStack.handlerPos=i,o}this._parseStack.handlers=[];break;case 6:if(r=e[this._parseStack.chunkPos],o=this._dcsParser.unhook(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(r=e[this._parseStack.chunkPos],o=this._oscParser.end(r!==24&&r!==26,n),o)return o;r===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,a=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=this._parseStack.transition&15}}for(let n=a;n<t;++n){switch(r=e[n],i=this._transitions.table[this.currentState<<8|(r<160?r:Vw)],i>>4){case 2:for(let i=n+1;;++i)if(i>=t||(r=e[i])<32||r>126&&r<Vw||++i>=t||(r=e[i])<32||r>126&&r<Vw||++i>=t||(r=e[i])<32||r>126&&r<Vw||++i>=t||(r=e[i])<32||r>126&&r<Vw){this._printHandler(e,n,i),n=i-1;break}break;case 3:this._executeHandlers[r]?this._executeHandlers[r]():this._executeHandlerFb(r),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:r,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let a=this._csiHandlers[this._collect<<8|r],s=a?a.length-1:-1;for(;s>=0&&(o=a[s](this._params),o!==!0);s--)if(o instanceof Promise)return this._preserveStack(3,a,s,i,n),o;s<0&&this._csiHandlerFb(this._collect<<8|r,this._params),this.precedingJoinState=0;break;case 8:do switch(r){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(r-48)}while(++n<t&&(r=e[n])>47&&r<60);n--;break;case 9:this._collect<<=8,this._collect|=r;break;case 10:let c=this._escHandlers[this._collect<<8|r],l=c?c.length-1:-1;for(;l>=0&&(o=c[l](),o!==!0);l--)if(o instanceof Promise)return this._preserveStack(4,c,l,i,n),o;l<0&&this._escHandlerFb(this._collect<<8|r),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|r,this._params);break;case 13:for(let i=n+1;;++i)if(i>=t||(r=e[i])===24||r===26||r===27||r>127&&r<Vw){this._dcsParser.put(e,n,i),n=i-1;break}break;case 14:if(o=this._dcsParser.unhook(r!==24&&r!==26),o)return this._preserveStack(6,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let i=n+1;;i++)if(i>=t||(r=e[i])<32||r>127&&r<Vw){this._oscParser.put(e,n,i),n=i-1;break}break;case 6:if(o=this._oscParser.end(r!==24&&r!==26),o)return this._preserveStack(5,[],0,i,n),o;r===27&&(i|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=i&15}}},Ww=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,Gw=/^[\da-f]+$/;function Kw(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=Ww.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),Gw.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}}function qw(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}function Jw(e,t=16){let[n,r,i]=e;return`rgb:${qw(n,t)}/${qw(r,t)}/${qw(i,t)}`}var Yw={"(":0,")":1,"*":2,"+":3,"-":1,".":2},Xw=131072,Zw=10;function Qw(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var $w=5e3,eT=0,tT=class extends ry{constructor(e,t,n,r,i,a,o,s,c=new Uw){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=a,this._coreMouseService=o,this._unicodeService=s,this._parser=c,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new tv,this._utf8Decoder=new nv,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=WC.clone(),this._eraseAttrDataInternal=WC.clone(),this._onRequestBell=this._register(new Cy),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new Cy),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new Cy),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new Cy),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new Cy),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new Cy),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new Cy),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new Cy),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new Cy),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new Cy),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new Cy),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new Cy),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new Cy),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new nT(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate(e=>this._activeBuffer=e.activeBuffer)),this._parser.setCsiHandlerFallback((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})}),this._parser.setEscHandlerFallback(e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})}),this._parser.setExecuteHandlerFallback(e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})}),this._parser.setOscHandlerFallback((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})}),this._parser.setDcsHandlerFallback((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})}),this._parser.setPrintHandler((e,t,n)=>this.print(e,t,n)),this._parser.registerCsiHandler({final:`@`},e=>this.insertChars(e)),this._parser.registerCsiHandler({intermediates:` `,final:`@`},e=>this.scrollLeft(e)),this._parser.registerCsiHandler({final:`A`},e=>this.cursorUp(e)),this._parser.registerCsiHandler({intermediates:` `,final:`A`},e=>this.scrollRight(e)),this._parser.registerCsiHandler({final:`B`},e=>this.cursorDown(e)),this._parser.registerCsiHandler({final:`C`},e=>this.cursorForward(e)),this._parser.registerCsiHandler({final:`D`},e=>this.cursorBackward(e)),this._parser.registerCsiHandler({final:`E`},e=>this.cursorNextLine(e)),this._parser.registerCsiHandler({final:`F`},e=>this.cursorPrecedingLine(e)),this._parser.registerCsiHandler({final:`G`},e=>this.cursorCharAbsolute(e)),this._parser.registerCsiHandler({final:`H`},e=>this.cursorPosition(e)),this._parser.registerCsiHandler({final:`I`},e=>this.cursorForwardTab(e)),this._parser.registerCsiHandler({final:`J`},e=>this.eraseInDisplay(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`J`},e=>this.eraseInDisplay(e,!0)),this._parser.registerCsiHandler({final:`K`},e=>this.eraseInLine(e,!1)),this._parser.registerCsiHandler({prefix:`?`,final:`K`},e=>this.eraseInLine(e,!0)),this._parser.registerCsiHandler({final:`L`},e=>this.insertLines(e)),this._parser.registerCsiHandler({final:`M`},e=>this.deleteLines(e)),this._parser.registerCsiHandler({final:`P`},e=>this.deleteChars(e)),this._parser.registerCsiHandler({final:`S`},e=>this.scrollUp(e)),this._parser.registerCsiHandler({final:`T`},e=>this.scrollDown(e)),this._parser.registerCsiHandler({final:`X`},e=>this.eraseChars(e)),this._parser.registerCsiHandler({final:`Z`},e=>this.cursorBackwardTab(e)),this._parser.registerCsiHandler({final:"`"},e=>this.charPosAbsolute(e)),this._parser.registerCsiHandler({final:`a`},e=>this.hPositionRelative(e)),this._parser.registerCsiHandler({final:`b`},e=>this.repeatPrecedingCharacter(e)),this._parser.registerCsiHandler({final:`c`},e=>this.sendDeviceAttributesPrimary(e)),this._parser.registerCsiHandler({prefix:`>`,final:`c`},e=>this.sendDeviceAttributesSecondary(e)),this._parser.registerCsiHandler({final:`d`},e=>this.linePosAbsolute(e)),this._parser.registerCsiHandler({final:`e`},e=>this.vPositionRelative(e)),this._parser.registerCsiHandler({final:`f`},e=>this.hVPosition(e)),this._parser.registerCsiHandler({final:`g`},e=>this.tabClear(e)),this._parser.registerCsiHandler({final:`h`},e=>this.setMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`h`},e=>this.setModePrivate(e)),this._parser.registerCsiHandler({final:`l`},e=>this.resetMode(e)),this._parser.registerCsiHandler({prefix:`?`,final:`l`},e=>this.resetModePrivate(e)),this._parser.registerCsiHandler({final:`m`},e=>this.charAttributes(e)),this._parser.registerCsiHandler({final:`n`},e=>this.deviceStatus(e)),this._parser.registerCsiHandler({prefix:`?`,final:`n`},e=>this.deviceStatusPrivate(e)),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},e=>this.softReset(e)),this._parser.registerCsiHandler({intermediates:` `,final:`q`},e=>this.setCursorStyle(e)),this._parser.registerCsiHandler({final:`r`},e=>this.setScrollRegion(e)),this._parser.registerCsiHandler({final:`s`},e=>this.saveCursor(e)),this._parser.registerCsiHandler({final:`t`},e=>this.windowOptions(e)),this._parser.registerCsiHandler({final:`u`},e=>this.restoreCursor(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},e=>this.insertColumns(e)),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},e=>this.deleteColumns(e)),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},e=>this.selectProtected(e)),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},e=>this.requestMode(e,!0)),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},e=>this.requestMode(e,!1)),this._parser.setExecuteHandler($.BEL,()=>this.bell()),this._parser.setExecuteHandler($.LF,()=>this.lineFeed()),this._parser.setExecuteHandler($.VT,()=>this.lineFeed()),this._parser.setExecuteHandler($.FF,()=>this.lineFeed()),this._parser.setExecuteHandler($.CR,()=>this.carriageReturn()),this._parser.setExecuteHandler($.BS,()=>this.backspace()),this._parser.setExecuteHandler($.HT,()=>this.tab()),this._parser.setExecuteHandler($.SO,()=>this.shiftOut()),this._parser.setExecuteHandler($.SI,()=>this.shiftIn()),this._parser.setExecuteHandler(Gx.IND,()=>this.index()),this._parser.setExecuteHandler(Gx.NEL,()=>this.nextLine()),this._parser.setExecuteHandler(Gx.HTS,()=>this.tabSet()),this._parser.registerOscHandler(0,new Fw(e=>(this.setTitle(e),this.setIconName(e),!0))),this._parser.registerOscHandler(1,new Fw(e=>this.setIconName(e))),this._parser.registerOscHandler(2,new Fw(e=>this.setTitle(e))),this._parser.registerOscHandler(4,new Fw(e=>this.setOrReportIndexedColor(e))),this._parser.registerOscHandler(8,new Fw(e=>this.setHyperlink(e))),this._parser.registerOscHandler(10,new Fw(e=>this.setOrReportFgColor(e))),this._parser.registerOscHandler(11,new Fw(e=>this.setOrReportBgColor(e))),this._parser.registerOscHandler(12,new Fw(e=>this.setOrReportCursorColor(e))),this._parser.registerOscHandler(104,new Fw(e=>this.restoreIndexedColor(e))),this._parser.registerOscHandler(110,new Fw(e=>this.restoreFgColor(e))),this._parser.registerOscHandler(111,new Fw(e=>this.restoreBgColor(e))),this._parser.registerOscHandler(112,new Fw(e=>this.restoreCursorColor(e))),this._parser.registerEscHandler({final:`7`},()=>this.saveCursor()),this._parser.registerEscHandler({final:`8`},()=>this.restoreCursor()),this._parser.registerEscHandler({final:`D`},()=>this.index()),this._parser.registerEscHandler({final:`E`},()=>this.nextLine()),this._parser.registerEscHandler({final:`H`},()=>this.tabSet()),this._parser.registerEscHandler({final:`M`},()=>this.reverseIndex()),this._parser.registerEscHandler({final:`=`},()=>this.keypadApplicationMode()),this._parser.registerEscHandler({final:`>`},()=>this.keypadNumericMode()),this._parser.registerEscHandler({final:`c`},()=>this.fullReset()),this._parser.registerEscHandler({final:`n`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`o`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`|`},()=>this.setgLevel(3)),this._parser.registerEscHandler({final:`}`},()=>this.setgLevel(2)),this._parser.registerEscHandler({final:`~`},()=>this.setgLevel(1)),this._parser.registerEscHandler({intermediates:`%`,final:`@`},()=>this.selectDefaultCharset()),this._parser.registerEscHandler({intermediates:`%`,final:`G`},()=>this.selectDefaultCharset());for(let e in tw)this._parser.registerEscHandler({intermediates:`(`,final:e},()=>this.selectCharset(`(`+e)),this._parser.registerEscHandler({intermediates:`)`,final:e},()=>this.selectCharset(`)`+e)),this._parser.registerEscHandler({intermediates:`*`,final:e},()=>this.selectCharset(`*`+e)),this._parser.registerEscHandler({intermediates:`+`,final:e},()=>this.selectCharset(`+`+e)),this._parser.registerEscHandler({intermediates:`-`,final:e},()=>this.selectCharset(`-`+e)),this._parser.registerEscHandler({intermediates:`.`,final:e},()=>this.selectCharset(`.`+e)),this._parser.registerEscHandler({intermediates:`/`,final:e},()=>this.selectCharset(`/`+e));this._parser.registerEscHandler({intermediates:`#`,final:`8`},()=>this.screenAlignmentPattern()),this._parser.setErrorHandler(e=>(this._logService.error(`Parsing error: `,e),e)),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new zw((e,t)=>this.requestStatusString(e,t)))}getAttrData(){return this._curAttrData}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=3&&Promise.race([e,new Promise((e,t)=>setTimeout(()=>t(`#SLOW_TIMEOUT`),$w))]).catch(e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than ${$w} ms`)})}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>Xw&&(a=this._parseStack.position+Xw)}if(this._logService.logLevel<=1&&this._logService.debug(`parsing data ${typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,e=>String.fromCharCode(e)).join(``)}"`}`),this._logService.logLevel===0&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map(e=>e.charCodeAt(0)):e),this._parseBuffer.length<e.length&&this._parseBuffer.length<Xw&&(this._parseBuffer=new Uint32Array(Math.min(e.length,Xw))),o||this._dirtyRowTracker.clearRange(),e.length>Xw)for(let t=a;t<e.length;t+=Xw){let a=t+Xw<e.length?t+Xw:e.length,o=typeof e==`string`?this._stringDecoder.decode(e.substring(t,a),this._parseBuffer):this._utf8Decoder.decode(e.subarray(t,a),this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,o))return this._preserveStack(r,i,o,t),this._logSlowResolvingAsync(n),n}else if(!o){let t=typeof e==`string`?this._stringDecoder.decode(e,this._parseBuffer):this._utf8Decoder.decode(e,this._parseBuffer);if(n=this._parser.parse(this._parseBuffer,t))return this._preserveStack(r,i,t,0),this._logSlowResolvingAsync(n),n}(this._activeBuffer.x!==r||this._activeBuffer.y!==i)&&this._onCursorMove.fire();let s=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),c=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);c<this._bufferService.rows&&this._onRequestRefreshRows.fire({start:Math.min(c,this._bufferService.rows-1),end:Math.min(s,this._bufferService.rows-1)})}print(e,t,n){let r,i,a=this._charsetService.charset,o=this._optionsService.rawOptions.screenReaderMode,s=this._bufferService.cols,c=this._coreService.decPrivateModes.wraparound,l=this._coreService.modes.insertMode,u=this._curAttrData,d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&n-t>0&&d.getWidth(this._activeBuffer.x-1)===2&&d.setCellFromCodepoint(this._activeBuffer.x-1,0,1,u);let f=this._parser.precedingJoinState;for(let p=t;p<n;++p){if(r=e[p],r<127&&a){let e=a[String.fromCharCode(r)];e&&(r=e.charCodeAt(0))}let t=this._unicodeService.charProperties(r,f);i=Dw.extractWidth(t);let n=Dw.extractShouldJoin(t),m=n?Dw.extractWidth(f):0;if(f=t,o&&this._onA11yChar.fire($_(r)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+i-m>s){if(c){let e=d,t=this._activeBuffer.x-m;for(this._activeBuffer.x=m,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),d=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),m>0&&d instanceof qC&&d.copyCellsFrom(e,t,0,m,!1);t<s;)e.setCellFromCodepoint(t++,0,1,u)}else if(this._activeBuffer.x=s-1,i===2)continue}if(n&&this._activeBuffer.x){let e=d.getWidth(this._activeBuffer.x-1)?1:2;d.addCodepointToCell(this._activeBuffer.x-e,r,i);for(let e=i-m;--e>=0;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}else if(l&&(d.insertCells(this._activeBuffer.x,i-m,this._activeBuffer.getNullCell(u)),d.getWidth(s-1)===2&&d.setCellFromCodepoint(s-1,0,1,u)),d.setCellFromCodepoint(this._activeBuffer.x++,r,i,u),i>0)for(;--i;)d.setCellFromCodepoint(this._activeBuffer.x++,0,0,u)}this._parser.precedingJoinState=f,this._activeBuffer.x<s&&n-t>0&&d.getWidth(this._activeBuffer.x)===0&&!d.hasContent(this._activeBuffer.x)&&d.setCellFromCodepoint(this._activeBuffer.x,0,1,u),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final===`t`&&!e.prefix&&!e.intermediates?this._parser.registerCsiHandler(e,e=>!Qw(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)):this._parser.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new zw(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new Fw(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),(t===2||t===0)&&(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){this._restrictCursor(this._bufferService.cols);let n;switch(e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n<this._bufferService.rows;n++)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(n);break;case 1:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n,0,this._activeBuffer.x+1,!0,t),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,i=this._bufferService.rows-1+this._activeBuffer.ybase-r+1;for(;t--;)this._activeBuffer.lines.splice(i-1,1),this._activeBuffer.lines.splice(n,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let n=this._activeBuffer.ybase+this._activeBuffer.y,r;for(r=this._bufferService.rows-1-this._activeBuffer.scrollBottom,r=this._bufferService.rows-1+this._activeBuffer.ybase-r;t--;)this._activeBuffer.lines.splice(n,1),this._activeBuffer.lines.splice(r,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.insertCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.deleteCells(this._activeBuffer.x,e.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(e){let t=e.params[0]||1;for(;t--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(WC));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(0,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.insertCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(e){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;let t=e.params[0]||1;for(let e=this._activeBuffer.scrollTop;e<=this._activeBuffer.scrollBottom;++e){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n.deleteCells(this._activeBuffer.x,t,this._activeBuffer.getNullCell(this._eraseAttrData())),n.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(e){this._restrictCursor();let t=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return t&&(t.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(e.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(e){let t=this._parser.precedingJoinState;if(!t)return!0;let n=e.params[0]||1,r=Dw.extractWidth(t),i=this._activeBuffer.x-r,a=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(i),o=new Uint32Array(a.length*n),s=0;for(let e=0;e<a.length;){let t=a.codePointAt(e)||0;o[s++]=t,e+=t>65535?2:1}let c=s;for(let e=1;e<n;++e)o.copyWithin(c,0,s),c+=s;return this.print(o,0,c),!0}sendDeviceAttributesPrimary(e){return e.params[0]>0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent($.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent($.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent($.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent($.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent($.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,nw),this._charsetService.setgCharset(1,nw),this._charsetService.setgCharset(2,nw),this._charsetService.setgCharset(3,nw);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol=`X10`;break;case 1e3:this._coreMouseService.activeProtocol=`VT200`;break;case 1002:this._coreMouseService.activeProtocol=`DRAG`;break;case 1003:this._coreMouseService.activeProtocol=`ANY`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug(`DECSET 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`SGR`;break;case 1015:this._logService.debug(`DECSET 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`SGR_PIXELS`;break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!0}return!0}resetMode(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(e){for(let t=0;t<e.length;t++)switch(e.params[t]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol=`NONE`;break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug(`DECRST 1005 not supported (see #2507)`);break;case 1006:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 1015:this._logService.debug(`DECRST 1015 not supported (see #2507)`);break;case 1016:this._coreMouseService.activeEncoding=`DEFAULT`;break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),e.params[t]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(void 0),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1;break;case 2026:this._coreService.decPrivateModes.synchronizedOutput=!1,this._onRequestRefreshRows.fire(void 0)}return!0}requestMode(e,t){let n;(e=>(e[e.NOT_RECOGNIZED=0]=`NOT_RECOGNIZED`,e[e.SET=1]=`SET`,e[e.RESET=2]=`RESET`,e[e.PERMANENTLY_SET=3]=`PERMANENTLY_SET`,e[e.PERMANENTLY_RESET=4]=`PERMANENTLY_RESET`))(n||={});let r=this._coreService.decPrivateModes,{activeProtocol:i,activeEncoding:a}=this._coreMouseService,o=this._coreService,{buffers:s,cols:c}=this._bufferService,{active:l,alt:u}=s,d=this._optionsService.rawOptions,f=(e,n)=>(o.triggerDataEvent(`${$.ESC}[${t?``:`?`}${e};${n}$y`),!0),p=e=>e?1:2,m=e.params[0];return t?m===2?f(m,4):m===4?f(m,p(o.modes.insertMode)):m===12?f(m,3):m===20?f(m,p(d.convertEol)):f(m,0):m===1?f(m,p(r.applicationCursorKeys)):m===3?f(m,d.windowOptions.setWinLines?c===80?2:+(c===132):0):m===6?f(m,p(r.origin)):m===7?f(m,p(r.wraparound)):m===8?f(m,3):m===9?f(m,p(i===`X10`)):m===12?f(m,p(d.cursorBlink)):m===25?f(m,p(!o.isCursorHidden)):m===45?f(m,p(r.reverseWraparound)):m===66?f(m,p(r.applicationKeypad)):m===67?f(m,4):m===1e3?f(m,p(i===`VT200`)):m===1002?f(m,p(i===`DRAG`)):m===1003?f(m,p(i===`ANY`)):m===1004?f(m,p(r.sendFocus)):m===1005?f(m,4):m===1006?f(m,p(a===`SGR`)):m===1015?f(m,4):m===1016?f(m,p(a===`SGR_PIXELS`)):m===1048?f(m,1):m===47||m===1047||m===1049?f(m,p(l===u)):m===2004?f(m,p(r.bracketedPasteMode)):m===2026?f(m,p(r.synchronizedOutput)):f(m,0)}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=av.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|n&255),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o<n.length&&o+a+1+i<r.length);break}if(r[1]===5&&a+i>=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t<e.length&&a+i<r.length);for(let e=2;e<r.length;++e)r[e]===-1&&(r[e]=0);switch(r[0]){case 38:n.fg=this._updateAttrColor(n.fg,r[1],r[3],r[4],r[5]);break;case 48:n.bg=this._updateAttrColor(n.bg,r[1],r[3],r[4],r[5]);break;case 58:n.extended=n.extended.clone(),n.extended.underlineColor=this._updateAttrColor(n.extended.underlineColor,r[1],r[3],r[4],r[5])}return a}_processUnderline(e,t){t.extended=t.extended.clone(),(!~e||e>5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=WC.fg,e.bg=WC.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i<t;i++)n=e.params[i],n>=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=n-90|16777224):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=n-100|16777224):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=WC.fg&16777215):n===49?(r.bg&=-67108864,r.bg|=WC.bg&16777215):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=WC.fg&16777215,r.bg&=-67108864,r.bg|=WC.bg&16777215):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${$.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${$.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=WC.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!Qw(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(0);break;case 16:this._onRequestWindowsOptionsReport.fire(1);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${$.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:(t===0||t===2)&&(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>Zw&&this._windowTitleStack.shift()),(t===0||t===1)&&(this._iconNameStack.push(this._iconName),this._iconNameStack.length>Zw&&this._iconNameStack.shift());break;case 23:(t===0||t===2)&&this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),(t===0||t===1)&&this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(rT(n)){if(r===`?`)t.push({type:0,index:n});else{let e=Kw(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex(e=>e.startsWith(`id=`));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e<n.length&&!(t>=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=Kw(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e<n.length;++e)if(/^\d+$/.exec(n[e])){let r=parseInt(n[e]);rT(r)&&t.push({type:2,index:r})}return t.length&&this._onColor.fire(t),!0}restoreFgColor(e){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(e){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(e){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug(`Serial port requested application keypad.`),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug(`Switching back to normal keypad.`),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,nw),!0}selectCharset(e){return e.length===2?(e[0]===`/`||this._charsetService.setgCharset(Yw[e[0]],tw[e[1]]||nw),!0):(this.selectDefaultCharset(),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=WC.clone(),this._eraseAttrDataInternal=WC.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=this._curAttrData.bg&67108863,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new sv;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t<this._bufferService.rows;++t){let n=this._activeBuffer.ybase+this._activeBuffer.y+t,r=this._activeBuffer.lines.get(n);r&&(r.fill(e),r.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(e,t){let n=e=>(this._coreService.triggerDataEvent(`${$.ESC}${e}${$.ESC}\\`),!0),r=this._bufferService.buffer,i=this._optionsService.rawOptions;return n(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${r.scrollTop+1};${r.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[i.cursorStyle]-+!!i.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}},nT=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){e<this.start?this.start=e:e>this.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(eT=e,e=t,t=eT),e<this.start&&(this.start=e),t>this.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};nT=B_([V_(0,mv)],nT);function rT(e){return 0<=e&&e<256}var iT=5e7,aT=12,oT=50,sT=class extends ry{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new Cy),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t){this._syncCalls=0;return}if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;this._isSyncWriting=!0;let n;for(;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>iT)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput){this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),this._innerWrite();return}setTimeout(()=>this._innerWrite())}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch(e=>(queueMicrotask(()=>{throw e}),Promise.resolve(!1))).then(e=>performance.now()-n>=aT?setTimeout(()=>this._innerWrite(0,e)):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=aT)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>oT&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout(()=>this._innerWrite())):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}},cT=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose(()=>this._removeMarkerFromLink(r,n)),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose(()=>this._removeMarkerFromLink(o,a)),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every(e=>e.line!==t)){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose(()=>this._removeMarkerFromLink(n,e))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};cT=B_([V_(0,mv)],cT);var lT=!1,uT=class extends ry{constructor(e){super(),this._windowsWrappingHeuristics=this._register(new iy),this._onBinary=this._register(new Cy),this.onBinary=this._onBinary.event,this._onData=this._register(new Cy),this.onData=this._onData.event,this._onLineFeed=this._register(new Cy),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new Cy),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new Cy),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new Cy),this._instantiationService=new LC,this.optionsService=this._register(new dw(e)),this._instantiationService.setService(bv,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(cw)),this._instantiationService.setService(mv,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(BC)),this._instantiationService.setService(yv,this._logService),this.coreService=this._register(this._instantiationService.createInstance(gw)),this._instantiationService.setService(gv,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(xw)),this._instantiationService.setService(hv,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(Dw)),this._instantiationService.setService(Sv,this.unicodeService),this._charsetService=this._instantiationService.createInstance(Ow),this._instantiationService.setService(_v,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(cT),this._instantiationService.setService(xv,this._oscLinkService),this._inputHandler=this._register(new tT(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(dy.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(dy.forward(this._bufferService.onResize,this._onResize)),this._register(dy.forward(this.coreService.onData,this._onData)),this._register(dy.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom(()=>this.scrollToBottom(!0))),this._register(this.coreService.onUserInput(()=>this._writeBuffer.handleUserInput())),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],()=>this._handleWindowsPtyOptionChange())),this._register(this._bufferService.onScroll(()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)})),this._writeBuffer=this._register(new sT((e,t)=>this._inputHandler.parse(e,t))),this._register(dy.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new Cy),this._onScroll.event(e=>{this._onScrollApi?.fire(e.position)})),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=3&&!lT&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),lT=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,ow),t=Math.max(t,sw),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(kw.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},()=>(kw(this._bufferService),!1))),this._windowsWrappingHeuristics.value=ey(()=>{for(let t of e)t.dispose()})}}},dT={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]};function fT(e,t,n,r){let i={type:0,cancel:!1,key:void 0},a=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?i.key=t?$.ESC+`OA`:$.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?i.key=t?$.ESC+`OD`:$.ESC+`[D`:e.key===`UIKeyInputRightArrow`?i.key=t?$.ESC+`OC`:$.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(i.key=t?$.ESC+`OB`:$.ESC+`[B`);break;case 8:i.key=e.ctrlKey?`\b`:$.DEL,e.altKey&&(i.key=$.ESC+i.key);break;case 9:if(e.shiftKey){i.key=$.ESC+`[Z`;break}i.key=$.HT,i.cancel=!0;break;case 13:i.key=e.altKey?$.ESC+$.CR:$.CR,i.cancel=!0;break;case 27:i.key=$.ESC,e.altKey&&(i.key=$.ESC+$.ESC),i.cancel=!0;break;case 37:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`D`:t?$.ESC+`OD`:$.ESC+`[D`;break;case 39:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`C`:t?$.ESC+`OC`:$.ESC+`[C`;break;case 38:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`A`:t?$.ESC+`OA`:$.ESC+`[A`;break;case 40:if(e.metaKey)break;i.key=a?$.ESC+`[1;`+(a+1)+`B`:t?$.ESC+`OB`:$.ESC+`[B`;break;case 45:!e.shiftKey&&!e.ctrlKey&&(i.key=$.ESC+`[2~`);break;case 46:i.key=a?$.ESC+`[3;`+(a+1)+`~`:$.ESC+`[3~`;break;case 36:i.key=a?$.ESC+`[1;`+(a+1)+`H`:t?$.ESC+`OH`:$.ESC+`[H`;break;case 35:i.key=a?$.ESC+`[1;`+(a+1)+`F`:t?$.ESC+`OF`:$.ESC+`[F`;break;case 33:e.shiftKey?i.type=2:i.key=e.ctrlKey?$.ESC+`[5;`+(a+1)+`~`:$.ESC+`[5~`;break;case 34:e.shiftKey?i.type=3:i.key=e.ctrlKey?$.ESC+`[6;`+(a+1)+`~`:$.ESC+`[6~`;break;case 112:i.key=a?$.ESC+`[1;`+(a+1)+`P`:$.ESC+`OP`;break;case 113:i.key=a?$.ESC+`[1;`+(a+1)+`Q`:$.ESC+`OQ`;break;case 114:i.key=a?$.ESC+`[1;`+(a+1)+`R`:$.ESC+`OR`;break;case 115:i.key=a?$.ESC+`[1;`+(a+1)+`S`:$.ESC+`OS`;break;case 116:i.key=a?$.ESC+`[15;`+(a+1)+`~`:$.ESC+`[15~`;break;case 117:i.key=a?$.ESC+`[17;`+(a+1)+`~`:$.ESC+`[17~`;break;case 118:i.key=a?$.ESC+`[18;`+(a+1)+`~`:$.ESC+`[18~`;break;case 119:i.key=a?$.ESC+`[19;`+(a+1)+`~`:$.ESC+`[19~`;break;case 120:i.key=a?$.ESC+`[20;`+(a+1)+`~`:$.ESC+`[20~`;break;case 121:i.key=a?$.ESC+`[21;`+(a+1)+`~`:$.ESC+`[21~`;break;case 122:i.key=a?$.ESC+`[23;`+(a+1)+`~`:$.ESC+`[23~`;break;case 123:i.key=a?$.ESC+`[24;`+(a+1)+`~`:$.ESC+`[24~`;break;default:if(e.ctrlKey&&!e.shiftKey&&!e.altKey&&!e.metaKey)e.keyCode>=65&&e.keyCode<=90?i.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?i.key=$.NUL:e.keyCode>=51&&e.keyCode<=55?i.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?i.key=$.DEL:e.keyCode===219?i.key=$.ESC:e.keyCode===220?i.key=$.FS:e.keyCode===221&&(i.key=$.GS);else if((!n||r)&&e.altKey&&!e.metaKey){let t=dT[e.keyCode]?.[+!!e.shiftKey];if(t)i.key=$.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),i.key=$.ESC+n}else if(e.keyCode===32)i.key=$.ESC+(e.ctrlKey?$.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),i.key=$.ESC+t,i.cancel=!0}}else n&&!e.altKey&&!e.ctrlKey&&!e.shiftKey&&e.metaKey?e.keyCode===65&&(i.type=1):e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?i.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(i.key=$.US),e.key===`@`&&(i.key=$.NUL))}return i}var pT=0,mT=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new eC,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new eC,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue(()=>this._flushInserted()),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort((e,t)=>this._getKey(e)-this._getKey(t)),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i<r.length;i++)n>=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(pT=this._search(t),pT===-1)||this._getKey(this._array[pT])!==t)return!1;do if(this._array[pT]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue(()=>this._flushDeleted()),this._deletedIndices.push(pT),!0;while(++pT<this._array.length&&this._getKey(this._array[pT])===t);return!1}_flushDeleted(){this._isFlushingDeleted=!0;let e=this._deletedIndices.sort((e,t)=>e-t),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i<this._array.length;i++)e[t]===i?t++:n[r++]=this._array[i];this._array=n,this._deletedIndices.length=0,this._isFlushingDeleted=!1}_flushCleanupDeleted(){!this._isFlushingDeleted&&this._deletedIndices.length>0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(pT=this._search(e),!(pT<0||pT>=this._array.length)&&this._getKey(this._array[pT])===e))do yield this._array[pT];while(++pT<this._array.length&&this._getKey(this._array[pT])===e)}forEachByKey(e,t){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(pT=this._search(e),!(pT<0||pT>=this._array.length)&&this._getKey(this._array[pT])===e))do t(this._array[pT]);while(++pT<this._array.length&&this._getKey(this._array[pT])===e)}values(){return this._flushCleanupInserted(),this._flushCleanupDeleted(),[...this._array].values()}_search(e){let t=0,n=this._array.length-1;for(;n>=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else if(i<e)t=r+1;else{for(;r>0&&this._getKey(this._array[r-1])===e;)r--;return r}}return t}},hT=0,gT=0,_T=class extends ry{constructor(){super(),this._decorations=new mT(e=>e?.marker.line),this._onDecorationRegistered=this._register(new Cy),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new Cy),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register(ey(()=>this.reset()))}get decorations(){return this._decorations.values()}registerDecoration(e){if(e.marker.isDisposed)return;let t=new vT(e);if(t){let e=t.marker.onDispose(()=>t.dispose()),n=t.onDispose(()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())});this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e<i&&(!n||(a.options.layer??`bottom`)===n)&&(yield a)}forEachDecorationAtCell(e,t,n,r){this._decorations.forEachByKey(t,t=>{hT=t.options.x??0,gT=hT+(t.options.width??1),e>=hT&&e<gT&&(!n||(t.options.layer??`bottom`)===n)&&r(t)})}},vT=class extends ny{constructor(e){super(),this.options=e,this.onRenderEmitter=this.add(new Cy),this.onRender=this.onRenderEmitter.event,this._onDispose=this.add(new Cy),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=e.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position=`full`)}get backgroundColorRGB(){return this._cachedBg===null&&(this._cachedBg=this.options.backgroundColor?tS.toColor(this.options.backgroundColor):void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this._cachedFg=this.options.foregroundColor?tS.toColor(this.options.foregroundColor):void 0),this._cachedFg}dispose(){this._onDispose.fire(),super.dispose()}},yT=1e3,bT=class{constructor(e,t=yT){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout(()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0},t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}},xT=20,ST=class extends ry{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);if(this._topBoundaryFocusListener=e=>this._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new bT(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize(e=>this._handleResize(e.rows))),this._register(this._terminal.onRender(e=>this._refreshRows(e.start,e.end))),this._register(this._terminal.onScroll(()=>this._refreshRows())),this._register(this._terminal.onA11yChar(e=>this._handleChar(e))),this._register(this._terminal.onLineFeed(()=>this._handleChar(`
|
|
331
331
|
`))),this._register(this._terminal.onA11yTab(e=>this._handleTab(e))),this._register(this._terminal.onKey(e=>this._handleKey(e.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(Jb(i,`selectionchange`,()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(ey(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(` `)}_handleChar(e){this._liveRegionLineCount<xT+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===`
|
|
332
332
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===xT+1&&(this._liveRegion.textContent+=G_.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error(`anchorNode and/or focusNode are null`);return}let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t<i.length?i[t]:i.slice(-1)[0]+1;return a>=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>e;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(e){e.style.transform=``;let t=e.getBoundingClientRect().width,n=this._rowColumns.get(e)?.slice(-1)?.[0];if(!n)return;let r=n*this._renderService.dimensions.css.cell.width;e.style.transform=`scaleX(${r/t})`}};ST=B_([V_(1,vv),V_(2,Dv),V_(3,kv)],ST);var CT=class extends ry{constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new Cy),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new Cy),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(ey(()=>{Qv(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(Jb(this._element,`mouseleave`,()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(Jb(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register(Jb(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register(Jb(this._element,`mouseup`,this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e<n.length;e++){let t=n[e];if(t.classList.contains(`xterm`))break;if(t.classList.contains(`xterm-hover`))return}(!this._lastBufferCell||t.x!==this._lastBufferCell.x||t.y!==this._lastBufferCell.y)&&(this._handleHover(t),this._lastBufferCell=t)}_handleHover(e){this._activeLine!==e.y||this._wasResized?(this._clearCurrentLink(),this._askForLink(e,!1),this._wasResized=!1):this._currentLink&&this._linkAtPosition(this._currentLink.link,e)||(this._clearCurrentLink(),this._askForLink(e,!0))}_askForLink(e,t){(!this._activeProviderReplies||!t)&&(this._activeProviderReplies?.forEach(e=>{e?.forEach(e=>{e.link.dispose&&e.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,t=>{if(this._isMouseOut)return;let i=t?.map(e=>({link:e}));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)})}_removeIntersectingLinks(e,t){let n=new Set;for(let r=0;r<t.size;r++){let i=t.get(r);if(i)for(let t=0;t<i.length;t++){let r=i[t],a=r.link.range.start.y<e?0:r.link.range.start.x,o=r.link.range.end.y>e?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;t<e;t++)(!this._activeProviderReplies.has(t)||this._activeProviderReplies.get(t))&&(i=!0);if(!i&&r){let e=r.find(e=>this._linkAtPosition(e.link,t));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;e<this._activeProviderReplies.size;e++){let r=this._activeProviderReplies.get(e)?.find(e=>this._linkAtPosition(e.link,t));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);t&&this._mouseDownLink&&wT(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){!this._currentLink||!this._lastMouseEvent||(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Qv(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}})))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};CT=B_([V_(1,Ov),V_(2,kv),V_(3,mv),V_(4,Nv)],CT);function wT(e,t){return e.text===t.text&&e.range.start.x===t.range.start.x&&e.range.start.y===t.range.start.y&&e.range.end.x===t.range.end.x&&e.range.end.y===t.range.end.y}var TT=class extends uT{constructor(e={}){super(e),this._linkifier=this._register(new iy),this.browser=LS,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new iy),this._onCursorMove=this._register(new Cy),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new Cy),this.onKey=this._onKey.event,this._onRender=this._register(new Cy),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new Cy),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new Cy),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new Cy),this.onBell=this._onBell.event,this._onFocus=this._register(new Cy),this._onBlur=this._register(new Cy),this._onA11yCharEmitter=this._register(new Cy),this._onA11yTabEmitter=this._register(new Cy),this._onWillOpen=this._register(new Cy),this._setup(),this._decorationService=this._instantiationService.createInstance(_T),this._instantiationService.setService(Cv,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(MS),this._instantiationService.setService(Nv,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(wv)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh(e?.start??0,e?.end??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(dy.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(dy.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(dy.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(dy.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(ey(()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=eS.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${$.ESC}]${n};${Jw(r)}${Kx.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors(e=>e.ansi[t.index]=$x.toColor(...t.color));else{let n=e;this._themeService.modifyColors(e=>e[n]=$x.toColor(...t.color))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(ST,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent($.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register(Jb(this.element,`copy`,e=>{this.hasSelection()&&J_(e,this._selectionService)}));let e=e=>Y_(e,this.textarea,this.coreService,this.optionsService);this._register(Jb(this.textarea,`paste`,e)),this._register(Jb(this.element,`paste`,e)),VS?this._register(Jb(this.element,`mousedown`,e=>{e.button===2&&Q_(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(Jb(this.element,`contextmenu`,e=>{Q_(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),YS&&this._register(Jb(this.element,`auxclick`,e=>{e.button===1&&Z_(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(Jb(this.textarea,`keyup`,e=>this._keyUp(e),!0)),this._register(Jb(this.textarea,`keydown`,e=>this._keyDown(e),!0)),this._register(Jb(this.textarea,`keypress`,e=>this._keyPress(e),!0)),this._register(Jb(this.textarea,`compositionstart`,()=>this._compositionHelper.compositionstart())),this._register(Jb(this.textarea,`compositionupdate`,e=>this._compositionHelper.compositionupdate(e))),this._register(Jb(this.textarea,`compositionend`,()=>this._compositionHelper.compositionend())),this._register(Jb(this.textarea,`input`,e=>this._inputEvent(e),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register(Jb(this.screenElement,`mousemove`,e=>this.updateCursorStyle(e))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,U_.get()),XS||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,()=>n.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(AS,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(Dv,this._coreBrowserService),this._register(Jb(this.textarea,`focus`,e=>this._handleTextAreaFocus(e))),this._register(Jb(this.textarea,`blur`,()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(ES,this._document,this._helperContainer),this._instantiationService.setService(Ev,this._charSizeService),this._themeService=this._instantiationService.createInstance(PC),this._instantiationService.setService(Mv,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(sS),this._instantiationService.setService(jv,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(nC,this.rows,this.screenElement)),this._instantiationService.setService(kv,this._renderService),this._register(this._renderService.onRenderedViewportChange(e=>this._onRender.fire(e))),this.onResize(e=>this._renderService.resize(e.cols,e.rows)),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(qx,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(FS),this._instantiationService.setService(Ov,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(CT,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(Rx,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(wC,this.element,this.screenElement,r)),this._instantiationService.setService(Av,this._selectionService),this._register(this._selectionService.onRequestScrollLines(e=>this.scrollLines(e.amount,e.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()})),this._register(dy.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{this._selectionService.refresh(),this._viewport?.queueSync()})),this._register(this._instantiationService.createInstance(zx,this.screenElement)),this._register(Jb(this.element,`mousedown`,e=>this._selectionService.handleMouseDown(e))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(ST,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,e=>this._handleScreenReaderModeOptionChange(e))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Wx,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(Wx,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(TS,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=t.buttons&1?0:t.buttons&4?1:t.buttons&2?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&e._customWheelEventHandler(t)===!1)return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return i===void 0||r===void 0||r>4?!1:e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange(e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),e&8?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),e&16?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),e&2?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),e&4?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(Jb(t,`mousedown`,e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)})),this._register(Jb(t,`wheel`,t=>{if(!r.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(t)===!1)return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=$.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}},{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){X_(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!t&&(e.key===`Dead`||e.key===`AltGraph`)&&(this._unprocessedDeadKey=!0);let n=fT(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}if(n.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key)||e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((n.key===$.ETX||n.key===$.CR)&&(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey)return this.cancel(e,!0);this._keyDownHandled=!0}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)&&(ET(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(e)===!1)return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else if(e.which!==0&&e.charCode!==0)t=e.which;else return!1;return!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)?!1:(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e===this.cols&&t===this.rows?this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure():super.resize(e,t)}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e<this.rows;e++)this.buffer.lines.push(this.buffer.getBlankLine(WC));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;let e=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this._customKeyEventHandler=e,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains(`focus`)?this.coreService.triggerDataEvent($.ESC+`[I`):this.coreService.triggerDataEvent($.ESC+`[O`)}_reportWindowsOptions(e){if(this._renderService)switch(e){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),t=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[4;${t};${e}t`);break;case 1:let n=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${$.ESC}[6;${r};${n}t`)}}cancel(e,t){if(this.options.cancelEvents||t)return e.preventDefault(),e.stopPropagation(),!1}};function ET(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}var DT=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n<this._addons.length;n++)if(this._addons[n]===e){t=n;break}if(t===-1)throw Error(`Could not dispose an addon that has not been loaded`);e.isDisposed=!0,e.dispose.apply(e.instance),this._addons.splice(t,1)}},OT=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new sv)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}},kT=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new OT(t)}getNullCell(){return new sv}},AT=class extends ry{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new Cy),this.onBufferChange=this._onBufferChange.event,this._normal=new kT(this._core.buffers.normal,`normal`),this._alternate=new kT(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},jT=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,e=>t(e.toArray()))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,(e,n)=>t(e,n.toArray()))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}},MT=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}},NT=[`cols`,`rows`],PT=0,FT=class extends ry{constructor(e){super(),this._core=this._register(new TT(e)),this._addonManager=this._register(new DT),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(NT.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new jT(this._core),this._parser}get unicode(){return this._checkProposedApi(),new MT(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new AT(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r
|
|
333
|
-
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return U_.get()},set promptLabel(e){U_.set(e)},get tooMuchOutput(){return G_.get()},set tooMuchOutput(e){G_.set(e)}}}_verifyIntegers(...e){for(PT of e)if(PT===1/0||isNaN(PT)||PT%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(PT of e)if(PT&&(PT===1/0||isNaN(PT)||PT%1!=0||PT<0))throw Error(`This API only accepts positive integers`)}},IT=2,LT=1,RT=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(IT,Math.floor(u/e.css.cell.width)),rows:Math.max(LT,Math.floor(l/e.css.cell.height))}}},zT=`super-pi.terminal-owner.v1`,BT=`super-pi.terminal-selection.v1.`,VT=20,HT=5,UT=240,WT=120,GT={checking:`正在连接`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`,empty:`没有打开的终端`},KT=new WeakSet,qT;function JT(){if(qT)return qT;try{let e=window.localStorage.getItem(zT);if(e&&/^[0-9a-f]{32}$/.test(e))return qT=e}catch{}qT=Array.from(window.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``);try{window.localStorage.setItem(zT,qT)}catch{}return qT}function YT(e){try{return window.sessionStorage.getItem(e)??void 0}catch{return}}function XT({workspaceId:e,workspaceLabel:t,cwd:n=``,connected:r,sendCommand:i,registerSink:a,conversationId:o,terminalShell:s,focusRequest:c}){let l=BT+JSON.stringify([e,o]),[u,d]=(0,p.useState)([]),[f,h]=(0,p.useState)(()=>YT(l)??``),[g,_]=(0,p.useState)(!1),[v,y]=(0,p.useState)(),[b,x]=(0,p.useState)(``),[S,C]=(0,p.useState)(``),w=(0,p.useRef)(new Map),T=(0,p.useRef)(new Map),E=(0,p.useRef)(new Map),D=(0,p.useRef)(new Map),O=(0,p.useRef)(!1),k=(0,p.useRef)(f);k.current=f;let A=(0,p.useRef)(!1),j=(0,p.useRef)(null),ee=(0,p.useRef)(!1),M=(0,p.useRef)(0),N=(0,p.useRef)(void 0),P=(0,p.useCallback)(()=>{cancelAnimationFrame(M.current),M.current=requestAnimationFrame(()=>{let e=k.current,t=T.current.get(e);ee.current&&O.current&&t&&!D.current.has(e)&&t.host.clientWidth&&t.host.clientHeight&&(t.terminal.focus(),ee.current=!1)})},[]);(0,p.useLayoutEffect)(()=>{c&&!KT.has(c)&&c.request!==N.current&&c.workspaceId===e&&c.conversationId===o&&(KT.add(c),N.current=c.request,ee.current=!0,P())},[c,e,o,P]),(0,p.useEffect)(()=>{let e=()=>{ee.current=!1,A.current=!1},t=t=>{t.target instanceof Node&&!j.current?.contains(t.target)&&e()};return document.addEventListener(`pointerdown`,t,!0),document.addEventListener(`keydown`,t,!0),window.addEventListener(`blur`,e),()=>{cancelAnimationFrame(M.current),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,t,!0),window.removeEventListener(`blur`,e)}},[]);let F=(0,p.useCallback)(e=>{let t=T.current.get(e);if(!t||!t.host.clientWidth||!t.host.clientHeight||D.current.has(e))return;let{terminal:n,fitAddon:r}=t,a=r.proposeDimensions();if(!a||!Number.isFinite(a.cols)||!Number.isFinite(a.rows))return;let o=Math.max(VT,Math.min(UT,a.cols)),s=Math.max(HT,Math.min(WT,a.rows));(n.cols!==o||n.rows!==s)&&n.resize(o,s);let c=w.current.get(e);O.current&&c&&c.exitCode===void 0&&(c.cols!==o||c.rows!==s)&&i({type:`terminal.resize`,sessionId:e,cols:o,rows:s})},[i]),I=(0,p.useCallback)((e,t)=>{let n=e.sessionId;if(e.type===`terminal.output`){t.write(e.data);return}let r=w.current.get(n),i=D.current.get(n);r&&t.resize(r.cols,r.rows),t.write(`\x1Bc\x1B[3J`+e.data,()=>{D.current.get(n)===i&&(D.current.delete(n),k.current===n&&(F(n),P()))})},[F,P]),te=(0,p.useCallback)((e,t)=>{if(!t||T.current.has(e))return;let n=getComputedStyle(t),r=(e,t)=>n.getPropertyValue(e).trim()||t,a=w.current.get(e),o=new FT({cols:a?.cols,rows:a?.rows,cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:r(`--term-fg`,`#dbe4f0`),cursor:r(`--term-fg`,`#dbe4f0`),selectionBackground:r(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),s=new RT;o.loadAddon(s),o.open(t),o.onData(t=>{O.current&&!D.current.has(e)&&w.current.get(e)?.exitCode===void 0&&i({type:`terminal.input`,sessionId:e,data:t})}),T.current.set(e,{terminal:o,fitAddon:s,host:t});for(let t of E.current.get(e)??[])I(t,o);E.current.delete(e),requestAnimationFrame(()=>F(e))},[F,i,I]),ne=(0,p.useCallback)(t=>{if(t.type===`terminal.sessions`){if(t.workspaceId!==e||t.conversationId!==o)return;let n=new Map(t.sessions.map(e=>[e.id,e]));for(let[e,r]of T.current)n.has(e)?!t.replay&&w.current.get(e)?.exitCode!==void 0&&n.get(e)?.exitCode===void 0&&r.terminal.write(`\x1Bc\x1B[3J`):(r.terminal.dispose(),T.current.delete(e));for(let e of E.current.keys())(!n.has(e)||t.replay)&&E.current.delete(e);if(t.replay){D.current.clear();for(let e of n.keys())D.current.set(e,Symbol())}!t.replay&&A.current&&t.activate&&n.has(t.activate)&&(ee.current=!0,A.current=!1),w.current=n,O.current=!0,d(t.sessions),h(e=>t.activate??(n.has(e)?e:t.sessions[0]?.id??``)),y(void 0),_(!0)}else if(t.type===`terminal.output`||t.type===`terminal.replay`){if(!w.current.has(t.sessionId))return;let e=T.current.get(t.sessionId)?.terminal;if(e)I(t,e);else{let e=E.current.get(t.sessionId)??[];e.push(t),E.current.set(t.sessionId,e)}}else if(t.type===`terminal.size`){let e=w.current.get(t.sessionId);e&&(Object.assign(e,{cols:t.cols,rows:t.rows}),T.current.get(e.id)?.terminal.resize(e.cols,e.rows))}else if(t.type===`terminal.exit`){let e=w.current.get(t.sessionId);if(!e)return;let n={...e,exitCode:t.exitCode,reason:t.reason};w.current.set(n.id,n),d(e=>e.map(e=>e.id===n.id?n:e))}else(t.type===`terminal.error`||t.type===`terminal.status`&&!t.enabled)&&(A.current=!1,y(void 0),x(t.type===`terminal.error`?t.message:t.reason||`终端未启用`))},[o,e,I]);(0,p.useEffect)(()=>(a(ne),()=>a(void 0)),[ne,a]);let re=(0,p.useCallback)(()=>{O.current=!1,_(!1),y(void 0),x(``),r&&e&&i({type:`terminal.sync`,ownerId:JT(),workspaceId:e,conversationId:o,cwd:n,initialize:YT(l)===void 0})},[r,e,o,n,l,i]);(0,p.useEffect)(()=>(re(),()=>{r&&i({type:`terminal.detach`})}),[r,i,re]),(0,p.useEffect)(()=>()=>{O.current=!1;for(let e of T.current.values())e.terminal.dispose();T.current.clear()},[]),(0,p.useEffect)(()=>{if(g)try{window.sessionStorage.setItem(l,f)}catch{}},[f,g,l]),(0,p.useEffect)(()=>{let e=!1;return Ie(`/api/terminal-shell`).then(e=>e.json()).then(t=>{let n=t.shell;!e&&n&&C(n.file+(n.args.length?` `+n.args.join(` `):``)+`(`+(t.source??``)+`)`)}).catch(()=>void 0),()=>{e=!0}},[s?.file,s?.args.join(`\0`)]),(0,p.useLayoutEffect)(()=>{let e=T.current.get(f);if(!e)return;let t=new ResizeObserver(()=>{F(f),P()});return t.observe(e.host),F(f),P(),()=>t.disconnect()},[f,F,u,P]);let ie=e=>!r||!g||v?!1:i(e)?(x(``),y(e.type===`terminal.open`?`open`:`close`),!0):!1,ae=e=>{let t=T.current.get(f)?.terminal;A.current=!0,ie({type:`terminal.open`,sessionId:e,cols:t?.cols,rows:t?.rows})||(A.current=!1)},oe=u.find(e=>e.id===f),se=r&&g&&!v,ce=e?r?g?v===`open`?`starting`:oe?oe.exitCode===void 0?`running`:`exited`:`empty`:b?`unavailable`:`checking`:`checking`:`unavailable`,le=b||oe?.reason;return(0,m.jsxs)(`div`,{ref:j,className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":ce,children:[(0,m.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[u.map(e=>(0,m.jsxs)(`div`,{className:`terminal-tab${e.id===f?` is-active`:``}`,children:[(0,m.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===f,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>{ee.current=!0,h(e.id),P()},title:GT[e.exitCode===void 0?`running`:`exited`],children:[(0,m.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.exitCode===void 0?`running`:`exited`}`,"aria-hidden":`true`}),e.title]}),(0,m.jsx)(`button`,{type:`button`,className:`terminal-tab-close`,disabled:!se,"aria-label":`关闭终端 ${e.title}`,"data-terminal-slot-close":e.id,onClick:()=>ie({type:`terminal.close`,sessionId:e.id}),children:(0,m.jsx)(vi,{name:`close`})})]},e.id)),u.length<5&&(0,m.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,disabled:!se,"data-terminal-add":`1`,onClick:()=>ae(),title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,m.jsxs)(`div`,{className:`terminal-toolbar`,children:[(0,m.jsxs)(`span`,{className:`terminal-status terminal-status-${ce}`,"data-terminal-status":ce,children:[(0,m.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),GT[ce]]}),(0,m.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[S&&(0,m.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-shell-hint":`1`,title:S,children:S}),t&&(0,m.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),oe?.exitCode!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,disabled:!se,onClick:()=>ae(oe.id),children:`重新打开`}),!g&&b&&r&&(0,m.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,onClick:re,children:`重试连接`})]})]}),le&&(0,m.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,title:Br(le),children:zr(le,`终端出错了。`)}),oe?.exitCode!==void 0&&oe.exitCode!==0&&(0,m.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,oe.exitCode,`。`]}),(0,m.jsxs)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:[u.map(e=>(0,m.jsx)(`div`,{ref:t=>te(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===f?`block`:`none`}},e.id)),ce===`empty`&&(0,m.jsx)(`div`,{className:`terminal-surface-empty`,"data-terminal-empty":`1`,children:(0,m.jsx)(`p`,{className:`rail-empty`,children:GT.empty})}),!oe&&ce===`checking`&&(0,m.jsx)(`p`,{className:`rail-empty terminal-surface-message`,"data-terminal-phase":`checking`,children:`正在连接终端…`}),!e&&(0,m.jsx)(`p`,{className:`rail-empty terminal-surface-message`,children:`选择一个工作区后即可打开终端。`})]})]})}function ZT({id:e,title:t,icon:n,count:r,actions:i,children:a}){let o=(0,p.useId)();return(0,m.jsx)(Mi,{id:e,header:!1,children:(0,m.jsxs)(`section`,{className:`rail-card`,"data-rail-section":e,"aria-labelledby":o,children:[(0,m.jsxs)(`div`,{className:`rail-section-head`,children:[(0,m.jsx)(`h2`,{className:`rail-section-title`,id:o,children:(0,m.jsxs)(Ni,{id:e,children:[(0,m.jsx)(QT,{kind:n}),t]})}),r&&(0,m.jsx)(`span`,{className:`rail-section-count`,children:r}),i,(0,m.jsx)(Pi,{id:e})]}),(0,m.jsx)(`div`,{className:`rail-card-body`,children:a})]})})}function QT({kind:e}){return(0,m.jsx)(`svg`,{className:`rail-section-icon`,viewBox:`0 0 24 24`,width:`16`,height:`16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.7`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:e===`tasks`?(0,m.jsx)(m.Fragment,{children:(0,m.jsx)(`path`,{d:`m3 6 2 2 3-4M11 6h10M3 13h5m3 0h10M3 20h5m3 0h10`})}):e===`clock`?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`}),(0,m.jsx)(`path`,{d:`M12 7v5l3 2`})]}):(0,m.jsx)(m.Fragment,{children:(0,m.jsx)(`path`,{d:`M3 12h4l3-7 4 14 3-7h4`})})})}var $T=[{day:1,label:`一`},{day:2,label:`二`},{day:3,label:`三`},{day:4,label:`四`},{day:5,label:`五`},{day:6,label:`六`},{day:0,label:`日`}];function eE(e){return e.kind===`interval`?`每隔 ${e.everyMinutes} 分钟`:e.kind===`daily`?`每天 ${e.time}`:e.kind===`weekly`?`每周${e.weekdays.map(e=>$T.find(t=>t.day===e)?.label??`?`).join(`、`)} ${e.time}`:`仅一次:${tE(e.at)}`}function tE(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function nE(){return typeof Intl<`u`?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function rE(e,t){let n=new Date(e);if(!t){let e=e=>String(e).padStart(2,`0`);return`${n.getFullYear()}-${e(n.getMonth()+1)}-${e(n.getDate())} ${e(n.getHours())}:${e(n.getMinutes())}`}let r=new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).formatToParts(n),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`year`)}-${i(`month`)}-${i(`day`)} ${i(`hour`)}:${i(`minute`)}`}function iE(e,t){let n=new Date(e);if(!t){let e=e=>String(e).padStart(2,`0`);return`${e(n.getHours())}:${e(n.getMinutes())}`}let r=new Intl.DateTimeFormat(`en-GB`,{timeZone:t,hour:`2-digit`,minute:`2-digit`,hour12:!1}).formatToParts(n),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`hour`)}:${i(`minute`)}`}function aE(e,t){if(!e)return``;try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e,timeZoneName:`shortOffset`}).formatToParts(t).find(e=>e.type===`timeZoneName`)?.value??e}catch{return e}}function oE(e,t,n){let r=iE(e,n),i=sE(e,t,n);return i===0?`今天 ${r}`:i===1?`明天 ${r}`:rE(e,n)}function sE(e,t,n){let r=e=>{let[t]=rE(e,n).split(` `),[r,i,a]=t.split(`-`).map(Number);return Date.UTC(r,i-1,a)},i=Math.round((r(e)-r(t))/864e5);return Number.isFinite(i)?i:0}function cE(e,t,n){if(!e||!t||e===t)return``;let r=aE(e,n),i=aE(t,n);return iE(n,e)===iE(n,t)?`服务器在 ${r} 时区,你的时区也是 ${i},下面的时间按你的时区显示`:`服务器在 ${r} 时区,下面的时间按你的时区(${i})显示`}function lE(e,t,n){return e.enabled?e.nextRunAt===void 0?{glyph:`✓`,word:`已结束`,detail:``}:{glyph:`●`,word:`启用中`,detail:`下次 ${oE(e.nextRunAt,t,n)}`}:e.schedule.kind===`once`&&e.lastRunAt!==void 0?{glyph:`✓`,word:`已结束`,detail:e.lastRunAt?`上次 ${rE(e.lastRunAt,n)}`:``}:{glyph:`○`,word:`已停用`,detail:``}}function uE(e,t){if(e.lastRunAt===void 0)return``;let n=rE(e.lastRunAt,t);return e.lastRunStatus===`failed`?`上次 ${n} · 失败${e.lastRunMessage?`:${e.lastRunMessage}`:``}`:`上次 ${n} · 成功`}function dE({tasks:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,serverTimeZone:o}){let[s,c]=(0,p.useState)(()=>Date.now()),[l,u]=(0,p.useState)();(0,p.useEffect)(()=>{let e=window.setInterval(()=>c(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let d=nE(),f=cE(o,d,s),h=e=>{i({type:`scheduledTask.toggle`,id:e.id,enabled:!e.enabled})},g=e=>{i({type:`scheduledTask.trigger`,id:e.id}),a(`已触发「${e.name}」,结果会出现在它自己的会话里。`,`info`)},_=e=>{i({type:`scheduledTask.delete`,id:e.id}),a(`已删除定时任务「${e.name}」,它的会话和结果保留着。`,`info`)};return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(ZT,{id:`scheduled`,title:`定时任务`,icon:`clock`,count:(0,m.jsx)(`span`,{"data-sched-count":`1`,children:e.length?`${e.length} 个`:`0 个`}),actions:(0,m.jsx)(`button`,{type:`button`,className:`scheduled-add`,"data-sched-add":`1`,title:`新建定时任务`,onClick:()=>u(`new`),children:`+ 新建`}),children:[f&&(0,m.jsx)(`p`,{className:`scheduled-zone-note`,"data-sched-zone-note":`1`,children:f}),e.length>0?(0,m.jsx)(`ul`,{className:`scheduled-list`,"data-sched-list":`1`,children:e.map(e=>{let t=lE(e,s,d),n=uE(e,d);return(0,m.jsxs)(`li`,{className:`scheduled-item`,"data-scheduled-task":e.id,children:[(0,m.jsx)(`button`,{type:`button`,className:`scheduled-toggle`,"data-sched-toggle":`1`,title:e.enabled?`点击停用`:`点击启用`,"aria-label":e.enabled?`停用 ${e.name}`:`启用 ${e.name}`,onClick:()=>h(e),children:t.glyph}),(0,m.jsxs)(`div`,{className:`scheduled-main`,children:[(0,m.jsxs)(`div`,{className:`scheduled-name-row`,children:[(0,m.jsx)(`span`,{className:`scheduled-name`,children:e.name}),(0,m.jsx)(`span`,{className:`scheduled-status-word`,"data-sched-word":`1`,children:t.word}),e.createdBy===`agent`&&(0,m.jsx)(`span`,{className:`scheduled-by`,title:`这个定时任务是 agent 创建的,你可以像编辑自己建的一样编辑它`,children:`agent`})]}),(0,m.jsxs)(`div`,{className:`scheduled-meta`,"data-sched-meta":`1`,children:[eE(e.schedule),t.detail?` · ${t.detail}`:``]}),n&&(0,m.jsx)(`div`,{className:`scheduled-last`,"data-sched-last":`1`,children:n})]}),(0,m.jsxs)(`div`,{className:`scheduled-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-trigger":`1`,title:`立即执行一次(不改变周期)`,"aria-label":`立即执行 ${e.name}`,onClick:()=>g(e),children:`⚡`}),(0,m.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-edit":`1`,title:`编辑`,"aria-label":`编辑 ${e.name}`,onClick:()=>u(e),children:`✎`}),(0,m.jsx)(`button`,{type:`button`,className:`scheduled-action scheduled-action-danger`,"data-sched-delete":`1`,title:`删除(会话与结果保留)`,"aria-label":`删除 ${e.name}`,onClick:()=>_(e),children:`✕`})]})]},e.id)})}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-sched-empty":`1`,children:`还没有定时任务。可以新建周期任务,或让 AI 安排。`})]}),l!==void 0&&(0,m.jsx)(hE,{task:l===`new`?void 0:l,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:()=>u(void 0)},l===`new`?`new`:l.id)]})}function fE(e){let t=e?.schedule;return{name:e?.name??``,prompt:e?.prompt??``,kind:t?.kind??`daily`,everyMinutes:t?.kind===`interval`?String(t.everyMinutes):`30`,time:t&&(t.kind===`daily`||t.kind===`weekly`)?t.time:`09:00`,weekdays:t?.kind===`weekly`?[...t.weekdays]:[1],onceAt:t?.kind===`once`?pE(t.at):``,modelKey:e?.model?`${e.model.provider}/${e.model.modelId}`:``,agentId:e?.agentId??``}}function pE(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function mE(e){if(e.kind===`interval`){let t=Number(e.everyMinutes);return!Number.isInteger(t)||t<1||t>10080?{ok:!1,reason:`间隔分钟数要是一个 1 到 10080 之间的整数。`}:{ok:!0,schedule:{kind:`interval`,everyMinutes:t}}}if(e.kind===`daily`||e.kind===`weekly`){let t=/^(\d{1,2}):(\d{2})$/.exec(e.time.trim()),n=t?Number(t[1]):NaN,r=t?Number(t[2]):NaN;if(!t||n>23||r>59)return{ok:!1,reason:`触发时刻要写成 HH:MM,比如 09:00。`};let i=`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`;return e.kind===`daily`?{ok:!0,schedule:{kind:`daily`,time:i}}:e.weekdays.length?{ok:!0,schedule:{kind:`weekly`,weekdays:[...e.weekdays].sort((e,t)=>e-t),time:i}}:{ok:!1,reason:`每周任务至少要选一天。`}}if(!e.onceAt)return{ok:!1,reason:`选一下这一次的运行时刻。`};let t=new Date(e.onceAt).getTime();return Number.isNaN(t)?{ok:!1,reason:`这一次的运行时刻不是有效时间。`}:{ok:!0,schedule:{kind:`once`,at:t}}}function hE({task:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:o}){let[s,c]=(0,p.useState)(()=>fE(e)),[l,u]=(0,p.useState)();(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let d=e=>{c(t=>({...t,...e})),u(void 0)};return(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-sched-dialog-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&o()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`scheduled-dialog-title`,"data-sched-dialog":`1`,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsx)(`h2`,{className:`tool-dialog-title`,id:`scheduled-dialog-title`,children:e?`编辑定时任务`:`新建定时任务`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-sched-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭定时任务编辑`,onClick:o,children:`✕`})]}),(0,m.jsxs)(`div`,{className:`tool-dialog-body scheduled-form`,children:[(0,m.jsxs)(`label`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`名称`}),(0,m.jsx)(`input`,{className:`scheduled-input`,"data-sched-field":`name`,value:s.name,placeholder:`留空则取提示词首句`,onChange:e=>d({name:e.target.value})})]}),(0,m.jsxs)(`label`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`提示词`}),(0,m.jsx)(`textarea`,{className:`scheduled-textarea`,"data-sched-field":`prompt`,rows:5,value:s.prompt,placeholder:`到点时这段话会作为用户消息发给 agent,所以它要是一条完整、自包含的指令`,onChange:e=>d({prompt:e.target.value})})]}),(0,m.jsxs)(`div`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`周期`}),(0,m.jsx)(`div`,{className:`scheduled-kind-row`,role:`radiogroup`,"aria-label":`周期类型`,children:[[`interval`,`每隔 N 分钟`],[`daily`,`每天`],[`weekly`,`每周`],[`once`,`仅一次`]].map(([e,t])=>(0,m.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":s.kind===e,className:`scheduled-kind${s.kind===e?` scheduled-kind-active`:``}`,"data-sched-kind":e,onClick:()=>d({kind:e}),children:t},e))})]}),s.kind===`interval`&&(0,m.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`间隔`}),(0,m.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`everyMinutes`,inputMode:`numeric`,value:s.everyMinutes,onChange:e=>d({everyMinutes:e.target.value})}),(0,m.jsx)(`span`,{className:`scheduled-hint`,children:`分钟(1 – 10080)`})]}),(s.kind===`daily`||s.kind===`weekly`)&&(0,m.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,m.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`time`,inputMode:`numeric`,placeholder:`09:00`,value:s.time,onChange:e=>d({time:e.target.value})}),(0,m.jsx)(`span`,{className:`scheduled-hint`,children:`服务器本地时间,每天/每周的这一天到点触发`})]}),s.kind===`weekly`&&(0,m.jsxs)(`div`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`星期`}),(0,m.jsx)(`div`,{className:`scheduled-weekdays`,children:$T.map(({day:e,label:t})=>{let n=s.weekdays.includes(e);return(0,m.jsx)(`button`,{type:`button`,"aria-pressed":n,className:`scheduled-weekday${n?` scheduled-weekday-on`:``}`,"data-sched-weekday":e,onClick:()=>d({weekdays:n?s.weekdays.filter(t=>t!==e):[...s.weekdays,e]}),children:t},e)})})]}),s.kind===`once`&&(0,m.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,m.jsx)(`input`,{className:`scheduled-input`,type:`datetime-local`,"data-sched-field":`onceAt`,value:s.onceAt,onChange:e=>d({onceAt:e.target.value})}),(0,m.jsx)(`span`,{className:`scheduled-hint`,children:`这一次运行之后就结束`})]}),(0,m.jsxs)(`label`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`模型`}),(0,m.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`model`,value:s.modelKey,onChange:e=>d({modelKey:e.target.value}),children:[(0,m.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(n?.models??[]).map(e=>(0,m.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,`(`,e.detail,`)`]},`${e.provider}/${e.modelId}`))]})]}),(0,m.jsxs)(`label`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`Agent`}),(0,m.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`agent`,value:s.agentId,onChange:e=>d({agentId:e.target.value}),children:[(0,m.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(r?.agents??[]).map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name??e.id},e.id))]})]}),l&&(0,m.jsx)(`p`,{className:`scheduled-error`,"data-sched-error":`1`,role:`alert`,children:l}),(0,m.jsxs)(`div`,{className:`scheduled-actions-row`,children:[(0,m.jsx)(`button`,{type:`button`,className:`scheduled-cancel`,onClick:o,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`scheduled-save`,"data-sched-save":`1`,onClick:()=>{let r=s.prompt.trim();if(!r){u(`定时任务需要一段提示词:到点时这段话会被当作用户消息发给 agent。`);return}if(!t){u(`先选一个工作区,再建定时任务。`);return}let c=mE(s);if(!c.ok){u(c.reason);return}let l=n?.models.find(e=>`${e.provider}/${e.modelId}`===s.modelKey),d=l?{provider:l.provider,modelId:l.modelId,label:l.label}:null,f=s.agentId||null,p=s.name.trim()||void 0;i(e?{type:`scheduledTask.update`,id:e.id,name:p,prompt:r,schedule:c.schedule,model:d,agentId:f}:{type:`scheduledTask.create`,name:p,prompt:r,schedule:c.schedule,workspaceId:t,model:d,agentId:f})?(a(e?`已保存对「${s.name.trim()||e.name}」的修改。`:`定时任务已创建,到点会自动运行。`,`info`),o()):u(`连接已断开,没能保存。等重连后再试一次。`)},children:e?`保存修改`:`创建任务`})]})]})]})}),document.body)}function gE(e){return e.status===`open`&&(e.audience===`boss`||e.audience===void 0)}function _E(e){return(e.escalations??[]).filter(gE)}function vE(e){let t=e.filter(e=>_E(e).length>0);return{projects:t.length,cases:t.reduce((e,t)=>e+_E(t).length,0)}}function yE(e,t=!1){return[`cancelled`,`failed`].includes(e.status??``)?!0:t}function bE(e,t,n){let r=yE(e,t),i=_E(e).length>0;return n===`history`?r&&!i:!r||i}function xE(e){return(e.reports??[]).filter(t=>!t.taskId&&[`progress`,`delivery`].includes(t.kind??``)&&(t.authorConversationId===e.ownerConversationId&&!!e.ownerConversationId||t.kind===`delivery`&&!t.authorConversationId))}function SE(e){return[...e.reports??[]].reverse().find(t=>t.kind===`delivery`&&!t.taskId&&(!t.authorConversationId||t.authorConversationId===e.ownerConversationId))}function CE(e){let t=_E(e),n=[...xE(e)].reverse().find(e=>e.kind===`progress`),r=SE(e),i=[`cancelled`,`failed`].includes(e.status),a=e.resources?.sessions?.find(t=>t.id===e.ownerConversationId),o=(e.resources?.activeWorkers??0)>0||[`running`,`waiting`,`awaiting_background`].includes(a?.status??``);return{label:e.status===`cancelled`?`已取消`:e.status===`failed`?`执行暂停`:t.length?`需要你决定`:o?`正在推进`:e.ownerConversationId?[`failed`,`stopped`].includes(a?.status??``)?`执行暂停`:r?`待继续`:`未交付`:`待启动`,summary:n?.progress?.trim()||n?.summary?.trim()||(i?`项目已结束,已有记录会保留。`:r?`可继续安排新任务或追加验证。`:`已交由负责人推进,进展和成果会在这里汇总。`),progress:n,delivery:r,decisions:t,ended:i,deliveryLabel:e.mode===`lightweight`?`自评交付`:`交付成果`}}var wE=/\.[A-Za-z][A-Za-z0-9]{0,9}$/,TE=new Set([`makefile`,`dockerfile`,`license`,`readme`,`changelog`]),EE=/^[A-Za-z]:/;function DE(e){let t=(e??``).trim();if(!t||/\s/.test(t)||t.includes(`://`)||t.startsWith(`/`)||t.startsWith(`\\`)||EE.test(t))return;let n=t.split(/[\\/]/);if(n.some(e=>e===``||e===`.`||e===`..`))return;let r=n[n.length-1];if(wE.test(r)||TE.has(r.toLowerCase()))return n.join(`/`)}function OE(e){return/\s/.test(e)||e.includes(`://`)||e.startsWith(`/`)||e.startsWith(`\\`)||EE.test(e)?!1:!e.split(/[\\/]/).some(e=>e===``||e===`.`||e===`..`)}function kE(e){let t=e.split(/[\\/]/);return t[t.length-1]||e}function AE(e,t){let n=DE(e);if(!n)return;let r=(t??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!r)return n;if(OE(r))return n===r||n.startsWith(`${r}/`)?n:`${r}/${n}`}function jE(e,t){let n=(e??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!n)return;let r=(t??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!r)return n;if(n!==r&&n.startsWith(`${r}/`))return n.slice(r.length+1)}function ME(e){return[`cancelled`,`failed`].includes(e.status??``)}function NE(e,t){return e.filter(e=>bE(e,e.ownerArchived===!0,t?`history`:`current`))}function PE(e){let[t,n]=(0,p.useState)(0),r=(0,p.useRef)(null),i=(0,p.useRef)(null);return(0,p.useLayoutEffect)(()=>{let e=()=>{let e=r.current,t=i.current;if(!e||!t)return;let a=getComputedStyle(e),o=Number.parseFloat(a.lineHeight)||Number.parseFloat(a.fontSize)*1.6||16,s=t.getBoundingClientRect().height;n(Math.max(1,Math.round(s/o)))};e();let t=typeof ResizeObserver==`function`?new ResizeObserver(()=>e()):null;return t&&(r.current&&t.observe(r.current),i.current&&t.observe(i.current)),window.addEventListener(`resize`,e),()=>{t?.disconnect(),window.removeEventListener(`resize`,e)}},[e]),{lines:t,visible:r,measured:i}}function FE({text:e,what:t}){let[n,r]=(0,p.useState)(!1),{lines:i,visible:a,measured:o}=PE(e),s=Math.max(0,i-2);return e?(0,m.jsxs)(`div`,{className:`project-prose-wrap`,children:[(0,m.jsx)(`p`,{className:`project-prose${n?` project-prose-open`:``}`,"data-prose-text":!0,ref:a,children:e}),(0,m.jsx)(`span`,{className:`project-prose-measure`,"aria-hidden":`true`,ref:o,children:e}),s>0?(0,m.jsx)(`button`,{type:`button`,className:`project-prose-expand`,"data-prose-expand":!0,"aria-expanded":n,onClick:()=>r(e=>!e),children:n?`收起${t}`:`展开完整${t}(还有 ${s} 行)`}):null]}):null}function IE({refs:e,baseCwd:t,cwd:n,onOpenFile:r}){return(0,m.jsx)(`ul`,{children:e.map((e,i)=>{let a=AE(e,t),o=a?jE(a,n):void 0;return(0,m.jsx)(`li`,{children:o&&r?(0,m.jsx)(`button`,{type:`button`,className:`project-evidence-path`,"data-team-evidence-file":o,onClick:()=>r({path:o,name:kE(o),text:null}),children:e}):e},i)})})}function LE(e){if(!e)return``;let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Math.max(0,Math.floor((Date.now()-t)/1e3));return n<60?`刚刚`:n<3600?`${Math.floor(n/60)} 分钟前`:n<86400?`${Math.floor(n/3600)} 小时前`:`${Math.floor(n/86400)} 天前`}async function RE(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(typeof t?.error==`string`?t.error:`请求失败(${e.status})`);return t}async function zE(e){let t=(await e.text().catch(()=>``)).trim();if(!t)return`报告打不开(${e.status})`;try{let n=JSON.parse(t);return n&&typeof n==`object`&&typeof n.error==`string`&&n.error.trim()?n.error.trim():`报告打不开(${e.status})`}catch{return t}}function BE(e,t){return`/api/projects/${encodeURIComponent(e)}/report?workspaceId=${encodeURIComponent(t??``)}`}function VE(e,t=60){let n=(e??``).replace(/\s+/g,` `).trim();return n?n.length<=t?n:`${n.slice(0,t-1)}…`:``}function HE(e){let t=(e.title??``).trim();if(t)return t;let n=(e.reason??``).trim();return n?n.match(/^[\s\S]*?[。!?!?]/)?.[0]?.trim()||n:`需要处理`}var UE={decision:0,delivery:1},WE=5;function GE(e,t){let n=_E(e)[0],r={projectId:e.id,projectTitle:e.title,updatedAt:Date.parse(e.updatedAt??``)||0};if(n)return{...r,reminderId:`${e.id}:decision:${_E(e).map(e=>e.id).join(`,`)}`,kind:`decision`,label:`要你决定`,detail:VE(n.title||n.reason||`需要你的决定`,ME(e)?36:60)+(ME(e)?`(项目已结束:记录后不会唤醒任何人)`:``),actionLabel:`去看看`,target:{kind:`exception`,escalationId:n.id}};let i=CE(e).delivery,a=Date.parse(i?.createdAt??``);return!i||!Number.isFinite(a)||t-a>864e5?null:{...r,updatedAt:a,reminderId:`${e.id}:delivery:${i.id}`,kind:`delivery`,label:`阶段交付`,detail:VE(i.progress||i.summary||`已提交阶段成果`),actionLabel:`查看交付`,target:{kind:`top`}}}function KE({text:e}){let[t,n]=(0,p.useState)(!1),{lines:r,visible:i,measured:a}=PE(e),o=Math.max(0,r-2);return e?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`project-exception-reason-wrap`,children:[(0,m.jsx)(`p`,{className:`project-exception-reason${t?` project-exception-reason-open`:``}`,"data-project-exception-reason":!0,ref:i,children:e}),(0,m.jsx)(`span`,{className:`project-exception-reason-measure`,"aria-hidden":`true`,ref:a,children:e})]}),o>0&&(0,m.jsx)(`button`,{type:`button`,className:`project-exception-expand`,"data-project-exception-expand":!0,"aria-expanded":t,onClick:()=>n(e=>!e),children:t?`收起理由`:`展开完整理由(还有 ${o} 行)`})]}):null}function qE({item:e,project:t,busy:n,onResolve:r,onReturn:i}){let[a,o]=(0,p.useState)(``),s=ME(t);return(0,m.jsxs)(`li`,{className:`project-exception`,"data-project-exception":e.id,children:[(0,m.jsx)(`strong`,{className:`project-exception-title`,"data-project-exception-title":!0,children:HE(e)}),e.reason&&(0,m.jsx)(KE,{text:e.reason}),s&&(0,m.jsx)(`p`,{className:`project-exception-ended`,"data-project-exception-ended":!0,"data-project-exception-ended-note":!0,children:`项目已结束:你的处理意见会记进项目记录,但不会唤醒任何人。`}),(0,m.jsxs)(`label`,{className:`project-decision-label`,children:[`你的决定`,(0,m.jsx)(`textarea`,{"data-project-decision":e.id,"data-project-exception-decision":!0,value:a,onChange:e=>o(e.target.value),disabled:n})]}),(0,m.jsxs)(`div`,{className:`project-detail-actions`,children:[(0,m.jsx)(`button`,{type:`button`,"data-project-decision-submit":e.id,"data-project-exception-resolve":!0,disabled:n||!a.trim(),onClick:()=>r(a.trim()),children:s?`记录处理意见`:`记录决定并答复主会话`}),(0,m.jsx)(`button`,{type:`button`,"data-project-decision-return":e.id,"data-project-exception-return":!0,disabled:n||!a.trim(),onClick:()=>i(a.trim()),children:`退回补充`})]})]})}function JE({project:e,workspaceId:t,notify:n,onOpenSession:r,onOpenFile:i,cwd:a,onChanged:o}){let s=CE(e),[c,l]=(0,p.useState)(!1),[u,d]=(0,p.useState)(``),[f,h]=(0,p.useState)(!1),[g,_]=(0,p.useState)(``),[v,y]=(0,p.useState)(``),b=(0,p.useRef)(``);(0,p.useEffect)(()=>()=>{b.current&&URL.revokeObjectURL(b.current)},[]);let x=async(r,i,a={})=>{if(t&&!c){l(!0),d(``);try{await Ie(`/api/projects/${encodeURIComponent(e.id)}/${r}`,{method:i,headers:{"content-type":`application/json`},body:JSON.stringify({...a,workspaceId:t})}).then(RE),await o?.(),n?.(`已记录并交给负责人`,`info`)}catch(e){d(e instanceof Error?e.message:`操作失败`)}finally{l(!1)}}},S=async()=>{if(t&&!f){h(!0),_(``);try{let n=await Ie(BE(e.id,t));if(!n.ok){_(await zE(n));return}let r=await n.text();b.current&&URL.revokeObjectURL(b.current);let i=URL.createObjectURL(new Blob([r],{type:`text/plain;charset=utf-8`}));b.current=i,y(i),window.open(i,`_blank`,`noopener`)}catch(e){_(e instanceof Error?e.message:`报告打不开`)}finally{h(!1)}}},C=e.resources?.usage,w=s.delivery?.evidenceRefs??[],T=e.resources?.sessions?.find(t=>t.id===e.ownerConversationId),E=!e.ownerConversationId||!!(T&&[`failed`,`stopped`].includes(T.status??``)&&!e.resources?.activeWorkers);return(0,m.jsxs)(`div`,{className:`project-detail project-overview`,"data-project-detail":e.id,children:[e.objective&&(0,m.jsxs)(`div`,{className:`project-goal`,children:[(0,m.jsx)(`span`,{children:`项目目标`}),(0,m.jsx)(`p`,{className:`project-detail-objective`,children:e.objective})]}),(0,m.jsxs)(`section`,{className:`project-section`,"data-project-owner-summary":!0,children:[(0,m.jsx)(`h3`,{children:`当前进展`}),(0,m.jsx)(FE,{text:s.summary,what:`进展`}),e.updatedAt&&(0,m.jsxs)(`p`,{className:`project-overview-time`,children:[LE(e.updatedAt),`更新`]})]}),s.delivery&&(0,m.jsxs)(`section`,{className:`project-section`,"data-project-stage-delivery":!0,children:[(0,m.jsx)(`h3`,{children:s.deliveryLabel}),(0,m.jsx)(FE,{text:s.delivery.progress||s.delivery.summary||`已提交阶段成果`,what:`交付`}),w.length?(0,m.jsx)(IE,{refs:w,baseCwd:e.resources?.ownerCwd??T?.cwd,cwd:a,onOpenFile:i}):(0,m.jsx)(`p`,{"data-project-no-evidence":!0,children:`未附可核对的交付证据。`})]}),s.decisions.length>0&&(0,m.jsxs)(`section`,{className:`project-section`,"data-project-exception-section":!0,children:[(0,m.jsx)(`h3`,{"data-project-exception-heading":!0,children:`需要你决定`}),(0,m.jsx)(`ul`,{className:`project-exception-list`,children:s.decisions.map(t=>(0,m.jsx)(qE,{item:t,project:e,busy:c,onResolve:e=>void x(`escalations/${encodeURIComponent(t.id)}`,`PATCH`,{decision:e,status:`resolved`}),onReturn:e=>void x(`escalations/${encodeURIComponent(t.id)}`,`PATCH`,{decision:e,status:`returned`})},t.id))})]}),u&&(0,m.jsx)(`p`,{className:`project-error`,role:`alert`,children:u}),(0,m.jsxs)(`div`,{className:`project-detail-actions project-overview-actions`,children:[T&&r&&(0,m.jsx)(`button`,{type:`button`,className:E&&!s.ended?``:`project-primary-action`,"data-project-open-owner":!0,onClick:()=>r(T.id),children:`查看负责人会话`}),!s.ended&&E&&(0,m.jsx)(`button`,{type:`button`,className:`project-primary-action`,disabled:c,"data-project-resume":!0,onClick:()=>void x(`start`,`POST`),children:`让负责人继续`}),!s.ended&&(0,m.jsx)(`button`,{type:`button`,className:`project-stop-action`,disabled:c,"data-project-stop":!0,onClick:()=>void x(``,`PATCH`,{status:`cancelled`}),children:`停止项目`}),(0,m.jsx)(`button`,{type:`button`,disabled:f,"data-project-report":e.id,onClick:()=>void S(),children:f?`正在读取…`:`导出记录`})]}),g&&(0,m.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-report-error":!0,children:g}),v&&(0,m.jsx)(`a`,{href:v,target:`_blank`,rel:`noopener noreferrer`,"data-project-report-link":!0,children:`打开已读取的记录`}),e.resources&&(0,m.jsxs)(`details`,{className:`project-section project-secondary`,"data-project-usage":!0,children:[(0,m.jsx)(`summary`,{children:`查看用量`}),(0,m.jsxs)(`div`,{"data-project-budget":e.id,children:[(0,m.jsxs)(`p`,{"data-project-budget-used":e.id,children:[`等效 Token `,e.resources.usageKnown?e.resources.tokens.toLocaleString():`未知`]}),C&&(0,m.jsxs)(`p`,{"data-project-budget-raw":e.id,children:[`原始口径 `,(e.resources.rawTokens??C.input+C.output+C.cacheRead+C.cacheWrite).toLocaleString(),`;输入 `,C.input.toLocaleString(),`;输出 `,C.output.toLocaleString(),`;缓存写入 `,C.cacheWrite.toLocaleString(),`;缓存读取 `,C.cacheRead.toLocaleString()]}),(0,m.jsx)(`p`,{"data-project-budget-basis":`1`,children:`等效 Token = 输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1`})]})]})]})}function YE({project:e,workspaceId:t,notify:n,onOpenSession:r,onOpenFile:i,cwd:a,onChanged:o,onClose:s}){let c=(0,p.useId)(),l=(0,p.useRef)(null),u=(0,p.useRef)(s);return u.current=s,(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u.current())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]),(0,p.useEffect)(()=>{l.current?.focus({preventScroll:!0})},[e.id]),(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay project-dialog-overlay`,"data-project-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&s()},children:(0,m.jsxs)(`div`,{ref:l,className:`tool-dialog project-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":c,"data-project-dialog":e.id,tabIndex:-1,onKeyDown:e=>{if(e.key!==`Tab`)return;let t=l.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), input:not([disabled]), textarea:not([disabled]), summary, [tabindex]:not([tabindex='-1'])`)).filter(e=>e.offsetParent!==null||e.getClientRects().length>0);if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey?(document.activeElement===r||document.activeElement===t)&&(e.preventDefault(),i.focus()):document.activeElement===i&&(e.preventDefault(),r.focus())},children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head project-dialog-head`,children:[(0,m.jsxs)(`div`,{className:`project-dialog-title-group`,children:[(0,m.jsx)(`h2`,{className:`tool-dialog-title project-dialog-title`,id:c,children:e.title}),(0,m.jsx)(`span`,{className:`project-detail-flags`,children:(0,m.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:CE(e).label})})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close project-dialog-close`,"data-project-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭 ${e.title}`,onClick:s,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body project-dialog-body`,children:(0,m.jsx)(JE,{project:e,workspaceId:t,notify:n,onOpenSession:r?e=>{s(),r(e)}:void 0,onOpenFile:i?e=>{s(),i(e)}:void 0,cwd:a,onChanged:o})})]})}),document.body)}function XE({workspaceId:e,notify:t,onOpenSession:n,onOpenFile:r,cwd:i}){let{visible:a}=ki(`projects`),[o,s]=(0,p.useState)([]),[c,l]=(0,p.useState)(!1),u=(0,p.useMemo)(()=>NE(o,c),[o,c]),[d,f]=(0,p.useState)(!1),[h,g]=(0,p.useState)(``),[_,v]=(0,p.useState)(null),y=(0,p.useRef)(null),[b,x]=(0,p.useState)([]),S=(0,p.useCallback)(async t=>{if(!e)s([]);else{g(``);try{let n=await Ie(`/api/projects?workspaceId=${encodeURIComponent(e)}${c?`&view=history`:``}`,{signal:t}).then(RE),r=Array.isArray(n)?n:Array.isArray(n.projects)?n.projects:[];s(r)}catch(e){e.name!==`AbortError`&&g(e instanceof Error?e.message:`项目列表加载失败`)}finally{t?.aborted||f(!0)}}},[e,c]);(0,p.useEffect)(()=>{if(!a)return;let e=new AbortController;return S(e.signal),()=>e.abort()},[S,a]),(0,p.useEffect)(()=>{if(!e||!a)return;let t=window.setInterval(()=>{document.visibilityState===`visible`&&S()},5e3);return()=>window.clearInterval(t)},[S,e,a]);let C=(0,p.useMemo)(()=>{let e=Date.now();return u.map(t=>GE(t,e)).filter(e=>!!e).filter(e=>!b.includes(e.reminderId)).sort((e,t)=>UE[e.kind]-UE[t.kind]||t.updatedAt-e.updatedAt)},[u,b]),w=(0,p.useMemo)(()=>u.flatMap(e=>_E(e).map(t=>({project:e,decision:t}))),[u]),T=(0,p.useMemo)(()=>vE(u).projects,[u]),E=(0,p.useMemo)(()=>C.slice(0,WE),[C]),D=C.length-E.length,[O,k]=(0,p.useState)(!1),A=O?C:E,[j,ee]=(0,p.useState)(!1),M=(0,p.useMemo)(()=>{let e=new Set;for(let t of C)e.add(t.projectId);return e},[u,C]),N=(0,p.useMemo)(()=>j?u.filter(e=>M.has(e.id)):u,[j,u,M]),P=(0,p.useMemo)(()=>_?u.find(e=>e.id===_)??null:null,[u,_]),F=(0,p.useRef)(null),[I,te]=(0,p.useState)(0),ne=(0,p.useCallback)((e,t,n)=>{y.current=t??document.querySelector(`[data-project-row="${e}"]`),v(e),n&&(F.current={projectId:e,target:n},te(e=>e+1))},[]),re=(0,p.useCallback)(()=>{let e=_,t=y.current;y.current=null,v(null),window.requestAnimationFrame(()=>{(t?.isConnected?t:e?document.querySelector(`[data-project-row="${e}"]`):null)?.focus()})},[_]),ie=e=>{let t=document.querySelector(`[data-project-row="${e.projectId}"]`);ne(e.projectId,t,e.target)};return(0,p.useEffect)(()=>{if(!I)return;let e=F.current;if(F.current=null,!e)return;let t=document.querySelector(`[data-project-detail="${e.projectId}"]`);if(!t)return;let n=null;if(e.target.kind===`exception`){let e=t.querySelector(`[data-project-exception-section]`);e&&(e.open=!0,n=e.querySelector(`[data-project-exception-heading]`)??e)}let r=n??t,i=window.requestAnimationFrame(()=>{r.scrollIntoView({block:e.target.kind===`top`?`start`:`center`,inline:`nearest`})});return()=>window.cancelAnimationFrame(i)},[I,P?.id]),(0,m.jsxs)(`section`,{className:`project-panel`,"data-project-panel":`1`,children:[(0,m.jsx)(`div`,{className:`rail-section-head project-panel-head`,children:(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`项目进展`}),(0,m.jsx)(`p`,{className:`project-panel-subtitle`,children:`查看负责人汇总的进展、成果和需要你决定的事。`})]})}),w.length>0&&(0,m.jsxs)(`div`,{className:`warning`,role:`status`,"data-project-team-notice":`1`,"data-project-team-notice-count":T,children:[(0,m.jsxs)(`span`,{"data-project-team-notice-text":!0,children:[T===1?`有 1 个项目的事需要你决定`:`有 ${T} 个项目的事需要你决定`,`:`,VE(HE(w[0].decision),48)]}),(0,m.jsx)(`button`,{type:`button`,"data-project-team-notice-action":`1`,onClick:()=>ne(w[0].project.id,void 0,{kind:`exception`,escalationId:w[0].decision.id}),children:`去看看`})]}),C.length>0&&(0,m.jsxs)(`div`,{className:`project-pending`,"data-project-pending":`1`,"data-project-pending-count":C.length,children:[A.map(e=>(0,m.jsxs)(`div`,{className:`project-pending-item`,"data-project-pending-item":e.projectId,"data-project-pending-kind":e.kind,children:[(0,m.jsxs)(`div`,{className:`project-pending-row`,children:[(0,m.jsx)(`span`,{className:`project-pending-kind project-pending-kind-${e.kind}`,"data-project-pending-label":e.kind,children:e.label}),(0,m.jsx)(`span`,{className:`project-pending-title`,"data-project-pending-title":e.projectId,children:e.projectTitle}),(0,m.jsx)(`button`,{type:`button`,className:`project-pending-action`,"data-project-pending-action":e.projectId,onClick:()=>ie(e),children:e.actionLabel}),(0,m.jsx)(`button`,{type:`button`,className:`project-pending-close`,"data-project-pending-dismiss":e.projectId,"aria-label":`关闭「${e.projectTitle}」的这条提醒`,title:`关闭这条提醒(不改变项目状态)`,onClick:()=>x(t=>[...t,e.reminderId]),children:`×`})]}),(0,m.jsx)(`p`,{className:`project-pending-detail`,"data-project-pending-detail":e.projectId,children:e.detail})]},`${e.projectId}:${e.kind}`)),D>0&&(0,m.jsx)(`button`,{type:`button`,className:`project-pending-more`,"data-project-pending-more":`1`,"aria-expanded":O,onClick:()=>k(e=>!e),children:O?`收起`:`还有 ${D} 个`})]}),(0,m.jsxs)(`label`,{className:`project-pending-filter`,"data-project-pending-only-label":`1`,children:[(0,m.jsx)(`input`,{type:`checkbox`,"data-project-pending-only":`1`,checked:j,onChange:e=>ee(e.target.checked)}),(0,m.jsx)(`span`,{className:`project-pending-filter-name`,children:`只看提醒`}),(0,m.jsx)(`span`,{className:`project-pending-filter-state`,"data-project-pending-only-state":j?`on`:`off`,children:j?`已开启`:`已关闭`})]}),(0,m.jsxs)(`label`,{className:`project-pending-filter`,children:[(0,m.jsx)(`input`,{type:`checkbox`,"data-project-history":`1`,checked:c,onChange:e=>{l(e.target.checked),ee(!1),v(null)}}),(0,m.jsx)(`span`,{className:`project-pending-filter-name`,children:`查看历史项目`})]}),h&&(0,m.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-error":`1`,children:h}),e?!d&&u.length===0?(0,m.jsx)(`p`,{className:`rail-empty`,children:`正在加载项目…`}):u.length===0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{className:`rail-empty`,"data-project-empty":`1`,children:c?`没有已结束的项目。`:`当前没有进行中的项目。`}),(0,m.jsx)(`p`,{className:`project-empty-hint`,"data-project-empty-hint":`1`,children:`在对话里告诉 AI 你要完成什么,负责人会推进工作并向你交付。`})]}):N.length===0?(0,m.jsx)(`p`,{className:`rail-empty`,"data-project-pending-empty":`1`,children:`没有需要关注的项目。`}):(0,m.jsx)(m.Fragment,{children:(0,m.jsx)(`div`,{className:`project-list`,"data-project-count":N.length,children:N.map(e=>{let t=P?.id===e.id;return(0,m.jsxs)(`button`,{type:`button`,className:`project-row`,"data-project-row":e.id,"data-project-block":e.id,"data-project-summary":e.id,"aria-haspopup":`dialog`,"aria-expanded":t,onClick:t=>ne(e.id,t.currentTarget),children:[(0,m.jsx)(`span`,{className:`project-list-title`,title:e.title,children:e.title}),(0,m.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:CE(e).label}),(0,m.jsx)(`span`,{className:`project-row-summary`,children:CE(e).summary}),e.updatedAt&&(0,m.jsxs)(`span`,{className:`project-row-updated`,children:[LE(e.updatedAt),`更新`]})]},e.id)})})}):(0,m.jsx)(`p`,{className:`rail-empty`,children:`请先选择工作区。`}),P?(0,m.jsx)(YE,{project:P,workspaceId:e,notify:t,onOpenSession:n,onOpenFile:r,cwd:i,onChanged:()=>S(),onClose:re}):null]})}var ZE=()=>({text:``,mentions:[],files:[]}),QE=(e,t)=>`super-pi.group-draft.v1:${JSON.stringify([e,t])}`;function $E(e,t){try{let n=JSON.parse(localStorage.getItem(QE(e,t))??`null`);return!n||typeof n.text!=`string`?ZE():{text:n.text.slice(0,32e3),replyTo:typeof n.replyTo==`string`?n.replyTo:void 0,mentions:Array.isArray(n.mentions)?n.mentions.filter(e=>typeof e?.memberId==`string`&&typeof e.text==`string`):[],files:Array.isArray(n.files)?n.files.filter(e=>typeof e?.path==`string`&&typeof e.text==`string`):[]}}catch{return ZE()}}function eD(e,t,n){try{let r=QE(e,t);!n.text&&!n.replyTo?localStorage.removeItem(r):localStorage.setItem(r,JSON.stringify(n))}catch{}}function tD(e,t,n){$E(e,t).text===n&&eD(e,t,ZE())}var nD=`super-pi.group-presets.v1`;function rD(){try{let e=JSON.parse(localStorage.getItem(`super-pi.group-presets.v1`)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e?.id==`string`&&typeof e.name==`string`&&Array.isArray(e.memberIds)&&e.memberIds.every(e=>typeof e==`string`)&&e.memberModels&&typeof e.memberModels==`object`&&!Array.isArray(e.memberModels)&&typeof e.moderator?.prompt==`string`).slice(0,100):[]}catch{return[]}}var iD=e=>JSON.stringify([e.provider,e.modelId]);function aD({value:e,models:t,onChange:n,label:r,inheritLabel:i}){let[a,o]=(0,p.useState)(``),[s,c]=(0,p.useState)(``),l=(0,p.useRef)(null),u=t.find(t=>iD(t)===e),d=t.filter(e=>(!a||e.provider===a)&&`${e.label} ${e.modelId}`.toLocaleLowerCase().includes(s.toLocaleLowerCase())),f=e=>{n(e),l.current&&(l.current.open=!1)};return(0,m.jsxs)(`details`,{className:`group-model-picker`,ref:l,onKeyDown:e=>{e.key===`Escape`&&l.current&&(l.current.open=!1,l.current.querySelector(`summary`)?.focus())},children:[(0,m.jsxs)(`summary`,{"aria-label":r,title:u?`${u.provider} / ${u.modelId}`:void 0,children:[(0,m.jsx)(`span`,{children:e?u?.label??`当前模型不可用,请重新选择`:i??`继承 Agent / 工作区模型`}),(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`⌄`})]}),(0,m.jsxs)(`div`,{className:`group-model-popup`,children:[(0,m.jsxs)(`select`,{"aria-label":`${r} Provider`,value:a,onChange:e=>o(e.target.value),children:[(0,m.jsx)(`option`,{value:``,children:`全部 Provider`}),[...new Set(t.map(e=>e.provider))].sort().map(e=>(0,m.jsx)(`option`,{children:e},e))]}),(0,m.jsx)(`input`,{"aria-label":`${r} 筛选`,placeholder:`筛选模型…`,value:s,onChange:e=>c(e.target.value)}),(0,m.jsxs)(`div`,{className:`group-model-options`,role:`group`,"aria-label":r,children:[(0,m.jsx)(`button`,{type:`button`,"aria-pressed":!e,onClick:()=>f(``),children:i??`继承默认模型`}),d.map(t=>(0,m.jsxs)(`button`,{type:`button`,"aria-pressed":e===iD(t),onClick:()=>f(iD(t)),children:[(0,m.jsx)(`span`,{children:t.label}),(0,m.jsx)(`small`,{children:t.provider})]},iD(t))),!d.length&&(0,m.jsx)(`p`,{children:`没有匹配的模型`})]})]})]})}var oD={queued:`排队中`,running:`进行中`,completed:`已完成`,failed:`失败`,cancelled:`已停止`,interrupted:`已中断`},sD=new Map([[`read`,`读取文件`],[`write`,`写入文件`],[`edit`,`编辑文件`],[`grep`,`搜索内容`],[`find`,`查找文件`],[`ls`,`列出目录`],[`bash`,`运行命令`],[`powershell`,`运行命令`]]),cD=new Map([[`solution-designer`,`案`],[`code-designer`,`码`],[`code-auditor`,`审`],[`document-organizer`,`文`]]),lD=e=>e.status===`queued`||e.status===`running`,uD=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),dD=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hourCycle:`h23`});function fD(e,t=!1){let n=Date.parse(e);return Number.isFinite(n)?(t?dD:uD).format(n):``}function pD({name:e,memberId:t,busy:n}){let r=e.trim(),i=t&&cD.get(t)||(/\p{Script=Han}/u.test(r)?Array.from(r).slice(-2).join(``):r.split(/\s+/u).filter(Boolean).map(e=>Array.from(e)[0]).slice(0,2).join(``).toUpperCase())||`?`,a=tr.findIndex(e=>e===t),o=a>=0?a:Array.from(t??``).reduce((e,t)=>(e*31+(t.codePointAt(0)??0))%4,0);return(0,m.jsx)(`span`,{className:`group-avatar`,"data-avatar-tone":t?o:`self`,"data-avatar-busy":n||void 0,"aria-hidden":`true`,children:i})}function mD({step:e}){return e.kind===`compaction`?(0,m.jsxs)(`li`,{className:`group-execution-step`,"data-execution-kind":`compaction`,"data-execution-status":e.status,children:[(0,m.jsxs)(`div`,{className:`group-execution-tool`,children:[(0,m.jsx)(`strong`,{children:`上下文压缩`}),(0,m.jsx)(`span`,{className:`group-execution-step-status`,children:oD[e.status]})]}),(0,m.jsx)(`p`,{children:e.text}),(0,m.jsx)(`time`,{className:`group-execution-muted`,dateTime:e.startedAt,children:fD(e.startedAt,!0)})]}):e.kind===`thinking`?(0,m.jsxs)(`details`,{className:`group-execution-step`,"data-execution-kind":`thinking`,"data-execution-status":e.status,open:!0,children:[(0,m.jsxs)(`summary`,{children:[(0,m.jsx)(`span`,{children:e.status===`running`?`正在思考`:`思考摘要`}),(0,m.jsx)(`time`,{dateTime:e.startedAt,children:fD(e.startedAt,!0)})]}),e.text?(0,m.jsx)(`div`,{className:`message-body`,children:(0,m.jsx)(ep,{source:e.text,handoffs:!1})}):(0,m.jsx)(`p`,{className:`group-execution-muted`,children:e.status===`running`?`正在等待模型返回摘要。`:`模型未提供可显示的摘要。`}),e.status===`interrupted`&&(0,m.jsx)(`p`,{className:`group-execution-muted`,children:`思考已中断`})]}):(0,m.jsxs)(`li`,{className:`group-execution-step`,"data-execution-kind":`tool`,"data-execution-status":e.status,children:[(0,m.jsxs)(`div`,{className:`group-execution-tool`,children:[(0,m.jsx)(`strong`,{children:sD.get(e.name)??`工具调用`}),(0,m.jsx)(`code`,{children:e.name}),(0,m.jsx)(`span`,{className:`group-execution-step-status`,children:oD[e.status]})]}),e.detail&&(0,m.jsx)(`p`,{className:`group-execution-target`,children:(0,m.jsx)(`code`,{children:e.detail})}),(0,m.jsxs)(`div`,{className:`group-execution-muted`,children:[(0,m.jsx)(`time`,{dateTime:e.startedAt,children:fD(e.startedAt,!0)}),e.durationMs===void 0?e.status===`running`&&e.lastUpdateAt?` · 最近更新 ${fD(e.lastUpdateAt,!0)}`:null:` · ${(e.durationMs/1e3).toFixed(1)} 秒`]})]})}function hD({workspaceId:e,roomId:t,memberId:n,name:r,runs:i,postId:a,onSelect:o,onClose:s,onStop:c,models:l,memberModel:u,onModelChange:d,onRetry:f}){let h=(0,p.useId)(),g=(0,p.useRef)(null),[_,v]=(0,p.useState)(),[y,b]=(0,p.useState)(),[x,S]=(0,p.useState)(!1),[C,w]=(0,p.useState)(``),[T,E]=(0,p.useState)(!1),D=i.find(e=>e.id===a)??i.find(e=>e.status===`running`)??i[0],O=D?.id,k=_?.id===O?_?.value:void 0,A=y?.id===O?y?.message:void 0;return(0,p.useLayoutEffect)(()=>{g.current?.focus()},[]),(0,p.useEffect)(()=>{if(!O)return;let n=new AbortController,r,i,a=!1,o=async()=>{try{let r=await pr(dr(e,t,i,O),{signal:n.signal});if(n.signal.aborted)return;b(void 0),r&&(i=r.revision,a=!lD(r),v({id:O,value:r}))}catch(e){n.signal.aborted||b({id:O,message:e instanceof Error?e.message:`暂时无法读取执行记录。`})}finally{!n.signal.aborted&&!a&&(r=window.setTimeout(o,500))}};return o(),()=>{n.abort(),window.clearTimeout(r)}},[O,e,t]),(0,m.jsxs)(`aside`,{className:`group-execution`,"aria-labelledby":h,"data-group-execution":n,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),s())},children:[(0,m.jsxs)(`header`,{className:`group-execution-header`,children:[(0,m.jsx)(pD,{name:r,memberId:n,busy:i.some(lD)}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`h2`,{id:h,children:r}),(0,m.jsx)(`p`,{children:`执行详情`})]}),(0,m.jsx)(`button`,{ref:g,type:`button`,className:`group-close-execution`,"data-close-group-execution":!0,"aria-label":`关闭执行详情`,title:`关闭执行详情`,onClick:s,children:(0,m.jsx)(vi,{name:`close`})})]}),d&&(0,m.jsxs)(`div`,{className:`group-execution-model-settings`,"aria-busy":x,children:[(0,m.jsx)(`span`,{children:`该成员后续使用的模型`}),(0,m.jsx)(aD,{label:`${r} 后续使用的模型`,value:u?iD(u):``,models:l,onChange:e=>{x||(S(!0),w(``),d(e).catch(e=>w(String(e.message??e))).finally(()=>S(!1)))}}),(0,m.jsx)(`small`,{children:x?`正在保存…`:`当前执行使用原模型。如需立即切换,请先停止再重试。`}),C&&(0,m.jsx)(`p`,{className:`group-error`,role:`alert`,children:C})]}),D?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`group-execution-summary`,children:[i.length>1&&(0,m.jsx)(`select`,{"aria-label":`选择执行记录`,value:O,onChange:e=>o(e.target.value),children:i.map(e=>(0,m.jsxs)(`option`,{value:e.id,children:[fD(e.createdAt,!0),` · `,e.assignment??oD[e.status]]},e.id))}),(0,m.jsx)(`div`,{"aria-live":`polite`,"data-execution-run-status":k?.status??D.status,children:oD[k?.status??D.status]}),D.assignment&&(0,m.jsx)(`p`,{children:D.assignment}),D.executionConversationId&&(0,m.jsx)(`button`,{type:`button`,"data-group-open-execution-session":!0,onClick:()=>window.dispatchEvent(new CustomEvent(`super-pi-open-execution-session`,{detail:D.executionConversationId})),children:`打开完整执行会话/回答工具提问`}),(0,m.jsx)(`p`,{"data-group-execution-model":!0,children:D.model?`${D.model.label} · ${D.model.provider}`:`模型尚未记录`}),lD(D)&&c&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>c(D.id),children:`停止这次执行`}),[`failed`,`cancelled`,`interrupted`].includes(D.status)&&f&&(0,m.jsx)(`button`,{type:`button`,"data-group-retry":!0,disabled:T||x,onClick:()=>{E(!0),w(``),f(D.id).catch(e=>w(String(e.message??e))).finally(()=>E(!1))},children:T?`正在提交重试…`:`用当前模型继续任务`}),D.error&&(0,m.jsx)(`p`,{className:`group-error`,children:D.error})]}),(0,m.jsxs)(`div`,{className:`group-execution-scroll`,children:[A&&(0,m.jsx)(`p`,{className:`group-error`,role:`alert`,children:A}),k?.steps.length?(0,m.jsx)(`ol`,{className:`group-execution-steps`,children:k.steps.map(e=>e.kind===`thinking`?(0,m.jsx)(`li`,{children:(0,m.jsx)(mD,{step:e})},e.id):(0,m.jsx)(mD,{step:e},e.id))}):!A&&(0,m.jsx)(`p`,{className:`group-execution-muted`,children:k?lD(k)?`等待模型或工具事件。`:`这次发言没有可查看的执行明细。`:`正在读取执行记录…`}),k?.truncated&&(0,m.jsx)(`p`,{className:`group-execution-muted`,children:`部分执行记录超过保留长度,已省略。`})]})]}):(0,m.jsx)(`p`,{className:`group-execution-scroll group-execution-muted`,children:`该成员还没有执行记录。`})]})}var gD=e=>JSON.stringify([e.provider,e.modelId]),_D=`super-pi.group-moderator-prompt-presets.v1`,vD=new Map;function yD(){try{let e=JSON.parse(localStorage.getItem(_D)??`[]`);return Array.isArray(e)?e.filter(e=>e&&typeof e.id==`string`&&typeof e.name==`string`&&typeof e.prompt==`string`).slice(0,100).map(e=>({id:e.id.slice(0,100),name:e.name.slice(0,80),prompt:e.prompt.slice(0,8e3)})):[]}catch{return[]}}var bD=e=>/\s/u.test(e)?`@"${e}"`:`@${e}`,xD=e=>new Set([...e.matchAll(/(?:^|[\s([{])(@(?:"(?:[^"\\]|\\.)+"|[^\s,。;、!?,::;!?,)\]}]+))/gu)].map(e=>e[1])),SD=mr;function CD({workspaceId:e,roomId:t,agents:n,catalog:r,userLabel:i,archivedAt:a,restoring:o,onRestore:s,onRoomSeen:c,onRoomRead:l,onRoomMissing:u,onCreated:d,onCancelCreate:f,onEnableNotifications:h,composerResize:g,sourceLink:_,onOpenRsi:v,rsiActive:x=!1}){let[S,C]=(0,p.useState)(),[w,T]=(0,p.useState)(!1);(0,p.useEffect)(()=>{let e=e=>{e.detail?.roomId===t&&T(!0)};return window.addEventListener(`super-pi-status-group-models`,e),()=>window.removeEventListener(`super-pi-status-group-models`,e)},[t]);let[E,D]=(0,p.useState)(``),[O,k]=(0,p.useState)(``),[A,j]=(0,p.useState)(!1),[ee,M]=(0,p.useState)({}),[N,P]=(0,p.useState)(),[F,I]=(0,p.useState)(``),[te]=(0,p.useState)(()=>$E(e,t)),[ne,re]=(0,p.useState)(te.text),ie=JSON.stringify([e,t]),[ae,oe]=(0,p.useState)(()=>vD.get(ie)??[]);(0,p.useEffect)(()=>{ae.length?vD.set(ie,ae):vD.delete(ie)},[ie,ae]);let[se,ce]=(0,p.useState)(!1),le=async t=>{if(!Me||se)return;if(t.length+ae.length>8){D(`每条群聊消息最多附加 8 张图片`);return}let n=Me.id;ce(!0),D(``);try{for(let r of t){if(![`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(r.type)||r.size>5242880)throw Error(`图片须为 PNG/JPEG/GIF/WebP,且不超过 5MB`);let t=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(String(n.result).split(`,`)[1]),n.onerror=t,n.readAsDataURL(r)}),i=await Ie(dr(e,n)+`&upload=image`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r.name,mimeType:r.type,data:t})}),a=await i.json();if(!i.ok)throw Error(a.error??`图片上传失败`);let o={id:b(y(n).server,a.id),name:a.name,mimeType:a.mimeType,bytes:a.bytes};ke.current&&Oe.current?.id===n&&oe(e=>[...e,o])}}catch(e){ke.current&&D(e instanceof Error?e.message:`图片上传失败`)}finally{ke.current&&ce(!1)}},[ue,de]=(0,p.useState)(te.replyTo),[fe,pe]=(0,p.useState)(),[L,me]=(0,p.useState)(te.mentions),[he,ge]=(0,p.useState)(te.files),[_e,ve]=(0,p.useState)([]),[ye,be]=(0,p.useState)(0),[xe,Se]=(0,p.useState)(),Ce=(0,p.useRef)(null),we=(0,p.useRef)(null),Te=(0,p.useRef)(void 0),Ee=(0,p.useRef)(null),De=(0,p.useRef)(!0),Oe=(0,p.useRef)(void 0),ke=(0,p.useRef)(!1),Ae=(0,p.useRef)(void 0),je=(0,p.useRef)(new Map),Me=S?.id===t?S:void 0,Ne=!!(a||Me?.archivedAt),Pe=Me?.messages.find(e=>e.id===ue),Le=e=>Me?.members.find(t=>t.id===e)?.name??e,Re=e=>e.role===`user`?i:e.memberName??Le(e.memberId),ze=Ne?void 0:fe?.query,Be=fe?[...(Me?.members??[]).filter(e=>`${e.name} ${e.id}`.toLocaleLowerCase().includes(fe.query.toLocaleLowerCase())).map(e=>({kind:`member`,member:e})),..._e.map(e=>({kind:`file`,file:e}))]:[];(0,p.useEffect)(()=>{eD(e,t,{text:ne,replyTo:ue,mentions:L,files:he})},[e,t,ne,ue,L,he]);let Ve=e=>{if(e.id!==t)return;let n=Oe.current;if(n?.id===e.id){let[t,r]=n.revision.split(`:`).map(Number),[i,a]=e.revision.split(`:`).map(Number);if(t>i||t===i&&r>a)return}Oe.current=e,C(e),e.archivedAt&&T(!1),(n?.title!==e.title||n?.archivedAt!==e.archivedAt||n?.activity.status!==e.activity.status||n?.activity.lastReplyAt!==e.activity.lastReplyAt)&&c(e)};(0,p.useEffect)(()=>{let e=Ee.current;if(!Me||w||!e)return;let t=!0,n=()=>{let n=e.getBoundingClientRect();t&&document.visibilityState===`visible`&&getComputedStyle(e).visibility===`visible`&&n.width>0&&n.height>0&&n.bottom>0&&n.top<window.innerHeight&&n.right>0&&n.left<window.innerWidth&&l(Me)};n();let r=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n()});return r.observe(e),document.addEventListener(`visibilitychange`,n),()=>{t=!1,r.disconnect(),document.removeEventListener(`visibilitychange`,n)}},[Me?.id,Me?.activity.lastReplyAt,w,xe?.memberId,xe?.postId,l]),(0,p.useEffect)(()=>(ke.current=!0,()=>{ke.current=!1}),[]),(0,p.useEffect)(()=>{if(!t)return;let n=new AbortController,r,i=!1,a=async()=>{try{let r=await pr(dr(e,t,Oe.current?.revision),{signal:n.signal});n.signal.aborted||(k(``),r&&Ve(r))}catch(r){n.signal.aborted||(r instanceof fr&&r.status===404?(i=!0,u({workspaceId:e,roomId:t})):k(Oe.current?`群聊连接暂时中断,正在重试。`:String(r.message??r)))}finally{!n.signal.aborted&&!i&&(r=window.setTimeout(a,Oe.current?.messages.some(lD)?450:1600))}};return a(),()=>{n.abort(),window.clearTimeout(r)}},[e,t,u]),(0,p.useEffect)(()=>{if(ve([]),!ze)return;let t=new AbortController,n,r=()=>{pr(`/api/files/mentions?${new URLSearchParams({workspaceId:e,cwd:``,q:ze})}`,{signal:t.signal}).then(e=>{!t.signal.aborted&&e&&(ve(e.hits.filter(e=>e.kind===`file`).slice(0,8)),e.indexed||(n=window.setTimeout(r,650)))}).catch(()=>{})};return n=window.setTimeout(r,160),()=>{window.clearTimeout(n),t.abort()}},[ze,e]),(0,p.useLayoutEffect)(()=>{Ee.current&&De.current&&(Ee.current.scrollTop=Ee.current.scrollHeight)},[Me?.revision]),(0,p.useLayoutEffect)(()=>{let e=Te.current;e!==void 0&&we.current&&(Te.current=void 0,we.current.focus(),we.current.setSelectionRange(e,e))},[ne]);async function He(n){j(!0),D(``);try{let r=await SD(dr(e,t),t?{action:`configure`,memberIds:n.memberIds,memberModels:n.memberModels,...n.moderator,model:n.moderator.model??null,cloneLimit:n.moderator.cloneLimit??null}:n);if(!r)throw Error(`服务没有返回群聊。`);t?(Ve(r),T(!1)):d(r,ke.current)}catch(e){D(String(e.message??e))}finally{j(!1)}}async function Ue(n){if(n.preventDefault(),!Me||Ne||!ne.trim()&&!ae.length||A||se)return;let r=ne.trim()||`请查看图片。`,i=xD(r),a=L.filter(e=>i.has(e.text)),o=Me.members.filter(e=>a.some(t=>t.memberId===e.id)||i.has(bD(e.name))&&Me.members.filter(t=>t.name===e.name).length===1).map(e=>e.id),s=he.filter(e=>i.has(e.text)).map(e=>e.path),c=JSON.stringify([Me.id,r,o,ue,s,ae]);Ae.current?.signature!==c&&(Ae.current={signature:c,clientId:tn()}),j(!0),D(``);try{let n=await SD(dr(e,Me.id),{action:`send`,content:r,memberIds:o,replyTo:ue,filePaths:s,images:ae,clientId:Ae.current.clientId});if(!n)throw Error(`服务没有确认收到消息。`);tD(e,t,ne),De.current=!0,Ve(n),ke.current&&t===n.id&&(re(``),oe([]),de(void 0),me([]),ge([]),pe(void 0)),Ae.current=void 0}catch(e){D(String(e.message??e))}finally{j(!1)}}function We(e){if(!fe)return;let t;if(e.kind===`member`){let n=e.member,r=bD(n.name);re(ne.slice(0,fe.start)+r+` `+ne.slice(fe.end)),me(e=>[...e.filter(e=>e.text!==r),{memberId:n.id,text:r}]),t=fe.start+r.length+1}else{let n=e.file,r=vp(ne,fe,n),i=r.text.slice(fe.start,r.caret).trimEnd();re(r.text),ge(e=>[...e.filter(e=>e.path!==n.path),{path:n.path,text:i}]),t=r.caret}Te.current=t,pe(void 0)}async function Ge(n){try{let r=await SD(dr(e,t),{action:`stop`,postId:n});r&&Ve(r)}catch(e){D(String(e.message??e))}}async function Ke(n,i){let a=r?.models.find(e=>gD(e)===i);if(i&&!a)throw Error(`所选模型不可用,请刷新模型列表后重试。`);if(!Me)throw Error(`群聊尚未加载,请稍后重试。`);let o=await SD(dr(e,t),{action:`configure`,memberModels:{[n]:a??null},...Me.moderator,model:Me.moderator.model??null,cloneLimit:Me.moderator.cloneLimit??null});if(!o)throw Error(`服务没有确认模型更改。`);Ve(o);let s=o.members.find(e=>e.id===n)?.model;if((s?gD(s):``)!==i)throw Error(`目标服务端没有应用成员模型设置,可能版本过旧。请先升级目标服务端后重试;群聊历史仍保留。`)}async function qe(n){let r=Me?.messages.find(e=>e.id===n&&e.role===`assistant`),i=r&&Me?.messages.find(e=>e.id===r.topicId);if(!r||!i||![`failed`,`interrupted`,`cancelled`].includes(r.status))throw Error(`只能重试已失败或停止的执行。`);let a=je.current.get(n)??tn();je.current.set(n,a);let o=`请使用当前模型继续这次未完成的任务。先检查已有产物,避免重复执行。\n原分工:${r.assignment??`按原请求完成工作`}\n原请求:${i.content}`.slice(0,32e3),s=await SD(dr(e,t),{action:`send`,content:o,memberIds:[r.memberId],replyTo:r.id,clientId:a,filePaths:i.role===`user`?i.files?.map(e=>e.path):void 0});if(!s)throw Error(`服务没有确认重试请求。`);Ve(s),je.current.delete(n)}async function Je(n,r,i){P(n),D(``);try{let a=await SD(dr(e,t),{action:`clone.resolve`,requestId:n,choice:r,name:i});a&&Ve(a)}catch(e){D(e instanceof Error?e.message:String(e))}finally{P(void 0)}}function Ye(e,t,n,r){let i=n.closest(`[data-group-post-id]`)?.querySelector(`[data-group-message-avatar]`)??void 0;Ce.current={origin:n,avatar:i},Se({memberId:e,name:t,postId:r})}function Xe(){let e=xe?.memberId;Se(void 0);let t=Ce.current;requestAnimationFrame(()=>{let n=[...document.querySelectorAll(`[data-group-message-avatar]`)].filter(t=>t.dataset.groupMessageAvatar===e).at(-1);(t?.origin.isConnected?t.origin:t?.avatar?.isConnected?t.avatar:n)?.focus({preventScroll:!0})})}let Ze=Me?.messages??[],Qe=rr(Ze),$e=Ze.filter(e=>e.role===`assistant`&&lD(e)).filter((e,t,n)=>n.findIndex(t=>t.memberId===e.memberId)===t),et=new Map(Ze.map(e=>[e.id,e])),tt=new Set(Ze.flatMap(e=>e.role===`assistant`&&lD(e)?[e.memberId]:[])),nt=xe?Ze.filter(e=>e.role===`assistant`&&e.memberId===xe.memberId).reverse():[],rt;return(0,m.jsxs)(`section`,{className:`group-chat`,"data-group-chat":t,children:[(E||O)&&(0,m.jsx)(`div`,{className:`group-error`,role:`alert`,children:E||O}),!t||w&&!Ne?(0,m.jsx)(wD,{room:w?Me:void 0,agents:n,catalog:r,saving:A,onSave:He,onCancel:t?()=>T(!1):f}):Me?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`group-members`,children:[(0,m.jsx)(`div`,{className:`group-roster`,"aria-label":`群成员`,children:Me.members.map(e=>(0,m.jsxs)(`button`,{type:`button`,className:`group-roster-member`,"data-group-member-avatar":e.id,"aria-label":`查看 ${e.name} 的执行详情${tt.has(e.id)?`,工作中`:``}`,title:`${e.name}${e.agentId?` · 分身 · ${e.worktreePath??e.agentId}`:``}`,"aria-pressed":xe?.memberId===e.id,onClick:t=>Ye(e.id,e.name,t.currentTarget),children:[(0,m.jsx)(pD,{name:e.name,memberId:e.id,busy:tt.has(e.id)}),(0,m.jsxs)(`span`,{children:[e.name,e.agentId?` · 分身`:``]})]},e.id))}),!Ne&&(0,m.jsx)(`button`,{type:`button`,"data-group-settings":!0,disabled:A,onClick:()=>{D(``),Se(void 0),T(!0)},children:`群聊设置`}),(0,m.jsxs)(`button`,{type:`button`,"data-group-rsi":!0,"aria-pressed":x,onClick:v,children:[`RSI`,Me.rsi?.status===`running`?` · 观察中`:Me.rsi?.status===`failed`?` · 需处理`:``]}),(0,m.jsx)(`button`,{type:`button`,onClick:()=>{h?h():to().then(e=>I(e===`granted`?`系统通知已开启`:`请在浏览器站点设置中允许通知`))},children:`系统通知`})]}),F&&(0,m.jsx)(`p`,{role:`status`,children:F}),(Me.cloneRequests??[]).filter((e,t,n)=>e.status===`pending`||t>=n.length-3).map(e=>{let t=Me.members.find(t=>t.id===e.memberId),n=2;for(;Me.members.some(e=>e.name===`${t?.name??`Agent`} ${n}`);)n+=1;let r=ee[e.id]??`${t?.name??`Agent`} ${n}`;return(0,m.jsx)(`section`,{className:`group-clone-request`,"data-clone-request":e.id,"aria-label":`创建 Agent 分身`,children:e.status===`pending`&&e.automatic?(0,m.jsx)(`span`,{children:`主持人正在准备独立分身…`}):e.status===`pending`&&!Ne?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`strong`,{children:[t?.name??`Agent`,` 正在工作,是否创建分身?`]}),(0,m.jsx)(`p`,{children:e.reason}),(0,m.jsx)(`p`,{children:e.assignment}),(0,m.jsxs)(`form`,{onSubmit:t=>{t.preventDefault(),Je(e.id,`create`,r)},children:[(0,m.jsxs)(`label`,{children:[`分身名字`,(0,m.jsx)(`input`,{maxLength:80,required:!0,value:r,onChange:t=>M(n=>({...n,[e.id]:t.target.value}))})]}),(0,m.jsx)(`button`,{disabled:!!N||!r.trim(),children:N===e.id?`正在准备…`:`创建分身并处理`}),(0,m.jsx)(`button`,{type:`button`,disabled:!!N,onClick:()=>void Je(e.id,`wait`,``),children:`等待空闲`})]}),(0,m.jsx)(`small`,{children:`分身共享源 Agent 的能力与经验,在独立 Git 工作树处理此 case。`})]}):(0,m.jsx)(`span`,{children:e.status===`created`?`已安排 ${Me.members.find(t=>t.id===e.cloneId)?.name??`分身`}`:e.status===`waiting`?`已选择等待原成员`:`成员或任务状态已变化,无需创建分身`})},e.id)}),(0,m.jsxs)(`div`,{className:`group-stage${xe?` group-stage-inspecting`:``}`,children:[(0,m.jsxs)(`div`,{className:`group-dialogue`,children:[(0,m.jsxs)(`div`,{className:`group-thread`,ref:Ee,onScroll:e=>{let t=e.currentTarget;De.current=t.scrollHeight-t.clientHeight-t.scrollTop<64},children:[!Ze.length&&(0,m.jsx)(`p`,{className:`group-empty`,children:Ne?`这个群聊没有消息。`:`发条消息开始讨论。用 @ 点名一个或多个成员。`}),Qe.map(e=>{let n=e.replyTo?et.get(e.replyTo):void 0;e.role===`user`&&(rt=e.id);let r=n&&(e.role===`user`||n.id!==e.topicId||e.topicId!==rt)?n:void 0,i=Re(e),a=e.role===`assistant`&&e.background&&e.status===`running`?`后台进行中`:oD[e.status],o=e.role===`assistant`&&xe?.postId===e.id;return(0,m.jsxs)(`article`,{className:`group-post group-post-${e.role}`,"data-group-post":e.role,"data-group-status":e.status,"data-group-post-id":e.id,children:[e.role===`assistant`?(0,m.jsx)(`button`,{className:`group-post-avatar`,type:`button`,"data-group-message-avatar":e.memberId,"aria-label":`查看 ${i} 这次发言的执行详情`,title:`${i} · 执行详情`,"aria-pressed":o,onClick:t=>Ye(e.memberId,i,t.currentTarget,e.id),children:(0,m.jsx)(pD,{name:i,memberId:e.memberId,busy:lD(e)})}):(0,m.jsx)(pD,{name:i}),(0,m.jsxs)(`div`,{className:`group-post-content`,children:[(0,m.jsxs)(`div`,{className:`group-post-head`,children:[(0,m.jsx)(`strong`,{children:i}),e.role===`assistant`&&(0,m.jsx)(`span`,{className:`group-message-model`,"data-group-message-model":e.model?gD(e.model):`unknown`,title:e.model?`${e.model.provider} / ${e.model.modelId}`:`这条历史消息没有记录使用的模型`,children:e.model?`${e.model.label} · ${e.model.provider}`:`模型未记录`}),e.status!==`completed`&&(0,m.jsx)(`span`,{className:`group-post-state`,children:a}),(0,m.jsx)(`time`,{dateTime:nr(e),children:fD(nr(e))}),!Ne&&(0,m.jsxs)(`div`,{className:`group-post-actions`,children:[!lD(e)&&(0,m.jsx)(`button`,{type:`button`,className:`group-reply-action`,disabled:A,onClick:()=>{de(e.id),we.current?.focus()},children:`回复`}),lD(e)&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>void Ge(e.id),children:`停止`})]})]}),(r||e.content||e.error||e.role===`user`&&e.memoryNotice)&&(0,m.jsxs)(`div`,{className:`group-bubble`,children:[r&&(0,m.jsxs)(`div`,{className:`group-quote`,children:[Re(r),` · `,r.content.slice(0,120)]}),e.content&&(0,m.jsx)(`div`,{className:`message-body`,children:(0,m.jsx)(ep,{source:e.content,handoffs:!1,sourceLink:e.role===`assistant`&&S?.members.some(t=>t.id===e.memberId&&!t.worktreePath)?_:void 0})}),e.role===`user`&&e.images?.map(e=>(0,m.jsx)(`img`,{className:`group-post-image`,alt:e.name??`群聊图片`,src:Fe(`/api/upload/${encodeURIComponent(t)}/${encodeURIComponent(e.id)}`)},e.id)),e.role===`user`&&e.memoryNotice&&(0,m.jsx)(`div`,{className:`group-route`,children:e.memoryNotice}),e.error&&(0,m.jsx)(`p`,{className:`group-error`,children:e.error})]}),e.role===`assistant`&&e.routeReason&&(0,m.jsxs)(`details`,{className:`group-route group-post-footer`,children:[(0,m.jsx)(`summary`,{children:`接话原因`}),e.routeReason]})]})]},e.id)})]}),$e.length>0&&(0,m.jsx)(`div`,{className:`group-preparing`,"data-group-preparing":!0,role:`group`,"aria-label":`正在准备回复的成员`,children:$e.map(e=>(0,m.jsx)(`button`,{type:`button`,"data-group-preparing-avatar":e.memberId,title:`${Re(e)} · 正在准备回复`,"aria-label":`查看 ${Re(e)} 的准备详情`,"aria-pressed":xe?.memberId===e.memberId,onClick:t=>Ye(e.memberId,Re(e),t.currentTarget,e.id),children:(0,m.jsx)(pD,{name:Re(e),memberId:e.memberId,busy:!0})},e.memberId))}),Ne?(0,m.jsxs)(`div`,{className:`group-archive-notice`,"data-group-archive-notice":!0,children:[(0,m.jsx)(`p`,{children:`群聊已归档。恢复后可继续发消息。`}),(0,m.jsx)(`button`,{type:`button`,"data-group-restore":!0,disabled:o,onClick:()=>s(Me),children:`恢复群聊`})]}):(0,m.jsxs)(`form`,{className:`group-composer`,onSubmit:Ue,onPaste:e=>{let t=Array.from(e.clipboardData.files).filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),le(t))},children:[g,(0,m.jsx)(`div`,{className:`group-image-attachments`,children:ae.map(e=>(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`img`,{alt:e.name??`待发送图片`,src:Fe(`/api/upload/${encodeURIComponent(t)}/${encodeURIComponent(e.id)}`)}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`移除图片`,onClick:()=>oe(t=>t.filter(t=>t.id!==e.id)),children:`×`})]},e.id))}),(0,m.jsxs)(`label`,{className:`group-image-upload`,title:`需主持人及所有群成员的模型支持图片输入`,children:[se?`上传中…`:`添加图片`,(0,m.jsx)(`input`,{type:`file`,"aria-label":`添加群聊图片`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,disabled:se||A,onChange:e=>{le(Array.from(e.target.files??[])),e.target.value=``}})]}),Pe&&(0,m.jsxs)(`div`,{className:`group-quote`,children:[`回复 `,Re(Pe),` · `,Pe.content.slice(0,60),` `,(0,m.jsx)(`button`,{type:`button`,onClick:()=>de(void 0),"aria-label":`取消引用`,children:`×`})]}),Be.length>0&&(0,m.jsx)(`div`,{className:`group-suggestions`,role:`listbox`,"aria-label":`点名群成员或引用文件`,children:Be.map((e,t)=>(0,m.jsx)(`button`,{type:`button`,role:`option`,"aria-selected":t===ye,"data-group-member-option":e.kind===`member`?e.member.id:void 0,onMouseDown:e=>e.preventDefault(),onClick:()=>We(e),children:e.kind===`member`?e.member.name:`文件 · ${e.file.path}`},e.kind===`member`?`member:${e.member.id}`:`file:${e.file.path}`))}),(0,m.jsx)(`textarea`,{ref:we,"data-group-composer":!0,"aria-label":`群聊消息`,placeholder:`输入消息,@ 点名或引用文件`,value:ne,maxLength:32e3,readOnly:A,onChange:e=>{re(e.target.value),pe(_p(e.target.value,e.target.selectionStart,e.target.selectionEnd)),be(0)},onSelect:e=>{let t=e.currentTarget;pe(_p(t.value,t.selectionStart,t.selectionEnd))},onKeyDown:e=>{e.nativeEvent.isComposing||(Be.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)?(e.preventDefault(),be(t=>(t+Be.length+(e.key===`ArrowDown`?1:-1))%Be.length)):Be.length&&(e.key===`Enter`||e.key===`Tab`)&&!e.shiftKey?(e.preventDefault(),We(Be[ye]??Be[0])):e.key===`Escape`?pe(void 0):e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit()))}}),(0,m.jsx)(`button`,{type:`submit`,"data-group-send":!0,disabled:!ne.trim()&&!ae.length||A||se,children:`发送`})]})]}),xe&&(0,m.jsx)(hD,{workspaceId:e,roomId:t,memberId:xe.memberId,name:xe.name,runs:nt,postId:xe.postId,onStop:e=>void Ge(e),onSelect:e=>Se({...xe,postId:e}),onClose:Xe,models:r?.models??[],memberModel:Me.members.find(e=>e.id===xe.memberId)?.model,onModelChange:Ne?void 0:e=>Ke(xe.memberId,e),onRetry:Ne?void 0:qe},xe.memberId)]})]}):!O&&(0,m.jsx)(`p`,{className:`group-empty`,children:`正在加载群聊…`})]})}function wD({room:e,agents:t,catalog:n,saving:r,onSave:i,onCancel:a}){let[o,s]=(0,p.useState)(e?.title??``),[c,l]=(0,p.useState)({}),u=t.filter(e=>e.mode===`primary`&&!e.hidden),d=[...u,...e?.members.filter(e=>!u.some(t=>t.id===e.id))??[]],f=e?.members.map(e=>e.id)??tr,h=[...new Set([...f,...d.map(e=>e.id)])].filter(e=>d.some(t=>t.id===e)&&(c[e]??f.includes(e))),[g,_]=(0,p.useState)(e?.moderator.model?gD(e.moderator.model):``),[v,y]=(0,p.useState)(e?.moderator.prompt??``),[b,x]=(0,p.useState)(e?.moderator.cloneLimit??0),[S,C]=(0,p.useState)(()=>Object.fromEntries((e?.members??[]).map(e=>[e.id,e.model?gD(e.model):``]))),[w,T]=(0,p.useState)(rD),[E,D]=(0,p.useState)(``),[O,k]=(0,p.useState)(``),[A,j]=(0,p.useState)(``),[ee,M]=(0,p.useState)(yD),[N,P]=(0,p.useState)(``),[F,I]=(0,p.useState)(``),[te,ne]=(0,p.useState)(``);(0,p.useEffect)(()=>{try{localStorage.setItem(_D,JSON.stringify(ee))}catch{ne(`浏览器无法保存预设,请检查本地存储空间或隐私设置。`)}},[ee]);let re=[...n?.models??[]];if(e?.moderator.model&&!re.some(t=>gD(t)===gD(e.moderator.model))){let t=e.moderator.model;n||re.push(t)}let ie=()=>Object.fromEntries(h.map(e=>[e,re.find(t=>gD(t)===S[e])??null])),ae=()=>({prompt:v,cloneLimit:b||void 0,model:re.find(e=>gD(e)===g)}),oe=!(!g||re.some(e=>gD(e)===g))||h.some(e=>S[e]&&!re.some(t=>gD(t)===S[e])),se=e=>{try{return localStorage.setItem(nD,JSON.stringify(e)),T(e),!0}catch{return j(`浏览器无法保存群聊预设,请检查本地存储空间或隐私设置。`),!1}};return(0,m.jsxs)(`form`,{className:`group-settings`,onSubmit:e=>{e.preventDefault();let t=re.find(e=>gD(e)===g);g&&!t||oe||i({title:o,memberIds:h,memberModels:ie(),moderator:ae()})},children:[(0,m.jsxs)(`div`,{className:`group-settings-heading`,children:[(0,m.jsx)(`h2`,{children:e?`群聊设置`:`创建群聊`}),(0,m.jsx)(`p`,{children:`安排成员与模型,让主持人协调讨论和执行。`})]}),(0,m.jsxs)(`section`,{className:`group-settings-card`,"data-group-presets":!0,children:[(0,m.jsx)(`h3`,{children:`群聊预设`}),(0,m.jsx)(`p`,{className:`group-settings-hint`,children:`一并保存成员、各自模型和主持人设置。`}),(0,m.jsxs)(`label`,{children:[`加载群聊预设`,(0,m.jsxs)(`select`,{"aria-label":`加载群聊预设`,value:E,onChange:e=>{D(e.target.value);let t=w.find(t=>t.id===e.target.value);if(!t)return;k(t.name),l(Object.fromEntries([...new Set([...f,...d.map(e=>e.id),...t.memberIds])].map(e=>[e,t.memberIds.includes(e)]))),C(Object.fromEntries(Object.entries(t.memberModels).map(([e,t])=>[e,t?gD(t):``]))),y(t.moderator.prompt),_(t.moderator.model?gD(t.moderator.model):``),x(t.moderator.cloneLimit??0);let n=t.memberIds.filter(e=>!d.some(t=>t.id===e));j(n.length?`已加载「${t.name}」。${n.length} 位成员在当前服务端不可用,请检查成员列表后保存。`:`已加载「${t.name}」。可继续调整,不影响其他群聊。`)},children:[(0,m.jsx)(`option`,{value:``,children:`选择预设…`}),w.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,m.jsxs)(`div`,{className:`group-prompt-preset-actions`,children:[(0,m.jsx)(`input`,{"aria-label":`群聊预设名称`,placeholder:`例如:日常开发评审`,value:O,maxLength:80,onChange:e=>k(e.target.value)}),(0,m.jsx)(`button`,{type:`button`,disabled:!O.trim()||h.length<2||oe,onClick:()=>{let t=O.trim(),n=w.find(e=>e.name.toLocaleLowerCase()===t.toLocaleLowerCase()),r=h.map(t=>e?.members.find(e=>e.id===t)?.agentId??t),i=ie(),a={id:n?.id??tn(),name:t,memberIds:[...new Set(r)],memberModels:Object.fromEntries(r.map((e,t)=>[e,i[h[t]]])),moderator:ae()};se(n?w.map(e=>e.id===n.id?a:e):[a,...w].slice(0,100))&&(D(a.id),j(`已保存群聊预设「${t}」。`))},children:`保存预设`}),E&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>{se(w.filter(e=>e.id!==E))&&(D(``),j(`群聊预设已删除。`))},children:`删除`})]}),A&&(0,m.jsx)(`p`,{className:`group-settings-hint`,role:`status`,children:A})]}),!e&&(0,m.jsxs)(`label`,{children:[`群名`,(0,m.jsx)(`input`,{autoFocus:!0,value:o,onChange:e=>s(e.target.value),maxLength:100,required:!0})]}),(0,m.jsxs)(`fieldset`,{className:`group-member-settings`,children:[(0,m.jsx)(`legend`,{children:`群成员与模型`}),d.map(e=>(0,m.jsxs)(`div`,{className:`group-member-card`,"data-selected":h.includes(e.id),children:[(0,m.jsxs)(`label`,{className:`group-choice`,title:e.description,children:[(0,m.jsx)(`input`,{type:`checkbox`,"data-group-member-choice":e.id,checked:h.includes(e.id),disabled:!h.includes(e.id)&&h.length>=8,onChange:t=>{let n=t.target.checked;l(t=>({...t,[e.id]:n}))}}),(0,m.jsx)(pD,{name:e.name,memberId:e.id}),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.jsx)(`small`,{children:e.description})]})]}),h.includes(e.id)&&(0,m.jsx)(aD,{label:`${e.name} 的模型`,value:S[e.id]??``,models:re,onChange:t=>C(n=>({...n,[e.id]:t}))})]},e.id))]}),(0,m.jsx)(`p`,{className:`group-settings-hint`,children:`取消勾选可移除成员。请选择 2 到 8 位主 Agent。`}),(0,m.jsxs)(`details`,{className:`group-settings-card`,open:!0,children:[(0,m.jsx)(`summary`,{children:`主持人设置`}),(0,m.jsxs)(`label`,{children:[`同类 Agent 分身`,(0,m.jsxs)(`select`,{value:b,onChange:e=>x(Number(e.target.value)),children:[(0,m.jsx)(`option`,{value:0,children:`创建前询问我`}),[2,3,4,8].map(e=>(0,m.jsxs)(`option`,{value:e,children:[`允许自动创建 · 同类最多 `,e,` 人`]},e))]})]}),(0,m.jsxs)(`div`,{className:`group-model-field`,children:[(0,m.jsx)(`span`,{children:`主持人模型`}),(0,m.jsx)(aD,{label:`主持人模型`,value:g,models:re,onChange:_})]}),(0,m.jsxs)(`label`,{children:[`主持人 Prompt`,(0,m.jsx)(`textarea`,{value:v,maxLength:8e3,onChange:e=>y(e.target.value),placeholder:`例如:先请最熟悉模块的成员回答,结论足够时结束。`})]}),(0,m.jsxs)(`details`,{className:`group-prompt-presets`,"data-moderator-prompt-presets":!0,children:[(0,m.jsx)(`summary`,{children:`旧版 Prompt 预设`}),(0,m.jsxs)(`label`,{children:[`加载已保存的 Prompt`,(0,m.jsxs)(`select`,{"aria-label":`加载主持人 Prompt 预设`,value:N,onChange:e=>{let t=ee.find(t=>t.id===e.target.value);P(e.target.value),t?(y(t.prompt),I(t.name),ne(`已加载「${t.name}」,可继续修改后用于当前群聊。`)):ne(``)},children:[(0,m.jsx)(`option`,{value:``,children:`选择预设…`}),ee.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,m.jsxs)(`div`,{className:`group-prompt-preset-actions`,children:[(0,m.jsx)(`input`,{"aria-label":`Prompt 预设名称`,value:F,maxLength:80,onChange:e=>I(e.target.value),placeholder:`预设名称`}),(0,m.jsx)(`button`,{type:`button`,disabled:!F.trim()||!v.trim(),onClick:()=>{let e=F.trim(),t=ee.find(t=>t.name.toLocaleLowerCase()===e.toLocaleLowerCase()),n={id:t?.id??tn(),name:e,prompt:v};M(e=>t?e.map(e=>e.id===t.id?n:e):[n,...e].slice(0,100)),P(n.id),ne(`已保存「${e}」。`)},children:`保存预设`}),N&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>{let e=ee.find(e=>e.id===N);M(e=>e.filter(e=>e.id!==N)),P(``),I(``),ne(e?`已删除「${e.name}」。`:`预设已删除。`)},children:`删除预设`})]}),te&&(0,m.jsx)(`p`,{className:`group-settings-hint`,role:`status`,children:te})]})]}),(0,m.jsxs)(`div`,{className:`group-settings-actions`,children:[(0,m.jsx)(`button`,{type:`button`,disabled:r,onClick:a,children:`取消`}),(0,m.jsx)(`button`,{type:`submit`,disabled:r||!o.trim()||h.length<2||h.length>8||oe,children:e?`保存`:`创建群聊`})]})]})}var TD=`__pi_default__`;function ED({workspaces:e,catalog:t,onClose:n,onSave:r}){let[i,a]=(0,p.useState)(TD),[o,s]=(0,p.useState)(TD);(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]);let c=t.models.find(e=>`${e.provider}/${e.modelId}`===i),l=c?.provider===t.defaultModel?.provider&&c?.modelId===t.defaultModel?.modelId,u=c?.thinkingLevels??(l?t.levels:[]),d=c?{provider:c.provider,modelId:c.modelId,label:c.label}:void 0;return(0,m.jsx)(`div`,{className:`overlay`,onClick:n,children:(0,m.jsxs)(`div`,{className:`picker settings-dialog bulk-workspace-settings`,"data-bulk-workspace-settings":`1`,onClick:e=>e.stopPropagation(),children:[(0,m.jsx)(`h2`,{children:`批量设置工作区`}),(0,m.jsxs)(`div`,{className:`settings-scope`,children:[`将统一修改 `,e.length,` 个现存工作区的默认模型与思考等级,只影响之后新建的会话。`]}),(0,m.jsxs)(`label`,{className:`bulk-settings-field`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,m.jsxs)(`select`,{className:`bulk-settings-select`,"aria-label":`批量默认模型`,value:i,disabled:t.source!==`pi`,onChange:e=>{a(e.target.value),s(TD)},children:[(0,m.jsx)(`option`,{value:TD,children:`跟随 Pi 默认`}),t.models.map(e=>(0,m.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,` · `,e.provider]},`${e.provider}/${e.modelId}`))]})]}),(0,m.jsxs)(`label`,{className:`bulk-settings-field`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认思考等级`}),(0,m.jsxs)(`select`,{className:`bulk-settings-select`,"aria-label":`批量默认思考等级`,value:o,disabled:!c||t.source!==`pi`,onChange:e=>s(e.target.value),children:[(0,m.jsx)(`option`,{value:TD,children:`跟随 Pi 默认`}),u.map(e=>(0,m.jsx)(`option`,{value:e,children:e},e))]})]}),c&&u.length===0&&(0,m.jsx)(`p`,{className:`bulk-settings-note`,children:`Pi 没有为此模型提供可选择的思考等级;新会话会使用 Pi 默认值。`}),(0,m.jsxs)(`div`,{className:`bulk-settings-workspaces`,"aria-label":`将被更新的工作区`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`应用到`}),(0,m.jsx)(`div`,{children:e.map(e=>(0,m.jsx)(`span`,{children:e.name},e.id))})]}),(0,m.jsxs)(`div`,{className:`picker-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:n,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-ok`,disabled:!e.length||t.source!==`pi`,onClick:()=>r(d,o===TD?void 0:o),children:`应用到全部工作区`})]})]})})}function DD({height:e,onHeight:t}){let n=(0,p.useRef)(void 0),r=e=>t(Math.max(120,Math.min(Math.round(window.innerHeight*.65),Math.round(e))));return(0,m.jsx)(`div`,{className:`workbench-bottom-divider`,"data-bottom-divider":!0,role:`separator`,"aria-label":`调整底部面板高度`,"aria-orientation":`horizontal`,"aria-valuemin":120,"aria-valuemax":Math.round(window.innerHeight*.65),"aria-valuenow":Math.min(e,Math.round(window.innerHeight*.65)),tabIndex:0,onPointerDown:t=>{t.preventDefault(),t.currentTarget.focus(),t.currentTarget.setPointerCapture(t.pointerId),n.current={y:t.clientY,height:Math.min(e,window.innerHeight*.65)}},onPointerMove:e=>{n.current&&r(n.current.height+n.current.y-e.clientY)},onLostPointerCapture:()=>{n.current=void 0},onDoubleClick:()=>r(260),onKeyDown:t=>{if(t.key===`ArrowUp`)r(e+24);else if(t.key===`ArrowDown`)r(e-24);else if(t.key===`Home`)r(120);else if(t.key===`End`)r(window.innerHeight);else return;t.preventDefault()}})}function OD({glyph:e,className:t}){return(0,m.jsx)(`span`,{className:t,"data-tool-glyph-length":Math.min(4,Math.max(1,Array.from(e).length)),"aria-hidden":`true`,children:e})}function kD(e){if(e!==void 0){if(typeof e!=`string`||!e.trim()||Array.from(e.trim()).length>4||/[<>\u0000-\u001f\u007f]/.test(e))throw Error(`工具图标须为 1 至 4 个字符的文字或符号`);return e.trim()}}function AD(e){try{let t=kD(e.glyph);if(t)return t}catch{}let t=`${e.name} ${e.slug??``}`.toLowerCase();return[[/json/,`{}`],[/正则|regex/,`.*`],[/计算|calc/,`∑`],[/时间|timestamp|date/,`◷`],[/差异|diff/,`±`],[/markdown/,`M↓`],[/图像|图片|image/,`▧`],[/表格|csv|excel/,`▦`],[/颜色|color/,`◐`],[/base64/,`64`],[/hash|哈希/,`#`],[/git/,`⑂`]].find(([e])=>e.test(t))?.[1]??(Array.from(e.name.trim()).slice(0,2).join(``)||`◇`)}function jD(e){return!!(e&&typeof e==`object`&&e.type===`message.send`)}function MD(e){let t=[],n=[];for(let r of e)(r.retry?t:n).push(r);return{retry:t,failed:n}}function ND(e){let t=new Map;for(let[n,r]of e.entries())t.has(r.id)||t.set(r.id,n);return t}function PD(e,t){if(!t||t.length===0)return e;let n=new Map(t.map((e,t)=>[e,t])),r=e.filter(e=>n.has(e.id)).sort((e,t)=>(n.get(e.id)??0)-(n.get(t.id)??0));return[...e.filter(e=>!n.has(e.id)),...r]}function FD(e,t,n){if(e.indexOf(t)<0)return[...e];let r=e.filter(e=>e!==t),i=Math.max(0,Math.min(n,r.length));return[...r.slice(0,i),t,...r.slice(i)]}var ID=`super-pi.session-order.v1`;function LD(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.session-order.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.filter(e=>typeof e==`string`));return t}catch{return{}}}function RD(e){try{typeof window<`u`&&window.localStorage.setItem(ID,JSON.stringify(e))}catch{}}function zD(e,t,n){let r=new Set(e.map(e=>e.id)),i=ND(e),a=(e,t)=>(i.get(e.id)??2**53-1)-(i.get(t.id)??2**53-1),o=new Map,s=[];for(let t of e){let e=t.parentConversationId;if(e&&r.has(e)){let n=o.get(e);n?n.push(t):o.set(e,[t])}else s.push(t)}for(let e of o.values())e.sort(a);let c=PD(s.sort(a),n?.manualRoots),l=[],u=new Set,d=(e,n,r,i=!0)=>{if(u.has(e.id))return;u.add(e.id);let a=o.get(e.id)??[];i&&l.push({conversation:e,depth:Math.min(n,8),childCount:a.length,isLastSibling:r});let s=!i||t.has(e.id);for(let[e,t]of a.entries())d(t,n+1,e===a.length-1,!s)};for(let e of c)d(e,0,!1);let f=e.filter(e=>!u.has(e.id)).sort(a);for(let e of f)d(e,0,!1);return l}var BD=`super-pi:tool-shortcuts:v1`,VD=new Set([`Control`,`Alt`,`Shift`,`Meta`,`AltGraph`,`CapsLock`,`Fn`,`FnLock`,`Hyper`,`Super`,`Symbol`,`SymbolLock`]),HD=new Set([`Escape`]),UD=new Set([`Enter`,` `,`Tab`]),WD={" ":`Space`,ArrowUp:`↑`,ArrowDown:`↓`,ArrowLeft:`←`,ArrowRight:`→`,Escape:`Esc`},GD={ctrl:`⌃`,alt:`⌥`,shift:`⇧`,meta:`⌘`};function KD(e){if(e===` `)return` `;let t=e.trim();return t?t.length===1?t.toLowerCase():t:``}function qD(e){return VD.has(e)}function JD(e){let t=e.key;if(!t||t===`Unidentified`||t===`Dead`||qD(t))return;let n=KD(t);if(!n)return;let r=!!e.shiftKey;if(r&&n.length===1&&!/[a-z]/.test(n)){let t=/^Digit([0-9])$/.exec(e.code??``);t&&(n=t[1])}let i={key:n};return e.ctrlKey&&(i.ctrl=!0),e.altKey&&(i.alt=!0),r&&(i.shift=!0),e.metaKey&&(i.meta=!0),i}function YD(e){return WD[e]||(e.length===1||/^f\d{1,2}$/.test(e)?e.toUpperCase():e)}function XD(e){let t=[];return e.ctrl&&t.push(`Ctrl`),e.alt&&t.push(`Alt`),e.shift&&t.push(`Shift`),e.meta&&t.push(`Meta`),t.push(YD(e.key)),t.join(`+`)}function ZD(e){let t=``;return e.ctrl&&(t+=GD.ctrl),e.alt&&(t+=GD.alt),e.shift&&(t+=GD.shift),e.meta&&(t+=GD.meta),t+YD(e.key)}function QD(e,t){return e.key===t.key&&!!e.ctrl==!!t.ctrl&&!!e.alt==!!t.alt&&!!e.shift==!!t.shift&&!!e.meta==!!t.meta}function $D(e){return!!(e.ctrl||e.alt||e.shift||e.meta)}function eO(e){return e.key?HD.has(e.key)?{ok:!1,reason:`Esc 是所有弹窗的退出键,不能拿来当工具快捷键。`}:!$D(e)&&UD.has(e.key)?{ok:!1,reason:`「${tO(e.key)}」是当前焦点控件的激活键,加一个修饰键(Ctrl / Alt / Shift)才能当快捷键用。`}:{ok:!0}:{ok:!1,reason:`这个组合键不完整,请按一个具体的键。`}}function tO(e){return YD(e)}function nO(e){let t=e;if(!t||typeof t!=`object`)return!1;let n=t.tagName;return n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.isContentEditable===!0}function rO(e,t){if(t.isComposing||t.defaultPrevented)return!1;let n=JD(t);return!(!n||!QD(e,n)||!$D(e)&&nO(t.target??null))}function iO(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{return{}}if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){if(!e||typeof r!=`object`||!r)continue;let t=r,i=KD(typeof t.key==`string`?t.key:``);if(!i)continue;let a={key:i};t.ctrl===!0&&(a.ctrl=!0),t.alt===!0&&(a.alt=!0),t.shift===!0&&(a.shift=!0),t.meta===!0&&(a.meta=!0),eO(a).ok&&(n[e]=a)}return n}function aO(e){let t={};for(let n of Object.keys(e).sort()){let r=e[n];if(!r)continue;let i={key:r.key};r.ctrl&&(i.ctrl=!0),r.alt&&(i.alt=!0),r.shift&&(i.shift=!0),r.meta&&(i.meta=!0),t[n]=i}return JSON.stringify(t)}function oO(e,t,n){for(let[r,i]of Object.entries(e))if(r!==n&&QD(i,t))return r}var sO=`super-pi:tool-settings-size:v1`,cO={width:480,height:320};function lO(){try{if(typeof window>`u`)return qt.slice();let e=$t(window.localStorage.getItem(Xt));return window.localStorage.getItem(`super-pi:tools:v1`)===null?qt.slice():e}catch{return qt.slice()}}function uO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(Xt,en(e))}catch{}}function dO(){try{return typeof window>`u`?{}:iO(window.localStorage.getItem(BD))}catch{return{}}}function fO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(BD,aO(e))}catch{}}function pO(e,t,n){let r={};for(let n of t)e[n.id]&&(r[n.id]=e[n.id]);for(let e of n)e.shortcut&&(r[e.id]=e.shortcut);return r}function mO(){try{if(typeof window>`u`)return;let e=window.localStorage.getItem(sO);if(!e)return;let t=JSON.parse(e);return typeof t?.width!=`number`||typeof t?.height!=`number`||!Number.isFinite(t.width)||!Number.isFinite(t.height)||t.width<cO.width||t.height<cO.height?void 0:{width:Math.round(t.width),height:Math.round(t.height)}}catch{return}}function hO(e){try{if(typeof window>`u`)return;e?window.localStorage.setItem(sO,JSON.stringify({width:Math.round(e.width),height:Math.round(e.height)})):window.localStorage.removeItem(sO)}catch{}}function gO(e,t,n){let r=Math.max(cO.width,t-32),i=Math.max(cO.height,n-32);return{width:Math.round(Math.min(Math.max(e.width,cO.width),r)),height:Math.round(Math.min(Math.max(e.height,cO.height),i))}}var _O=dO(),vO={tools:lO(),mountedTools:[],settingsOpen:!1,shortcuts:{}};vO.shortcuts=pO(_O,vO.tools,vO.mountedTools);var yO=new Set;function bO(e){vO={...vO,...e};for(let e of yO)e()}function xO(e){return yO.add(e),()=>{yO.delete(e)}}var SO=()=>vO;function CO(){return(0,p.useSyncExternalStore)(xO,SO,SO)}var wO={setTools(e){uO(e);let t=new Set(e.map(e=>e.id));_O=Object.fromEntries(Object.entries(_O).filter(([e])=>t.has(e))),fO(_O),bO({tools:e,shortcuts:pO(_O,e,vO.mountedTools)})},removeTool(e){let t=an(vO.tools,e);_O[e]&&(_O={..._O},delete _O[e],fO(_O)),uO(t),bO({tools:t,shortcuts:pO(_O,t,vO.mountedTools),openToolId:vO.openToolId===e?void 0:vO.openToolId})},setMountedTools(e){let t=new Set(vO.tools.map(e=>e.id));_O=Object.fromEntries(Object.entries(_O).filter(([e])=>t.has(e))),fO(_O),bO({mountedTools:e,shortcuts:pO(_O,vO.tools,e)})},openTool(e){bO({openToolId:e,settingsOpen:!1})},closeTool(){bO({openToolId:void 0})},toggleTool(e){vO.openToolId===e?wO.closeTool():wO.openTool(e)},openSettings(){bO({settingsOpen:!0,openToolId:void 0})},closeSettings(){bO({settingsOpen:!1})},async setShortcut(e,t){let n=vO.mountedTools.find(t=>t.id===e);if(n){try{let e=await Ie(`/api/tools/shortcut`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({slug:n.slug,shortcut:t})}),r=await e.json();if(!e.ok)return r.error??`快捷键保存失败(HTTP ${e.status})。`}catch(e){return e instanceof Error?e.message:String(e)}bO({mountedTools:vO.mountedTools.map(n=>n.id===e?{...n,shortcut:t}:n),shortcuts:{...vO.shortcuts,[e]:t}})}else _O={..._O,[e]:t},fO(_O),bO({shortcuts:pO(_O,vO.tools,vO.mountedTools)})},async clearShortcut(e){if(!vO.shortcuts[e])return;let t=vO.mountedTools.find(t=>t.id===e);if(t){try{let e=await Ie(`/api/tools/shortcut`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({slug:t.slug,shortcut:null})}),n=await e.json();if(!e.ok)return n.error??`快捷键清除失败(HTTP ${e.status})。`}catch(e){return e instanceof Error?e.message:String(e)}bO({mountedTools:vO.mountedTools.map(t=>t.id===e?{...t,shortcut:void 0}:t),shortcuts:Object.fromEntries(Object.entries(vO.shortcuts).filter(([t])=>t!==e))})}else _O={..._O},delete _O[e],fO(_O),bO({shortcuts:pO(_O,vO.tools,vO.mountedTools)})},persistTools(){uO(vO.tools)}};async function TO(){let e=me();try{let t=await Ie(`/api/tools`),n=await t.json();me()===e&&t.ok&&Array.isArray(n.tools)&&wO.setMountedTools(n.tools.filter(e=>e.enabled))}catch{}}async function EO(e){try{let t=await Ie(`/api/tools?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);wO.closeTool(),await TO();return}catch(e){return e instanceof Error?e.message:String(e)}}var DO=`.super-pi-tool.json`,OO=512e3,kO=/^[a-z0-9][a-z0-9-]{0,63}$/,AO=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function jO(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${DO})。`}}if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`这个 JSON 不是一个工具包。`};let r=n,i;try{i=kD(r.glyph)}catch{return{ok:!1,reason:`工具图标须为 1 至 4 个字符的文字或符号。`}}let a=typeof r.format==`string`?r.format:void 0;if(a!==void 0&&a!==`super-pi.tool`)return{ok:!1,reason:`这不是 Super Pi 的工具文件(format: ${a})。`};if(typeof r.version==`number`&&r.version>1)return{ok:!1,reason:`这个工具文件是更新版本的 Super Pi 导出的(version: ${r.version}),当前版本读不了。`};let o=typeof r.slug==`string`?r.slug.trim():``,s=typeof r.name==`string`?r.name.trim():``;if(!o)return{ok:!1,reason:`这个工具包里没有 slug(那是它的短名字,也是它在磁盘上的目录名)。`};if(!s)return{ok:!1,reason:`这个工具包里没有名字。`};if(!Array.isArray(r.files)||!r.files.length)return{ok:!1,reason:`这个工具包里没有文件。`};if(r.files.length>32)return{ok:!1,reason:`文件太多了:${r.files.length} 个,上限 32 个。`};let c=[],l=0;for(let e of r.files){let t=e;if(!t||typeof t.path!=`string`||typeof t.content!=`string`)return{ok:!1,reason:`工具包里的文件项格式不对(每一项都要有 path 和 content)。`};let n=t.path.trim();if(!n||n.startsWith(`/`)||n.includes(`\\`)||n.includes(`\0`)||n.split(`/`).includes(`..`))return{ok:!1,reason:`文件路径「${n}」不合法:不能是绝对路径,也不能跳出工具自己的目录。`};if(c.some(e=>e.path===n))return{ok:!1,reason:`工具包里有重复的文件:${n}`};if(l+=new TextEncoder().encode(t.content).length,l>512e3)return{ok:!1,reason:`工具文件合计超过 ${zO(OO)} 的上限。`};c.push({path:n,content:t.content})}let u=typeof r.entrypoint==`string`&&r.entrypoint.trim()?r.entrypoint.trim():`index.html`;if(!u.endsWith(`.html`))return{ok:!1,reason:`入口文件必须是一个 HTML 文件。`};if(!c.some(e=>e.path===u))return{ok:!1,reason:`工具包里没有包含入口文件 ${u}。`};let d;if(r.script!==void 0&&r.script!==null){let e=r.script,t=typeof e.path==`string`?e.path.trim():``;if(!t.endsWith(`.py`))return{ok:!1,reason:`工具包声明的脚本必须是一个 .py 文件。`};if(!c.some(e=>e.path===t))return{ok:!1,reason:`工具包里没有包含它声明的脚本 ${t}。`};d={path:t,timeoutMs:typeof e.timeoutMs==`number`?e.timeoutMs:void 0,parameters:typeof e.parameters==`object`&&e.parameters!==null?e.parameters:void 0}}let f;if(r.environment!==void 0&&r.environment!==null){let e=r.environment,t=e.requires;if(t!==void 0&&!Array.isArray(t))return{ok:!1,reason:`工具包声明的依赖列表格式不对(requires 必须是数组)。`};if(Array.isArray(t)){for(let e of t)if(typeof e!=`string`||!AO.test(e.trim()))return{ok:!1,reason:`依赖必须钉死到精确版本(写成 pkg==version):${String(e).slice(0,60)}。`}}let n=e.fingerprint&&typeof e.fingerprint==`object`?e.fingerprint:void 0;f={requiresPython:typeof e.requiresPython==`string`?e.requiresPython:void 0,requires:Array.isArray(t)?t.map(e=>String(e).trim()):void 0,fingerprint:n}}let p=r.permissions&&typeof r.permissions==`object`&&r.permissions.llm===!0?{llm:!0}:void 0;return{ok:!0,unnamedFormat:a===void 0,bundle:{...a===void 0?{}:{format:a},...typeof r.version==`number`?{version:r.version}:{},...typeof r.exportedAt==`string`?{exportedAt:r.exportedAt}:{},slug:o,name:s,...i?{glyph:i}:{},...typeof r.description==`string`&&r.description.trim()?{description:r.description.trim().slice(0,500)}:{},entrypoint:u,files:c,script:d,environment:f,...p?{permissions:p}:{}}}}function MO(e){let t=e.trim().toLowerCase();return t?kO.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function NO(e,t){let n=e.trim().toLowerCase().slice(0,60).replace(/[^a-z0-9-]+/g,`-`).replace(/^-+|-+$/g,``)||`tool`;if(!t.includes(n))return n;for(let e=2;e<100;e+=1){let r=`${n}-${e}`;if(!t.includes(r))return r}return n}function PO(e){return`${e.slug}${DO}`}function FO(e){let t=e.trim().replace(/[\\/:*?"<>|]/g,``).replace(/\.+$/,``).trim();return t?t.length>80?{ok:!1,reason:`文件名太长了,请控制在 80 个字符以内。`}:{ok:!0,name:t.endsWith(`.super-pi-tool.json`)?t:`${t}${DO}`}:{ok:!1,reason:`请填写文件名。`}}function IO(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function LO(e){let t=e.environment?.requires??[];return!e.script&&t.length===0?{tone:`ok`,text:`纯页面工具 · 导入即用,不需要 Python`}:t.length===0?{tone:`ok`,text:`只用 Python 标准库 · 导入即用,不需要安装任何包${e.environment?.requiresPython?`(需要 Python ${e.environment.requiresPython})`:``}`}:{tone:`warn`,text:`首次运行时会安装 ${t.length} 个依赖:${t.join(`、`)}(装进这个工具自己的虚拟环境)${e.environment?.requiresPython?` · 需要 Python ${e.environment.requiresPython}`:``}`}}function RO(e){if(e)return e.state===`zero-deps`?{text:`零依赖`,warn:!1}:e.state===`ready`?{text:`环境就绪`,warn:!1}:e.state===`needs-env`?{text:`首次运行时安装依赖`,warn:!1}:e.state===`needs-python`?{text:`缺少可用的 Python`,warn:!0}:{text:`与导出方环境不一致`,warn:!0}}function zO(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function BO(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var VO=`请基于上面的请求、已输出的内容和已完成的操作继续完成任务。优先给出简洁结论或执行必要的小步骤,不要重复已有内容或已成功的写入。`;function HO(e){return/^\s*<continue_output>([\s\S]*?)<\/continue_output>\s*$/.exec(e)?.[1].trim()}function UO(e){return!Number.isFinite(e)||e<=0?``:e>=1e6?`${Math.round(e/1e6)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function WO(e){return!Number.isFinite(e)||e<=0?``:e>=1e6?`${Math.round(e/1e6)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function GO(e,t){if(!e)return 0;let n=0;for(let r of t)n+=e[r]??0;return n}var KO=128e3;function qO(e){let t=[[]],n=0,r=0,i=[0,0],a=e=>{for(;t.length<=e;)t.push([])},o=e=>{let i=t[n];for(;i.length<r;)i.push(` `);for(let t of e)i[r]=t,r+=1},s=e=>e.replace(/^[?>!]/u,``).split(`;`).map(e=>Number.parseInt(e,10)||0),c=(e,o)=>{let c=s(e),l=Math.max(1,c[0]||1);switch(o){case`A`:n=Math.max(0,n-l);break;case`B`:case`e`:n+=l,a(n);break;case`C`:case`a`:r+=l;break;case`D`:r=Math.max(0,r-l);break;case`E`:n+=l,a(n),r=0;break;case`F`:n=Math.max(0,n-l),r=0;break;case`G`:case"`":r=Math.max(0,l-1);break;case`d`:n=Math.max(0,l-1),a(n);break;case`H`:case`f`:n=Math.max(0,l-1),a(n),r=Math.max(0,(c[1]||1)-1);break;case`K`:{let e=t[n];(c[0]??0)===2?t[n]=[]:(c[0]??0)===1?t[n]=[...Array.from({length:Math.min(r+1,e.length)},()=>` `),...e.slice(r+1)]:e.splice(r);break}case`J`:(c[0]??0)===2||(c[0]??0)===3?(t.splice(0,t.length,[]),n=0,r=0):(c[0]??0)===0?t.splice(n+1):(c[0]??0)===1&&(t.splice(0,n),n=0,t[0]=[]);break;case`s`:i=[n,r];break;case`u`:[n,r]=i,a(n);break;case`P`:t[n].splice(r,l);break;case`X`:{let e=t[n];for(let t=r;t<Math.min(e.length,r+l);t+=1)e[t]=` `;break}case`@`:t[n].splice(r,0,...Array.from({length:l},()=>` `))}},l=t=>{for(let n=t;n<e.length;n+=1){if(e[n]===`\x07`)return n+1;if(e[n]===`\x1B`&&e[n+1]===`\\`)return n+2}return e.length};for(let t=0;t<e.length;){let i=e[t];if(i===``||i===``||i===``||i===``){t=l(t+1);continue}if(i===`\x1B`||i===``){let n=e[t+1];if(i===`\x1B`&&(n===`]`||n===`P`||n===`^`||n===`_`)){t=l(t+2);continue}if(i===`\x1B`&&n===`[`||i===``){let n=t+(i===``?1:2),r=n;for(;r<e.length&&!(e.charCodeAt(r)>=64&&e.charCodeAt(r)<=126);)r+=1;r<e.length&&c(e.slice(n,r),e[r]),t=Math.min(e.length,r+1);continue}t+=n===void 0?1:2;continue}if(i===`\r`){t+=1,r=0;continue}if(i===`
|
|
333
|
+
`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return U_.get()},set promptLabel(e){U_.set(e)},get tooMuchOutput(){return G_.get()},set tooMuchOutput(e){G_.set(e)}}}_verifyIntegers(...e){for(PT of e)if(PT===1/0||isNaN(PT)||PT%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(PT of e)if(PT&&(PT===1/0||isNaN(PT)||PT%1!=0||PT<0))throw Error(`This API only accepts positive integers`)}},IT=2,LT=1,RT=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;(this._terminal.rows!==e.rows||this._terminal.cols!==e.cols)&&(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o={top:parseInt(a.getPropertyValue(`padding-top`)),bottom:parseInt(a.getPropertyValue(`padding-bottom`)),right:parseInt(a.getPropertyValue(`padding-right`)),left:parseInt(a.getPropertyValue(`padding-left`))},s=o.top+o.bottom,c=o.right+o.left,l=r-s,u=i-c-t;return{cols:Math.max(IT,Math.floor(u/e.css.cell.width)),rows:Math.max(LT,Math.floor(l/e.css.cell.height))}}},zT=`super-pi.terminal-owner.v1`,BT=`super-pi.terminal-selection.v1.`,VT=20,HT=5,UT=240,WT=120,GT={checking:`正在连接`,unavailable:`不可用`,starting:`启动中`,running:`运行中`,exited:`已结束`,empty:`没有打开的终端`},KT=new WeakSet,qT;function JT(){if(qT)return qT;try{let e=window.localStorage.getItem(zT);if(e&&/^[0-9a-f]{32}$/.test(e))return qT=e}catch{}qT=Array.from(window.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``);try{window.localStorage.setItem(zT,qT)}catch{}return qT}function YT(e){try{return window.sessionStorage.getItem(e)??void 0}catch{return}}function XT({workspaceId:e,workspaceLabel:t,cwd:n=``,connected:r,sendCommand:i,registerSink:a,conversationId:o,terminalShell:s,focusRequest:c}){let l=BT+JSON.stringify([e,o]),[u,d]=(0,p.useState)([]),[f,h]=(0,p.useState)(()=>YT(l)??``),[g,_]=(0,p.useState)(!1),[v,y]=(0,p.useState)(),[b,x]=(0,p.useState)(``),[S,C]=(0,p.useState)(``),w=(0,p.useRef)(new Map),T=(0,p.useRef)(new Map),E=(0,p.useRef)(new Map),D=(0,p.useRef)(new Map),O=(0,p.useRef)(!1),k=(0,p.useRef)(f);k.current=f;let A=(0,p.useRef)(!1),j=(0,p.useRef)(null),ee=(0,p.useRef)(!1),M=(0,p.useRef)(0),N=(0,p.useRef)(void 0),P=(0,p.useCallback)(()=>{cancelAnimationFrame(M.current),M.current=requestAnimationFrame(()=>{let e=k.current,t=T.current.get(e);ee.current&&O.current&&t&&!D.current.has(e)&&t.host.clientWidth&&t.host.clientHeight&&(t.terminal.focus(),ee.current=!1)})},[]);(0,p.useLayoutEffect)(()=>{c&&!KT.has(c)&&c.request!==N.current&&c.workspaceId===e&&c.conversationId===o&&(KT.add(c),N.current=c.request,ee.current=!0,P())},[c,e,o,P]),(0,p.useEffect)(()=>{let e=()=>{ee.current=!1,A.current=!1},t=t=>{t.target instanceof Node&&!j.current?.contains(t.target)&&e()};return document.addEventListener(`pointerdown`,t,!0),document.addEventListener(`keydown`,t,!0),window.addEventListener(`blur`,e),()=>{cancelAnimationFrame(M.current),document.removeEventListener(`pointerdown`,t,!0),document.removeEventListener(`keydown`,t,!0),window.removeEventListener(`blur`,e)}},[]);let F=(0,p.useCallback)(e=>{let t=T.current.get(e);if(!t||!t.host.clientWidth||!t.host.clientHeight||D.current.has(e))return;let{terminal:n,fitAddon:r}=t,a=r.proposeDimensions();if(!a||!Number.isFinite(a.cols)||!Number.isFinite(a.rows))return;let o=Math.max(VT,Math.min(UT,a.cols)),s=Math.max(HT,Math.min(WT,a.rows));(n.cols!==o||n.rows!==s)&&n.resize(o,s);let c=w.current.get(e);O.current&&c&&c.exitCode===void 0&&(c.cols!==o||c.rows!==s)&&i({type:`terminal.resize`,sessionId:e,cols:o,rows:s})},[i]),I=(0,p.useCallback)((e,t)=>{let n=e.sessionId;if(e.type===`terminal.output`){t.write(e.data);return}let r=w.current.get(n),i=D.current.get(n);r&&t.resize(r.cols,r.rows),t.write(`\x1Bc\x1B[3J`+e.data,()=>{D.current.get(n)===i&&(D.current.delete(n),k.current===n&&(F(n),P()))})},[F,P]),te=(0,p.useCallback)((e,t)=>{if(!t||T.current.has(e))return;let n=getComputedStyle(t),r=(e,t)=>n.getPropertyValue(e).trim()||t,a=w.current.get(e),o=new FT({cols:a?.cols,rows:a?.rows,cursorBlink:!0,convertEol:!1,scrollback:5e3,fontFamily:`Consolas, 'Cascadia Mono', 'DejaVu Sans Mono', monospace`,fontSize:12,lineHeight:1.35,theme:{background:`#00000000`,foreground:r(`--term-fg`,`#dbe4f0`),cursor:r(`--term-fg`,`#dbe4f0`),selectionBackground:r(`--term-selection`,`#3a4f6b`)},allowProposedApi:!0}),s=new RT;o.loadAddon(s),o.open(t),o.onData(t=>{O.current&&!D.current.has(e)&&w.current.get(e)?.exitCode===void 0&&i({type:`terminal.input`,sessionId:e,data:t})}),T.current.set(e,{terminal:o,fitAddon:s,host:t});for(let t of E.current.get(e)??[])I(t,o);E.current.delete(e),requestAnimationFrame(()=>F(e))},[F,i,I]),ne=(0,p.useCallback)(t=>{if(t.type===`terminal.sessions`){if(t.workspaceId!==e||t.conversationId!==o)return;let n=new Map(t.sessions.map(e=>[e.id,e]));for(let[e,r]of T.current)n.has(e)?!t.replay&&w.current.get(e)?.exitCode!==void 0&&n.get(e)?.exitCode===void 0&&r.terminal.write(`\x1Bc\x1B[3J`):(r.terminal.dispose(),T.current.delete(e));for(let e of E.current.keys())(!n.has(e)||t.replay)&&E.current.delete(e);if(t.replay){D.current.clear();for(let e of n.keys())D.current.set(e,Symbol())}!t.replay&&A.current&&t.activate&&n.has(t.activate)&&(ee.current=!0,A.current=!1),w.current=n,O.current=!0,d(t.sessions),h(e=>t.activate??(n.has(e)?e:t.sessions[0]?.id??``)),y(void 0),_(!0)}else if(t.type===`terminal.output`||t.type===`terminal.replay`){if(!w.current.has(t.sessionId))return;let e=T.current.get(t.sessionId)?.terminal;if(e)I(t,e);else{let e=E.current.get(t.sessionId)??[];e.push(t),E.current.set(t.sessionId,e)}}else if(t.type===`terminal.size`){let e=w.current.get(t.sessionId);e&&(Object.assign(e,{cols:t.cols,rows:t.rows}),T.current.get(e.id)?.terminal.resize(e.cols,e.rows))}else if(t.type===`terminal.exit`){let e=w.current.get(t.sessionId);if(!e)return;let n={...e,exitCode:t.exitCode,reason:t.reason};w.current.set(n.id,n),d(e=>e.map(e=>e.id===n.id?n:e))}else(t.type===`terminal.error`||t.type===`terminal.status`&&!t.enabled)&&(A.current=!1,y(void 0),x(t.type===`terminal.error`?t.message:t.reason||`终端未启用`))},[o,e,I]);(0,p.useEffect)(()=>(a(ne),()=>a(void 0)),[ne,a]);let re=(0,p.useCallback)(()=>{O.current=!1,_(!1),y(void 0),x(``),r&&e&&i({type:`terminal.sync`,ownerId:JT(),workspaceId:e,conversationId:o,cwd:n,initialize:YT(l)===void 0})},[r,e,o,n,l,i]);(0,p.useEffect)(()=>(re(),()=>{r&&i({type:`terminal.detach`})}),[r,i,re]),(0,p.useEffect)(()=>()=>{O.current=!1;for(let e of T.current.values())e.terminal.dispose();T.current.clear()},[]),(0,p.useEffect)(()=>{if(g)try{window.sessionStorage.setItem(l,f)}catch{}},[f,g,l]),(0,p.useEffect)(()=>{let e=!1;return Ie(`/api/terminal-shell`).then(e=>e.json()).then(t=>{let n=t.shell;!e&&n&&C(n.file+(n.args.length?` `+n.args.join(` `):``)+`(`+(t.source??``)+`)`)}).catch(()=>void 0),()=>{e=!0}},[s?.file,s?.args.join(`\0`)]),(0,p.useLayoutEffect)(()=>{let e=T.current.get(f);if(!e)return;let t=new ResizeObserver(()=>{F(f),P()});return t.observe(e.host),F(f),P(),()=>t.disconnect()},[f,F,u,P]);let ie=e=>!r||!g||v?!1:i(e)?(x(``),y(e.type===`terminal.open`?`open`:`close`),!0):!1,ae=e=>{let t=T.current.get(f)?.terminal;A.current=!0,ie({type:`terminal.open`,sessionId:e,cols:t?.cols,rows:t?.rows})||(A.current=!1)},oe=u.find(e=>e.id===f),se=r&&g&&!v,ce=e?r?g?v===`open`?`starting`:oe?oe.exitCode===void 0?`running`:`exited`:`empty`:b?`unavailable`:`checking`:`checking`:`unavailable`,le=b||oe?.reason;return(0,m.jsxs)(`div`,{ref:j,className:`terminal-panel`,"data-terminal-panel":`1`,"data-terminal-phase":ce,children:[(0,m.jsxs)(`div`,{className:`terminal-strip`,role:`tablist`,"aria-label":`终端会话`,"data-terminal-strip":`1`,children:[u.map(e=>(0,m.jsxs)(`div`,{className:`terminal-tab${e.id===f?` is-active`:``}`,children:[(0,m.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":e.id===f,className:`terminal-tab-btn`,"data-terminal-slot":e.id,onClick:()=>{ee.current=!0,h(e.id),P()},title:GT[e.exitCode===void 0?`running`:`exited`],children:[(0,m.jsx)(`span`,{className:`terminal-tab-dot terminal-tab-dot-${e.exitCode===void 0?`running`:`exited`}`,"aria-hidden":`true`}),e.title]}),(0,m.jsx)(`button`,{type:`button`,className:`terminal-tab-close`,disabled:!se,"aria-label":`关闭终端 ${e.title}`,"data-terminal-slot-close":e.id,onClick:()=>ie({type:`terminal.close`,sessionId:e.id}),children:(0,m.jsx)(vi,{name:`close`})})]},e.id)),u.length<5&&(0,m.jsx)(`button`,{type:`button`,className:`terminal-strip-add`,disabled:!se,"data-terminal-add":`1`,onClick:()=>ae(),title:`新建终端`,"aria-label":`新建终端`,children:`+`})]}),(0,m.jsxs)(`div`,{className:`terminal-toolbar`,children:[(0,m.jsxs)(`span`,{className:`terminal-status terminal-status-${ce}`,"data-terminal-status":ce,children:[(0,m.jsx)(`span`,{className:`terminal-status-dot`,"aria-hidden":`true`}),GT[ce]]}),(0,m.jsxs)(`span`,{className:`terminal-toolbar-right`,children:[S&&(0,m.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-shell-hint":`1`,title:S,children:S}),t&&(0,m.jsx)(`span`,{className:`terminal-cwd`,"data-terminal-hint":`1`,title:t,children:t}),oe?.exitCode!==void 0&&(0,m.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,"data-terminal-restart":`1`,disabled:!se,onClick:()=>ae(oe.id),children:`重新打开`}),!g&&b&&r&&(0,m.jsx)(`button`,{type:`button`,className:`terminal-restart-btn`,onClick:re,children:`重试连接`})]})]}),le&&(0,m.jsx)(`p`,{className:`tool-error`,"data-terminal-error":`1`,role:`alert`,title:Br(le),children:zr(le,`终端出错了。`)}),oe?.exitCode!==void 0&&oe.exitCode!==0&&(0,m.jsxs)(`p`,{className:`tool-error`,"data-terminal-exit":`1`,children:[`会话已结束,退出码 `,oe.exitCode,`。`]}),(0,m.jsxs)(`div`,{className:`terminal-surface`,"data-terminal-surface":`1`,children:[u.map(e=>(0,m.jsx)(`div`,{ref:t=>te(e.id,t),className:`terminal-xterm-host`,"data-terminal-xterm":e.id,style:{display:e.id===f?`block`:`none`}},e.id)),ce===`empty`&&(0,m.jsx)(`div`,{className:`terminal-surface-empty`,"data-terminal-empty":`1`,children:(0,m.jsx)(`p`,{className:`rail-empty`,children:GT.empty})}),!oe&&ce===`checking`&&(0,m.jsx)(`p`,{className:`rail-empty terminal-surface-message`,"data-terminal-phase":`checking`,children:`正在连接终端…`}),!e&&(0,m.jsx)(`p`,{className:`rail-empty terminal-surface-message`,children:`选择一个工作区后即可打开终端。`})]})]})}function ZT({id:e,title:t,icon:n,count:r,actions:i,children:a}){let o=(0,p.useId)();return(0,m.jsx)(Mi,{id:e,header:!1,children:(0,m.jsxs)(`section`,{className:`rail-card`,"data-rail-section":e,"aria-labelledby":o,children:[(0,m.jsxs)(`div`,{className:`rail-section-head`,children:[(0,m.jsx)(`h2`,{className:`rail-section-title`,id:o,children:(0,m.jsxs)(Ni,{id:e,children:[(0,m.jsx)(QT,{kind:n}),t]})}),r&&(0,m.jsx)(`span`,{className:`rail-section-count`,children:r}),i,(0,m.jsx)(Pi,{id:e})]}),(0,m.jsx)(`div`,{className:`rail-card-body`,children:a})]})})}function QT({kind:e}){return(0,m.jsx)(`svg`,{className:`rail-section-icon`,viewBox:`0 0 24 24`,width:`16`,height:`16`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.7`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":`true`,children:e===`tasks`?(0,m.jsx)(m.Fragment,{children:(0,m.jsx)(`path`,{d:`m3 6 2 2 3-4M11 6h10M3 13h5m3 0h10M3 20h5m3 0h10`})}):e===`clock`?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`circle`,{cx:`12`,cy:`12`,r:`9`}),(0,m.jsx)(`path`,{d:`M12 7v5l3 2`})]}):(0,m.jsx)(m.Fragment,{children:(0,m.jsx)(`path`,{d:`M3 12h4l3-7 4 14 3-7h4`})})})}var $T=[{day:1,label:`一`},{day:2,label:`二`},{day:3,label:`三`},{day:4,label:`四`},{day:5,label:`五`},{day:6,label:`六`},{day:0,label:`日`}];function eE(e){return e.kind===`interval`?`每隔 ${e.everyMinutes} 分钟`:e.kind===`daily`?`每天 ${e.time}`:e.kind===`weekly`?`每周${e.weekdays.map(e=>$T.find(t=>t.day===e)?.label??`?`).join(`、`)} ${e.time}`:`仅一次:${tE(e.at)}`}function tE(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}`}function nE(){return typeof Intl<`u`?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0}function rE(e,t){let n=new Date(e);if(!t){let e=e=>String(e).padStart(2,`0`);return`${n.getFullYear()}-${e(n.getMonth()+1)}-${e(n.getDate())} ${e(n.getHours())}:${e(n.getMinutes())}`}let r=new Intl.DateTimeFormat(`en-CA`,{timeZone:t,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,hour12:!1}).formatToParts(n),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`year`)}-${i(`month`)}-${i(`day`)} ${i(`hour`)}:${i(`minute`)}`}function iE(e,t){let n=new Date(e);if(!t){let e=e=>String(e).padStart(2,`0`);return`${e(n.getHours())}:${e(n.getMinutes())}`}let r=new Intl.DateTimeFormat(`en-GB`,{timeZone:t,hour:`2-digit`,minute:`2-digit`,hour12:!1}).formatToParts(n),i=e=>r.find(t=>t.type===e)?.value??``;return`${i(`hour`)}:${i(`minute`)}`}function aE(e,t){if(!e)return``;try{return new Intl.DateTimeFormat(`en-US`,{timeZone:e,timeZoneName:`shortOffset`}).formatToParts(t).find(e=>e.type===`timeZoneName`)?.value??e}catch{return e}}function oE(e,t,n){let r=iE(e,n),i=sE(e,t,n);return i===0?`今天 ${r}`:i===1?`明天 ${r}`:rE(e,n)}function sE(e,t,n){let r=e=>{let[t]=rE(e,n).split(` `),[r,i,a]=t.split(`-`).map(Number);return Date.UTC(r,i-1,a)},i=Math.round((r(e)-r(t))/864e5);return Number.isFinite(i)?i:0}function cE(e,t,n){if(!e||!t||e===t)return``;let r=aE(e,n),i=aE(t,n);return iE(n,e)===iE(n,t)?`服务器在 ${r} 时区,你的时区也是 ${i},下面的时间按你的时区显示`:`服务器在 ${r} 时区,下面的时间按你的时区(${i})显示`}function lE(e,t,n){return e.enabled?e.nextRunAt===void 0?{glyph:`✓`,word:`已结束`,detail:``}:{glyph:`●`,word:`启用中`,detail:`下次 ${oE(e.nextRunAt,t,n)}`}:e.schedule.kind===`once`&&e.lastRunAt!==void 0?{glyph:`✓`,word:`已结束`,detail:e.lastRunAt?`上次 ${rE(e.lastRunAt,n)}`:``}:{glyph:`○`,word:`已停用`,detail:``}}function uE(e,t){if(e.lastRunAt===void 0)return``;let n=rE(e.lastRunAt,t);return e.lastRunStatus===`failed`?`上次 ${n} · 失败${e.lastRunMessage?`:${e.lastRunMessage}`:``}`:`上次 ${n} · 成功`}function dE({tasks:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,serverTimeZone:o}){let[s,c]=(0,p.useState)(()=>Date.now()),[l,u]=(0,p.useState)();(0,p.useEffect)(()=>{let e=window.setInterval(()=>c(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let d=nE(),f=cE(o,d,s),h=e=>{i({type:`scheduledTask.toggle`,id:e.id,enabled:!e.enabled})},g=e=>{i({type:`scheduledTask.trigger`,id:e.id}),a(`已触发「${e.name}」,结果会出现在它自己的会话里。`,`info`)},_=e=>{i({type:`scheduledTask.delete`,id:e.id}),a(`已删除定时任务「${e.name}」,它的会话和结果保留着。`,`info`)};return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(ZT,{id:`scheduled`,title:`定时任务`,icon:`clock`,count:(0,m.jsx)(`span`,{"data-sched-count":`1`,children:e.length?`${e.length} 个`:`0 个`}),actions:(0,m.jsx)(`button`,{type:`button`,className:`scheduled-add`,"data-sched-add":`1`,title:`新建定时任务`,onClick:()=>u(`new`),children:`+ 新建`}),children:[f&&(0,m.jsx)(`p`,{className:`scheduled-zone-note`,"data-sched-zone-note":`1`,children:f}),e.length>0?(0,m.jsx)(`ul`,{className:`scheduled-list`,"data-sched-list":`1`,children:e.map(e=>{let t=lE(e,s,d),n=uE(e,d);return(0,m.jsxs)(`li`,{className:`scheduled-item`,"data-scheduled-task":e.id,children:[(0,m.jsx)(`button`,{type:`button`,className:`scheduled-toggle`,"data-sched-toggle":`1`,title:e.enabled?`点击停用`:`点击启用`,"aria-label":e.enabled?`停用 ${e.name}`:`启用 ${e.name}`,onClick:()=>h(e),children:t.glyph}),(0,m.jsxs)(`div`,{className:`scheduled-main`,children:[(0,m.jsxs)(`div`,{className:`scheduled-name-row`,children:[(0,m.jsx)(`span`,{className:`scheduled-name`,children:e.name}),(0,m.jsx)(`span`,{className:`scheduled-status-word`,"data-sched-word":`1`,children:t.word}),e.createdBy===`agent`&&(0,m.jsx)(`span`,{className:`scheduled-by`,title:`这个定时任务是 agent 创建的,你可以像编辑自己建的一样编辑它`,children:`agent`})]}),(0,m.jsxs)(`div`,{className:`scheduled-meta`,"data-sched-meta":`1`,children:[eE(e.schedule),t.detail?` · ${t.detail}`:``]}),n&&(0,m.jsx)(`div`,{className:`scheduled-last`,"data-sched-last":`1`,children:n})]}),(0,m.jsxs)(`div`,{className:`scheduled-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-trigger":`1`,title:`立即执行一次(不改变周期)`,"aria-label":`立即执行 ${e.name}`,onClick:()=>g(e),children:`⚡`}),(0,m.jsx)(`button`,{type:`button`,className:`scheduled-action`,"data-sched-edit":`1`,title:`编辑`,"aria-label":`编辑 ${e.name}`,onClick:()=>u(e),children:`✎`}),(0,m.jsx)(`button`,{type:`button`,className:`scheduled-action scheduled-action-danger`,"data-sched-delete":`1`,title:`删除(会话与结果保留)`,"aria-label":`删除 ${e.name}`,onClick:()=>_(e),children:`✕`})]})]},e.id)})}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-sched-empty":`1`,children:`还没有定时任务。可以新建周期任务,或让 AI 安排。`})]}),l!==void 0&&(0,m.jsx)(hE,{task:l===`new`?void 0:l,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:()=>u(void 0)},l===`new`?`new`:l.id)]})}function fE(e){let t=e?.schedule;return{name:e?.name??``,prompt:e?.prompt??``,kind:t?.kind??`daily`,everyMinutes:t?.kind===`interval`?String(t.everyMinutes):`30`,time:t&&(t.kind===`daily`||t.kind===`weekly`)?t.time:`09:00`,weekdays:t?.kind===`weekly`?[...t.weekdays]:[1],onceAt:t?.kind===`once`?pE(t.at):``,modelKey:e?.model?`${e.model.provider}/${e.model.modelId}`:``,agentId:e?.agentId??``}}function pE(e){let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`}function mE(e){if(e.kind===`interval`){let t=Number(e.everyMinutes);return!Number.isInteger(t)||t<1||t>10080?{ok:!1,reason:`间隔分钟数要是一个 1 到 10080 之间的整数。`}:{ok:!0,schedule:{kind:`interval`,everyMinutes:t}}}if(e.kind===`daily`||e.kind===`weekly`){let t=/^(\d{1,2}):(\d{2})$/.exec(e.time.trim()),n=t?Number(t[1]):NaN,r=t?Number(t[2]):NaN;if(!t||n>23||r>59)return{ok:!1,reason:`触发时刻要写成 HH:MM,比如 09:00。`};let i=`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`;return e.kind===`daily`?{ok:!0,schedule:{kind:`daily`,time:i}}:e.weekdays.length?{ok:!0,schedule:{kind:`weekly`,weekdays:[...e.weekdays].sort((e,t)=>e-t),time:i}}:{ok:!1,reason:`每周任务至少要选一天。`}}if(!e.onceAt)return{ok:!1,reason:`选一下这一次的运行时刻。`};let t=new Date(e.onceAt).getTime();return Number.isNaN(t)?{ok:!1,reason:`这一次的运行时刻不是有效时间。`}:{ok:!0,schedule:{kind:`once`,at:t}}}function hE({task:e,workspaceId:t,catalog:n,agents:r,sendCommand:i,notify:a,onClose:o}){let[s,c]=(0,p.useState)(()=>fE(e)),[l,u]=(0,p.useState)();(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let d=e=>{c(t=>({...t,...e})),u(void 0)};return(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-sched-dialog-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&o()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`scheduled-dialog-title`,"data-sched-dialog":`1`,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsx)(`h2`,{className:`tool-dialog-title`,id:`scheduled-dialog-title`,children:e?`编辑定时任务`:`新建定时任务`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-sched-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭定时任务编辑`,onClick:o,children:`✕`})]}),(0,m.jsxs)(`div`,{className:`tool-dialog-body scheduled-form`,children:[(0,m.jsxs)(`label`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`名称`}),(0,m.jsx)(`input`,{className:`scheduled-input`,"data-sched-field":`name`,value:s.name,placeholder:`留空则取提示词首句`,onChange:e=>d({name:e.target.value})})]}),(0,m.jsxs)(`label`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`提示词`}),(0,m.jsx)(`textarea`,{className:`scheduled-textarea`,"data-sched-field":`prompt`,rows:5,value:s.prompt,placeholder:`到点时这段话会作为用户消息发给 agent,所以它要是一条完整、自包含的指令`,onChange:e=>d({prompt:e.target.value})})]}),(0,m.jsxs)(`div`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`周期`}),(0,m.jsx)(`div`,{className:`scheduled-kind-row`,role:`radiogroup`,"aria-label":`周期类型`,children:[[`interval`,`每隔 N 分钟`],[`daily`,`每天`],[`weekly`,`每周`],[`once`,`仅一次`]].map(([e,t])=>(0,m.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":s.kind===e,className:`scheduled-kind${s.kind===e?` scheduled-kind-active`:``}`,"data-sched-kind":e,onClick:()=>d({kind:e}),children:t},e))})]}),s.kind===`interval`&&(0,m.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`间隔`}),(0,m.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`everyMinutes`,inputMode:`numeric`,value:s.everyMinutes,onChange:e=>d({everyMinutes:e.target.value})}),(0,m.jsx)(`span`,{className:`scheduled-hint`,children:`分钟(1 – 10080)`})]}),(s.kind===`daily`||s.kind===`weekly`)&&(0,m.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,m.jsx)(`input`,{className:`scheduled-input scheduled-input-narrow`,"data-sched-field":`time`,inputMode:`numeric`,placeholder:`09:00`,value:s.time,onChange:e=>d({time:e.target.value})}),(0,m.jsx)(`span`,{className:`scheduled-hint`,children:`服务器本地时间,每天/每周的这一天到点触发`})]}),s.kind===`weekly`&&(0,m.jsxs)(`div`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`星期`}),(0,m.jsx)(`div`,{className:`scheduled-weekdays`,children:$T.map(({day:e,label:t})=>{let n=s.weekdays.includes(e);return(0,m.jsx)(`button`,{type:`button`,"aria-pressed":n,className:`scheduled-weekday${n?` scheduled-weekday-on`:``}`,"data-sched-weekday":e,onClick:()=>d({weekdays:n?s.weekdays.filter(t=>t!==e):[...s.weekdays,e]}),children:t},e)})})]}),s.kind===`once`&&(0,m.jsxs)(`label`,{className:`scheduled-field scheduled-field-inline`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`时刻`}),(0,m.jsx)(`input`,{className:`scheduled-input`,type:`datetime-local`,"data-sched-field":`onceAt`,value:s.onceAt,onChange:e=>d({onceAt:e.target.value})}),(0,m.jsx)(`span`,{className:`scheduled-hint`,children:`这一次运行之后就结束`})]}),(0,m.jsxs)(`label`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`模型`}),(0,m.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`model`,value:s.modelKey,onChange:e=>d({modelKey:e.target.value}),children:[(0,m.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(n?.models??[]).map(e=>(0,m.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,`(`,e.detail,`)`]},`${e.provider}/${e.modelId}`))]})]}),(0,m.jsxs)(`label`,{className:`scheduled-field`,children:[(0,m.jsx)(`span`,{className:`scheduled-label`,children:`Agent`}),(0,m.jsxs)(`select`,{className:`scheduled-input`,"data-sched-field":`agent`,value:s.agentId,onChange:e=>d({agentId:e.target.value}),children:[(0,m.jsx)(`option`,{value:``,children:`跟随工作区默认`}),(r?.agents??[]).map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name??e.id},e.id))]})]}),l&&(0,m.jsx)(`p`,{className:`scheduled-error`,"data-sched-error":`1`,role:`alert`,children:l}),(0,m.jsxs)(`div`,{className:`scheduled-actions-row`,children:[(0,m.jsx)(`button`,{type:`button`,className:`scheduled-cancel`,onClick:o,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`scheduled-save`,"data-sched-save":`1`,onClick:()=>{let r=s.prompt.trim();if(!r){u(`定时任务需要一段提示词:到点时这段话会被当作用户消息发给 agent。`);return}if(!t){u(`先选一个工作区,再建定时任务。`);return}let c=mE(s);if(!c.ok){u(c.reason);return}let l=n?.models.find(e=>`${e.provider}/${e.modelId}`===s.modelKey),d=l?{provider:l.provider,modelId:l.modelId,label:l.label}:null,f=s.agentId||null,p=s.name.trim()||void 0;i(e?{type:`scheduledTask.update`,id:e.id,name:p,prompt:r,schedule:c.schedule,model:d,agentId:f}:{type:`scheduledTask.create`,name:p,prompt:r,schedule:c.schedule,workspaceId:t,model:d,agentId:f})?(a(e?`已保存对「${s.name.trim()||e.name}」的修改。`:`定时任务已创建,到点会自动运行。`,`info`),o()):u(`连接已断开,没能保存。等重连后再试一次。`)},children:e?`保存修改`:`创建任务`})]})]})]})}),document.body)}var gE=e=>Math.min(1,e.width/e.imageWidth,e.height/e.imageHeight),_E=(e,t,n)=>{let r=Math.max(0,(t-n)/2);return Math.max(-r,Math.min(r,e))};function vE(e,t){return{...e,x:_E(e.x,t.imageWidth*e.scale,t.width),y:_E(e.y,t.imageHeight*e.scale,t.height)}}function yE({image:e,onClose:t}){let n=(0,p.useRef)(null),r=(0,p.useRef)(null),i=(0,p.useRef)(null),a=(0,p.useRef)(null),o=(0,p.useRef)(void 0),[s,c]=(0,p.useState)(),[l,u]=(0,p.useState)({scale:1,x:0,y:0}),[d,f]=(0,p.useState)(!1),h=(0,p.useCallback)(()=>{let e=n.current,t=r.current;if(!e?.clientWidth||!e.clientHeight||!t?.naturalWidth||!t.naturalHeight)return;let i={width:e.clientWidth,height:e.clientHeight,imageWidth:t.naturalWidth,imageHeight:t.naturalHeight};c(i),u({scale:gE(i),x:0,y:0})},[]);(0,p.useLayoutEffect)(()=>{let e=new ResizeObserver(h);return e.observe(n.current),h(),()=>e.disconnect()},[h]),(0,p.useLayoutEffect)(()=>{let e=document.activeElement instanceof HTMLElement?document.activeElement:void 0;return a.current?.focus({preventScroll:!0}),()=>{e?.isConnected&&e.focus({preventScroll:!0})}},[]),(0,p.useEffect)(()=>{let e=e=>{if(e.key===`Escape`&&(e.preventDefault(),e.stopImmediatePropagation(),t()),e.key!==`Tab`)return;let n=i.current?.querySelectorAll(`button:not(:disabled)`);if(!n?.length)return;let r=n[0],a=n[n.length-1];(e.shiftKey&&document.activeElement===r||!e.shiftKey&&document.activeElement===a)&&(e.preventDefault(),(e.shiftKey?a:r).focus())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[t]);let g=(0,p.useCallback)((e,t=0,n=0)=>{s&&u(r=>{let i=Math.max(Math.min(gE(s),.1),Math.min(16,r.scale*e)),a=i/r.scale;return vE({scale:i,x:t-(t-r.x)*a,y:n-(n-r.y)*a},s)})},[s]);(0,p.useEffect)(()=>{let e=i.current?.parentElement,t=e=>{e.preventDefault(),e.stopPropagation();let t=n.current;if(!t?.contains(e.target))return;let r=t.getBoundingClientRect(),i=e.deltaMode===1?16:e.deltaMode===2?r.height:1;g(Math.exp(-Math.max(-600,Math.min(600,e.deltaY*i))/480),e.clientX-r.left-r.width/2,e.clientY-r.top-r.height/2)};return e?.addEventListener(`wheel`,t,{passive:!1}),()=>e?.removeEventListener(`wheel`,t)},[g]);let _=s&&(s.imageWidth*l.scale>s.width+.5||s.imageHeight*l.scale>s.height+.5);function v(){o.current=void 0,f(!1)}return(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{ref:i,className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,m.jsxs)(`div`,{className:`lightbox-head`,children:[(0,m.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,title:e.name,children:e.name||`图片大图`}),(0,m.jsxs)(`div`,{className:`lightbox-controls`,role:`group`,"aria-label":`图片缩放`,children:[(0,m.jsx)(`button`,{type:`button`,"aria-label":`缩小图片`,disabled:!s||l.scale<=Math.min(.1,gE(s)),onClick:()=>g(.8),children:`−`}),(0,m.jsx)(`output`,{"aria-label":`图片缩放比例`,children:s?Math.round(l.scale*100)+`%`:`…`}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`放大图片`,disabled:!s||l.scale>=16,onClick:()=>g(1.25),children:`+`}),(0,m.jsx)(`button`,{type:`button`,"data-lightbox-original":!0,disabled:!s,onClick:()=>u({scale:1,x:0,y:0}),children:`原始尺寸`}),(0,m.jsx)(`button`,{type:`button`,"data-lightbox-fit":!0,disabled:!s,onClick:()=>s&&u({scale:gE(s),x:0,y:0}),children:`适应窗口`})]}),(0,m.jsx)(`button`,{type:`button`,ref:a,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,m.jsx)(`div`,{className:`lightbox-body`,ref:n,"data-pan":d?`dragging`:_?`ready`:void 0,onPointerDown:e=>{_&&e.isPrimary&&e.button===0&&(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),o.current={pointer:e.pointerId,x:e.clientX,y:e.clientY},f(!0))},onPointerMove:e=>{let t=o.current;if(!s||!t||t.pointer!==e.pointerId)return;let n=e.clientX-t.x,r=e.clientY-t.y;t.x=e.clientX,t.y=e.clientY,u(e=>vE({...e,x:e.x+n,y:e.y+r},s))},onLostPointerCapture:v,children:(0,m.jsx)(`img`,{ref:r,src:e.url,alt:e.name||`图片大图`,draggable:!1,onLoad:h,className:`lightbox-image`,style:s?{width:s.imageWidth*l.scale,height:s.imageHeight*l.scale,transform:`translate(calc(-50% + ${l.x}px), calc(-50% + ${l.y}px))`}:{visibility:`hidden`}})})]})}),document.body)}function bE(e){return e.status===`open`&&(e.audience===`boss`||e.audience===void 0)}function xE(e){return(e.escalations??[]).filter(bE)}function SE(e){let t=e.filter(e=>xE(e).length>0);return{projects:t.length,cases:t.reduce((e,t)=>e+xE(t).length,0)}}function CE(e,t=!1){return[`cancelled`,`failed`].includes(e.status??``)?!0:t}function wE(e,t,n){let r=CE(e,t),i=xE(e).length>0;return n===`history`?r&&!i:!r||i}function TE(e){return(e.reports??[]).filter(t=>!t.taskId&&[`progress`,`delivery`].includes(t.kind??``)&&(t.authorConversationId===e.ownerConversationId&&!!e.ownerConversationId||t.kind===`delivery`&&!t.authorConversationId))}function EE(e){return[...e.reports??[]].reverse().find(t=>t.kind===`delivery`&&!t.taskId&&(!t.authorConversationId||t.authorConversationId===e.ownerConversationId))}function DE(e){let t=xE(e),n=[...TE(e)].reverse().find(e=>e.kind===`progress`),r=EE(e),i=[`cancelled`,`failed`].includes(e.status),a=e.resources?.sessions?.find(t=>t.id===e.ownerConversationId),o=(e.resources?.activeWorkers??0)>0||[`running`,`waiting`,`awaiting_background`].includes(a?.status??``);return{label:e.status===`cancelled`?`已取消`:e.status===`failed`?`执行暂停`:t.length?`需要你决定`:o?`正在推进`:e.ownerConversationId?[`failed`,`stopped`].includes(a?.status??``)?`执行暂停`:r?`待继续`:`未交付`:`待启动`,summary:n?.progress?.trim()||n?.summary?.trim()||(i?`项目已结束,已有记录会保留。`:r?`可继续安排新任务或追加验证。`:`已交由负责人推进,进展和成果会在这里汇总。`),progress:n,delivery:r,decisions:t,ended:i,deliveryLabel:e.mode===`lightweight`?`自评交付`:`交付成果`}}var OE=/\.[A-Za-z][A-Za-z0-9]{0,9}$/,kE=new Set([`makefile`,`dockerfile`,`license`,`readme`,`changelog`]),AE=/^[A-Za-z]:/;function jE(e){let t=(e??``).trim();if(!t||/\s/.test(t)||t.includes(`://`)||t.startsWith(`/`)||t.startsWith(`\\`)||AE.test(t))return;let n=t.split(/[\\/]/);if(n.some(e=>e===``||e===`.`||e===`..`))return;let r=n[n.length-1];if(OE.test(r)||kE.has(r.toLowerCase()))return n.join(`/`)}function ME(e){return/\s/.test(e)||e.includes(`://`)||e.startsWith(`/`)||e.startsWith(`\\`)||AE.test(e)?!1:!e.split(/[\\/]/).some(e=>e===``||e===`.`||e===`..`)}function NE(e){let t=e.split(/[\\/]/);return t[t.length-1]||e}function PE(e,t){let n=jE(e);if(!n)return;let r=(t??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!r)return n;if(ME(r))return n===r||n.startsWith(`${r}/`)?n:`${r}/${n}`}function FE(e,t){let n=(e??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!n)return;let r=(t??``).trim().replaceAll(`\\`,`/`).replace(/^\/+|\/+$/g,``);if(!r)return n;if(n!==r&&n.startsWith(`${r}/`))return n.slice(r.length+1)}function IE(e){return[`cancelled`,`failed`].includes(e.status??``)}function LE(e,t){return e.filter(e=>wE(e,e.ownerArchived===!0,t?`history`:`current`))}function RE(e){let[t,n]=(0,p.useState)(0),r=(0,p.useRef)(null),i=(0,p.useRef)(null);return(0,p.useLayoutEffect)(()=>{let e=()=>{let e=r.current,t=i.current;if(!e||!t)return;let a=getComputedStyle(e),o=Number.parseFloat(a.lineHeight)||Number.parseFloat(a.fontSize)*1.6||16,s=t.getBoundingClientRect().height;n(Math.max(1,Math.round(s/o)))};e();let t=typeof ResizeObserver==`function`?new ResizeObserver(()=>e()):null;return t&&(r.current&&t.observe(r.current),i.current&&t.observe(i.current)),window.addEventListener(`resize`,e),()=>{t?.disconnect(),window.removeEventListener(`resize`,e)}},[e]),{lines:t,visible:r,measured:i}}function zE({text:e,what:t}){let[n,r]=(0,p.useState)(!1),{lines:i,visible:a,measured:o}=RE(e),s=Math.max(0,i-2);return e?(0,m.jsxs)(`div`,{className:`project-prose-wrap`,children:[(0,m.jsx)(`p`,{className:`project-prose${n?` project-prose-open`:``}`,"data-prose-text":!0,ref:a,children:e}),(0,m.jsx)(`span`,{className:`project-prose-measure`,"aria-hidden":`true`,ref:o,children:e}),s>0?(0,m.jsx)(`button`,{type:`button`,className:`project-prose-expand`,"data-prose-expand":!0,"aria-expanded":n,onClick:()=>r(e=>!e),children:n?`收起${t}`:`展开完整${t}(还有 ${s} 行)`}):null]}):null}function BE({refs:e,baseCwd:t,cwd:n,onOpenFile:r}){return(0,m.jsx)(`ul`,{children:e.map((e,i)=>{let a=PE(e,t),o=a?FE(a,n):void 0;return(0,m.jsx)(`li`,{children:o&&r?(0,m.jsx)(`button`,{type:`button`,className:`project-evidence-path`,"data-team-evidence-file":o,onClick:()=>r({path:o,name:NE(o),text:null}),children:e}):e},i)})})}function VE(e){if(!e)return``;let t=Date.parse(e);if(!Number.isFinite(t))return``;let n=Math.max(0,Math.floor((Date.now()-t)/1e3));return n<60?`刚刚`:n<3600?`${Math.floor(n/60)} 分钟前`:n<86400?`${Math.floor(n/3600)} 小时前`:`${Math.floor(n/86400)} 天前`}async function HE(e){let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(typeof t?.error==`string`?t.error:`请求失败(${e.status})`);return t}async function UE(e){let t=(await e.text().catch(()=>``)).trim();if(!t)return`报告打不开(${e.status})`;try{let n=JSON.parse(t);return n&&typeof n==`object`&&typeof n.error==`string`&&n.error.trim()?n.error.trim():`报告打不开(${e.status})`}catch{return t}}function WE(e,t){return`/api/projects/${encodeURIComponent(e)}/report?workspaceId=${encodeURIComponent(t??``)}`}function GE(e,t=60){let n=(e??``).replace(/\s+/g,` `).trim();return n?n.length<=t?n:`${n.slice(0,t-1)}…`:``}function KE(e){let t=(e.title??``).trim();if(t)return t;let n=(e.reason??``).trim();return n?n.match(/^[\s\S]*?[。!?!?]/)?.[0]?.trim()||n:`需要处理`}var qE={decision:0,delivery:1},JE=5;function YE(e,t){let n=xE(e)[0],r={projectId:e.id,projectTitle:e.title,updatedAt:Date.parse(e.updatedAt??``)||0};if(n)return{...r,reminderId:`${e.id}:decision:${xE(e).map(e=>e.id).join(`,`)}`,kind:`decision`,label:`要你决定`,detail:GE(n.title||n.reason||`需要你的决定`,IE(e)?36:60)+(IE(e)?`(项目已结束:记录后不会唤醒任何人)`:``),actionLabel:`去看看`,target:{kind:`exception`,escalationId:n.id}};let i=DE(e).delivery,a=Date.parse(i?.createdAt??``);return!i||!Number.isFinite(a)||t-a>864e5?null:{...r,updatedAt:a,reminderId:`${e.id}:delivery:${i.id}`,kind:`delivery`,label:`阶段交付`,detail:GE(i.progress||i.summary||`已提交阶段成果`),actionLabel:`查看交付`,target:{kind:`top`}}}function XE({text:e}){let[t,n]=(0,p.useState)(!1),{lines:r,visible:i,measured:a}=RE(e),o=Math.max(0,r-2);return e?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`project-exception-reason-wrap`,children:[(0,m.jsx)(`p`,{className:`project-exception-reason${t?` project-exception-reason-open`:``}`,"data-project-exception-reason":!0,ref:i,children:e}),(0,m.jsx)(`span`,{className:`project-exception-reason-measure`,"aria-hidden":`true`,ref:a,children:e})]}),o>0&&(0,m.jsx)(`button`,{type:`button`,className:`project-exception-expand`,"data-project-exception-expand":!0,"aria-expanded":t,onClick:()=>n(e=>!e),children:t?`收起理由`:`展开完整理由(还有 ${o} 行)`})]}):null}function ZE({item:e,project:t,busy:n,onResolve:r,onReturn:i}){let[a,o]=(0,p.useState)(``),s=IE(t);return(0,m.jsxs)(`li`,{className:`project-exception`,"data-project-exception":e.id,children:[(0,m.jsx)(`strong`,{className:`project-exception-title`,"data-project-exception-title":!0,children:KE(e)}),e.reason&&(0,m.jsx)(XE,{text:e.reason}),s&&(0,m.jsx)(`p`,{className:`project-exception-ended`,"data-project-exception-ended":!0,"data-project-exception-ended-note":!0,children:`项目已结束:你的处理意见会记进项目记录,但不会唤醒任何人。`}),(0,m.jsxs)(`label`,{className:`project-decision-label`,children:[`你的决定`,(0,m.jsx)(`textarea`,{"data-project-decision":e.id,"data-project-exception-decision":!0,value:a,onChange:e=>o(e.target.value),disabled:n})]}),(0,m.jsxs)(`div`,{className:`project-detail-actions`,children:[(0,m.jsx)(`button`,{type:`button`,"data-project-decision-submit":e.id,"data-project-exception-resolve":!0,disabled:n||!a.trim(),onClick:()=>r(a.trim()),children:s?`记录处理意见`:`记录决定并答复主会话`}),(0,m.jsx)(`button`,{type:`button`,"data-project-decision-return":e.id,"data-project-exception-return":!0,disabled:n||!a.trim(),onClick:()=>i(a.trim()),children:`退回补充`})]})]})}function QE({project:e,workspaceId:t,notify:n,onOpenSession:r,onOpenFile:i,cwd:a,onChanged:o}){let s=DE(e),[c,l]=(0,p.useState)(!1),[u,d]=(0,p.useState)(``),[f,h]=(0,p.useState)(!1),[g,_]=(0,p.useState)(``),[v,y]=(0,p.useState)(``),b=(0,p.useRef)(``);(0,p.useEffect)(()=>()=>{b.current&&URL.revokeObjectURL(b.current)},[]);let x=async(r,i,a={})=>{if(t&&!c){l(!0),d(``);try{await Ie(`/api/projects/${encodeURIComponent(e.id)}/${r}`,{method:i,headers:{"content-type":`application/json`},body:JSON.stringify({...a,workspaceId:t})}).then(HE),await o?.(),n?.(`已记录并交给负责人`,`info`)}catch(e){d(e instanceof Error?e.message:`操作失败`)}finally{l(!1)}}},S=async()=>{if(t&&!f){h(!0),_(``);try{let n=await Ie(WE(e.id,t));if(!n.ok){_(await UE(n));return}let r=await n.text();b.current&&URL.revokeObjectURL(b.current);let i=URL.createObjectURL(new Blob([r],{type:`text/plain;charset=utf-8`}));b.current=i,y(i),window.open(i,`_blank`,`noopener`)}catch(e){_(e instanceof Error?e.message:`报告打不开`)}finally{h(!1)}}},C=e.resources?.usage,w=s.delivery?.evidenceRefs??[],T=e.resources?.sessions?.find(t=>t.id===e.ownerConversationId),E=!e.ownerConversationId||!!(T&&[`failed`,`stopped`].includes(T.status??``)&&!e.resources?.activeWorkers);return(0,m.jsxs)(`div`,{className:`project-detail project-overview`,"data-project-detail":e.id,children:[e.objective&&(0,m.jsxs)(`div`,{className:`project-goal`,children:[(0,m.jsx)(`span`,{children:`项目目标`}),(0,m.jsx)(`p`,{className:`project-detail-objective`,children:e.objective})]}),(0,m.jsxs)(`section`,{className:`project-section`,"data-project-owner-summary":!0,children:[(0,m.jsx)(`h3`,{children:`当前进展`}),(0,m.jsx)(zE,{text:s.summary,what:`进展`}),e.updatedAt&&(0,m.jsxs)(`p`,{className:`project-overview-time`,children:[VE(e.updatedAt),`更新`]})]}),s.delivery&&(0,m.jsxs)(`section`,{className:`project-section`,"data-project-stage-delivery":!0,children:[(0,m.jsx)(`h3`,{children:s.deliveryLabel}),(0,m.jsx)(zE,{text:s.delivery.progress||s.delivery.summary||`已提交阶段成果`,what:`交付`}),w.length?(0,m.jsx)(BE,{refs:w,baseCwd:e.resources?.ownerCwd??T?.cwd,cwd:a,onOpenFile:i}):(0,m.jsx)(`p`,{"data-project-no-evidence":!0,children:`未附可核对的交付证据。`})]}),s.decisions.length>0&&(0,m.jsxs)(`section`,{className:`project-section`,"data-project-exception-section":!0,children:[(0,m.jsx)(`h3`,{"data-project-exception-heading":!0,children:`需要你决定`}),(0,m.jsx)(`ul`,{className:`project-exception-list`,children:s.decisions.map(t=>(0,m.jsx)(ZE,{item:t,project:e,busy:c,onResolve:e=>void x(`escalations/${encodeURIComponent(t.id)}`,`PATCH`,{decision:e,status:`resolved`}),onReturn:e=>void x(`escalations/${encodeURIComponent(t.id)}`,`PATCH`,{decision:e,status:`returned`})},t.id))})]}),u&&(0,m.jsx)(`p`,{className:`project-error`,role:`alert`,children:u}),(0,m.jsxs)(`div`,{className:`project-detail-actions project-overview-actions`,children:[T&&r&&(0,m.jsx)(`button`,{type:`button`,className:E&&!s.ended?``:`project-primary-action`,"data-project-open-owner":!0,onClick:()=>r(T.id),children:`查看负责人会话`}),!s.ended&&E&&(0,m.jsx)(`button`,{type:`button`,className:`project-primary-action`,disabled:c,"data-project-resume":!0,onClick:()=>void x(`start`,`POST`),children:`让负责人继续`}),!s.ended&&(0,m.jsx)(`button`,{type:`button`,className:`project-stop-action`,disabled:c,"data-project-stop":!0,onClick:()=>void x(``,`PATCH`,{status:`cancelled`}),children:`停止项目`}),(0,m.jsx)(`button`,{type:`button`,disabled:f,"data-project-report":e.id,onClick:()=>void S(),children:f?`正在读取…`:`导出记录`})]}),g&&(0,m.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-report-error":!0,children:g}),v&&(0,m.jsx)(`a`,{href:v,target:`_blank`,rel:`noopener noreferrer`,"data-project-report-link":!0,children:`打开已读取的记录`}),e.resources&&(0,m.jsxs)(`details`,{className:`project-section project-secondary`,"data-project-usage":!0,children:[(0,m.jsx)(`summary`,{children:`查看用量`}),(0,m.jsxs)(`div`,{"data-project-budget":e.id,children:[(0,m.jsxs)(`p`,{"data-project-budget-used":e.id,children:[`等效 Token `,e.resources.usageKnown?e.resources.tokens.toLocaleString():`未知`]}),C&&(0,m.jsxs)(`p`,{"data-project-budget-raw":e.id,children:[`原始口径 `,(e.resources.rawTokens??C.input+C.output+C.cacheRead+C.cacheWrite).toLocaleString(),`;输入 `,C.input.toLocaleString(),`;输出 `,C.output.toLocaleString(),`;缓存写入 `,C.cacheWrite.toLocaleString(),`;缓存读取 `,C.cacheRead.toLocaleString()]}),(0,m.jsx)(`p`,{"data-project-budget-basis":`1`,children:`等效 Token = 输入 + 输出 + 缓存写入×1.25 + 缓存读取×0.1`})]})]})]})}function $E({project:e,workspaceId:t,notify:n,onOpenSession:r,onOpenFile:i,cwd:a,onChanged:o,onClose:s}){let c=(0,p.useId)(),l=(0,p.useRef)(null),u=(0,p.useRef)(s);return u.current=s,(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u.current())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]),(0,p.useEffect)(()=>{l.current?.focus({preventScroll:!0})},[e.id]),(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay project-dialog-overlay`,"data-project-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&s()},children:(0,m.jsxs)(`div`,{ref:l,className:`tool-dialog project-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":c,"data-project-dialog":e.id,tabIndex:-1,onKeyDown:e=>{if(e.key!==`Tab`)return;let t=l.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), a[href], select:not([disabled]), input:not([disabled]), textarea:not([disabled]), summary, [tabindex]:not([tabindex='-1'])`)).filter(e=>e.offsetParent!==null||e.getClientRects().length>0);if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey?(document.activeElement===r||document.activeElement===t)&&(e.preventDefault(),i.focus()):document.activeElement===i&&(e.preventDefault(),r.focus())},children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head project-dialog-head`,children:[(0,m.jsxs)(`div`,{className:`project-dialog-title-group`,children:[(0,m.jsx)(`h2`,{className:`tool-dialog-title project-dialog-title`,id:c,children:e.title}),(0,m.jsx)(`span`,{className:`project-detail-flags`,children:(0,m.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:DE(e).label})})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close project-dialog-close`,"data-project-dialog-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭 ${e.title}`,onClick:s,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body project-dialog-body`,children:(0,m.jsx)(QE,{project:e,workspaceId:t,notify:n,onOpenSession:r?e=>{s(),r(e)}:void 0,onOpenFile:i?e=>{s(),i(e)}:void 0,cwd:a,onChanged:o})})]})}),document.body)}function eD({workspaceId:e,notify:t,onOpenSession:n,onOpenFile:r,cwd:i,visible:a=!0}){let[o,s]=(0,p.useState)([]),[c,l]=(0,p.useState)(!1),u=(0,p.useMemo)(()=>LE(o,c),[o,c]),[d,f]=(0,p.useState)(!1),[h,g]=(0,p.useState)(``),[_,v]=(0,p.useState)(null),y=(0,p.useRef)(null),[b,x]=(0,p.useState)([]),S=(0,p.useCallback)(async t=>{if(!e)s([]);else{g(``);try{let n=await Ie(`/api/projects?workspaceId=${encodeURIComponent(e)}${c?`&view=history`:``}`,{signal:t}).then(HE),r=Array.isArray(n)?n:Array.isArray(n.projects)?n.projects:[];s(r)}catch(e){e.name!==`AbortError`&&g(e instanceof Error?e.message:`项目列表加载失败`)}finally{t?.aborted||f(!0)}}},[e,c]);(0,p.useEffect)(()=>{if(!a)return;let e=new AbortController;return S(e.signal),()=>e.abort()},[S,a]),(0,p.useEffect)(()=>{if(!e||!a)return;let t=window.setInterval(()=>{document.visibilityState===`visible`&&S()},5e3);return()=>window.clearInterval(t)},[S,e,a]);let C=(0,p.useMemo)(()=>{let e=Date.now();return u.map(t=>YE(t,e)).filter(e=>!!e).filter(e=>!b.includes(e.reminderId)).sort((e,t)=>qE[e.kind]-qE[t.kind]||t.updatedAt-e.updatedAt)},[u,b]),w=(0,p.useMemo)(()=>u.flatMap(e=>xE(e).map(t=>({project:e,decision:t}))),[u]),T=(0,p.useMemo)(()=>SE(u).projects,[u]),E=(0,p.useMemo)(()=>C.slice(0,JE),[C]),D=C.length-E.length,[O,k]=(0,p.useState)(!1),A=O?C:E,[j,ee]=(0,p.useState)(!1),M=(0,p.useMemo)(()=>{let e=new Set;for(let t of C)e.add(t.projectId);return e},[u,C]),N=(0,p.useMemo)(()=>j?u.filter(e=>M.has(e.id)):u,[j,u,M]),P=(0,p.useMemo)(()=>_?u.find(e=>e.id===_)??null:null,[u,_]),F=(0,p.useRef)(null),[I,te]=(0,p.useState)(0),ne=(0,p.useCallback)((e,t,n)=>{y.current=t??document.querySelector(`[data-project-row="${e}"]`),v(e),n&&(F.current={projectId:e,target:n},te(e=>e+1))},[]),re=(0,p.useCallback)(()=>{let e=_,t=y.current;y.current=null,v(null),window.requestAnimationFrame(()=>{(t?.isConnected?t:e?document.querySelector(`[data-project-row="${e}"]`):null)?.focus()})},[_]),ie=e=>{let t=document.querySelector(`[data-project-row="${e.projectId}"]`);ne(e.projectId,t,e.target)};return(0,p.useEffect)(()=>{if(!I)return;let e=F.current;if(F.current=null,!e)return;let t=document.querySelector(`[data-project-detail="${e.projectId}"]`);if(!t)return;let n=null;if(e.target.kind===`exception`){let e=t.querySelector(`[data-project-exception-section]`);e&&(e.open=!0,n=e.querySelector(`[data-project-exception-heading]`)??e)}let r=n??t,i=window.requestAnimationFrame(()=>{r.scrollIntoView({block:e.target.kind===`top`?`start`:`center`,inline:`nearest`})});return()=>window.cancelAnimationFrame(i)},[I,P?.id]),(0,m.jsxs)(`section`,{className:`project-panel`,"data-project-panel":`1`,children:[(0,m.jsx)(`div`,{className:`rail-section-head project-panel-head`,children:(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`项目进展`}),(0,m.jsx)(`p`,{className:`project-panel-subtitle`,children:`查看负责人汇总的进展、成果和需要你决定的事。`})]})}),w.length>0&&(0,m.jsxs)(`div`,{className:`warning`,role:`status`,"data-project-team-notice":`1`,"data-project-team-notice-count":T,children:[(0,m.jsxs)(`span`,{"data-project-team-notice-text":!0,children:[T===1?`有 1 个项目的事需要你决定`:`有 ${T} 个项目的事需要你决定`,`:`,GE(KE(w[0].decision),48)]}),(0,m.jsx)(`button`,{type:`button`,"data-project-team-notice-action":`1`,onClick:()=>ne(w[0].project.id,void 0,{kind:`exception`,escalationId:w[0].decision.id}),children:`去看看`})]}),C.length>0&&(0,m.jsxs)(`div`,{className:`project-pending`,"data-project-pending":`1`,"data-project-pending-count":C.length,children:[A.map(e=>(0,m.jsxs)(`div`,{className:`project-pending-item`,"data-project-pending-item":e.projectId,"data-project-pending-kind":e.kind,children:[(0,m.jsxs)(`div`,{className:`project-pending-row`,children:[(0,m.jsx)(`span`,{className:`project-pending-kind project-pending-kind-${e.kind}`,"data-project-pending-label":e.kind,children:e.label}),(0,m.jsx)(`span`,{className:`project-pending-title`,"data-project-pending-title":e.projectId,children:e.projectTitle}),(0,m.jsx)(`button`,{type:`button`,className:`project-pending-action`,"data-project-pending-action":e.projectId,onClick:()=>ie(e),children:e.actionLabel}),(0,m.jsx)(`button`,{type:`button`,className:`project-pending-close`,"data-project-pending-dismiss":e.projectId,"aria-label":`关闭「${e.projectTitle}」的这条提醒`,title:`关闭这条提醒(不改变项目状态)`,onClick:()=>x(t=>[...t,e.reminderId]),children:`×`})]}),(0,m.jsx)(`p`,{className:`project-pending-detail`,"data-project-pending-detail":e.projectId,children:e.detail})]},`${e.projectId}:${e.kind}`)),D>0&&(0,m.jsx)(`button`,{type:`button`,className:`project-pending-more`,"data-project-pending-more":`1`,"aria-expanded":O,onClick:()=>k(e=>!e),children:O?`收起`:`还有 ${D} 个`})]}),(0,m.jsxs)(`label`,{className:`project-pending-filter`,"data-project-pending-only-label":`1`,children:[(0,m.jsx)(`input`,{type:`checkbox`,"data-project-pending-only":`1`,checked:j,onChange:e=>ee(e.target.checked)}),(0,m.jsx)(`span`,{className:`project-pending-filter-name`,children:`只看提醒`}),(0,m.jsx)(`span`,{className:`project-pending-filter-state`,"data-project-pending-only-state":j?`on`:`off`,children:j?`已开启`:`已关闭`})]}),(0,m.jsxs)(`label`,{className:`project-pending-filter`,children:[(0,m.jsx)(`input`,{type:`checkbox`,"data-project-history":`1`,checked:c,onChange:e=>{l(e.target.checked),ee(!1),v(null)}}),(0,m.jsx)(`span`,{className:`project-pending-filter-name`,children:`查看历史项目`})]}),h&&(0,m.jsx)(`p`,{className:`project-error`,role:`alert`,"data-project-error":`1`,children:h}),e?!d&&u.length===0?(0,m.jsx)(`p`,{className:`rail-empty`,children:`正在加载项目…`}):u.length===0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{className:`rail-empty`,"data-project-empty":`1`,children:c?`没有已结束的项目。`:`当前没有进行中的项目。`}),(0,m.jsx)(`p`,{className:`project-empty-hint`,"data-project-empty-hint":`1`,children:`在对话里告诉 AI 你要完成什么,负责人会推进工作并向你交付。`})]}):N.length===0?(0,m.jsx)(`p`,{className:`rail-empty`,"data-project-pending-empty":`1`,children:`没有需要关注的项目。`}):(0,m.jsx)(m.Fragment,{children:(0,m.jsx)(`div`,{className:`project-list`,"data-project-count":N.length,children:N.map(e=>{let t=P?.id===e.id;return(0,m.jsxs)(`button`,{type:`button`,className:`project-row`,"data-project-row":e.id,"data-project-block":e.id,"data-project-summary":e.id,"aria-haspopup":`dialog`,"aria-expanded":t,onClick:t=>ne(e.id,t.currentTarget),children:[(0,m.jsx)(`span`,{className:`project-list-title`,title:e.title,children:e.title}),(0,m.jsx)(`span`,{className:`project-status project-status-${e.status}`,children:DE(e).label}),(0,m.jsx)(`span`,{className:`project-row-summary`,children:DE(e).summary}),e.updatedAt&&(0,m.jsxs)(`span`,{className:`project-row-updated`,children:[VE(e.updatedAt),`更新`]})]},e.id)})})}):(0,m.jsx)(`p`,{className:`rail-empty`,children:`请先选择工作区。`}),P?(0,m.jsx)($E,{project:P,workspaceId:e,notify:t,onOpenSession:n,onOpenFile:r,cwd:i,onChanged:()=>S(),onClose:re}):null]})}var tD=()=>({text:``,mentions:[],files:[]}),nD=(e,t)=>`super-pi.group-draft.v1:${JSON.stringify([e,t])}`;function rD(e,t){try{let n=JSON.parse(localStorage.getItem(nD(e,t))??`null`);return!n||typeof n.text!=`string`?tD():{text:n.text.slice(0,32e3),replyTo:typeof n.replyTo==`string`?n.replyTo:void 0,mentions:Array.isArray(n.mentions)?n.mentions.filter(e=>typeof e?.memberId==`string`&&typeof e.text==`string`):[],files:Array.isArray(n.files)?n.files.filter(e=>typeof e?.path==`string`&&typeof e.text==`string`):[]}}catch{return tD()}}function iD(e,t,n){try{let r=nD(e,t);!n.text&&!n.replyTo?localStorage.removeItem(r):localStorage.setItem(r,JSON.stringify(n))}catch{}}function aD(e,t,n){rD(e,t).text===n&&iD(e,t,tD())}var oD=`super-pi.group-presets.v1`;function sD(){try{let e=JSON.parse(localStorage.getItem(`super-pi.group-presets.v1`)??`[]`);return Array.isArray(e)?e.filter(e=>typeof e?.id==`string`&&typeof e.name==`string`&&Array.isArray(e.memberIds)&&e.memberIds.every(e=>typeof e==`string`)&&e.memberModels&&typeof e.memberModels==`object`&&!Array.isArray(e.memberModels)&&typeof e.moderator?.prompt==`string`).slice(0,100):[]}catch{return[]}}var cD=e=>JSON.stringify([e.provider,e.modelId]);function lD({value:e,models:t,onChange:n,label:r,inheritLabel:i,savedModel:a}){let[o,s]=(0,p.useState)(``),[c,l]=(0,p.useState)(``),u=(0,p.useRef)(null),d=t.find(t=>cD(t)===e),f=d??a,h=t.filter(e=>(!o||e.provider===o)&&`${e.label} ${e.modelId}`.toLocaleLowerCase().includes(c.toLocaleLowerCase())),g=e=>{n(e),u.current&&(u.current.open=!1)};return(0,m.jsxs)(`details`,{className:`group-model-picker`,ref:u,onKeyDown:e=>{e.key===`Escape`&&u.current&&(u.current.open=!1,u.current.querySelector(`summary`)?.focus())},children:[(0,m.jsxs)(`summary`,{"aria-label":r,title:f?`${f.provider} / ${f.modelId}`:void 0,children:[(0,m.jsx)(`span`,{children:e?d?.label??(a?`${a.label||a.modelId}(目录中不可用)`:`当前模型不可用,请重新选择`):i??`继承 Agent / 工作区模型`}),(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`⌄`})]}),(0,m.jsxs)(`div`,{className:`group-model-popup`,children:[(0,m.jsxs)(`select`,{"aria-label":`${r} Provider`,value:o,onChange:e=>s(e.target.value),children:[(0,m.jsx)(`option`,{value:``,children:`全部 Provider`}),[...new Set(t.map(e=>e.provider))].sort().map(e=>(0,m.jsx)(`option`,{children:e},e))]}),(0,m.jsx)(`input`,{"aria-label":`${r} 筛选`,placeholder:`筛选模型…`,value:c,onChange:e=>l(e.target.value)}),(0,m.jsxs)(`div`,{className:`group-model-options`,role:`group`,"aria-label":r,children:[(0,m.jsx)(`button`,{type:`button`,"aria-pressed":!e,onClick:()=>g(``),children:i??`继承默认模型`}),h.map(t=>(0,m.jsxs)(`button`,{type:`button`,"aria-pressed":e===cD(t),onClick:()=>g(cD(t)),children:[(0,m.jsx)(`span`,{children:t.label}),(0,m.jsx)(`small`,{children:t.provider})]},cD(t))),!h.length&&(0,m.jsx)(`p`,{children:`没有匹配的模型`})]})]})]})}var uD={queued:`排队中`,running:`进行中`,completed:`已完成`,failed:`失败`,cancelled:`已停止`,interrupted:`已中断`},dD=new Map([[`read`,`读取文件`],[`write`,`写入文件`],[`edit`,`编辑文件`],[`grep`,`搜索内容`],[`find`,`查找文件`],[`ls`,`列出目录`],[`bash`,`运行命令`],[`powershell`,`运行命令`]]),fD=new Map([[`solution-designer`,`案`],[`code-designer`,`码`],[`code-auditor`,`审`],[`document-organizer`,`文`]]),pD=e=>e.status===`queued`||e.status===`running`,mD=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`}),hD=new Intl.DateTimeFormat(void 0,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hourCycle:`h23`});function gD(e,t=!1){let n=Date.parse(e);return Number.isFinite(n)?(t?hD:mD).format(n):``}function _D({name:e,memberId:t,busy:n}){let r=e.trim(),i=t&&fD.get(t)||(/\p{Script=Han}/u.test(r)?Array.from(r).slice(-2).join(``):r.split(/\s+/u).filter(Boolean).map(e=>Array.from(e)[0]).slice(0,2).join(``).toUpperCase())||`?`,a=tr.findIndex(e=>e===t),o=a>=0?a:Array.from(t??``).reduce((e,t)=>(e*31+(t.codePointAt(0)??0))%4,0);return(0,m.jsx)(`span`,{className:`group-avatar`,"data-avatar-tone":t?o:`self`,"data-avatar-busy":n||void 0,"aria-hidden":`true`,children:i})}function vD({step:e}){return e.kind===`compaction`?(0,m.jsxs)(`li`,{className:`group-execution-step`,"data-execution-kind":`compaction`,"data-execution-status":e.status,children:[(0,m.jsxs)(`div`,{className:`group-execution-tool`,children:[(0,m.jsx)(`strong`,{children:`上下文压缩`}),(0,m.jsx)(`span`,{className:`group-execution-step-status`,children:uD[e.status]})]}),(0,m.jsx)(`p`,{children:e.text}),(0,m.jsx)(`time`,{className:`group-execution-muted`,dateTime:e.startedAt,children:gD(e.startedAt,!0)})]}):e.kind===`thinking`?(0,m.jsxs)(`details`,{className:`group-execution-step`,"data-execution-kind":`thinking`,"data-execution-status":e.status,open:!0,children:[(0,m.jsxs)(`summary`,{children:[(0,m.jsx)(`span`,{children:e.status===`running`?`正在思考`:`思考摘要`}),(0,m.jsx)(`time`,{dateTime:e.startedAt,children:gD(e.startedAt,!0)})]}),e.text?(0,m.jsx)(`div`,{className:`message-body`,children:(0,m.jsx)(ep,{source:e.text,handoffs:!1})}):(0,m.jsx)(`p`,{className:`group-execution-muted`,children:e.status===`running`?`正在等待模型返回摘要。`:`模型未提供可显示的摘要。`}),e.status===`interrupted`&&(0,m.jsx)(`p`,{className:`group-execution-muted`,children:`思考已中断`})]}):(0,m.jsxs)(`li`,{className:`group-execution-step`,"data-execution-kind":`tool`,"data-execution-status":e.status,children:[(0,m.jsxs)(`div`,{className:`group-execution-tool`,children:[(0,m.jsx)(`strong`,{children:dD.get(e.name)??`工具调用`}),(0,m.jsx)(`code`,{children:e.name}),(0,m.jsx)(`span`,{className:`group-execution-step-status`,children:uD[e.status]})]}),e.detail&&(0,m.jsx)(`p`,{className:`group-execution-target`,children:(0,m.jsx)(`code`,{children:e.detail})}),(0,m.jsxs)(`div`,{className:`group-execution-muted`,children:[(0,m.jsx)(`time`,{dateTime:e.startedAt,children:gD(e.startedAt,!0)}),e.durationMs===void 0?e.status===`running`&&e.lastUpdateAt?` · 最近更新 ${gD(e.lastUpdateAt,!0)}`:null:` · ${(e.durationMs/1e3).toFixed(1)} 秒`]})]})}function yD({workspaceId:e,roomId:t,memberId:n,name:r,runs:i,postId:a,onSelect:o,onClose:s,onStop:c,models:l,memberModel:u,onModelChange:d,onRetry:f}){let h=(0,p.useId)(),g=(0,p.useRef)(null),[_,v]=(0,p.useState)(),[y,b]=(0,p.useState)(),[x,S]=(0,p.useState)(!1),[C,w]=(0,p.useState)(``),[T,E]=(0,p.useState)(!1),D=i.find(e=>e.id===a)??i.find(e=>e.status===`running`)??i[0],O=D?.id,k=_?.id===O?_?.value:void 0,A=y?.id===O?y?.message:void 0;return(0,p.useLayoutEffect)(()=>{g.current?.focus()},[]),(0,p.useEffect)(()=>{if(!O)return;let n=new AbortController,r,i,a=!1,o=async()=>{try{let r=await pr(dr(e,t,i,O),{signal:n.signal});if(n.signal.aborted)return;b(void 0),r&&(i=r.revision,a=!pD(r),v({id:O,value:r}))}catch(e){n.signal.aborted||b({id:O,message:e instanceof Error?e.message:`暂时无法读取执行记录。`})}finally{!n.signal.aborted&&!a&&(r=window.setTimeout(o,500))}};return o(),()=>{n.abort(),window.clearTimeout(r)}},[O,e,t]),(0,m.jsxs)(`aside`,{className:`group-execution`,"aria-labelledby":h,"data-group-execution":n,onKeyDown:e=>{e.key===`Escape`&&(e.stopPropagation(),s())},children:[(0,m.jsxs)(`header`,{className:`group-execution-header`,children:[(0,m.jsx)(_D,{name:r,memberId:n,busy:i.some(pD)}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`h2`,{id:h,children:r}),(0,m.jsx)(`p`,{children:`执行详情`})]}),(0,m.jsx)(`button`,{ref:g,type:`button`,className:`group-close-execution`,"data-close-group-execution":!0,"aria-label":`关闭执行详情`,title:`关闭执行详情`,onClick:s,children:(0,m.jsx)(vi,{name:`close`})})]}),d&&(0,m.jsxs)(`div`,{className:`group-execution-model-settings`,"aria-busy":x,children:[(0,m.jsx)(`span`,{children:`该成员后续使用的模型`}),(0,m.jsx)(lD,{label:`${r} 后续使用的模型`,value:u?cD(u):``,models:l,onChange:e=>{x||(S(!0),w(``),d(e).catch(e=>w(String(e.message??e))).finally(()=>S(!1)))}}),(0,m.jsx)(`small`,{children:x?`正在保存…`:`当前执行使用原模型。如需立即切换,请先停止再重试。`}),C&&(0,m.jsx)(`p`,{className:`group-error`,role:`alert`,children:C})]}),D?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`group-execution-summary`,children:[i.length>1&&(0,m.jsx)(`select`,{"aria-label":`选择执行记录`,value:O,onChange:e=>o(e.target.value),children:i.map(e=>(0,m.jsxs)(`option`,{value:e.id,children:[gD(e.createdAt,!0),` · `,e.assignment??uD[e.status]]},e.id))}),(0,m.jsx)(`div`,{"aria-live":`polite`,"data-execution-run-status":k?.status??D.status,children:uD[k?.status??D.status]}),D.assignment&&(0,m.jsx)(`p`,{children:D.assignment}),D.executionConversationId&&(0,m.jsx)(`button`,{type:`button`,"data-group-open-execution-session":!0,onClick:()=>window.dispatchEvent(new CustomEvent(`super-pi-open-execution-session`,{detail:D.executionConversationId})),children:`打开完整执行会话/回答工具提问`}),(0,m.jsx)(`p`,{"data-group-execution-model":!0,children:D.model?`${D.model.label} · ${D.model.provider}`:`模型尚未记录`}),pD(D)&&c&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>c(D.id),children:`停止这次执行`}),[`failed`,`cancelled`,`interrupted`].includes(D.status)&&f&&(0,m.jsx)(`button`,{type:`button`,"data-group-retry":!0,disabled:T||x,onClick:()=>{E(!0),w(``),f(D.id).catch(e=>w(String(e.message??e))).finally(()=>E(!1))},children:T?`正在提交重试…`:`用当前模型继续任务`}),D.error&&(0,m.jsx)(`p`,{className:`group-error`,children:D.error})]}),(0,m.jsxs)(`div`,{className:`group-execution-scroll`,children:[A&&(0,m.jsx)(`p`,{className:`group-error`,role:`alert`,children:A}),k?.steps.length?(0,m.jsx)(`ol`,{className:`group-execution-steps`,children:k.steps.map(e=>e.kind===`thinking`?(0,m.jsx)(`li`,{children:(0,m.jsx)(vD,{step:e})},e.id):(0,m.jsx)(vD,{step:e},e.id))}):!A&&(0,m.jsx)(`p`,{className:`group-execution-muted`,children:k?pD(k)?`等待模型或工具事件。`:`这次发言没有可查看的执行明细。`:`正在读取执行记录…`}),k?.truncated&&(0,m.jsx)(`p`,{className:`group-execution-muted`,children:`部分执行记录超过保留长度,已省略。`})]})]}):(0,m.jsx)(`p`,{className:`group-execution-scroll group-execution-muted`,children:`该成员还没有执行记录。`})]})}var bD=e=>JSON.stringify([e.provider,e.modelId]),xD=`super-pi.group-moderator-prompt-presets.v1`,SD=new Map;function CD(){try{let e=JSON.parse(localStorage.getItem(xD)??`[]`);return Array.isArray(e)?e.filter(e=>e&&typeof e.id==`string`&&typeof e.name==`string`&&typeof e.prompt==`string`).slice(0,100).map(e=>({id:e.id.slice(0,100),name:e.name.slice(0,80),prompt:e.prompt.slice(0,8e3)})):[]}catch{return[]}}var wD=e=>/\s/u.test(e)?`@"${e}"`:`@${e}`,TD=e=>new Set([...e.matchAll(/(?:^|[\s([{])(@(?:"(?:[^"\\]|\\.)+"|[^\s,。;、!?,::;!?,)\]}]+))/gu)].map(e=>e[1])),ED=mr;function DD({workspaceId:e,roomId:t,agents:n,catalog:r,userLabel:i,archivedAt:a,restoring:o,onRestore:s,onRoomSeen:c,onRoomRead:l,onRoomMissing:u,onCreated:d,onCancelCreate:f,onEnableNotifications:h,composerResize:g,sourceLink:_,onImageOpen:v,onOpenRsi:x,rsiActive:S=!1}){function C(e,n){let r=Fe(`/api/upload/${encodeURIComponent(t)}/${encodeURIComponent(e.id)}`),i=e.name||n;return(0,m.jsx)(`button`,{type:`button`,className:`group-image-preview`,"aria-label":`查看图片:${i}`,onClick:()=>v({url:r,name:i}),children:(0,m.jsx)(`img`,{className:`group-post-image`,src:r,alt:i})},e.id)}let[w,T]=(0,p.useState)(),[E,D]=(0,p.useState)(!1);(0,p.useEffect)(()=>{let e=e=>{e.detail?.roomId===t&&D(!0)};return window.addEventListener(`super-pi-status-group-models`,e),()=>window.removeEventListener(`super-pi-status-group-models`,e)},[t]);let[O,k]=(0,p.useState)(``),[A,j]=(0,p.useState)(``),[ee,M]=(0,p.useState)(!1),[N,P]=(0,p.useState)({}),[F,I]=(0,p.useState)(),[te,ne]=(0,p.useState)(``),[re]=(0,p.useState)(()=>rD(e,t)),[ie,ae]=(0,p.useState)(re.text),oe=JSON.stringify([e,t]),[se,ce]=(0,p.useState)(()=>SD.get(oe)??[]);(0,p.useEffect)(()=>{se.length?SD.set(oe,se):SD.delete(oe)},[oe,se]);let[le,ue]=(0,p.useState)(!1),de=async t=>{if(!Pe||le)return;if(t.length+se.length>8){k(`每条群聊消息最多附加 8 张图片`);return}let n=Pe.id;ue(!0),k(``);try{for(let r of t){if(![`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(r.type)||r.size>5242880)throw Error(`图片须为 PNG/JPEG/GIF/WebP,且不超过 5MB`);let t=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(String(n.result).split(`,`)[1]),n.onerror=t,n.readAsDataURL(r)}),i=await Ie(dr(e,n)+`&upload=image`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({name:r.name,mimeType:r.type,data:t})}),a=await i.json();if(!i.ok)throw Error(a.error??`图片上传失败`);let o={id:b(y(n).server,a.id),name:a.name,mimeType:a.mimeType,bytes:a.bytes};je.current&&Ae.current?.id===n&&ce(e=>[...e,o])}}catch(e){je.current&&k(e instanceof Error?e.message:`图片上传失败`)}finally{je.current&&ue(!1)}},[fe,pe]=(0,p.useState)(re.replyTo),[L,me]=(0,p.useState)(),[he,ge]=(0,p.useState)(re.mentions),[_e,ve]=(0,p.useState)(re.files),[ye,be]=(0,p.useState)([]),[xe,Se]=(0,p.useState)(0),[Ce,we]=(0,p.useState)(),Te=(0,p.useRef)(null),Ee=(0,p.useRef)(null),De=(0,p.useRef)(void 0),Oe=(0,p.useRef)(null),ke=(0,p.useRef)(!0),Ae=(0,p.useRef)(void 0),je=(0,p.useRef)(!1),Me=(0,p.useRef)(void 0),Ne=(0,p.useRef)(new Map),Pe=w?.id===t?w:void 0,Le=!!(a||Pe?.archivedAt),Re=Pe?.messages.find(e=>e.id===fe),ze=e=>Pe?.members.find(t=>t.id===e)?.name??e,Be=e=>e.role===`user`?i:e.memberName??ze(e.memberId),Ve=Le?void 0:L?.query,He=L?[...(Pe?.members??[]).filter(e=>`${e.name} ${e.id}`.toLocaleLowerCase().includes(L.query.toLocaleLowerCase())).map(e=>({kind:`member`,member:e})),...ye.map(e=>({kind:`file`,file:e}))]:[];(0,p.useEffect)(()=>{iD(e,t,{text:ie,replyTo:fe,mentions:he,files:_e})},[e,t,ie,fe,he,_e]);let Ue=e=>{if(e.id!==t)return;let n=Ae.current;if(n?.id===e.id){let[t,r]=n.revision.split(`:`).map(Number),[i,a]=e.revision.split(`:`).map(Number);if(t>i||t===i&&r>a)return}Ae.current=e,T(e),e.archivedAt&&D(!1),(n?.title!==e.title||n?.archivedAt!==e.archivedAt||n?.activity.status!==e.activity.status||n?.activity.lastReplyAt!==e.activity.lastReplyAt)&&c(e)};(0,p.useEffect)(()=>{let e=Oe.current;if(!Pe||E||!e)return;let t=!0,n=()=>{let n=e.getBoundingClientRect();t&&document.visibilityState===`visible`&&getComputedStyle(e).visibility===`visible`&&n.width>0&&n.height>0&&n.bottom>0&&n.top<window.innerHeight&&n.right>0&&n.left<window.innerWidth&&l(Pe)};n();let r=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n()});return r.observe(e),document.addEventListener(`visibilitychange`,n),()=>{t=!1,r.disconnect(),document.removeEventListener(`visibilitychange`,n)}},[Pe?.id,Pe?.activity.lastReplyAt,E,Ce?.memberId,Ce?.postId,l]),(0,p.useEffect)(()=>(je.current=!0,()=>{je.current=!1}),[]),(0,p.useEffect)(()=>{if(!t)return;let n=new AbortController,r,i=!1,a=async()=>{try{let r=await pr(dr(e,t,Ae.current?.revision),{signal:n.signal});n.signal.aborted||(j(``),r&&Ue(r))}catch(r){n.signal.aborted||(r instanceof fr&&r.status===404?(i=!0,u({workspaceId:e,roomId:t})):j(Ae.current?`群聊连接暂时中断,正在重试。`:String(r.message??r)))}finally{!n.signal.aborted&&!i&&(r=window.setTimeout(a,Ae.current?.messages.some(pD)?450:1600))}};return a(),()=>{n.abort(),window.clearTimeout(r)}},[e,t,u]),(0,p.useEffect)(()=>{if(be([]),!Ve)return;let t=new AbortController,n,r=()=>{pr(`/api/files/mentions?${new URLSearchParams({workspaceId:e,cwd:``,q:Ve})}`,{signal:t.signal}).then(e=>{!t.signal.aborted&&e&&(be(e.hits.filter(e=>e.kind===`file`).slice(0,8)),e.indexed||(n=window.setTimeout(r,650)))}).catch(()=>{})};return n=window.setTimeout(r,160),()=>{window.clearTimeout(n),t.abort()}},[Ve,e]),(0,p.useLayoutEffect)(()=>{Oe.current&&ke.current&&(Oe.current.scrollTop=Oe.current.scrollHeight)},[Pe?.revision]),(0,p.useLayoutEffect)(()=>{let e=De.current;e!==void 0&&Ee.current&&(De.current=void 0,Ee.current.focus(),Ee.current.setSelectionRange(e,e))},[ie]);async function We(n){M(!0),k(``);try{let r=await ED(dr(e,t),t?{action:`configure`,memberIds:n.memberIds,memberModels:n.memberModels,...n.moderator,model:n.moderator.model??null,cloneLimit:n.moderator.cloneLimit??null}:n);if(!r)throw Error(`服务没有返回群聊。`);t?(Ue(r),D(!1)):d(r,je.current)}catch(e){k(String(e.message??e))}finally{M(!1)}}async function Ge(n){if(n.preventDefault(),!Pe||Le||!ie.trim()&&!se.length||ee||le)return;let r=ie.trim()||`请查看图片。`,i=TD(r),a=he.filter(e=>i.has(e.text)),o=Pe.members.filter(e=>a.some(t=>t.memberId===e.id)||i.has(wD(e.name))&&Pe.members.filter(t=>t.name===e.name).length===1).map(e=>e.id),s=_e.filter(e=>i.has(e.text)).map(e=>e.path),c=JSON.stringify([Pe.id,r,o,fe,s,se]);Me.current?.signature!==c&&(Me.current={signature:c,clientId:tn()}),M(!0),k(``);try{let n=await ED(dr(e,Pe.id),{action:`send`,content:r,memberIds:o,replyTo:fe,filePaths:s,images:se,clientId:Me.current.clientId});if(!n)throw Error(`服务没有确认收到消息。`);aD(e,t,ie),ke.current=!0,Ue(n),je.current&&t===n.id&&(ae(``),ce([]),pe(void 0),ge([]),ve([]),me(void 0)),Me.current=void 0}catch(e){k(String(e.message??e))}finally{M(!1)}}function Ke(e){if(!L)return;let t;if(e.kind===`member`){let n=e.member,r=wD(n.name);ae(ie.slice(0,L.start)+r+` `+ie.slice(L.end)),ge(e=>[...e.filter(e=>e.text!==r),{memberId:n.id,text:r}]),t=L.start+r.length+1}else{let n=e.file,r=vp(ie,L,n),i=r.text.slice(L.start,r.caret).trimEnd();ae(r.text),ve(e=>[...e.filter(e=>e.path!==n.path),{path:n.path,text:i}]),t=r.caret}De.current=t,me(void 0)}async function qe(n){try{let r=await ED(dr(e,t),{action:`stop`,postId:n});r&&Ue(r)}catch(e){k(String(e.message??e))}}async function Je(n,i){let a=r?.models.find(e=>bD(e)===i);if(i&&!a)throw Error(`所选模型不可用,请刷新模型列表后重试。`);if(!Pe)throw Error(`群聊尚未加载,请稍后重试。`);let o=await ED(dr(e,t),{action:`configure`,memberModels:{[n]:a??null},...Pe.moderator,model:Pe.moderator.model??null,cloneLimit:Pe.moderator.cloneLimit??null});if(!o)throw Error(`服务没有确认模型更改。`);Ue(o);let s=o.members.find(e=>e.id===n)?.model;if((s?bD(s):``)!==i)throw Error(`目标服务端没有应用成员模型设置,可能版本过旧。请先升级目标服务端后重试;群聊历史仍保留。`)}async function Ye(n){let r=Pe?.messages.find(e=>e.id===n&&e.role===`assistant`),i=r&&Pe?.messages.find(e=>e.id===r.topicId);if(!r||!i||![`failed`,`interrupted`,`cancelled`].includes(r.status))throw Error(`只能重试已失败或停止的执行。`);let a=Ne.current.get(n)??tn();Ne.current.set(n,a);let o=`请使用当前模型继续这次未完成的任务。先检查已有产物,避免重复执行。\n原分工:${r.assignment??`按原请求完成工作`}\n原请求:${i.content}`.slice(0,32e3),s=await ED(dr(e,t),{action:`send`,content:o,memberIds:[r.memberId],replyTo:r.id,clientId:a,filePaths:i.role===`user`?i.files?.map(e=>e.path):void 0});if(!s)throw Error(`服务没有确认重试请求。`);Ue(s),Ne.current.delete(n)}async function Xe(n,r,i){I(n),k(``);try{let a=await ED(dr(e,t),{action:`clone.resolve`,requestId:n,choice:r,name:i});a&&Ue(a)}catch(e){k(e instanceof Error?e.message:String(e))}finally{I(void 0)}}function Ze(e,t,n,r){let i=n.closest(`[data-group-post-id]`)?.querySelector(`[data-group-message-avatar]`)??void 0;Te.current={origin:n,avatar:i},we({memberId:e,name:t,postId:r})}function Qe(){let e=Ce?.memberId;we(void 0);let t=Te.current;requestAnimationFrame(()=>{let n=[...document.querySelectorAll(`[data-group-message-avatar]`)].filter(t=>t.dataset.groupMessageAvatar===e).at(-1);(t?.origin.isConnected?t.origin:t?.avatar?.isConnected?t.avatar:n)?.focus({preventScroll:!0})})}let $e=Pe?.messages??[],et=rr($e),tt=$e.filter(e=>e.role===`assistant`&&pD(e)).filter((e,t,n)=>n.findIndex(t=>t.memberId===e.memberId)===t),nt=new Map($e.map(e=>[e.id,e])),rt=new Set($e.flatMap(e=>e.role===`assistant`&&pD(e)?[e.memberId]:[])),it=Ce?$e.filter(e=>e.role===`assistant`&&e.memberId===Ce.memberId).reverse():[],R;return(0,m.jsxs)(`section`,{className:`group-chat`,"data-group-chat":t,children:[(O||A)&&(0,m.jsx)(`div`,{className:`group-error`,role:`alert`,children:O||A}),!t||E&&!Le?(0,m.jsx)(OD,{room:E?Pe:void 0,agents:n,catalog:r,saving:ee,onSave:We,onCancel:t?()=>D(!1):f}):Pe?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`group-members`,children:[(0,m.jsx)(`div`,{className:`group-roster`,"aria-label":`群成员`,children:Pe.members.map(e=>(0,m.jsxs)(`button`,{type:`button`,className:`group-roster-member`,"data-group-member-avatar":e.id,"aria-label":`查看 ${e.name} 的执行详情${rt.has(e.id)?`,工作中`:``}`,title:`${e.name}${e.agentId?` · 分身 · ${e.worktreePath??e.agentId}`:``}`,"aria-pressed":Ce?.memberId===e.id,onClick:t=>Ze(e.id,e.name,t.currentTarget),children:[(0,m.jsx)(_D,{name:e.name,memberId:e.id,busy:rt.has(e.id)}),(0,m.jsxs)(`span`,{children:[e.name,e.agentId?` · 分身`:``]})]},e.id))}),!Le&&(0,m.jsx)(`button`,{type:`button`,"data-group-settings":!0,disabled:ee,onClick:()=>{k(``),we(void 0),D(!0)},children:`群聊设置`}),(0,m.jsxs)(`button`,{type:`button`,"data-group-rsi":!0,"aria-pressed":S,onClick:x,children:[`RSI`,Pe.rsi?.status===`running`?` · 观察中`:Pe.rsi?.status===`failed`?` · 需处理`:``]}),(0,m.jsx)(`button`,{type:`button`,onClick:()=>{h?h():to().then(e=>ne(e===`granted`?`系统通知已开启`:`请在浏览器站点设置中允许通知`))},children:`系统通知`})]}),te&&(0,m.jsx)(`p`,{role:`status`,children:te}),(Pe.cloneRequests??[]).filter((e,t,n)=>e.status===`pending`||t>=n.length-3).map(e=>{let t=Pe.members.find(t=>t.id===e.memberId),n=2;for(;Pe.members.some(e=>e.name===`${t?.name??`Agent`} ${n}`);)n+=1;let r=N[e.id]??`${t?.name??`Agent`} ${n}`;return(0,m.jsx)(`section`,{className:`group-clone-request`,"data-clone-request":e.id,"aria-label":`创建 Agent 分身`,children:e.status===`pending`&&e.automatic?(0,m.jsx)(`span`,{children:`主持人正在准备独立分身…`}):e.status===`pending`&&!Le?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`strong`,{children:[t?.name??`Agent`,` 正在工作,是否创建分身?`]}),(0,m.jsx)(`p`,{children:e.reason}),(0,m.jsx)(`p`,{children:e.assignment}),(0,m.jsxs)(`form`,{onSubmit:t=>{t.preventDefault(),Xe(e.id,`create`,r)},children:[(0,m.jsxs)(`label`,{children:[`分身名字`,(0,m.jsx)(`input`,{maxLength:80,required:!0,value:r,onChange:t=>P(n=>({...n,[e.id]:t.target.value}))})]}),(0,m.jsx)(`button`,{disabled:!!F||!r.trim(),children:F===e.id?`正在准备…`:`创建分身并处理`}),(0,m.jsx)(`button`,{type:`button`,disabled:!!F,onClick:()=>void Xe(e.id,`wait`,``),children:`等待空闲`})]}),(0,m.jsx)(`small`,{children:`分身共享源 Agent 的能力与经验,在独立 Git 工作树处理此 case。`})]}):(0,m.jsx)(`span`,{children:e.status===`created`?`已安排 ${Pe.members.find(t=>t.id===e.cloneId)?.name??`分身`}`:e.status===`waiting`?`已选择等待原成员`:`成员或任务状态已变化,无需创建分身`})},e.id)}),(0,m.jsxs)(`div`,{className:`group-stage${Ce?` group-stage-inspecting`:``}`,children:[(0,m.jsxs)(`div`,{className:`group-dialogue`,children:[(0,m.jsxs)(`div`,{className:`group-thread`,ref:Oe,onScroll:e=>{let t=e.currentTarget;ke.current=t.scrollHeight-t.clientHeight-t.scrollTop<64},children:[!$e.length&&(0,m.jsx)(`p`,{className:`group-empty`,children:Le?`这个群聊没有消息。`:`发条消息开始讨论。用 @ 点名一个或多个成员。`}),et.map(e=>{let t=e.replyTo?nt.get(e.replyTo):void 0;e.role===`user`&&(R=e.id);let n=t&&(e.role===`user`||t.id!==e.topicId||e.topicId!==R)?t:void 0,r=Be(e),i=e.role===`assistant`&&e.background&&e.status===`running`?`后台进行中`:uD[e.status],a=e.role===`assistant`&&Ce?.postId===e.id;return(0,m.jsxs)(`article`,{className:`group-post group-post-${e.role}`,"data-group-post":e.role,"data-group-status":e.status,"data-group-post-id":e.id,children:[e.role===`assistant`?(0,m.jsx)(`button`,{className:`group-post-avatar`,type:`button`,"data-group-message-avatar":e.memberId,"aria-label":`查看 ${r} 这次发言的执行详情`,title:`${r} · 执行详情`,"aria-pressed":a,onClick:t=>Ze(e.memberId,r,t.currentTarget,e.id),children:(0,m.jsx)(_D,{name:r,memberId:e.memberId,busy:pD(e)})}):(0,m.jsx)(_D,{name:r}),(0,m.jsxs)(`div`,{className:`group-post-content`,children:[(0,m.jsxs)(`div`,{className:`group-post-head`,children:[(0,m.jsx)(`strong`,{children:r}),e.role===`assistant`&&(0,m.jsx)(`span`,{className:`group-message-model`,"data-group-message-model":e.model?bD(e.model):`unknown`,title:e.model?`${e.model.provider} / ${e.model.modelId}`:`这条历史消息没有记录使用的模型`,children:e.model?`${e.model.label} · ${e.model.provider}`:`模型未记录`}),e.status!==`completed`&&(0,m.jsx)(`span`,{className:`group-post-state`,children:i}),(0,m.jsx)(`time`,{dateTime:nr(e),children:gD(nr(e))}),!Le&&(0,m.jsxs)(`div`,{className:`group-post-actions`,children:[!pD(e)&&(0,m.jsx)(`button`,{type:`button`,className:`group-reply-action`,disabled:ee,onClick:()=>{pe(e.id),Ee.current?.focus()},children:`回复`}),pD(e)&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>void qe(e.id),children:`停止`})]})]}),(n||e.content||e.error||e.role===`user`&&(e.memoryNotice||e.images?.length))&&(0,m.jsxs)(`div`,{className:`group-bubble`,children:[n&&(0,m.jsxs)(`div`,{className:`group-quote`,children:[Be(n),` · `,n.content.slice(0,120)]}),e.content&&(0,m.jsx)(`div`,{className:`message-body`,children:(0,m.jsx)(ep,{source:e.content,handoffs:!1,sourceLink:e.role===`assistant`&&w?.members.some(t=>t.id===e.memberId&&!t.worktreePath)?_:void 0})}),e.role===`user`&&e.images?.map(e=>C(e,`群聊图片`)),e.role===`user`&&e.memoryNotice&&(0,m.jsx)(`div`,{className:`group-route`,children:e.memoryNotice}),e.error&&(0,m.jsx)(`p`,{className:`group-error`,children:e.error})]}),e.role===`assistant`&&e.routeReason&&(0,m.jsxs)(`details`,{className:`group-route group-post-footer`,children:[(0,m.jsx)(`summary`,{children:`接话原因`}),e.routeReason]})]})]},e.id)})]}),tt.length>0&&(0,m.jsx)(`div`,{className:`group-preparing`,"data-group-preparing":!0,role:`group`,"aria-label":`正在准备回复的成员`,children:tt.map(e=>(0,m.jsx)(`button`,{type:`button`,"data-group-preparing-avatar":e.memberId,title:`${Be(e)} · 正在准备回复`,"aria-label":`查看 ${Be(e)} 的准备详情`,"aria-pressed":Ce?.memberId===e.memberId,onClick:t=>Ze(e.memberId,Be(e),t.currentTarget,e.id),children:(0,m.jsx)(_D,{name:Be(e),memberId:e.memberId,busy:!0})},e.memberId))}),Le?(0,m.jsxs)(`div`,{className:`group-archive-notice`,"data-group-archive-notice":!0,children:[(0,m.jsx)(`p`,{children:`群聊已归档。恢复后可继续发消息。`}),(0,m.jsx)(`button`,{type:`button`,"data-group-restore":!0,disabled:o,onClick:()=>s(Pe),children:`恢复群聊`})]}):(0,m.jsxs)(`form`,{className:`group-composer`,onSubmit:Ge,onPaste:e=>{let t=Array.from(e.clipboardData.files).filter(e=>e.type.startsWith(`image/`));t.length&&(e.preventDefault(),de(t))},children:[g,(0,m.jsx)(`div`,{className:`group-image-attachments`,children:se.map(e=>(0,m.jsxs)(`span`,{children:[C(e,`待发送图片`),(0,m.jsx)(`button`,{type:`button`,"aria-label":`移除图片`,onClick:()=>ce(t=>t.filter(t=>t.id!==e.id)),children:`×`})]},e.id))}),(0,m.jsxs)(`label`,{className:`group-image-upload`,title:`需主持人及所有群成员的模型支持图片输入`,children:[le?`上传中…`:`添加图片`,(0,m.jsx)(`input`,{type:`file`,"aria-label":`添加群聊图片`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,disabled:le||ee,onChange:e=>{de(Array.from(e.target.files??[])),e.target.value=``}})]}),Re&&(0,m.jsxs)(`div`,{className:`group-quote`,children:[`回复 `,Be(Re),` · `,Re.content.slice(0,60),` `,(0,m.jsx)(`button`,{type:`button`,onClick:()=>pe(void 0),"aria-label":`取消引用`,children:`×`})]}),He.length>0&&(0,m.jsx)(`div`,{className:`group-suggestions`,role:`listbox`,"aria-label":`点名群成员或引用文件`,children:He.map((e,t)=>(0,m.jsx)(`button`,{type:`button`,role:`option`,"aria-selected":t===xe,"data-group-member-option":e.kind===`member`?e.member.id:void 0,onMouseDown:e=>e.preventDefault(),onClick:()=>Ke(e),children:e.kind===`member`?e.member.name:`文件 · ${e.file.path}`},e.kind===`member`?`member:${e.member.id}`:`file:${e.file.path}`))}),(0,m.jsx)(`textarea`,{ref:Ee,"data-group-composer":!0,"aria-label":`群聊消息`,placeholder:`输入消息,@ 点名或引用文件`,value:ie,maxLength:32e3,readOnly:ee,onChange:e=>{ae(e.target.value),me(_p(e.target.value,e.target.selectionStart,e.target.selectionEnd)),Se(0)},onSelect:e=>{let t=e.currentTarget;me(_p(t.value,t.selectionStart,t.selectionEnd))},onKeyDown:e=>{e.nativeEvent.isComposing||(He.length&&(e.key===`ArrowDown`||e.key===`ArrowUp`)?(e.preventDefault(),Se(t=>(t+He.length+(e.key===`ArrowDown`?1:-1))%He.length)):He.length&&(e.key===`Enter`||e.key===`Tab`)&&!e.shiftKey?(e.preventDefault(),Ke(He[xe]??He[0])):e.key===`Escape`?me(void 0):e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit()))}}),(0,m.jsx)(`button`,{type:`submit`,"data-group-send":!0,disabled:!ie.trim()&&!se.length||ee||le,children:`发送`})]})]}),Ce&&(0,m.jsx)(yD,{workspaceId:e,roomId:t,memberId:Ce.memberId,name:Ce.name,runs:it,postId:Ce.postId,onStop:e=>void qe(e),onSelect:e=>we({...Ce,postId:e}),onClose:Qe,models:r?.models??[],memberModel:Pe.members.find(e=>e.id===Ce.memberId)?.model,onModelChange:Le?void 0:e=>Je(Ce.memberId,e),onRetry:Le?void 0:Ye},Ce.memberId)]})]}):!A&&(0,m.jsx)(`p`,{className:`group-empty`,children:`正在加载群聊…`})]})}function OD({room:e,agents:t,catalog:n,saving:r,onSave:i,onCancel:a}){let[o,s]=(0,p.useState)(e?.title??``),[c,l]=(0,p.useState)({}),u=t.filter(e=>e.mode===`primary`&&!e.hidden),d=[...u,...e?.members.filter(e=>!u.some(t=>t.id===e.id))??[]],f=e?.members.map(e=>e.id)??tr,h=[...new Set([...f,...d.map(e=>e.id)])].filter(e=>d.some(t=>t.id===e)&&(c[e]??f.includes(e))),[g,_]=(0,p.useState)(e?.moderator.model?bD(e.moderator.model):``),[v,y]=(0,p.useState)(e?.moderator.prompt??``),[b,x]=(0,p.useState)(e?.moderator.cloneLimit??0),[S,C]=(0,p.useState)(()=>Object.fromEntries((e?.members??[]).map(e=>[e.id,e.model?bD(e.model):``]))),[w,T]=(0,p.useState)(sD),[E,D]=(0,p.useState)(``),[O,k]=(0,p.useState)(``),[A,j]=(0,p.useState)(``),[ee,M]=(0,p.useState)(CD),[N,P]=(0,p.useState)(``),[F,I]=(0,p.useState)(``),[te,ne]=(0,p.useState)(``);(0,p.useEffect)(()=>{try{localStorage.setItem(xD,JSON.stringify(ee))}catch{ne(`浏览器无法保存预设,请检查本地存储空间或隐私设置。`)}},[ee]);let re=[...n?.models??[]];if(e?.moderator.model&&!re.some(t=>bD(t)===bD(e.moderator.model))){let t=e.moderator.model;n||re.push(t)}let ie=()=>Object.fromEntries(h.map(e=>[e,re.find(t=>bD(t)===S[e])??null])),ae=()=>({prompt:v,cloneLimit:b||void 0,model:re.find(e=>bD(e)===g)}),oe=!(!g||re.some(e=>bD(e)===g))||h.some(e=>S[e]&&!re.some(t=>bD(t)===S[e])),se=e=>{try{return localStorage.setItem(oD,JSON.stringify(e)),T(e),!0}catch{return j(`浏览器无法保存群聊预设,请检查本地存储空间或隐私设置。`),!1}};return(0,m.jsxs)(`form`,{className:`group-settings`,onSubmit:e=>{e.preventDefault();let t=re.find(e=>bD(e)===g);g&&!t||oe||i({title:o,memberIds:h,memberModels:ie(),moderator:ae()})},children:[(0,m.jsxs)(`div`,{className:`group-settings-heading`,children:[(0,m.jsx)(`h2`,{children:e?`群聊设置`:`创建群聊`}),(0,m.jsx)(`p`,{children:`安排成员与模型,让主持人协调讨论和执行。`})]}),(0,m.jsxs)(`section`,{className:`group-settings-card`,"data-group-presets":!0,children:[(0,m.jsx)(`h3`,{children:`群聊预设`}),(0,m.jsx)(`p`,{className:`group-settings-hint`,children:`一并保存成员、各自模型和主持人设置。`}),(0,m.jsxs)(`label`,{children:[`加载群聊预设`,(0,m.jsxs)(`select`,{"aria-label":`加载群聊预设`,value:E,onChange:e=>{D(e.target.value);let t=w.find(t=>t.id===e.target.value);if(!t)return;k(t.name),l(Object.fromEntries([...new Set([...f,...d.map(e=>e.id),...t.memberIds])].map(e=>[e,t.memberIds.includes(e)]))),C(Object.fromEntries(Object.entries(t.memberModels).map(([e,t])=>[e,t?bD(t):``]))),y(t.moderator.prompt),_(t.moderator.model?bD(t.moderator.model):``),x(t.moderator.cloneLimit??0);let n=t.memberIds.filter(e=>!d.some(t=>t.id===e));j(n.length?`已加载「${t.name}」。${n.length} 位成员在当前服务端不可用,请检查成员列表后保存。`:`已加载「${t.name}」。可继续调整,不影响其他群聊。`)},children:[(0,m.jsx)(`option`,{value:``,children:`选择预设…`}),w.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,m.jsxs)(`div`,{className:`group-prompt-preset-actions`,children:[(0,m.jsx)(`input`,{"aria-label":`群聊预设名称`,placeholder:`例如:日常开发评审`,value:O,maxLength:80,onChange:e=>k(e.target.value)}),(0,m.jsx)(`button`,{type:`button`,disabled:!O.trim()||h.length<2||oe,onClick:()=>{let t=O.trim(),n=w.find(e=>e.name.toLocaleLowerCase()===t.toLocaleLowerCase()),r=h.map(t=>e?.members.find(e=>e.id===t)?.agentId??t),i=ie(),a={id:n?.id??tn(),name:t,memberIds:[...new Set(r)],memberModels:Object.fromEntries(r.map((e,t)=>[e,i[h[t]]])),moderator:ae()};se(n?w.map(e=>e.id===n.id?a:e):[a,...w].slice(0,100))&&(D(a.id),j(`已保存群聊预设「${t}」。`))},children:`保存预设`}),E&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>{se(w.filter(e=>e.id!==E))&&(D(``),j(`群聊预设已删除。`))},children:`删除`})]}),A&&(0,m.jsx)(`p`,{className:`group-settings-hint`,role:`status`,children:A})]}),!e&&(0,m.jsxs)(`label`,{children:[`群名`,(0,m.jsx)(`input`,{autoFocus:!0,value:o,onChange:e=>s(e.target.value),maxLength:100,required:!0})]}),(0,m.jsxs)(`fieldset`,{className:`group-member-settings`,children:[(0,m.jsx)(`legend`,{children:`群成员与模型`}),d.map(e=>(0,m.jsxs)(`div`,{className:`group-member-card`,"data-selected":h.includes(e.id),children:[(0,m.jsxs)(`label`,{className:`group-choice`,title:e.description,children:[(0,m.jsx)(`input`,{type:`checkbox`,"data-group-member-choice":e.id,checked:h.includes(e.id),disabled:!h.includes(e.id)&&h.length>=8,onChange:t=>{let n=t.target.checked;l(t=>({...t,[e.id]:n}))}}),(0,m.jsx)(_D,{name:e.name,memberId:e.id}),(0,m.jsxs)(`span`,{children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.jsx)(`small`,{children:e.description})]})]}),h.includes(e.id)&&(0,m.jsx)(lD,{label:`${e.name} 的模型`,value:S[e.id]??``,models:re,onChange:t=>C(n=>({...n,[e.id]:t}))})]},e.id))]}),(0,m.jsx)(`p`,{className:`group-settings-hint`,children:`取消勾选可移除成员。请选择 2 到 8 位主 Agent。`}),(0,m.jsxs)(`details`,{className:`group-settings-card`,open:!0,children:[(0,m.jsx)(`summary`,{children:`主持人设置`}),(0,m.jsxs)(`label`,{children:[`同类 Agent 分身`,(0,m.jsxs)(`select`,{value:b,onChange:e=>x(Number(e.target.value)),children:[(0,m.jsx)(`option`,{value:0,children:`创建前询问我`}),[2,3,4,8].map(e=>(0,m.jsxs)(`option`,{value:e,children:[`允许自动创建 · 同类最多 `,e,` 人`]},e))]})]}),(0,m.jsxs)(`div`,{className:`group-model-field`,children:[(0,m.jsx)(`span`,{children:`主持人模型`}),(0,m.jsx)(lD,{label:`主持人模型`,value:g,models:re,onChange:_})]}),(0,m.jsxs)(`label`,{children:[`主持人 Prompt`,(0,m.jsx)(`textarea`,{value:v,maxLength:8e3,onChange:e=>y(e.target.value),placeholder:`例如:先请最熟悉模块的成员回答,结论足够时结束。`})]}),(0,m.jsxs)(`details`,{className:`group-prompt-presets`,"data-moderator-prompt-presets":!0,children:[(0,m.jsx)(`summary`,{children:`旧版 Prompt 预设`}),(0,m.jsxs)(`label`,{children:[`加载已保存的 Prompt`,(0,m.jsxs)(`select`,{"aria-label":`加载主持人 Prompt 预设`,value:N,onChange:e=>{let t=ee.find(t=>t.id===e.target.value);P(e.target.value),t?(y(t.prompt),I(t.name),ne(`已加载「${t.name}」,可继续修改后用于当前群聊。`)):ne(``)},children:[(0,m.jsx)(`option`,{value:``,children:`选择预设…`}),ee.map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,m.jsxs)(`div`,{className:`group-prompt-preset-actions`,children:[(0,m.jsx)(`input`,{"aria-label":`Prompt 预设名称`,value:F,maxLength:80,onChange:e=>I(e.target.value),placeholder:`预设名称`}),(0,m.jsx)(`button`,{type:`button`,disabled:!F.trim()||!v.trim(),onClick:()=>{let e=F.trim(),t=ee.find(t=>t.name.toLocaleLowerCase()===e.toLocaleLowerCase()),n={id:t?.id??tn(),name:e,prompt:v};M(e=>t?e.map(e=>e.id===t.id?n:e):[n,...e].slice(0,100)),P(n.id),ne(`已保存「${e}」。`)},children:`保存预设`}),N&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>{let e=ee.find(e=>e.id===N);M(e=>e.filter(e=>e.id!==N)),P(``),I(``),ne(e?`已删除「${e.name}」。`:`预设已删除。`)},children:`删除预设`})]}),te&&(0,m.jsx)(`p`,{className:`group-settings-hint`,role:`status`,children:te})]})]}),(0,m.jsxs)(`div`,{className:`group-settings-actions`,children:[(0,m.jsx)(`button`,{type:`button`,disabled:r,onClick:a,children:`取消`}),(0,m.jsx)(`button`,{type:`submit`,disabled:r||!o.trim()||h.length<2||h.length>8||oe,children:e?`保存`:`创建群聊`})]})]})}var kD=`__pi_default__`;function AD({workspaces:e,catalog:t,onClose:n,onSave:r}){let[i,a]=(0,p.useState)(kD),[o,s]=(0,p.useState)(kD);(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&n()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[n]);let c=t.models.find(e=>`${e.provider}/${e.modelId}`===i),l=c?.provider===t.defaultModel?.provider&&c?.modelId===t.defaultModel?.modelId,u=c?.thinkingLevels??(l?t.levels:[]),d=c?{provider:c.provider,modelId:c.modelId,label:c.label}:void 0;return(0,m.jsx)(`div`,{className:`overlay`,onClick:n,children:(0,m.jsxs)(`div`,{className:`picker settings-dialog bulk-workspace-settings`,"data-bulk-workspace-settings":`1`,onClick:e=>e.stopPropagation(),children:[(0,m.jsx)(`h2`,{children:`批量设置工作区`}),(0,m.jsxs)(`div`,{className:`settings-scope`,children:[`将统一修改 `,e.length,` 个现存工作区的默认模型与思考等级,只影响之后新建的会话。`]}),(0,m.jsxs)(`label`,{className:`bulk-settings-field`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,m.jsxs)(`select`,{className:`bulk-settings-select`,"aria-label":`批量默认模型`,value:i,disabled:t.source!==`pi`,onChange:e=>{a(e.target.value),s(kD)},children:[(0,m.jsx)(`option`,{value:kD,children:`跟随 Pi 默认`}),t.models.map(e=>(0,m.jsxs)(`option`,{value:`${e.provider}/${e.modelId}`,children:[e.label,` · `,e.provider]},`${e.provider}/${e.modelId}`))]})]}),(0,m.jsxs)(`label`,{className:`bulk-settings-field`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认思考等级`}),(0,m.jsxs)(`select`,{className:`bulk-settings-select`,"aria-label":`批量默认思考等级`,value:o,disabled:!c||t.source!==`pi`,onChange:e=>s(e.target.value),children:[(0,m.jsx)(`option`,{value:kD,children:`跟随 Pi 默认`}),u.map(e=>(0,m.jsx)(`option`,{value:e,children:e},e))]})]}),c&&u.length===0&&(0,m.jsx)(`p`,{className:`bulk-settings-note`,children:`Pi 没有为此模型提供可选择的思考等级;新会话会使用 Pi 默认值。`}),(0,m.jsxs)(`div`,{className:`bulk-settings-workspaces`,"aria-label":`将被更新的工作区`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`应用到`}),(0,m.jsx)(`div`,{children:e.map(e=>(0,m.jsx)(`span`,{children:e.name},e.id))})]}),(0,m.jsxs)(`div`,{className:`picker-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`picker-cancel`,onClick:n,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-ok`,disabled:!e.length||t.source!==`pi`,onClick:()=>r(d,o===kD?void 0:o),children:`应用到全部工作区`})]})]})})}function jD({height:e,onHeight:t}){let n=(0,p.useRef)(void 0),r=e=>t(Math.max(120,Math.min(Math.round(window.innerHeight*.65),Math.round(e))));return(0,m.jsx)(`div`,{className:`workbench-bottom-divider`,"data-bottom-divider":!0,role:`separator`,"aria-label":`调整底部面板高度`,"aria-orientation":`horizontal`,"aria-valuemin":120,"aria-valuemax":Math.round(window.innerHeight*.65),"aria-valuenow":Math.min(e,Math.round(window.innerHeight*.65)),tabIndex:0,onPointerDown:t=>{t.preventDefault(),t.currentTarget.focus(),t.currentTarget.setPointerCapture(t.pointerId),n.current={y:t.clientY,height:Math.min(e,window.innerHeight*.65)}},onPointerMove:e=>{n.current&&r(n.current.height+n.current.y-e.clientY)},onLostPointerCapture:()=>{n.current=void 0},onDoubleClick:()=>r(260),onKeyDown:t=>{if(t.key===`ArrowUp`)r(e+24);else if(t.key===`ArrowDown`)r(e-24);else if(t.key===`Home`)r(120);else if(t.key===`End`)r(window.innerHeight);else return;t.preventDefault()}})}function MD({glyph:e,className:t}){return(0,m.jsx)(`span`,{className:t,"data-tool-glyph-length":Math.min(4,Math.max(1,Array.from(e).length)),"aria-hidden":`true`,children:e})}function ND(e){if(e!==void 0){if(typeof e!=`string`||!e.trim()||Array.from(e.trim()).length>4||/[<>\u0000-\u001f\u007f]/.test(e))throw Error(`工具图标须为 1 至 4 个字符的文字或符号`);return e.trim()}}function PD(e){try{let t=ND(e.glyph);if(t)return t}catch{}let t=`${e.name} ${e.slug??``}`.toLowerCase();return[[/json/,`{}`],[/正则|regex/,`.*`],[/计算|calc/,`∑`],[/时间|timestamp|date/,`◷`],[/差异|diff/,`±`],[/markdown/,`M↓`],[/图像|图片|image/,`▧`],[/表格|csv|excel/,`▦`],[/颜色|color/,`◐`],[/base64/,`64`],[/hash|哈希/,`#`],[/git/,`⑂`]].find(([e])=>e.test(t))?.[1]??(Array.from(e.name.trim()).slice(0,2).join(``)||`◇`)}function FD(e){return!!(e&&typeof e==`object`&&e.type===`message.send`)}function ID(e){let t=[],n=[];for(let r of e)(r.retry?t:n).push(r);return{retry:t,failed:n}}function LD(e){let t=new Map;for(let[n,r]of e.entries())t.has(r.id)||t.set(r.id,n);return t}function RD(e,t){if(!t||t.length===0)return e;let n=new Map(t.map((e,t)=>[e,t])),r=e.filter(e=>n.has(e.id)).sort((e,t)=>(n.get(e.id)??0)-(n.get(t.id)??0));return[...e.filter(e=>!n.has(e.id)),...r]}function zD(e,t,n){if(e.indexOf(t)<0)return[...e];let r=e.filter(e=>e!==t),i=Math.max(0,Math.min(n,r.length));return[...r.slice(0,i),t,...r.slice(i)]}var BD=`super-pi.session-order.v1`;function VD(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.session-order.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)&&(t[n]=r.filter(e=>typeof e==`string`));return t}catch{return{}}}function HD(e){try{typeof window<`u`&&window.localStorage.setItem(BD,JSON.stringify(e))}catch{}}function UD(e,t,n){let r=new Set(e.map(e=>e.id)),i=LD(e),a=(e,t)=>(i.get(e.id)??2**53-1)-(i.get(t.id)??2**53-1),o=new Map,s=[];for(let t of e){let e=t.parentConversationId;if(e&&r.has(e)){let n=o.get(e);n?n.push(t):o.set(e,[t])}else s.push(t)}for(let e of o.values())e.sort(a);let c=RD(s.sort(a),n?.manualRoots),l=[],u=new Set,d=(e,n,r,i=!0)=>{if(u.has(e.id))return;u.add(e.id);let a=o.get(e.id)??[];i&&l.push({conversation:e,depth:Math.min(n,8),childCount:a.length,isLastSibling:r});let s=!i||t.has(e.id);for(let[e,t]of a.entries())d(t,n+1,e===a.length-1,!s)};for(let e of c)d(e,0,!1);let f=e.filter(e=>!u.has(e.id)).sort(a);for(let e of f)d(e,0,!1);return l}var WD=`super-pi:tool-shortcuts:v1`,GD=new Set([`Control`,`Alt`,`Shift`,`Meta`,`AltGraph`,`CapsLock`,`Fn`,`FnLock`,`Hyper`,`Super`,`Symbol`,`SymbolLock`]),KD=new Set([`Escape`]),qD=new Set([`Enter`,` `,`Tab`]),JD={" ":`Space`,ArrowUp:`↑`,ArrowDown:`↓`,ArrowLeft:`←`,ArrowRight:`→`,Escape:`Esc`},YD={ctrl:`⌃`,alt:`⌥`,shift:`⇧`,meta:`⌘`};function XD(e){if(e===` `)return` `;let t=e.trim();return t?t.length===1?t.toLowerCase():t:``}function ZD(e){return GD.has(e)}function QD(e){let t=e.key;if(!t||t===`Unidentified`||t===`Dead`||ZD(t))return;let n=XD(t);if(!n)return;let r=!!e.shiftKey;if(r&&n.length===1&&!/[a-z]/.test(n)){let t=/^Digit([0-9])$/.exec(e.code??``);t&&(n=t[1])}let i={key:n};return e.ctrlKey&&(i.ctrl=!0),e.altKey&&(i.alt=!0),r&&(i.shift=!0),e.metaKey&&(i.meta=!0),i}function $D(e){return JD[e]||(e.length===1||/^f\d{1,2}$/.test(e)?e.toUpperCase():e)}function eO(e){let t=[];return e.ctrl&&t.push(`Ctrl`),e.alt&&t.push(`Alt`),e.shift&&t.push(`Shift`),e.meta&&t.push(`Meta`),t.push($D(e.key)),t.join(`+`)}function tO(e){let t=``;return e.ctrl&&(t+=YD.ctrl),e.alt&&(t+=YD.alt),e.shift&&(t+=YD.shift),e.meta&&(t+=YD.meta),t+$D(e.key)}function nO(e,t){return e.key===t.key&&!!e.ctrl==!!t.ctrl&&!!e.alt==!!t.alt&&!!e.shift==!!t.shift&&!!e.meta==!!t.meta}function rO(e){return!!(e.ctrl||e.alt||e.shift||e.meta)}function iO(e){return e.key?KD.has(e.key)?{ok:!1,reason:`Esc 是所有弹窗的退出键,不能拿来当工具快捷键。`}:!rO(e)&&qD.has(e.key)?{ok:!1,reason:`「${aO(e.key)}」是当前焦点控件的激活键,加一个修饰键(Ctrl / Alt / Shift)才能当快捷键用。`}:{ok:!0}:{ok:!1,reason:`这个组合键不完整,请按一个具体的键。`}}function aO(e){return $D(e)}function oO(e){let t=e;if(!t||typeof t!=`object`)return!1;let n=t.tagName;return n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.isContentEditable===!0}function sO(e,t){if(t.isComposing||t.defaultPrevented)return!1;let n=QD(t);return!(!n||!nO(e,n)||!rO(e)&&oO(t.target??null))}function cO(e){if(!e)return{};let t;try{t=JSON.parse(e)}catch{return{}}if(!t||typeof t!=`object`||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){if(!e||typeof r!=`object`||!r)continue;let t=r,i=XD(typeof t.key==`string`?t.key:``);if(!i)continue;let a={key:i};t.ctrl===!0&&(a.ctrl=!0),t.alt===!0&&(a.alt=!0),t.shift===!0&&(a.shift=!0),t.meta===!0&&(a.meta=!0),iO(a).ok&&(n[e]=a)}return n}function lO(e){let t={};for(let n of Object.keys(e).sort()){let r=e[n];if(!r)continue;let i={key:r.key};r.ctrl&&(i.ctrl=!0),r.alt&&(i.alt=!0),r.shift&&(i.shift=!0),r.meta&&(i.meta=!0),t[n]=i}return JSON.stringify(t)}function uO(e,t,n){for(let[r,i]of Object.entries(e))if(r!==n&&nO(i,t))return r}var dO=`super-pi:tool-settings-size:v1`,fO={width:480,height:320};function pO(){try{if(typeof window>`u`)return qt.slice();let e=$t(window.localStorage.getItem(Xt));return window.localStorage.getItem(`super-pi:tools:v1`)===null?qt.slice():e}catch{return qt.slice()}}function mO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(Xt,en(e))}catch{}}function hO(){try{return typeof window>`u`?{}:cO(window.localStorage.getItem(WD))}catch{return{}}}function gO(e){try{if(typeof window>`u`)return;window.localStorage.setItem(WD,lO(e))}catch{}}function _O(e,t,n){let r={};for(let n of t)e[n.id]&&(r[n.id]=e[n.id]);for(let e of n)e.shortcut&&(r[e.id]=e.shortcut);return r}function vO(){try{if(typeof window>`u`)return;let e=window.localStorage.getItem(dO);if(!e)return;let t=JSON.parse(e);return typeof t?.width!=`number`||typeof t?.height!=`number`||!Number.isFinite(t.width)||!Number.isFinite(t.height)||t.width<fO.width||t.height<fO.height?void 0:{width:Math.round(t.width),height:Math.round(t.height)}}catch{return}}function yO(e){try{if(typeof window>`u`)return;e?window.localStorage.setItem(dO,JSON.stringify({width:Math.round(e.width),height:Math.round(e.height)})):window.localStorage.removeItem(dO)}catch{}}function bO(e,t,n){let r=Math.max(fO.width,t-32),i=Math.max(fO.height,n-32);return{width:Math.round(Math.min(Math.max(e.width,fO.width),r)),height:Math.round(Math.min(Math.max(e.height,fO.height),i))}}var xO=hO(),SO={tools:pO(),mountedTools:[],settingsOpen:!1,shortcuts:{}};SO.shortcuts=_O(xO,SO.tools,SO.mountedTools);var CO=new Set;function wO(e){SO={...SO,...e};for(let e of CO)e()}function TO(e){return CO.add(e),()=>{CO.delete(e)}}var EO=()=>SO;function DO(){return(0,p.useSyncExternalStore)(TO,EO,EO)}var OO={setTools(e){mO(e);let t=new Set(e.map(e=>e.id));xO=Object.fromEntries(Object.entries(xO).filter(([e])=>t.has(e))),gO(xO),wO({tools:e,shortcuts:_O(xO,e,SO.mountedTools)})},removeTool(e){let t=an(SO.tools,e);xO[e]&&(xO={...xO},delete xO[e],gO(xO)),mO(t),wO({tools:t,shortcuts:_O(xO,t,SO.mountedTools),openToolId:SO.openToolId===e?void 0:SO.openToolId})},setMountedTools(e){let t=new Set(SO.tools.map(e=>e.id));xO=Object.fromEntries(Object.entries(xO).filter(([e])=>t.has(e))),gO(xO),wO({mountedTools:e,shortcuts:_O(xO,SO.tools,e)})},openTool(e){wO({openToolId:e,settingsOpen:!1})},closeTool(){wO({openToolId:void 0})},toggleTool(e){SO.openToolId===e?OO.closeTool():OO.openTool(e)},openSettings(){wO({settingsOpen:!0,openToolId:void 0})},closeSettings(){wO({settingsOpen:!1})},async setShortcut(e,t){let n=SO.mountedTools.find(t=>t.id===e);if(n){try{let e=await Ie(`/api/tools/shortcut`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({slug:n.slug,shortcut:t})}),r=await e.json();if(!e.ok)return r.error??`快捷键保存失败(HTTP ${e.status})。`}catch(e){return e instanceof Error?e.message:String(e)}wO({mountedTools:SO.mountedTools.map(n=>n.id===e?{...n,shortcut:t}:n),shortcuts:{...SO.shortcuts,[e]:t}})}else xO={...xO,[e]:t},gO(xO),wO({shortcuts:_O(xO,SO.tools,SO.mountedTools)})},async clearShortcut(e){if(!SO.shortcuts[e])return;let t=SO.mountedTools.find(t=>t.id===e);if(t){try{let e=await Ie(`/api/tools/shortcut`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({slug:t.slug,shortcut:null})}),n=await e.json();if(!e.ok)return n.error??`快捷键清除失败(HTTP ${e.status})。`}catch(e){return e instanceof Error?e.message:String(e)}wO({mountedTools:SO.mountedTools.map(t=>t.id===e?{...t,shortcut:void 0}:t),shortcuts:Object.fromEntries(Object.entries(SO.shortcuts).filter(([t])=>t!==e))})}else xO={...xO},delete xO[e],gO(xO),wO({shortcuts:_O(xO,SO.tools,SO.mountedTools)})},persistTools(){mO(SO.tools)}};async function kO(){let e=me();try{let t=await Ie(`/api/tools`),n=await t.json();me()===e&&t.ok&&Array.isArray(n.tools)&&OO.setMountedTools(n.tools.filter(e=>e.enabled))}catch{}}async function AO(e){try{let t=await Ie(`/api/tools?id=${encodeURIComponent(e)}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);OO.closeTool(),await kO();return}catch(e){return e instanceof Error?e.message:String(e)}}var jO=`.super-pi-tool.json`,MO=512e3,NO=/^[a-z0-9][a-z0-9-]{0,63}$/,PO=/^[A-Za-z0-9][A-Za-z0-9_.-]*==[^=\s,;<>|'"`\\]{1,80}$/;function FO(e,t){let n;try{n=JSON.parse(e)}catch{return{ok:!1,reason:`「${t}」不是 JSON。确认一下选的是别人分享的工具文件(${jO})。`}}if(!n||typeof n!=`object`||Array.isArray(n))return{ok:!1,reason:`这个 JSON 不是一个工具包。`};let r=n,i;try{i=ND(r.glyph)}catch{return{ok:!1,reason:`工具图标须为 1 至 4 个字符的文字或符号。`}}let a=typeof r.format==`string`?r.format:void 0;if(a!==void 0&&a!==`super-pi.tool`)return{ok:!1,reason:`这不是 Super Pi 的工具文件(format: ${a})。`};if(typeof r.version==`number`&&r.version>1)return{ok:!1,reason:`这个工具文件是更新版本的 Super Pi 导出的(version: ${r.version}),当前版本读不了。`};let o=typeof r.slug==`string`?r.slug.trim():``,s=typeof r.name==`string`?r.name.trim():``;if(!o)return{ok:!1,reason:`这个工具包里没有 slug(那是它的短名字,也是它在磁盘上的目录名)。`};if(!s)return{ok:!1,reason:`这个工具包里没有名字。`};if(!Array.isArray(r.files)||!r.files.length)return{ok:!1,reason:`这个工具包里没有文件。`};if(r.files.length>32)return{ok:!1,reason:`文件太多了:${r.files.length} 个,上限 32 个。`};let c=[],l=0;for(let e of r.files){let t=e;if(!t||typeof t.path!=`string`||typeof t.content!=`string`)return{ok:!1,reason:`工具包里的文件项格式不对(每一项都要有 path 和 content)。`};let n=t.path.trim();if(!n||n.startsWith(`/`)||n.includes(`\\`)||n.includes(`\0`)||n.split(`/`).includes(`..`))return{ok:!1,reason:`文件路径「${n}」不合法:不能是绝对路径,也不能跳出工具自己的目录。`};if(c.some(e=>e.path===n))return{ok:!1,reason:`工具包里有重复的文件:${n}`};if(l+=new TextEncoder().encode(t.content).length,l>512e3)return{ok:!1,reason:`工具文件合计超过 ${UO(MO)} 的上限。`};c.push({path:n,content:t.content})}let u=typeof r.entrypoint==`string`&&r.entrypoint.trim()?r.entrypoint.trim():`index.html`;if(!u.endsWith(`.html`))return{ok:!1,reason:`入口文件必须是一个 HTML 文件。`};if(!c.some(e=>e.path===u))return{ok:!1,reason:`工具包里没有包含入口文件 ${u}。`};let d;if(r.script!==void 0&&r.script!==null){let e=r.script,t=typeof e.path==`string`?e.path.trim():``;if(!t.endsWith(`.py`))return{ok:!1,reason:`工具包声明的脚本必须是一个 .py 文件。`};if(!c.some(e=>e.path===t))return{ok:!1,reason:`工具包里没有包含它声明的脚本 ${t}。`};d={path:t,timeoutMs:typeof e.timeoutMs==`number`?e.timeoutMs:void 0,parameters:typeof e.parameters==`object`&&e.parameters!==null?e.parameters:void 0}}let f;if(r.environment!==void 0&&r.environment!==null){let e=r.environment,t=e.requires;if(t!==void 0&&!Array.isArray(t))return{ok:!1,reason:`工具包声明的依赖列表格式不对(requires 必须是数组)。`};if(Array.isArray(t)){for(let e of t)if(typeof e!=`string`||!PO.test(e.trim()))return{ok:!1,reason:`依赖必须钉死到精确版本(写成 pkg==version):${String(e).slice(0,60)}。`}}let n=e.fingerprint&&typeof e.fingerprint==`object`?e.fingerprint:void 0;f={requiresPython:typeof e.requiresPython==`string`?e.requiresPython:void 0,requires:Array.isArray(t)?t.map(e=>String(e).trim()):void 0,fingerprint:n}}let p=r.permissions&&typeof r.permissions==`object`&&r.permissions.llm===!0?{llm:!0}:void 0;return{ok:!0,unnamedFormat:a===void 0,bundle:{...a===void 0?{}:{format:a},...typeof r.version==`number`?{version:r.version}:{},...typeof r.exportedAt==`string`?{exportedAt:r.exportedAt}:{},slug:o,name:s,...i?{glyph:i}:{},...typeof r.description==`string`&&r.description.trim()?{description:r.description.trim().slice(0,500)}:{},entrypoint:u,files:c,script:d,environment:f,...p?{permissions:p}:{}}}}function IO(e){let t=e.trim().toLowerCase();return t?NO.test(t)?{ok:!0,slug:t}:{ok:!1,reason:`slug 只能用小写字母、数字和连字符,且要以字母或数字开头。`}:{ok:!1,reason:`请填写 slug(工具的短名字,只能用小写字母、数字和连字符)。`}}function LO(e,t){let n=e.trim().toLowerCase().slice(0,60).replace(/[^a-z0-9-]+/g,`-`).replace(/^-+|-+$/g,``)||`tool`;if(!t.includes(n))return n;for(let e=2;e<100;e+=1){let r=`${n}-${e}`;if(!t.includes(r))return r}return n}function RO(e){return`${e.slug}${jO}`}function zO(e){let t=e.trim().replace(/[\\/:*?"<>|]/g,``).replace(/\.+$/,``).trim();return t?t.length>80?{ok:!1,reason:`文件名太长了,请控制在 80 个字符以内。`}:{ok:!0,name:t.endsWith(`.super-pi-tool.json`)?t:`${t}${jO}`}:{ok:!1,reason:`请填写文件名。`}}function BO(e){if(e.permissions?.llm)return{tone:`warn`,text:`这个工具可以调用模型:它能把内容发给你的模型回答,每次调用都会用你的模型额度`}}function VO(e){let t=e.environment?.requires??[];return!e.script&&t.length===0?{tone:`ok`,text:`纯页面工具 · 导入即用,不需要 Python`}:t.length===0?{tone:`ok`,text:`只用 Python 标准库 · 导入即用,不需要安装任何包${e.environment?.requiresPython?`(需要 Python ${e.environment.requiresPython})`:``}`}:{tone:`warn`,text:`首次运行时会安装 ${t.length} 个依赖:${t.join(`、`)}(装进这个工具自己的虚拟环境)${e.environment?.requiresPython?` · 需要 Python ${e.environment.requiresPython}`:``}`}}function HO(e){if(e)return e.state===`zero-deps`?{text:`零依赖`,warn:!1}:e.state===`ready`?{text:`环境就绪`,warn:!1}:e.state===`needs-env`?{text:`首次运行时安装依赖`,warn:!1}:e.state===`needs-python`?{text:`缺少可用的 Python`,warn:!0}:{text:`与导出方环境不一致`,warn:!0}}function UO(e){return e<1024?`${e} B`:e<1048576?`${(e/1024).toFixed(1)} KB`:`${(e/1048576).toFixed(1)} MB`}function WO(e,t){let{format:n,version:r,exportedAt:i,...a}=e;return{...a,slug:t}}var GO=`请基于上面的请求、已输出的内容和已完成的操作继续完成任务。优先给出简洁结论或执行必要的小步骤,不要重复已有内容或已成功的写入。`;function KO(e){return/^\s*<continue_output>([\s\S]*?)<\/continue_output>\s*$/.exec(e)?.[1].trim()}function qO(e){return!Number.isFinite(e)||e<=0?``:e>=1e6?`${Math.round(e/1e6)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function JO(e){return!Number.isFinite(e)||e<=0?``:e>=1e6?`${Math.round(e/1e6)}M`:e>=1e3?`${Math.round(e/1e3)}K`:String(e)}function YO(e,t){if(!e)return 0;let n=0;for(let r of t)n+=e[r]??0;return n}var XO=128e3;function ZO(e){let t=[[]],n=0,r=0,i=[0,0],a=e=>{for(;t.length<=e;)t.push([])},o=e=>{let i=t[n];for(;i.length<r;)i.push(` `);for(let t of e)i[r]=t,r+=1},s=e=>e.replace(/^[?>!]/u,``).split(`;`).map(e=>Number.parseInt(e,10)||0),c=(e,o)=>{let c=s(e),l=Math.max(1,c[0]||1);switch(o){case`A`:n=Math.max(0,n-l);break;case`B`:case`e`:n+=l,a(n);break;case`C`:case`a`:r+=l;break;case`D`:r=Math.max(0,r-l);break;case`E`:n+=l,a(n),r=0;break;case`F`:n=Math.max(0,n-l),r=0;break;case`G`:case"`":r=Math.max(0,l-1);break;case`d`:n=Math.max(0,l-1),a(n);break;case`H`:case`f`:n=Math.max(0,l-1),a(n),r=Math.max(0,(c[1]||1)-1);break;case`K`:{let e=t[n];(c[0]??0)===2?t[n]=[]:(c[0]??0)===1?t[n]=[...Array.from({length:Math.min(r+1,e.length)},()=>` `),...e.slice(r+1)]:e.splice(r);break}case`J`:(c[0]??0)===2||(c[0]??0)===3?(t.splice(0,t.length,[]),n=0,r=0):(c[0]??0)===0?t.splice(n+1):(c[0]??0)===1&&(t.splice(0,n),n=0,t[0]=[]);break;case`s`:i=[n,r];break;case`u`:[n,r]=i,a(n);break;case`P`:t[n].splice(r,l);break;case`X`:{let e=t[n];for(let t=r;t<Math.min(e.length,r+l);t+=1)e[t]=` `;break}case`@`:t[n].splice(r,0,...Array.from({length:l},()=>` `))}},l=t=>{for(let n=t;n<e.length;n+=1){if(e[n]===`\x07`)return n+1;if(e[n]===`\x1B`&&e[n+1]===`\\`)return n+2}return e.length};for(let t=0;t<e.length;){let i=e[t];if(i===``||i===``||i===``||i===``){t=l(t+1);continue}if(i===`\x1B`||i===``){let n=e[t+1];if(i===`\x1B`&&(n===`]`||n===`P`||n===`^`||n===`_`)){t=l(t+2);continue}if(i===`\x1B`&&n===`[`||i===``){let n=t+(i===``?1:2),r=n;for(;r<e.length&&!(e.charCodeAt(r)>=64&&e.charCodeAt(r)<=126);)r+=1;r<e.length&&c(e.slice(n,r),e[r]),t=Math.min(e.length,r+1);continue}t+=n===void 0?1:2;continue}if(i===`\r`){t+=1,r=0;continue}if(i===`
|
|
334
334
|
`){t+=1,n+=1,a(n),r=0;continue}if(i===`\b`){t+=1,r=Math.max(0,r-1);continue}if(i===` `){t+=1,o(` `.repeat(8-r%8));continue}let s=e.codePointAt(t)??0;if(s<32||s===127||s>=128&&s<=159){t+=s>65535?2:1;continue}let u=String.fromCodePoint(s);o(u),t+=u.length}return t.map(e=>e.join(``)).join(`
|
|
335
|
-
`).replace(/\n+$/u,``)}function
|
|
335
|
+
`).replace(/\n+$/u,``)}function QO(e){return[e.partialOutput??e.output,...(e.toolCalls??[]).map(e=>e.output)].filter(Boolean).join(`
|
|
336
336
|
|
|
337
|
-
`)}var YO=95e3;function XO({value:e}){return(0,m.jsx)(`div`,{className:`rsi-prose`,children:(0,m.jsx)(ep,{source:e,handoffs:!1})})}function ZO({state:e,models:t,archived:n,onAction:r,onClose:i,extra:a,discussion:o,memoryKey:s=``}){let[c,l]=(0,p.useState)(e?.enabled!==!1),[u,d]=(0,p.useState)(e?.automaticImprovements===!0),[f,h]=(0,p.useState)(e?.prompt??``),[g,_]=(0,p.useState)(e?.model?iD(e.model):``),[v,y]=(0,p.useState)(!1),[b,x]=(0,p.useState)(``),S=(e?.reports??[]).at(-1),C=b.trim()||e?.error?.trim()||(e?.status===`failed`?`本次观察失败,但服务端没有提供错误详情。请重新观察;若仍失败,请查看对应服务端日志。`:``),w=async e=>{if(!v){y(!0),x(``);try{await r(e)}catch(e){x(e instanceof Error?e.message:`RSI 操作失败`)}finally{y(!1)}}};return(0,m.jsxs)(`aside`,{className:`group-rsi-panel`,"data-group-rsi-panel":!0,"aria-label":`RSI 观察与建议`,children:[(0,m.jsxs)(`header`,{children:[(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`h3`,{children:`RSI 观察与建议`}),(0,m.jsx)(`span`,{role:`status`,children:e?.enabled===!1?`已暂停`:e?.status===`running`?`后台观察中`:e?.status===`failed`?`观察失败`:e?.status===`interrupted`?`观察已中断`:e?.pending&&e.requestedAt?`观察请求已排队`:e?.pending?`有新过程,等待更新观察`:S?`观察已更新`:`尚无观察报告`})]}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`关闭 RSI 面板`,onClick:i,children:`关闭`})]}),(0,m.jsxs)(`div`,{className:`group-rsi-body`,children:[(0,m.jsx)(`p`,{className:`rsi-intro`,children:`观察任务效率和交付质量。通用缺口归平台,企业专用能力在用户侧开发、验证并复用。`}),!n&&(0,m.jsx)(`button`,{type:`button`,"data-rsi-refresh":!0,disabled:v||e?.status===`running`||e?.enabled===!1||!!(e?.pending&&e.requestedAt),onClick:()=>void w({action:`rsi.refresh`}),children:v?`正在提交…`:e?.status===`running`?`正在观察…`:e?.pending&&e.requestedAt?`已排队`:`更新观察`}),e?.notice&&(0,m.jsx)(`p`,{role:`status`,"data-rsi-notice":!0,children:e.notice}),!S&&!e?.notice&&e?.status!==`running`&&(0,m.jsx)(`p`,{"data-rsi-empty":!0,children:`尚无报告。更新观察后,这里会显示任务效率、工具缺口、证据及改进建议。`}),C&&(0,m.jsx)(`p`,{role:`alert`,"data-rsi-error":!0,children:C}),S&&(0,m.jsxs)(`section`,{"data-rsi-report":S.id,children:[(0,m.jsxs)(`div`,{className:`rsi-report-meta`,children:[(0,m.jsxs)(`span`,{children:[S.observedMessages,` / `,S.totalMessages,` 条发言`]}),S.model&&(0,m.jsx)(`span`,{title:`观察模型`,children:S.model.label||S.model.modelId})]}),(0,m.jsxs)(`section`,{className:`rsi-overview`,"data-rsi-overview":!0,children:[(0,m.jsx)(`h4`,{children:`核心摘要`}),(0,m.jsx)(XO,{value:S.summary})]}),!n&&(0,m.jsx)(`button`,{type:`button`,"data-rsi-discuss-report":!0,disabled:v,onClick:()=>void w({action:`rsi.repair.discuss`,reportId:S.id}),children:o?`结合最新观察继续讨论`:`讨论整体改进`}),(S.compressed||S.retrospective||!!S.artifactReads?.length||!!S.runEvidence?.length)&&(0,m.jsxs)(`details`,{className:`rsi-detail`,"data-rsi-evidence":!0,children:[(0,m.jsx)(`summary`,{children:`观察范围与过程`}),S.compressed&&(0,m.jsx)(`p`,{className:`group-rsi-coverage`,children:`部分历史或执行摘要已压缩;结论仅基于已覆盖过程。`}),S.retrospective&&(0,m.jsx)(XO,{value:S.retrospective}),!!S.artifactReads?.length&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`h5`,{children:`实际读取的产物`}),(0,m.jsx)(`ul`,{children:S.artifactReads.map((e,t)=>(0,m.jsx)(`li`,{children:e},t))})]}),!!S.runEvidence?.length&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`h5`,{children:`实际运行用时(含工具及等人)`}),(0,m.jsx)(`ul`,{children:S.runEvidence.map((e,t)=>(0,m.jsxs)(`li`,{children:[Math.round(e.elapsedMs/1e3),` 秒 · `,new Date(e.finishedAt).toLocaleTimeString()]},t))}),(0,m.jsx)(`p`,{children:`完整运行用时不等同于模型思考耗时。`})]})]}),!!S.findings.length&&(0,m.jsxs)(`section`,{className:`rsi-analysis`,"aria-label":`详细分析`,children:[(0,m.jsxs)(`h4`,{children:[`详细分析 `,(0,m.jsx)(`span`,{children:S.findings.length})]}),S.findings.map(e=>(0,m.jsxs)(`details`,{className:`rsi-analysis-item`,"data-rsi-finding":e.id,children:[(0,m.jsx)(`summary`,{children:e.title||e.observation.split(/[。\n]/u)[0].slice(0,70)}),(0,m.jsxs)(`div`,{className:`rsi-analysis-body`,children:[(0,m.jsx)(XO,{value:e.observation}),(0,m.jsx)(`h5`,{children:`改进方向`}),(0,m.jsx)(XO,{value:e.recommendation}),(0,m.jsxs)(`p`,{"data-rsi-ownership":e.ownership??`unclassified`,children:[(0,m.jsx)(`strong`,{children:{platform:`平台通用能力`,user:`用户专用能力`,mixed:`通用底座与专用适配需拆分`,unclassified:`归属待澄清`}[e.ownership??`unclassified`]}),e.ownershipReason&&` · ${e.ownershipReason}`]}),(0,m.jsx)(`h5`,{children:`适用与验证`}),(0,m.jsx)(XO,{value:`${e.applicability}\n\n${e.verification}`}),e.evidence.map((e,t)=>(0,m.jsxs)(`blockquote`,{children:[e.quote,(0,m.jsx)(`button`,{type:`button`,onClick:()=>{[...document.querySelectorAll(`[data-group-post-id],[data-transcript-key]`)].find(t=>t.dataset.groupPostId===e.messageId||t.dataset.transcriptKey===`m:${e.messageId}`)?.scrollIntoView({block:`center`,behavior:`smooth`})},children:`定位原消息`})]},t)),e.feedback&&(0,m.jsxs)(`p`,{children:[`此前反馈:`,e.feedback]})]})]},e.id))]})]}),o,a,!n&&(0,m.jsxs)(`details`,{className:`group-rsi-settings`,children:[(0,m.jsx)(`summary`,{children:`RSI 设置`}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:c,onChange:e=>l(e.target.checked)}),`启用整体观察`]}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:u,onChange:e=>d(e.target.checked)}),`预先授权自动开发符合条件的用户专用能力`]}),(0,m.jsx)(`p`,{children:`默认在统一讨论中确认方案并授权。勾选上项会预先授权符合条件的用户专用 tool / skill 开发;普通修复仍需确认方案。`}),(0,m.jsx)(`p`,{children:`新对话先积累为观察材料,不逐轮生成报告。点击更新观察会重新综合当前整体情况,并产生独立模型请求与费用;当前任务仍在执行时等待结束。每次最多 90 秒、12 次只读检查;同一工作区同时最多一个能力开发,预算十分钟。未指定模型时跟随来源会话、主持人或工作区。`}),(0,m.jsx)(aD,{value:g,models:t,label:`RSI 模型`,inheritLabel:`跟随会话 / 主持人 / 工作区模型`,onChange:_}),(0,m.jsxs)(`label`,{children:[`补充观察要求`,(0,m.jsx)(`textarea`,{"aria-label":`RSI 补充要求`,value:f,onChange:e=>h(e.target.value),maxLength:8e3})]}),(0,m.jsx)(`button`,{type:`button`,"data-rsi-save":!0,disabled:v,onClick:()=>void w({action:`rsi.configure`,enabled:c,automaticImprovements:u,model:t.find(e=>iD(e)===g)??null,prompt:f}),children:`保存 RSI 设置`})]})]})]})}function QO(e){try{return JSON.parse(Gn(`super-pi.rsi-view.v1:${e}`)??`null`)}catch{return null}}function $O(e,t){try{Kn(`super-pi.rsi-view.v1:${e}`,JSON.stringify(t))}catch{}}function ek(e){let t=QO(e);return t&&typeof t==`object`&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,e])=>typeof e==`string`&&e.length<=16e3)):{}}function tk(e){let t=QO(e);return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>e&&typeof e.text==`string`&&e.text.length<=16e3&&(e.revision===void 0||typeof e.revision==`string`)))}var nk={discussing:`讨论方案`,implementing:`实施中`,review:`待你验收`,completed:`已验收`,failed:`执行失败`,interrupted:`已中断`,cancelled:`已取消`};function rk({repairs:e,archived:t,onAction:n,memoryKey:r}){let i=e.find(e=>e.status===`implementing`||e.status===`review`)??e.at(-1),[a,o]=(0,p.useState)(()=>ek(r+`:drafts`)),[s,c]=(0,p.useState)(()=>tk(r+`:plans`));(0,p.useEffect)(()=>$O(r+`:drafts`,a),[r,a]),(0,p.useEffect)(()=>$O(r+`:plans`,s),[r,s]);let[l,u]=(0,p.useState)(!1),[d,f]=(0,p.useState)(``),h=(0,p.useRef)(null),g=(0,p.useRef)(null),_=(0,p.useRef)(!0),v=(0,p.useRef)(``);(0,p.useLayoutEffect)(()=>{v.current!==i?.id&&(_.current=!0,v.current=i?.id??``),g.current&&_.current&&(g.current.scrollTop=g.current.scrollHeight)},[i?.id,i?.messages.length,i?.messages.at(-1)?.content]);let y=(0,p.useRef)(e.length);if((0,p.useEffect)(()=>{e.length>y.current&&(h.current?.closest(`[data-rsi-discussion]`)?.scrollIntoView({block:`start`}),h.current?.focus({preventScroll:!0})),y.current=e.length},[e]),!i)return null;let b=a[i.id]??``,x=s[i.id]??{text:i.proposedPlan??``,revision:i.revision},S=!t&&!i.busy&&!l&&i.status!==`implementing`,C=S&&i.status===`discussing`&&!!i.revision&&x.revision===i.revision&&!!x.text.trim(),w=async e=>{if(!l){u(!0),f(``);try{return await n({...e,repairId:i.id}),!0}catch(e){return f(e instanceof Error?e.message:`RSI 操作未完成`),!1}finally{u(!1)}}},T=async()=>{if(!b.trim()||!S)return;let e=b,t=i.id;if(!await w({action:`rsi.repair.send`,message:e}))return;let n=ek(r+`:drafts`);n[t]===e&&(n[t]=``,$O(r+`:drafts`,n)),o(n=>n[t]===e?{...n,[t]:``}:n)};return(0,m.jsxs)(`section`,{className:`rsi-repair`,"data-rsi-discussion":!0,"aria-label":`RSI 讨论与修复`,children:[(0,m.jsxs)(`header`,{children:[(0,m.jsx)(`h4`,{children:`讨论与修复`}),(0,m.jsx)(`span`,{role:`status`,"data-rsi-repair-status":!0,children:i.busy&&i.status===`discussing`?`正在准备方案…`:nk[i.status]})]}),(0,m.jsxs)(`p`,{className:`rsi-repair-record`,children:[`整体改进讨论 · `,nk[i.status]]}),(0,m.jsx)(`p`,{className:`rsi-repair-hint`,children:`讨论阶段只读。确认下面的实施范围并授权后,才会开始修改。`}),(0,m.jsxs)(`div`,{ref:g,className:`rsi-repair-thread`,role:`log`,"aria-label":`RSI 讨论消息`,"aria-live":`polite`,onScroll:e=>{let t=e.currentTarget;_.current=t.scrollHeight-t.scrollTop-t.clientHeight<32},children:[!i.messages.length&&(0,m.jsx)(`p`,{children:`正在核对建议并准备讨论方案…`}),i.messages.map(e=>(0,m.jsxs)(`article`,{"data-rsi-discussion-role":e.role,children:[(0,m.jsx)(`strong`,{children:e.role===`user`?`你`:`RSI`}),(0,m.jsx)(ep,{source:e.content,handoffs:!1})]},e.id))]}),(d||i.error)&&(0,m.jsx)(`p`,{role:`alert`,children:d||i.error}),!t&&![`implementing`,`completed`,`cancelled`].includes(i.status)&&(0,m.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),T()},children:[(0,m.jsxs)(`label`,{children:[`继续讨论`,(0,m.jsx)(`textarea`,{ref:h,"aria-label":`与 RSI 讨论方案`,value:b,maxLength:12e3,placeholder:`补充约束、询问原因,或修改实施方案…`,onChange:e=>o(t=>({...t,[i.id]:e.target.value}))})]}),(0,m.jsx)(`button`,{type:`submit`,disabled:!S||!b.trim(),children:`发送讨论`})]}),i.status===`discussing`&&(0,m.jsxs)(`section`,{className:`rsi-repair-approval`,"aria-label":`授权实施方案`,children:[(0,m.jsx)(`h5`,{children:`确认实施范围与验收要求`}),(0,m.jsx)(`textarea`,{"aria-label":`RSI 实施范围与验收要求`,value:x.text,disabled:i.busy||l||t,maxLength:16e3,placeholder:`RSI 回复后可在这里检查或调整最终方案`,onChange:e=>c(t=>({...t,[i.id]:{text:e.target.value,revision:x.revision}}))}),x.revision!==i.revision&&(0,m.jsx)(`p`,{role:`status`,children:`讨论已有新回复,请重新核对最新方案。`}),i.revision&&(0,m.jsx)(`button`,{type:`button`,disabled:l||i.busy||t,onClick:()=>c(e=>({...e,[i.id]:{text:i.proposedPlan??``,revision:i.revision}})),children:`使用最新讨论方案`}),(0,m.jsx)(`button`,{type:`button`,className:`rsi-repair-primary`,"data-rsi-authorize":!0,disabled:!C,onClick:()=>void w({action:`rsi.repair.approve`,revision:x.revision,plan:x.text,confirmed:!0}),children:`授权实施此方案`}),(0,m.jsx)(`small`,{children:`授权只覆盖这份方案;不会自动提交、推送或发布。执行结束后仍需你验收。`})]}),i.approvedPlan&&(0,m.jsxs)(`details`,{children:[(0,m.jsx)(`summary`,{children:`查看本次授权范围`}),(0,m.jsx)(ep,{source:i.approvedPlan,handoffs:!1})]}),(0,m.jsxs)(`div`,{className:`rsi-repair-actions`,children:[(0,m.jsx)(`button`,{type:`button`,onClick:()=>window.dispatchEvent(new CustomEvent(`super-pi-open-rsi-work`,{detail:i.conversationId})),children:`查看完整执行过程`}),i.status===`review`&&!t&&(0,m.jsx)(`button`,{type:`button`,disabled:l||i.busy,onClick:()=>void w({action:`rsi.repair.accept`}),children:`验收通过`}),![`completed`,`cancelled`].includes(i.status)&&(0,m.jsx)(`button`,{type:`button`,disabled:l,onClick:()=>void w({action:`rsi.repair.cancel`}),children:i.busy?`停止本次处理`:`取消此项改进`})]})]})}function ik({source:e,models:t,archived:n=!1,visible:r=!0,onClose:i}){let[a,o]=(0,p.useState)(),[s,c]=(0,p.useState)(``),l=`/api/rsi?${new URLSearchParams({kind:e.kind,workspaceId:e.workspaceId,id:e.id})}`,u=(0,p.useRef)(0),d=(0,p.useRef)(0),f=(0,p.useRef)(l);f.current=l,(0,p.useEffect)(()=>{if(!r)return;let e=!1,t=new AbortController,n=async()=>{if(d.current)return;let n=u.current;try{let r=await Ie(l,{signal:t.signal}),i=await r.json();if(!r.ok)throw Error(i.error??`RSI 暂时不可用。`);!e&&n===u.current&&(o(i),c(``))}catch(t){!e&&n===u.current&&c(t instanceof Error?t.message:String(t))}};n();let i=setInterval(()=>{document.visibilityState===`visible`&&n()},3e3);return()=>{e=!0,t.abort(),clearInterval(i)}},[l,r]);let h=async e=>{let t=++u.current;d.current++;try{let n=await Ie(l,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)}),r=await n.json();if(!n.ok)throw Error(r.error??`RSI 操作失败。`);f.current===l&&t===u.current&&o(r)}finally{d.current--}};return a?(0,m.jsx)(ZO,{memoryKey:l,state:a?.state,models:t,archived:n,onClose:i,onAction:h,discussion:a.repairs?.length?(0,m.jsx)(rk,{memoryKey:l,repairs:a.repairs,archived:n,onAction:h}):void 0,extra:(0,m.jsxs)(m.Fragment,{children:[s&&(0,m.jsx)(`p`,{role:`alert`,children:s}),(!!a.improvements.length||!!a.usage.length)&&(0,m.jsxs)(`details`,{className:`rsi-work`,"data-rsi-work":!0,children:[(0,m.jsx)(`summary`,{children:`能力执行与复用记录`}),a?.improvements.map(e=>(0,m.jsxs)(`article`,{"data-rsi-job":e.id,children:[(0,m.jsxs)(`h5`,{children:[e.name,` · `,{queued:`等待开发`,running:`开发与验证中`,available:`已注册可用 · 收益待验证`,failed:`开发未通过`,interrupted:`已中断`,cancelled:`已取消`}[e.status]]}),(0,m.jsxs)(`p`,{children:[e.slug,e.version?` · v${e.version}`:``]}),e.error&&(0,m.jsx)(`p`,{role:`alert`,children:e.error}),e.conversationId&&(0,m.jsx)(`button`,{type:`button`,"data-rsi-open-work":e.id,onClick:()=>{window.dispatchEvent(new CustomEvent(`super-pi-open-rsi-work`,{detail:e.conversationId})),i()},children:`查看开发过程`}),[`running`,`queued`].includes(e.status)&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>void h({action:`rsi.cancel`,jobId:e.id}).catch(e=>c(String(e))),children:`取消改进`})]},e.id)),!!a?.usage.length&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`h4`,{children:`实际复用记录`}),(0,m.jsx)(`ul`,{children:a.usage.slice(-8).reverse().map((e,t)=>(0,m.jsxs)(`li`,{children:[e.slug,` v`,e.version,` · `,e.status,` · `,e.durationMs,` ms`]},t))}),(0,m.jsx)(`p`,{children:`调用成功仅表示执行成功,不能单独证明整个任务更快或质量更好。`})]})]})]})},l):(0,m.jsxs)(`aside`,{className:`group-rsi-panel`,"data-group-rsi-panel":!0,children:[(0,m.jsxs)(`header`,{children:[(0,m.jsx)(`h3`,{children:`RSI 观察与建议`}),(0,m.jsx)(`button`,{type:`button`,onClick:i,children:`关闭`})]}),(0,m.jsx)(`div`,{className:`group-rsi-body`,children:(0,m.jsx)(`p`,{role:s?`alert`:`status`,children:s||`正在读取观察与能力改进记录…`})})]})}function ak({id:e,expanded:t,onClick:n}){return(0,m.jsx)(`button`,{type:`button`,"data-session-rsi":e,"aria-expanded":t,title:`在侧栏打开 RSI:任务效率与能力改进`,onClick:n,children:`RSI`})}function ok({context:e,models:t,onClose:n}){let{visible:r}=ki(`rsi`);return e?(0,m.jsxs)(`div`,{className:`rsi-sidebar-panel`,"data-rsi-sidebar-source":e.source.id,"data-rsi-sidebar-kind":e.source.kind,children:[(0,m.jsxs)(`div`,{className:`rsi-sidebar-context`,children:[(0,m.jsx)(`span`,{children:e.source.kind===`group`?`群聊`:`会话`}),(0,m.jsx)(`strong`,{title:e.title,children:e.title}),e.archived&&(0,m.jsx)(`small`,{children:`已归档 · 仅查看`})]}),(0,m.jsx)(ik,{visible:r,source:e.source,models:t,archived:e.archived,onClose:n},JSON.stringify(e.source))]}):(0,m.jsxs)(`div`,{className:`rsi-sidebar-empty`,"data-rsi-sidebar-empty":!0,children:[(0,m.jsx)(`h3`,{children:`选择观察来源`}),(0,m.jsx)(`p`,{children:`打开一个会话或群聊,在这里查看观察、讨论改进并授权修复。`}),(0,m.jsx)(`p`,{children:`切换文件、Git 或终端不会取消已开始的观察和修复。`})]})}function sk(e){let t=`归档整棵会话树「${e.title}」?本次将归档 ${e.activeCount} 个会话(1 个根会话和 ${e.activeDescendants} 个活跃子孙)${e.alreadyArchived?`,跳过 ${e.alreadyArchived} 个已归档子孙`:``};恢复根会话时,整棵树会一起恢复。`;return e.pendingDecisions>0?`${t}\n还有 ${e.pendingDecisions} 个未拍板的决策,归档后它们会作废。`:t}function ck(e){return e.activeDescendants>0||e.pendingDecisions>0}var lk={workspaces:[],conversations:[],subagentRuns:[]},uk=e=>e.nativeEvent.isComposing||e.keyCode===229,dk=(e,t,n)=>{let r=e.filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),i=r.findIndex(e=>e.id===t);if(i<0||r[i].delivery===`sending`)return e;let a=r.reduce((e,t,n)=>t.delivery===`sending`?n:e,-1),o=Math.max(a+1,Math.min(n,r.length-1));if(o===i)return e;let s=[...r],[c]=s.splice(i,1);s.splice(o,0,c);let l=[...e],u=0;for(let e=0;e<l.length;e+=1)(l[e].role===`user`||l[e].role===`tool`)&&l[e].delivery&&(l[e]=s[u++]);return l},fk=(e,t)=>{for(let n=e.length-1;n>=0;--n)if(e[n].at===t)return n;return-1},pk=(e,t,n)=>{if(t===void 0)return fk(e,n);let r=e.findIndex(e=>e.blockIndex===t);if(r>=0)return r;let i=e.findIndex(e=>e.blockIndex!==void 0);if(i<0)return fk(e,n);let a=t-((e[i].blockIndex??0)-i);return a>=0&&a<e.length?a:-1},mk=(e,t,n)=>{let r=t.at??n,i=[...e],a=pk(i,t.blockIndex,r);return a>=0?i[a]={...i[a],text:i[a].text+t.delta,blockIndex:t.blockIndex??i[a].blockIndex}:i.push({at:r,text:t.delta,blockIndex:t.blockIndex}),i},hk=(e,t)=>{let n=e??[],r=t??[];return r.length>n.length?r:e},gk=e=>{if(typeof e!=`string`||e.length===0)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(`zh-CN`,{hour:`2-digit`,minute:`2-digit`}).format(t)},_k=6e4,vk=60*_k,yk=24*vk,bk=7*yk,xk=30*yk,Sk=365*yk,Ck=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<vk?`${Math.max(1,Math.floor(r/_k))}m ago`:r<yk?`${Math.floor(r/vk)}h ago`:r<bk?`${Math.floor(r/yk)}d ago`:r<xk?`${Math.floor(r/bk)}w ago`:r<Sk?`${Math.floor(r/xk)}mo ago`:`${Math.floor(r/Sk)}y ago`},wk=(e,t)=>{let n=e.find(e=>e.id===t);if(!n)return[];let r=new Map;for(let t of e){if(t.workspaceId!==n.workspaceId||!t.parentConversationId)continue;let e=r.get(t.parentConversationId);e?e.push(t):r.set(t.parentConversationId,[t])}let i=[],a=new Set,o=e=>{if(!a.has(e.id)){a.add(e.id),i.push(e);for(let t of r.get(e.id)??[])o(t)}};return o(n),i},Tk=e=>{if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`};function Ek({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,p.useRef)(null),[o,s]=(0,p.useState)({left:t,top:n});(0,p.useLayoutEffect)(()=>{let e=a.current;if(!e)return;let r=e.getBoundingClientRect();s({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),i())},t=e=>{a.current?.contains(e.target)||i()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&i()},o=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&i()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,o),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,r,!0),window.removeEventListener(`resize`,o)}},[i]);let c=async()=>{let t=await Hi(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,m.jsxs)(`div`,{ref:a,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-workspace-id":e.id,style:{left:o.left,top:o.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,m.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function Dk({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a,sendCommand:o,orchestrated:s,childCount:c}){let l=(0,p.useRef)(null),[u,d]=(0,p.useState)({left:t,top:n});(0,p.useLayoutEffect)(()=>{let e=l.current;if(!e)return;let r=e.getBoundingClientRect();d({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),a())},t=e=>{l.current?.contains(e.target)||a()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&a()},i=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&a()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,i),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,r,!0),window.removeEventListener(`resize`,i)}},[a]);let f=async e=>{try{let t=await Ie(`/api/orchestrator/stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`,conversationId:e,mode:`all`})}),n=await t.json();if(!t.ok)throw Error(n.error);r(`已停止会话(含排队消息)`,`info`)}catch(e){r(`停止失败:${zr(e)}`,`error`)}},h=async e=>{try{let t=await Ie(`/api/orchestrator/stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`,conversationId:e,mode:`all`,subtree:!0})}),n=await t.json();if(!t.ok)throw Error(n.error);let i=typeof n.descendantCount==`number`?n.descendantCount:0;r(i>0?`已停止会话及其下属 ${i} 个`:`已停止会话(它没有下属会话)`,`info`)}catch(e){r(`停止子树失败:${zr(e)}`,`error`)}},g=async()=>{let t=await Hi(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,m.jsxs)(`div`,{ref:l,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:u.left,top:u.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void g(),children:`复制会话 ID`}),(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),![`running`,`waiting`,`awaiting_background`].includes(e.status)&&(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-save-warm-session":e.id,onClick:()=>{a();let t=window.prompt(`保存为当前工作区的预热会话。以后选用时会带上当前对话历史。`,e.title)?.trim();t&&!o({type:`conversation.warm.save`,conversationId:e.id,title:t})&&r(`连接断开,未保存预热会话`,`error`)},children:`保存为预热会话`}),(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-stop-turn-session":e.id,onClick:()=>{a(),o({type:`run.stop`,conversationId:e.id})},children:`停止当前回合`}),s&&(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-queue":e.id,onClick:()=>{a(),f(e.id)},children:`停止会话(含排队消息)`}),c>0&&(0,m.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-tree":e.id,onClick:()=>{a(),h(e.id)},children:[`停止整棵子树(`,c,` 个下属)`]}),(0,m.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var Ok={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},kk=VO,Ak={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},jk={model:`没有可用的模型`,thinking:`Pi 没有给出当前模型的思考等级`,agent:`没有可用的智能体`,subagent:`没有可用的子智能体`},Mk={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},Nk=`图文`,Pk=e=>e.imageInput?Nk:void 0,Fk=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),Ik=(e,t)=>{let n=Fk(t.trim());return n?e.filter(e=>Fk(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function Lk({workspaceId:e,value:t,onChange:n}){let[r,i]=(0,p.useState)([]),[a,o]=(0,p.useState)(``);(0,p.useEffect)(()=>{i([]),o(``)},[e]),(0,p.useEffect)(()=>{let n=!0;return o(``),Ie(`/api/files?workspaceId=${encodeURIComponent(e)}&path=${encodeURIComponent(t)}`).then(async e=>{let r=await e.json();if(!e.ok)throw Error(r.error??`HTTP ${e.status}`);if(!n)return;let a=(r.entries??[]).filter(e=>e.kind===`directory`).map(e=>e.path);i(e=>[...new Set([...e,t,...a])].filter(Boolean).sort())}).catch(e=>{n&&o(e instanceof Error?e.message:`子目录读取失败`)}),()=>{n=!1}},[e,t]);let s=[...new Set([...r,t])].filter(Boolean).sort();return(0,m.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,m.jsx)(`label`,{htmlFor:`empty-session-cwd`,children:`工作目录:`}),(0,m.jsxs)(`select`,{id:`empty-session-cwd`,"data-session-cwd-select":`1`,"aria-label":`会话工作目录(可选)`,value:t,onChange:e=>n(e.target.value),children:[(0,m.jsx)(`option`,{value:``,children:`工作区根目录`}),s.map(e=>(0,m.jsx)(`option`,{value:e,children:e},e))]}),a&&(0,m.jsx)(`span`,{role:`status`,children:a})]})}function Rk({workspace:e,onClose:t,onCreate:n}){let[r,i]=(0,p.useState)(``),a=(0,p.useRef)(null);return(0,p.useEffect)(()=>{i(``)},[e.id]),(0,p.useEffect)(()=>{let e=a.current;e&&e.focus();let n=e=>{e.key===`Escape`&&(e.preventDefault(),t())};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[t]),(0,m.jsx)(`div`,{className:`overlay session-create-overlay`,onClick:t,children:(0,m.jsxs)(`div`,{className:`session-create-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`session-create-title`,tabIndex:-1,ref:a,onClick:e=>e.stopPropagation(),onKeyDown:e=>{if(e.key!==`Tab`)return;let t=a.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), select:not([disabled]), input:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`));if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey?document.activeElement===r&&(e.preventDefault(),i.focus()):document.activeElement===i&&(e.preventDefault(),r.focus())},children:[(0,m.jsx)(`h2`,{id:`session-create-title`,children:`新建会话`}),(0,m.jsxs)(`p`,{className:`session-create-workspace`,children:[`工作区:`,e.name,(0,m.jsx)(`small`,{children:e.path})]}),(0,m.jsx)(Lk,{workspaceId:e.id,value:r,onChange:i}),(0,m.jsxs)(`div`,{className:`session-create-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`session-create-cancel`,onClick:t,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`session-create-confirm picker-ok`,onClick:()=>n(r),children:`创建会话`})]})]})})}function zk({onClose:e,onCreate:t}){let{connections:n,activeServer:r}=pe(),i=(0,p.useRef)(0),[a,o]=(0,p.useState)(),[s,c]=(0,p.useState)(!0),[l,u]=(0,p.useState)(),[d,f]=(0,p.useState)(``),[h,g]=(0,p.useState)(``),[_,v]=(0,p.useState)(!1),y=async(e,t)=>{let n=++i.current;t===void 0&&v(!1),c(!0),u(void 0);try{let a=new URLSearchParams;e&&a.set(`path`,e),t!==void 0&&a.set(`prefix`,t);let s=await Ie(`/api/fs/dirs?${a}`,{},r),c=await s.json();if(!s.ok)throw Error(c.error??`HTTP ${s.status}`);if(n!==i.current)return;let l=c;o(l),t===void 0&&(g(l.path),f(l.suggestedName),v(!1))}catch(e){n===i.current&&u(e instanceof Error?e.message:`目录加载失败`)}finally{n===i.current&&c(!1)}};(0,p.useEffect)(()=>{o(void 0),g(``),y()},[r]),(0,p.useEffect)(()=>{if(!_||!a)return;let e=br(h,a.path),t=window.setTimeout(()=>{y(e.path,e.prefix)},180);return()=>{window.clearTimeout(t)}},[h,_,r]),(0,p.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let b=e=>{e?.preventDefault();let t=h.trim();t&&y(t)};return(0,m.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,m.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,m.jsx)(`h2`,{children:`选择工作区目录`}),(0,m.jsxs)(`label`,{className:`server-settings-scope`,children:[`目标服务器`,(0,m.jsx)(`select`,{"aria-label":`新建工作区的服务器`,value:r,onChange:e=>xe(e.target.value),children:n.filter(e=>e.enabled).map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id))})]}),(0,m.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:b,children:[(0,m.jsx)(`input`,{className:`picker-path-input`,value:h,onChange:e=>{i.current++,c(!0),g(e.target.value),v(!0)},"aria-label":`工作区目录路径`,onKeyDown:e=>{e.key===`Tab`&&!e.shiftKey&&!e.nativeEvent.isComposing&&_&&!s&&a?.entries.length===1?(e.preventDefault(),y(a.entries[0].path)):e.key===`Enter`&&(uk(e)?e.preventDefault():(e.preventDefault(),b()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,m.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!h.trim(),children:`跳转`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!a?.parent||s,onClick:()=>a?.parent&&void y(a.parent),title:`返回上一级目录`,children:`上一级`})]}),a?.drives?.length||a?.homeDir?(0,m.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,m.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),a?.homeDir&&(0,m.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void y(`~`),title:a.homeDir,children:`🏠 主目录`}),a?.drives?.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void y(e),children:e},e))]}):null,(0,m.jsxs)(`div`,{className:`picker-list`,children:[s&&(0,m.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!s&&l&&(0,m.jsxs)(`div`,{className:`picker-error`,children:[l,(0,m.jsx)(`button`,{onClick:()=>void y(a?.path||h),children:`重试`})]}),!s&&!l&&a?.entries.map(e=>(0,m.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void y(e.path),children:[`📁 `,e.name]},e.path)),!s&&!l&&a&&a.entries.length===0&&(0,m.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!s&&!l&&a?.truncated&&(0,m.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,m.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,m.jsx)(`input`,{value:d,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(uk(e)?e.preventDefault():(e.preventDefault(),d.trim()&&a&&!_&&!s&&!l&&t(d.trim(),a.path)))},placeholder:`工作区名称`})]}),(0,m.jsxs)(`div`,{className:`picker-actions`,children:[(0,m.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,m.jsx)(`button`,{className:`picker-ok`,disabled:!d.trim()||s||!!l||!a||_,onClick:()=>a&&t(d.trim(),a.path),children:`使用这个目录`})]})]})})}var Bk={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},Vk=10;function Hk(e,t,n=!1){if(!t)return`正在从 Pi 读取${e}列表…`;if(t.source!==`pi`)return`读取 Pi ${e}列表失败:${t.error??`未知原因`}`;if(t.configError)return`Pi 拒绝了自己的模型配置,文件里的自定义供应商都没有被提供:${t.configError.split(`
|
|
338
|
-
`).find(e=>e.trim().startsWith(`-`))?.trim()??`详情见设置`}`;if(e===`模型`&&n)return`此会话已包含图片,仅显示支持图文的模型`;if(e===`思考等级`&&!t.levels.length)return`Pi 没有给出当前模型的思考等级`}function
|
|
337
|
+
`)}var $O=95e3;function ek({value:e}){return(0,m.jsx)(`div`,{className:`rsi-prose`,children:(0,m.jsx)(ep,{source:e,handoffs:!1})})}function tk({state:e,models:t,inherited:n,archived:r,onAction:i,onClose:a,extra:o,discussion:s,memoryKey:c=``}){let[l,u]=(0,p.useState)(e?.enabled!==!1),[d,f]=(0,p.useState)(e?.automaticImprovements===!0),[h,g]=(0,p.useState)(e?.prompt??``),_=e?.model?cD(e.model):``,[v,y]=(0,p.useState)(!1),[b,x]=(0,p.useState)(``),S=(e?.reports??[]).at(-1),C=b.trim()||e?.error?.trim()||(e?.status===`failed`?`本次观察失败,但服务端没有提供错误详情。请重新观察;若仍失败,请查看对应服务端日志。`:``),w=async e=>{if(!v){y(!0),x(``);try{await i(e)}catch(e){x(e instanceof Error?e.message:`RSI 操作失败`)}finally{y(!1)}}};return(0,m.jsxs)(`aside`,{className:`group-rsi-panel`,"data-group-rsi-panel":!0,"aria-label":`RSI 观察与建议`,children:[(0,m.jsxs)(`header`,{children:[(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`h3`,{children:`RSI 观察与建议`}),(0,m.jsx)(`span`,{role:`status`,children:e?.enabled===!1?`已暂停`:e?.status===`running`?`后台观察中`:e?.status===`failed`?`观察失败`:e?.status===`interrupted`?`观察已中断`:e?.pending&&e.requestedAt?`观察请求已排队`:e?.pending?`有新过程,等待更新观察`:S?`观察已更新`:`尚无观察报告`})]}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`关闭 RSI 面板`,onClick:a,children:`关闭`})]}),(0,m.jsxs)(`div`,{className:`group-rsi-body`,children:[(0,m.jsx)(`p`,{className:`rsi-intro`,children:`观察任务效率和交付质量。通用缺口归平台,企业专用能力在用户侧开发、验证并复用。`}),(0,m.jsxs)(`fieldset`,{className:`rsi-model-setting`,"data-rsi-model":!0,disabled:v||r,children:[(0,m.jsx)(`legend`,{children:`观察模型`}),(0,m.jsx)(lD,{value:_,models:t,savedModel:e?.model,label:`RSI 模型`,inheritLabel:n?`跟随来源模型 · ${n.label||n.modelId}`:`跟随来源模型`,onChange:e=>{if(r||v||e===_)return;let n=t.find(t=>cD(t)===e);(!e||n)&&w({action:`rsi.model`,model:n??null})}})]}),!r&&(0,m.jsx)(`button`,{type:`button`,"data-rsi-refresh":!0,disabled:v||e?.status===`running`||e?.enabled===!1||!!(e?.pending&&e.requestedAt),onClick:()=>void w({action:`rsi.refresh`}),children:v?`正在提交…`:e?.status===`running`?`正在观察…`:e?.pending&&e.requestedAt?`已排队`:`更新观察`}),e?.notice&&(0,m.jsx)(`p`,{role:`status`,"data-rsi-notice":!0,children:e.notice}),!S&&!e?.notice&&e?.status!==`running`&&(0,m.jsx)(`p`,{"data-rsi-empty":!0,children:`尚无报告。更新观察后,这里会显示任务效率、工具缺口、证据及改进建议。`}),C&&(0,m.jsx)(`p`,{role:`alert`,"data-rsi-error":!0,children:C}),S&&(0,m.jsxs)(`section`,{"data-rsi-report":S.id,children:[(0,m.jsxs)(`div`,{className:`rsi-report-meta`,children:[(0,m.jsxs)(`span`,{children:[S.observedMessages,` / `,S.totalMessages,` 条发言`]}),S.model&&(0,m.jsx)(`span`,{title:`本次观察实际使用 ${S.model.provider} / ${S.model.modelId}`,children:S.model.label||S.model.modelId})]}),(0,m.jsxs)(`section`,{className:`rsi-overview`,"data-rsi-overview":!0,children:[(0,m.jsx)(`h4`,{children:`核心摘要`}),(0,m.jsx)(ek,{value:S.summary})]}),!r&&(0,m.jsx)(`button`,{type:`button`,"data-rsi-discuss-report":!0,disabled:v,onClick:()=>void w({action:`rsi.repair.discuss`,reportId:S.id}),children:s?`结合最新观察继续讨论`:`讨论整体改进`}),(S.compressed||S.retrospective||!!S.artifactReads?.length||!!S.runEvidence?.length)&&(0,m.jsxs)(`details`,{className:`rsi-detail`,"data-rsi-evidence":!0,children:[(0,m.jsx)(`summary`,{children:`观察范围与过程`}),S.compressed&&(0,m.jsx)(`p`,{className:`group-rsi-coverage`,children:`部分历史或执行摘要已压缩;结论仅基于已覆盖过程。`}),S.retrospective&&(0,m.jsx)(ek,{value:S.retrospective}),!!S.artifactReads?.length&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`h5`,{children:`实际读取的产物`}),(0,m.jsx)(`ul`,{children:S.artifactReads.map((e,t)=>(0,m.jsx)(`li`,{children:e},t))})]}),!!S.runEvidence?.length&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`h5`,{children:`实际运行用时(含工具及等人)`}),(0,m.jsx)(`ul`,{children:S.runEvidence.map((e,t)=>(0,m.jsxs)(`li`,{children:[Math.round(e.elapsedMs/1e3),` 秒 · `,new Date(e.finishedAt).toLocaleTimeString()]},t))}),(0,m.jsx)(`p`,{children:`完整运行用时不等同于模型思考耗时。`})]})]}),!!S.findings.length&&(0,m.jsxs)(`section`,{className:`rsi-analysis`,"aria-label":`详细分析`,children:[(0,m.jsxs)(`h4`,{children:[`详细分析 `,(0,m.jsx)(`span`,{children:S.findings.length})]}),S.findings.map(e=>(0,m.jsxs)(`details`,{className:`rsi-analysis-item`,"data-rsi-finding":e.id,children:[(0,m.jsx)(`summary`,{children:e.title||e.observation.split(/[。\n]/u)[0].slice(0,70)}),(0,m.jsxs)(`div`,{className:`rsi-analysis-body`,children:[(0,m.jsx)(ek,{value:e.observation}),(0,m.jsx)(`h5`,{children:`改进方向`}),(0,m.jsx)(ek,{value:e.recommendation}),(0,m.jsxs)(`p`,{"data-rsi-ownership":e.ownership??`unclassified`,children:[(0,m.jsx)(`strong`,{children:{platform:`平台通用能力`,user:`用户专用能力`,mixed:`通用底座与专用适配需拆分`,unclassified:`归属待澄清`}[e.ownership??`unclassified`]}),e.ownershipReason&&` · ${e.ownershipReason}`]}),(0,m.jsx)(`h5`,{children:`适用与验证`}),(0,m.jsx)(ek,{value:`${e.applicability}\n\n${e.verification}`}),e.evidence.map((e,t)=>(0,m.jsxs)(`blockquote`,{children:[e.quote,(0,m.jsx)(`button`,{type:`button`,onClick:()=>{[...document.querySelectorAll(`[data-group-post-id],[data-transcript-key]`)].find(t=>t.dataset.groupPostId===e.messageId||t.dataset.transcriptKey===`m:${e.messageId}`)?.scrollIntoView({block:`center`,behavior:`smooth`})},children:`定位原消息`})]},t)),e.feedback&&(0,m.jsxs)(`p`,{children:[`此前反馈:`,e.feedback]})]})]},e.id))]})]}),s,o,!r&&(0,m.jsxs)(`details`,{className:`group-rsi-settings`,children:[(0,m.jsx)(`summary`,{children:`RSI 设置`}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:l,onChange:e=>u(e.target.checked)}),`启用整体观察`]}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`input`,{type:`checkbox`,checked:d,onChange:e=>f(e.target.checked)}),`预先授权自动开发符合条件的用户专用能力`]}),(0,m.jsx)(`p`,{children:`默认在统一讨论中确认方案并授权。勾选上项会预先授权符合条件的用户专用 tool / skill 开发;普通修复仍需确认方案。`}),(0,m.jsx)(`p`,{children:`新对话先积累为观察材料,不逐轮生成报告。点击更新观察会重新综合当前整体情况,并产生独立模型请求与费用;当前任务仍在执行时等待结束。每次最多 90 秒、12 次只读检查;同一工作区同时最多一个能力开发,预算十分钟。未指定模型时跟随来源会话、主持人或工作区。`}),(0,m.jsxs)(`label`,{children:[`补充观察要求`,(0,m.jsx)(`textarea`,{"aria-label":`RSI 补充要求`,value:h,onChange:e=>g(e.target.value),maxLength:8e3})]}),(0,m.jsx)(`button`,{type:`button`,"data-rsi-save":!0,disabled:v,onClick:()=>void w({action:`rsi.configure`,enabled:l,automaticImprovements:d,prompt:h}),children:`保存 RSI 设置`})]})]})]})}function nk(e){try{return JSON.parse(Gn(`super-pi.rsi-view.v1:${e}`)??`null`)}catch{return null}}function rk(e,t){try{Kn(`super-pi.rsi-view.v1:${e}`,JSON.stringify(t))}catch{}}function ik(e){let t=nk(e);return t&&typeof t==`object`&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).filter(([,e])=>typeof e==`string`&&e.length<=16e3)):{}}function ak(e){let t=nk(e);return!t||typeof t!=`object`||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(([,e])=>e&&typeof e.text==`string`&&e.text.length<=16e3&&(e.revision===void 0||typeof e.revision==`string`)))}var ok={discussing:`讨论方案`,implementing:`实施中`,review:`待你验收`,completed:`已验收`,failed:`执行失败`,interrupted:`已中断`,cancelled:`已取消`};function sk({repairs:e,archived:t,onAction:n,memoryKey:r}){let i=e.find(e=>e.status===`implementing`||e.status===`review`)??e.at(-1),[a,o]=(0,p.useState)(()=>ik(r+`:drafts`)),[s,c]=(0,p.useState)(()=>ak(r+`:plans`));(0,p.useEffect)(()=>rk(r+`:drafts`,a),[r,a]),(0,p.useEffect)(()=>rk(r+`:plans`,s),[r,s]);let[l,u]=(0,p.useState)(!1),[d,f]=(0,p.useState)(``),h=(0,p.useRef)(null),g=(0,p.useRef)(null),_=(0,p.useRef)(!0),v=(0,p.useRef)(``);(0,p.useLayoutEffect)(()=>{v.current!==i?.id&&(_.current=!0,v.current=i?.id??``),g.current&&_.current&&(g.current.scrollTop=g.current.scrollHeight)},[i?.id,i?.messages.length,i?.messages.at(-1)?.content]);let y=(0,p.useRef)(e.length);if((0,p.useEffect)(()=>{e.length>y.current&&(h.current?.closest(`[data-rsi-discussion]`)?.scrollIntoView({block:`start`}),h.current?.focus({preventScroll:!0})),y.current=e.length},[e]),!i)return null;let b=a[i.id]??``,x=s[i.id]??{text:i.proposedPlan??``,revision:i.revision},S=!t&&!i.busy&&!l&&i.status!==`implementing`,C=S&&i.status===`discussing`&&!!i.revision&&x.revision===i.revision&&!!x.text.trim(),w=async e=>{if(!l){u(!0),f(``);try{return await n({...e,repairId:i.id}),!0}catch(e){return f(e instanceof Error?e.message:`RSI 操作未完成`),!1}finally{u(!1)}}},T=async()=>{if(!b.trim()||!S)return;let e=b,t=i.id;if(!await w({action:`rsi.repair.send`,message:e}))return;let n=ik(r+`:drafts`);n[t]===e&&(n[t]=``,rk(r+`:drafts`,n)),o(n=>n[t]===e?{...n,[t]:``}:n)};return(0,m.jsxs)(`section`,{className:`rsi-repair`,"data-rsi-discussion":!0,"aria-label":`RSI 讨论与修复`,children:[(0,m.jsxs)(`header`,{children:[(0,m.jsx)(`h4`,{children:`讨论与修复`}),(0,m.jsx)(`span`,{role:`status`,"data-rsi-repair-status":!0,children:i.busy&&i.status===`discussing`?`正在准备方案…`:ok[i.status]})]}),(0,m.jsxs)(`p`,{className:`rsi-repair-record`,children:[`整体改进讨论 · `,ok[i.status],` · 会话模型 `,i.model?`${i.model.label} · ${i.model.provider}`:`跟随默认`]}),(0,m.jsx)(`p`,{className:`rsi-repair-hint`,children:`讨论阶段只读。确认下面的实施范围并授权后,才会开始修改。`}),(0,m.jsxs)(`div`,{ref:g,className:`rsi-repair-thread`,role:`log`,"aria-label":`RSI 讨论消息`,"aria-live":`polite`,onScroll:e=>{let t=e.currentTarget;_.current=t.scrollHeight-t.scrollTop-t.clientHeight<32},children:[!i.messages.length&&(0,m.jsx)(`p`,{children:`正在核对建议并准备讨论方案…`}),i.messages.map(e=>(0,m.jsxs)(`article`,{"data-rsi-discussion-role":e.role,children:[(0,m.jsx)(`strong`,{children:e.role===`user`?`你`:`RSI`}),e.actualModel&&(0,m.jsxs)(`small`,{title:`${e.actualModel.provider} / ${e.actualModel.modelId}`,children:[` · `,e.actualModel.label]}),(0,m.jsx)(ep,{source:e.content,handoffs:!1})]},e.id))]}),(d||i.error)&&(0,m.jsx)(`p`,{role:`alert`,children:d||i.error}),!t&&![`implementing`,`completed`,`cancelled`].includes(i.status)&&(0,m.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),T()},children:[(0,m.jsxs)(`label`,{children:[`继续讨论`,(0,m.jsx)(`textarea`,{ref:h,"aria-label":`与 RSI 讨论方案`,value:b,maxLength:12e3,placeholder:`补充约束、询问原因,或修改实施方案…`,onChange:e=>o(t=>({...t,[i.id]:e.target.value}))})]}),(0,m.jsx)(`button`,{type:`submit`,disabled:!S||!b.trim(),children:`发送讨论`})]}),i.status===`discussing`&&(0,m.jsxs)(`section`,{className:`rsi-repair-approval`,"aria-label":`授权实施方案`,children:[(0,m.jsx)(`h5`,{children:`确认实施范围与验收要求`}),(0,m.jsx)(`textarea`,{"aria-label":`RSI 实施范围与验收要求`,value:x.text,disabled:i.busy||l||t,maxLength:16e3,placeholder:`RSI 回复后可在这里检查或调整最终方案`,onChange:e=>c(t=>({...t,[i.id]:{text:e.target.value,revision:x.revision}}))}),x.revision!==i.revision&&(0,m.jsx)(`p`,{role:`status`,children:`讨论已有新回复,请重新核对最新方案。`}),i.revision&&(0,m.jsx)(`button`,{type:`button`,disabled:l||i.busy||t,onClick:()=>c(e=>({...e,[i.id]:{text:i.proposedPlan??``,revision:i.revision}})),children:`使用最新讨论方案`}),(0,m.jsx)(`button`,{type:`button`,className:`rsi-repair-primary`,"data-rsi-authorize":!0,disabled:!C,onClick:()=>void w({action:`rsi.repair.approve`,revision:x.revision,plan:x.text,confirmed:!0}),children:`授权实施此方案`}),(0,m.jsx)(`small`,{children:`授权只覆盖这份方案;不会自动提交、推送或发布。执行结束后仍需你验收。`})]}),i.approvedPlan&&(0,m.jsxs)(`details`,{children:[(0,m.jsx)(`summary`,{children:`查看本次授权范围`}),(0,m.jsx)(ep,{source:i.approvedPlan,handoffs:!1})]}),(0,m.jsxs)(`div`,{className:`rsi-repair-actions`,children:[(0,m.jsx)(`button`,{type:`button`,onClick:()=>window.dispatchEvent(new CustomEvent(`super-pi-open-rsi-work`,{detail:i.conversationId})),children:`查看完整执行过程 / 切换模型`}),i.status===`review`&&!t&&(0,m.jsx)(`button`,{type:`button`,disabled:l||i.busy,onClick:()=>void w({action:`rsi.repair.accept`}),children:`验收通过`}),![`completed`,`cancelled`].includes(i.status)&&(0,m.jsx)(`button`,{type:`button`,disabled:l,onClick:()=>void w({action:`rsi.repair.cancel`}),children:i.busy?`停止本次处理`:`取消此项改进`})]})]})}function ck({source:e,archived:t=!1,visible:n=!0,onClose:r}){let[i,a]=(0,p.useState)({models:[]}),[o,s]=(0,p.useState)(``),[c,l]=(0,p.useState)(),[u,d]=(0,p.useState)(``),f=`/api/rsi?${new URLSearchParams({kind:e.kind,workspaceId:e.workspaceId,id:e.id})}`,h=(0,p.useRef)(0),g=(0,p.useRef)(0),_=(0,p.useRef)(f);_.current=f,(0,p.useEffect)(()=>{if(!n)return;let e=!1,t=new AbortController,r=async()=>{if(g.current)return;let n=h.current;try{let r=await Ie(f,{signal:t.signal}),i=await r.json();if(!r.ok)throw Error(i.error??`RSI 暂时不可用。`);!e&&n===h.current&&(l(i),d(``))}catch(t){!e&&n===h.current&&d(t instanceof Error?t.message:String(t))}};Ie(f+`&view=models`,{signal:t.signal}).then(async t=>{let n=await t.json();if(!t.ok)throw Error(n.error??`模型目录暂时不可用。`);e||(a({models:n.models??[],inherited:n.inherited}),s(``))}).catch(t=>{e||s(t instanceof Error?t.message:String(t))}),r();let i=setInterval(()=>{document.visibilityState===`visible`&&r()},3e3);return()=>{e=!0,t.abort(),clearInterval(i)}},[f,n]);let v=async e=>{let t=++h.current;g.current++;try{let n=await Ie(f,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(e),signal:AbortSignal.timeout(15e3)}),r=await n.json();if(!n.ok)throw Error(r.error??`RSI 操作失败。`);_.current===f&&t===h.current&&l(r)}finally{g.current--}};return c?(0,m.jsx)(tk,{memoryKey:f,state:c?.state,models:i.models,inherited:i.inherited,archived:t,onClose:r,onAction:v,discussion:c.repairs?.length?(0,m.jsx)(sk,{memoryKey:f,repairs:c.repairs,archived:t,onAction:v}):void 0,extra:(0,m.jsxs)(m.Fragment,{children:[(u||o)&&(0,m.jsx)(`p`,{role:`alert`,children:u||o}),(!!c.improvements.length||!!c.usage.length)&&(0,m.jsxs)(`details`,{className:`rsi-work`,"data-rsi-work":!0,children:[(0,m.jsx)(`summary`,{children:`能力执行与复用记录`}),c?.improvements.map(e=>(0,m.jsxs)(`article`,{"data-rsi-job":e.id,children:[(0,m.jsxs)(`h5`,{children:[e.name,` · `,{queued:`等待开发`,running:`开发与验证中`,available:`已注册可用 · 收益待验证`,failed:`开发未通过`,interrupted:`已中断`,cancelled:`已取消`}[e.status]]}),(0,m.jsxs)(`p`,{children:[e.slug,e.version?` · v${e.version}`:``]}),e.conversationId&&(0,m.jsxs)(`p`,{children:[`会话模型 `,e.model?.label??`跟随默认`,e.actualModel&&` · 最近实际使用 ${e.actualModel.label}(${e.actualModel.provider})`]}),e.error&&(0,m.jsx)(`p`,{role:`alert`,children:e.error}),e.conversationId&&(0,m.jsx)(`button`,{type:`button`,"data-rsi-open-work":e.id,onClick:()=>{window.dispatchEvent(new CustomEvent(`super-pi-open-rsi-work`,{detail:e.conversationId})),r()},children:`查看开发过程 / 切换模型`}),[`running`,`queued`].includes(e.status)&&(0,m.jsx)(`button`,{type:`button`,onClick:()=>void v({action:`rsi.cancel`,jobId:e.id}).catch(e=>d(String(e))),children:`取消改进`})]},e.id)),!!c?.usage.length&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`h4`,{children:`实际复用记录`}),(0,m.jsx)(`ul`,{children:c.usage.slice(-8).reverse().map((e,t)=>(0,m.jsxs)(`li`,{children:[e.slug,` v`,e.version,` · `,e.status,` · `,e.durationMs,` ms`]},t))}),(0,m.jsx)(`p`,{children:`调用成功仅表示执行成功,不能单独证明整个任务更快或质量更好。`})]})]})]})},f):(0,m.jsxs)(`aside`,{className:`group-rsi-panel`,"data-group-rsi-panel":!0,children:[(0,m.jsxs)(`header`,{children:[(0,m.jsx)(`h3`,{children:`RSI 观察与建议`}),(0,m.jsx)(`button`,{type:`button`,onClick:r,children:`关闭`})]}),(0,m.jsx)(`div`,{className:`group-rsi-body`,children:(0,m.jsx)(`p`,{role:u?`alert`:`status`,children:u||`正在读取观察与能力改进记录…`})})]})}function lk({id:e,expanded:t,onClick:n}){return(0,m.jsx)(`button`,{type:`button`,"data-session-rsi":e,"aria-expanded":t,title:`在侧栏打开 RSI:任务效率与能力改进`,onClick:n,children:`RSI`})}function uk({context:e,visible:t=!0,onClose:n}){return e?(0,m.jsxs)(`div`,{className:`rsi-sidebar-panel`,"data-rsi-sidebar-source":e.source.id,"data-rsi-sidebar-kind":e.source.kind,children:[(0,m.jsxs)(`div`,{className:`rsi-sidebar-context`,children:[(0,m.jsx)(`span`,{children:e.source.kind===`group`?`群聊`:`会话`}),(0,m.jsx)(`strong`,{title:e.title,children:e.title}),e.archived&&(0,m.jsx)(`small`,{children:`已归档 · 仅查看`})]}),(0,m.jsx)(ck,{visible:t,source:e.source,archived:e.archived,onClose:n},JSON.stringify(e.source))]}):(0,m.jsxs)(`div`,{className:`rsi-sidebar-empty`,"data-rsi-sidebar-empty":!0,children:[(0,m.jsx)(`h3`,{children:`选择观察来源`}),(0,m.jsx)(`p`,{children:`打开一个会话或群聊,在这里查看观察、讨论改进并授权修复。`}),(0,m.jsx)(`p`,{children:`切换文件、Git 或终端不会取消已开始的观察和修复。`})]})}function dk(e){let t=`归档整棵会话树「${e.title}」?本次将归档 ${e.activeCount} 个会话(1 个根会话和 ${e.activeDescendants} 个活跃子孙)${e.alreadyArchived?`,跳过 ${e.alreadyArchived} 个已归档子孙`:``};恢复根会话时,整棵树会一起恢复。`;return e.pendingDecisions>0?`${t}\n还有 ${e.pendingDecisions} 个未拍板的决策,归档后它们会作废。`:t}function fk(e){return e.activeDescendants>0||e.pendingDecisions>0}var pk={workspaces:[],conversations:[],subagentRuns:[]},mk=e=>e.nativeEvent.isComposing||e.keyCode===229,hk=(e,t,n)=>{let r=e.filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),i=r.findIndex(e=>e.id===t);if(i<0||r[i].delivery===`sending`)return e;let a=r.reduce((e,t,n)=>t.delivery===`sending`?n:e,-1),o=Math.max(a+1,Math.min(n,r.length-1));if(o===i)return e;let s=[...r],[c]=s.splice(i,1);s.splice(o,0,c);let l=[...e],u=0;for(let e=0;e<l.length;e+=1)(l[e].role===`user`||l[e].role===`tool`)&&l[e].delivery&&(l[e]=s[u++]);return l},gk=(e,t)=>{for(let n=e.length-1;n>=0;--n)if(e[n].at===t)return n;return-1},_k=(e,t,n)=>{if(t===void 0)return gk(e,n);let r=e.findIndex(e=>e.blockIndex===t);if(r>=0)return r;let i=e.findIndex(e=>e.blockIndex!==void 0);if(i<0)return gk(e,n);let a=t-((e[i].blockIndex??0)-i);return a>=0&&a<e.length?a:-1},vk=(e,t,n)=>{let r=t.at??n,i=[...e],a=_k(i,t.blockIndex,r);return a>=0?i[a]={...i[a],text:i[a].text+t.delta,blockIndex:t.blockIndex??i[a].blockIndex}:i.push({at:r,text:t.delta,blockIndex:t.blockIndex}),i},yk=(e,t)=>{let n=e??[],r=t??[];return r.length>n.length?r:e},bk=e=>{if(typeof e!=`string`||e.length===0)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:new Intl.DateTimeFormat(`zh-CN`,{hour:`2-digit`,minute:`2-digit`}).format(t)},xk=6e4,Sk=60*xk,Ck=24*Sk,wk=7*Ck,Tk=30*Ck,Ek=365*Ck,Dk=(e,t)=>{let n=new Date(e);if(Number.isNaN(n.getTime()))return``;let r=t-n.getTime();return r<3e4?`now`:r<Sk?`${Math.max(1,Math.floor(r/xk))}m ago`:r<Ck?`${Math.floor(r/Sk)}h ago`:r<wk?`${Math.floor(r/Ck)}d ago`:r<Tk?`${Math.floor(r/wk)}w ago`:r<Ek?`${Math.floor(r/Tk)}mo ago`:`${Math.floor(r/Ek)}y ago`},Ok=(e,t)=>{let n=e.find(e=>e.id===t);if(!n)return[];let r=new Map;for(let t of e){if(t.workspaceId!==n.workspaceId||!t.parentConversationId)continue;let e=r.get(t.parentConversationId);e?e.push(t):r.set(t.parentConversationId,[t])}let i=[],a=new Set,o=e=>{if(!a.has(e.id)){a.add(e.id),i.push(e);for(let t of r.get(e.id)??[])o(t)}};return o(n),i},kk=e=>{if(!e)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}`};function Ak({workspace:e,x:t,y:n,notify:r,onClose:i}){let a=(0,p.useRef)(null),[o,s]=(0,p.useState)({left:t,top:n});(0,p.useLayoutEffect)(()=>{let e=a.current;if(!e)return;let r=e.getBoundingClientRect();s({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),i())},t=e=>{a.current?.contains(e.target)||i()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&i()},o=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&i()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,o),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,r,!0),window.removeEventListener(`resize`,o)}},[i]);let c=async()=>{let t=await Hi(e.path);i(),t?r(`已复制工作区路径:${e.path}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中路径复制`,`error`)};return(0,m.jsxs)(`div`,{ref:a,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-workspace-id":e.id,style:{left:o.left,top:o.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-workspace-path":e.id,onClick:()=>void c(),children:`复制工作区路径`}),(0,m.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.path})]})}function jk({conversation:e,x:t,y:n,notify:r,onRename:i,onClose:a,sendCommand:o,orchestrated:s,childCount:c}){let l=(0,p.useRef)(null),[u,d]=(0,p.useState)({left:t,top:n});(0,p.useLayoutEffect)(()=>{let e=l.current;if(!e)return;let r=e.getBoundingClientRect();d({left:Math.max(8,Math.min(t,window.innerWidth-r.width-8)),top:Math.max(8,Math.min(n,window.innerHeight-r.height-8))})},[t,n]),(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),a())},t=e=>{l.current?.contains(e.target)||a()},n={x:window.scrollX,y:window.scrollY,width:window.innerWidth,height:window.innerHeight},r=()=>{(window.scrollX!==n.x||window.scrollY!==n.y)&&a()},i=()=>{(window.innerWidth!==n.width||window.innerHeight!==n.height)&&a()};return window.addEventListener(`keydown`,e,!0),window.addEventListener(`pointerdown`,t,!0),window.addEventListener(`scroll`,r,!0),window.addEventListener(`resize`,i),()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`pointerdown`,t,!0),window.removeEventListener(`scroll`,r,!0),window.removeEventListener(`resize`,i)}},[a]);let f=async e=>{try{let t=await Ie(`/api/orchestrator/stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`,conversationId:e,mode:`all`})}),n=await t.json();if(!t.ok)throw Error(n.error);r(`已停止会话(含排队消息)`,`info`)}catch(e){r(`停止失败:${zr(e)}`,`error`)}},h=async e=>{try{let t=await Ie(`/api/orchestrator/stop`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`stop`,conversationId:e,mode:`all`,subtree:!0})}),n=await t.json();if(!t.ok)throw Error(n.error);let i=typeof n.descendantCount==`number`?n.descendantCount:0;r(i>0?`已停止会话及其下属 ${i} 个`:`已停止会话(它没有下属会话)`,`info`)}catch(e){r(`停止子树失败:${zr(e)}`,`error`)}},g=async()=>{let t=await Hi(e.id);a(),t?r(`已复制会话 ID:${e.id}`,`info`):r(`复制失败:浏览器拒绝了剪贴板写入`,`error`)};return(0,m.jsxs)(`div`,{ref:l,className:`ctx-menu`,role:`menu`,"data-ctx-menu":`1`,"data-session-id":e.id,style:{left:u.left,top:u.top},onContextMenu:e=>e.preventDefault(),onPointerDown:e=>e.stopPropagation(),children:[(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-copy-session-id":e.id,onClick:()=>void g(),children:`复制会话 ID`}),(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-ai-rename-session":e.id,onClick:()=>{a(),i()},children:`AI 智能重命名`}),![`running`,`waiting`,`awaiting_background`].includes(e.status)&&(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-save-warm-session":e.id,onClick:()=>{a();let t=window.prompt(`保存为当前工作区的预热会话。以后选用时会带上当前对话历史。`,e.title)?.trim();t&&!o({type:`conversation.warm.save`,conversationId:e.id,title:t})&&r(`连接断开,未保存预热会话`,`error`)},children:`保存为预热会话`}),(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item`,"data-stop-turn-session":e.id,onClick:()=>{a(),o({type:`run.stop`,conversationId:e.id})},children:`停止当前回合`}),s&&(0,m.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-queue":e.id,onClick:()=>{a(),f(e.id)},children:`停止会话(含排队消息)`}),c>0&&(0,m.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item ctx-menu-item-danger`,"data-stop-session-tree":e.id,onClick:()=>{a(),h(e.id)},children:[`停止整棵子树(`,c,` 个下属)`]}),(0,m.jsx)(`div`,{className:`ctx-menu-hint`,"aria-hidden":`true`,children:e.id})]})}var Mk={model:`模型`,thinking:`思考`,agent:`智能体`,subagent:`子智能体`},Nk=GO,Pk={model:`模型`,thinking:`思考等级`,agent:`智能体`,subagent:`子智能体`},Fk={model:`没有可用的模型`,thinking:`Pi 没有给出当前模型的思考等级`,agent:`没有可用的智能体`,subagent:`没有可用的子智能体`},Ik={model:`选择模型`,thinking:`选择思考等级`,agent:`选择智能体`,subagent:`选择子智能体`},Lk=`图文`,Rk=e=>e.imageInput?Lk:void 0,zk=e=>e.normalize(`NFKD`).replace(/\p{M}/gu,``).toLowerCase(),Bk=(e,t)=>{let n=zk(t.trim());return n?e.filter(e=>zk(`${e.label} ${e.detail??``} ${e.badge??``}`).includes(n)):e};function Vk({workspaceId:e,value:t,onChange:n}){let[r,i]=(0,p.useState)([]),[a,o]=(0,p.useState)(``);(0,p.useEffect)(()=>{i([]),o(``)},[e]),(0,p.useEffect)(()=>{let n=!0;return o(``),Ie(`/api/files?workspaceId=${encodeURIComponent(e)}&path=${encodeURIComponent(t)}`).then(async e=>{let r=await e.json();if(!e.ok)throw Error(r.error??`HTTP ${e.status}`);if(!n)return;let a=(r.entries??[]).filter(e=>e.kind===`directory`).map(e=>e.path);i(e=>[...new Set([...e,t,...a])].filter(Boolean).sort())}).catch(e=>{n&&o(e instanceof Error?e.message:`子目录读取失败`)}),()=>{n=!1}},[e,t]);let s=[...new Set([...r,t])].filter(Boolean).sort();return(0,m.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,m.jsx)(`label`,{htmlFor:`empty-session-cwd`,children:`工作目录:`}),(0,m.jsxs)(`select`,{id:`empty-session-cwd`,"data-session-cwd-select":`1`,"aria-label":`会话工作目录(可选)`,value:t,onChange:e=>n(e.target.value),children:[(0,m.jsx)(`option`,{value:``,children:`工作区根目录`}),s.map(e=>(0,m.jsx)(`option`,{value:e,children:e},e))]}),a&&(0,m.jsx)(`span`,{role:`status`,children:a})]})}function Hk({workspace:e,onClose:t,onCreate:n}){let[r,i]=(0,p.useState)(``),a=(0,p.useRef)(null);return(0,p.useEffect)(()=>{i(``)},[e.id]),(0,p.useEffect)(()=>{let e=a.current;e&&e.focus();let n=e=>{e.key===`Escape`&&(e.preventDefault(),t())};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[t]),(0,m.jsx)(`div`,{className:`overlay session-create-overlay`,onClick:t,children:(0,m.jsxs)(`div`,{className:`session-create-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`session-create-title`,tabIndex:-1,ref:a,onClick:e=>e.stopPropagation(),onKeyDown:e=>{if(e.key!==`Tab`)return;let t=a.current;if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), select:not([disabled]), input:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex='-1'])`));if(n.length===0)return;let r=n[0],i=n[n.length-1];e.shiftKey?document.activeElement===r&&(e.preventDefault(),i.focus()):document.activeElement===i&&(e.preventDefault(),r.focus())},children:[(0,m.jsx)(`h2`,{id:`session-create-title`,children:`新建会话`}),(0,m.jsxs)(`p`,{className:`session-create-workspace`,children:[`工作区:`,e.name,(0,m.jsx)(`small`,{children:e.path})]}),(0,m.jsx)(Vk,{workspaceId:e.id,value:r,onChange:i}),(0,m.jsxs)(`div`,{className:`session-create-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`session-create-cancel`,onClick:t,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`session-create-confirm picker-ok`,onClick:()=>n(r),children:`创建会话`})]})]})})}function Uk({onClose:e,onCreate:t}){let{connections:n,activeServer:r}=pe(),i=(0,p.useRef)(0),[a,o]=(0,p.useState)(),[s,c]=(0,p.useState)(!0),[l,u]=(0,p.useState)(),[d,f]=(0,p.useState)(``),[h,g]=(0,p.useState)(``),[_,v]=(0,p.useState)(!1),y=async(e,t)=>{let n=++i.current;t===void 0&&v(!1),c(!0),u(void 0);try{let a=new URLSearchParams;e&&a.set(`path`,e),t!==void 0&&a.set(`prefix`,t);let s=await Ie(`/api/fs/dirs?${a}`,{},r),c=await s.json();if(!s.ok)throw Error(c.error??`HTTP ${s.status}`);if(n!==i.current)return;let l=c;o(l),t===void 0&&(g(l.path),f(l.suggestedName),v(!1))}catch(e){n===i.current&&u(e instanceof Error?e.message:`目录加载失败`)}finally{n===i.current&&c(!1)}};(0,p.useEffect)(()=>{o(void 0),g(``),y()},[r]),(0,p.useEffect)(()=>{if(!_||!a)return;let e=br(h,a.path),t=window.setTimeout(()=>{y(e.path,e.prefix)},180);return()=>{window.clearTimeout(t)}},[h,_,r]),(0,p.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let b=e=>{e?.preventDefault();let t=h.trim();t&&y(t)};return(0,m.jsx)(`div`,{className:`overlay`,onClick:e,children:(0,m.jsxs)(`div`,{className:`picker workspace-picker`,onClick:e=>e.stopPropagation(),children:[(0,m.jsx)(`h2`,{children:`选择工作区目录`}),(0,m.jsxs)(`label`,{className:`server-settings-scope`,children:[`目标服务器`,(0,m.jsx)(`select`,{"aria-label":`新建工作区的服务器`,value:r,onChange:e=>xe(e.target.value),children:n.filter(e=>e.enabled).map(e=>(0,m.jsx)(`option`,{value:e.id,children:e.name},e.id))})]}),(0,m.jsxs)(`form`,{className:`picker-path-bar`,onSubmit:b,children:[(0,m.jsx)(`input`,{className:`picker-path-input`,value:h,onChange:e=>{i.current++,c(!0),g(e.target.value),v(!0)},"aria-label":`工作区目录路径`,onKeyDown:e=>{e.key===`Tab`&&!e.shiftKey&&!e.nativeEvent.isComposing&&_&&!s&&a?.entries.length===1?(e.preventDefault(),y(a.entries[0].path)):e.key===`Enter`&&(mk(e)?e.preventDefault():(e.preventDefault(),b()))},placeholder:`输入或粘贴目录绝对路径(如 D:\\projects 或 ~/code)`}),(0,m.jsx)(`button`,{type:`submit`,className:`picker-go-btn`,disabled:!h.trim(),children:`跳转`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-up-btn`,disabled:!a?.parent||s,onClick:()=>a?.parent&&void y(a.parent),title:`返回上一级目录`,children:`上一级`})]}),a?.drives?.length||a?.homeDir?(0,m.jsxs)(`div`,{className:`picker-shortcuts`,children:[(0,m.jsx)(`span`,{className:`picker-shortcuts-label`,children:`快捷位置:`}),a?.homeDir&&(0,m.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void y(`~`),title:a.homeDir,children:`🏠 主目录`}),a?.drives?.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`picker-shortcut`,onClick:()=>void y(e),children:e},e))]}):null,(0,m.jsxs)(`div`,{className:`picker-list`,children:[s&&(0,m.jsx)(`div`,{className:`picker-status`,children:`加载中…`}),!s&&l&&(0,m.jsxs)(`div`,{className:`picker-error`,children:[l,(0,m.jsx)(`button`,{onClick:()=>void y(a?.path||h),children:`重试`})]}),!s&&!l&&a?.entries.map(e=>(0,m.jsxs)(`button`,{className:`picker-dir`,onClick:()=>void y(e.path),children:[`📁 `,e.name]},e.path)),!s&&!l&&a&&a.entries.length===0&&(0,m.jsx)(`div`,{className:`picker-status`,children:`此目录下没有子目录`}),!s&&!l&&a?.truncated&&(0,m.jsx)(`div`,{className:`picker-status`,children:`目录过多,仅显示前 2000 项`})]}),(0,m.jsxs)(`label`,{className:`picker-name`,children:[`工作区名称`,(0,m.jsx)(`input`,{value:d,onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(mk(e)?e.preventDefault():(e.preventDefault(),d.trim()&&a&&!_&&!s&&!l&&t(d.trim(),a.path)))},placeholder:`工作区名称`})]}),(0,m.jsxs)(`div`,{className:`picker-actions`,children:[(0,m.jsx)(`button`,{className:`picker-cancel`,onClick:e,children:`取消`}),(0,m.jsx)(`button`,{className:`picker-ok`,disabled:!d.trim()||s||!!l||!a||_,onClick:()=>a&&t(d.trim(),a.path),children:`使用这个目录`})]})]})})}var Wk={timeout:`扩展提问超时,已取消`,aborted:`运行已停止,扩展提问已取消`,expired:`运行已结束,扩展提问已取消`},Gk=10;function Kk(e,t,n=!1){if(!t)return`正在从 Pi 读取${e}列表…`;if(t.source!==`pi`)return`读取 Pi ${e}列表失败:${t.error??`未知原因`}`;if(t.configError)return`Pi 拒绝了自己的模型配置,文件里的自定义供应商都没有被提供:${t.configError.split(`
|
|
338
|
+
`).find(e=>e.trim().startsWith(`-`))?.trim()??`详情见设置`}`;if(e===`模型`&&n)return`此会话已包含图片,仅显示支持图文的模型`;if(e===`思考等级`&&!t.levels.length)return`Pi 没有给出当前模型的思考等级`}function qk(e){if(!e)return`正在读取 agent 列表…`;if(e.source!==`directory`)return`读取 agent 列表失败:${e.error??`未知原因`}`;if(e.problems.length)return`${e.problems.length} 个 agent 文件无法使用:${e.problems.map(e=>e.file).join(`、`)}`;if(!e.agents.length)return`${e.directory} 下没有 primary agent`}var Jk=e=>Math.abs(e)<1e3?String(e):`${(e/1e3).toFixed(1).replace(/\.0$/,``)}k`;function Yk(e){if(e===void 0||!Number.isFinite(e))return``;let t=Math.max(0,e);return t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}分${Math.round(t%6e4/1e3)}秒`}var Xk={dispatch:`派发时(子进程还没起来)`,prompt:`派活时(Pi 拒收了任务)`,turn:`生成回答时`,tool:`调用工具时`,settle:`收尾时`};function Zk(e){return e.replace(/\u001b\][^\u0007]*(?:\u0007|\u001b\\)/g,``).replace(/\u001b\[[0-?]*[ -/]*[@-~]/g,``).replace(/\u001b[@-_]/g,``).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,``).split(/\r?\n/).map(e=>e.trim()).filter(Boolean).at(-1)??``}function Qk(e,t){let[n,r]=(0,p.useState)(()=>t.get(e));return(0,p.useEffect)(()=>{r(t.get(e));let n,i=i=>{i.detail===e&&n===void 0&&(n=requestAnimationFrame(()=>{n=void 0,r(t.get(e))}))};return window.addEventListener(`super-pi-exec-output`,i),()=>{window.removeEventListener(`super-pi-exec-output`,i),n!==void 0&&cancelAnimationFrame(n)}},[e,t]),n}function $k({task:e,execOutputs:t,expanded:n}){let r=Qk(e.id,t),i=e.status===`running`?r?.text||e.output:e.output??r?.text,a=i&&ZO(i),o=e.status===`running`?r?.truncated??e.outputTruncated:e.outputTruncated;return(0,m.jsxs)(m.Fragment,{children:[!n&&a&&(0,m.jsx)(`div`,{className:`call-live-preview`,"data-background-preview":e.id,title:`展开调用查看完整输出`,children:Zk(a)}),n&&(0,m.jsx)(`pre`,{className:`call-result-body`,"data-background-output":e.id,children:[e.reason,o?`日志仅保留最近一段。`:``,a].filter(Boolean).join(`
|
|
339
339
|
|
|
340
|
-
`)||(e.status===`running`?`等待输出…`:`任务未产生输出。`)})]})}function Xk({call:e,index:t,expanded:n,onToggle:r,backgroundOutput:i,runCard:a}){let o=e.args??[];return(0,m.jsxs)(`div`,{className:`call-block call-block-${e.status??`running`}`,"data-call-block":t,"data-call-tool":e.label,"data-call-detail":e.detail??void 0,"data-call-status":e.status??`running`,"data-call-expanded":n?`true`:`false`,"data-call-arg-count":o.length,"data-thinking-at":e.thinkingAt,"data-background-exec":e.backgroundTask?.id,"data-background-status":e.backgroundTask?.status,children:[(0,m.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-call-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`} ${e.label} 调用`,title:n?`折叠这次调用`:`展开这次调用`,onClick:r}),(0,m.jsxs)(`div`,{className:`call-head-row`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,m.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,m.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,m.jsx)(`span`,{className:`call-label`,title:e.label,children:e.label}),e.detail&&(0,m.jsx)(`span`,{className:`call-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,m.jsx)(`span`,{className:`call-duration`,children:Gk(e.durationMs)}),e.backgroundTask&&(0,m.jsxs)(`span`,{className:`call-background-status`,"data-background-status-text":e.backgroundTask.status,children:[`后台任务 · `,TA[e.backgroundTask.status]??`未知状态`,e.backgroundTask.exitCode===void 0?``:` · 退出码:${e.backgroundTask.exitCode}`]}),e.preparing&&(0,m.jsx)(`span`,{className:`call-preparing`,"data-call-preparing":t,children:`生成参数中…`})]}),n&&(0,m.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),!n&&e.live&&(0,m.jsx)(`div`,{className:`call-live-preview`,"data-call-live-preview":t,title:`展开查看完整输出`,children:qk(e.live)}),n&&(0,m.jsx)(`div`,{className:`call-args`,"data-call-args":o.length,children:o.length===0?(0,m.jsx)(`div`,{className:`call-arg call-arg-empty`,"data-call-arg-empty":t,children:`(这次调用没有可显示的参数)`}):o.map(e=>(0,m.jsxs)(`div`,{className:`call-arg`,"data-call-arg":e.key,"data-call-arg-value":e.value,children:[(0,m.jsx)(`span`,{className:`call-arg-key`,children:e.key}),(0,m.jsx)(`span`,{className:`call-arg-value`,title:e.value,children:e.value})]},e.key))}),n&&(e.result||e.live||i)&&(0,m.jsxs)(`div`,{className:`call-result`,"data-call-result":t,"data-call-result-state":e.result?`done`:`running`,children:[(e.result||e.live)&&(0,m.jsxs)(`div`,{className:`call-result-head`,children:[(0,m.jsx)(`span`,{className:`call-result-title`,children:e.result&&!e.live?`执行结果`:e.result?`执行结果 · 完整输出`:`执行中 · 输出预览`}),e.result?(0,m.jsx)(Zk,{index:t,text:e.live??e.result.text}):null]}),(e.result||e.live)&&(0,m.jsx)(`pre`,{className:`call-result-body`,"data-call-result-body":t,children:e.live??e.result?.text}),e.result?.truncated&&e.live&&(0,m.jsx)(`div`,{className:`call-result-truncated`,children:`(服务端已截断到末尾 8 KB;上方显示的是执行中累积的完整输出)`}),e.result?.truncated&&!e.live&&(0,m.jsxs)(`div`,{className:`call-result-truncated`,children:[`(输出过长,已保留末尾关键内容`,e.result.droppedLines?`,省略前 ${e.result.droppedLines} 行`:``,`)`]}),i]}),!n&&i,a]})}function Zk({index:e,text:t}){let[n,r]=(0,p.useState)(!1);return(0,m.jsx)(`button`,{type:`button`,className:`call-result-copy`,"data-call-result-copy":e,onClick:async()=>{await Hi(t)&&(r(!0),window.setTimeout(()=>r(!1),1600))},children:n?`已复制`:`复制`})}function Qk({messageId:e,nestedCount:t,liveCall:n,liveAwaitingReader:r,liveExtra:i,preview:a,expanded:o,onToggle:s,children:c}){return(0,m.jsxs)(`section`,{className:`thinking-block`,"data-thinking-block":e,"data-thinking-expanded":o?`true`:`false`,"data-thinking-calls":t,children:[(0,m.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-thinking-fold-edge":e,"aria-expanded":o,"aria-label":`${o?`折叠`:`展开`}这段思考`,title:o?`折叠这段思考`:`展开这段思考`,onClick:s}),(0,m.jsxs)(`button`,{type:`button`,className:`thinking-head`,"data-thinking-head":e,"aria-expanded":o,title:o?`折叠这段思考`:`展开这段思考`,onClick:s,children:[(0,m.jsx)(`span`,{className:`thinking-chevron`,"aria-hidden":`true`,children:o?`▾`:`▸`}),(0,m.jsx)(`span`,{className:`thinking-label`,children:`思考`}),t>0&&(0,m.jsxs)(`span`,{className:`thinking-count`,"data-thinking-count":t,children:[t,` 次工具调用`]}),!o&&n&&(0,m.jsxs)(`span`,{className:`thinking-live${r?` thinking-live-question`:``}`,"data-thinking-live":n,"data-thinking-live-extra":i??0,"data-thinking-awaiting-reader":r?`1`:void 0,children:[(0,m.jsx)(`span`,{className:`thinking-live-glyph`,"aria-hidden":`true`,children:r?`?`:`⚙`}),r?`等你回答`:`正在执行 ${n}`,i?` 等 ${i+1} 个`:``]}),!o&&a&&(0,m.jsx)(`span`,{className:`thinking-preview`,title:a,children:a})]}),o&&(0,m.jsx)(`div`,{className:`thinking-body`,"data-thinking-body":e,children:c})]})}function $k({run:e,name:t,expanded:n,onToggle:r,onStop:i,stopping:a}){let o=e.toolCalls??[],s=n?o:o.slice(-10),c=o.length-s.length,l=e.status===`running`,u=e.partialOutput??e.output??``,d=e.dispatchedBy===`model`,[f,h]=(0,p.useState)(0);(0,p.useEffect)(()=>{if(!l)return;h(Date.now());let e=window.setInterval(()=>h(Date.now()),200);return()=>window.clearInterval(e)},[l,e.startedAt]);let g=Date.parse(e.startedAt),_=l&&f>0&&Number.isFinite(g)?f-g:void 0,v=[...o].reverse().find(e=>e.status===void 0)?.label;return(0,m.jsxs)(`article`,{className:`subagent-card subagent-${e.status}${d?` subagent-by-model`:``}`,"data-subagent-card":e.id,"data-subagent-status":e.status,"data-subagent-agent":e.agentId,"data-subagent-tools":o.length,"data-subagent-dispatched-by":d?`model`:`human`,children:[(0,m.jsxs)(`div`,{className:`subagent-head`,children:[(0,m.jsx)(`span`,{className:`subagent-badge`,children:`子智能体`}),d&&(0,m.jsxs)(`span`,{className:`subagent-source`,"data-subagent-source":`model`,title:`primary 模型自己决定派这个子智能体去干活`,children:[(0,m.jsx)(`span`,{className:`subagent-source-glyph`,"aria-hidden":`true`,children:`⚡`}),`模型自主派发`]}),(0,m.jsx)(`strong`,{className:`subagent-name`,"data-subagent-name":`1`,children:t||e.agentId}),(0,m.jsx)(`span`,{className:`subagent-status`,"data-subagent-status-text":`1`,children:l?`运行中`:e.status===`completed`?`已完成`:e.status===`stopped`?`已停止`:`失败`}),l?_!==void 0&&(0,m.jsxs)(`span`,{className:`subagent-clock`,"data-subagent-elapsed":`1`,"data-subagent-elapsed-ms":_,children:[`已运行 `,Gk(_)]}):e.durationMs!==void 0&&(0,m.jsxs)(`span`,{className:`subagent-duration`,"data-subagent-duration":`1`,"data-subagent-duration-ms":e.durationMs,children:[`用时 `,Gk(e.durationMs)]}),l&&(0,m.jsx)(`button`,{type:`button`,className:`subagent-stop`,"data-subagent-stop":e.id,disabled:a,onClick:i,children:`停止`})]}),l&&e.activity&&(0,m.jsxs)(`div`,{className:`subagent-activity`,"data-subagent-activity":e.activity.kind,"data-subagent-activity-at":e.activity.at,children:[(0,m.jsx)(`span`,{className:`subagent-activity-dot`,"aria-hidden":`true`}),e.activity.kind===`tool`?`正在调用 ${e.activity.label??`工具`}`:`正在思考…`]}),(0,m.jsxs)(`div`,{className:`subagent-task`,"data-subagent-task":`1`,children:[d&&(0,m.jsx)(`span`,{className:`subagent-task-source`,"data-subagent-model-task":`1`,children:`模型给的任务`}),e.task]}),(0,m.jsxs)(`div`,{className:`subagent-output`,"data-subagent-output":`1`,"data-live-length":u.length,children:[u||(l?`…`:`(没有输出)`),e.outputTruncated&&`(输出已截断)`]}),e.failure&&(0,m.jsxs)(`div`,{className:`subagent-failure`,"data-subagent-failure":`1`,"data-subagent-failure-stage":e.failure.stage,children:[(0,m.jsx)(`span`,{className:`subagent-failure-label`,children:`卡在`}),(0,m.jsx)(`span`,{className:`subagent-failure-stage`,"data-subagent-failure-text":`1`,children:Kk[e.failure.stage]}),e.failure.stage===`tool`&&v&&(0,m.jsxs)(`span`,{className:`subagent-failure-tool`,"data-subagent-failure-tool":`1`,children:[`· 正在跑 `,v]}),o.length>0&&(0,m.jsxs)(`span`,{className:`subagent-failure-progress`,children:[`· 死前已尝试 `,o.length,` 次工具调用`]})]}),e.error&&(0,m.jsx)(`div`,{className:`subagent-error`,"data-subagent-error":`1`,title:Br(e.error),children:zr(e.error,`这条子任务没有完成。`)}),o.length>0&&(0,m.jsxs)(`div`,{className:`subagent-tools`,"data-subagent-tool-count":o.length,children:[c>0&&!n&&(0,m.jsxs)(`button`,{type:`button`,className:`subagent-more`,"data-subagent-hidden":c,onClick:r,children:[`… 另有 `,c,` 条工具调用`]}),s.map((e,t)=>(0,m.jsxs)(`div`,{children:[(0,m.jsxs)(`div`,{className:`subagent-tool${e.status?` subagent-tool-${e.status}`:``}`,"data-subagent-tool":e.label,"data-subagent-tool-detail":e.detail??void 0,"data-subagent-tool-status":e.status??`running`,children:[(0,m.jsx)(`span`,{className:`subagent-tool-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,m.jsx)(`span`,{className:`subagent-tool-label`,title:e.label,children:e.label}),e.detail&&(0,m.jsx)(`span`,{className:`subagent-tool-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,m.jsx)(`span`,{className:`subagent-tool-duration`,children:Gk(e.durationMs)})]}),e.output&&(0,m.jsxs)(`details`,{className:`subagent-tool-log`,children:[(0,m.jsxs)(`summary`,{children:[`命令输出`,e.outputTruncated&&`(尾部)`]}),(0,m.jsx)(`pre`,{className:`call-result-body`,"data-subagent-tool-output":!0,children:e.output})]})]},`${c&&!n?c+t:t}:${e.label}`))]}),e.usage&&(0,m.jsxs)(`div`,{className:`subagent-usage`,"data-subagent-usage":`1`,"data-subagent-turns":e.usage.turns,children:[(0,m.jsxs)(`span`,{children:[e.usage.turns,` 轮`]}),(0,m.jsxs)(`span`,{title:`输入 token`,children:[`↑`,Wk(e.usage.input)]}),(0,m.jsxs)(`span`,{title:`输出 token`,children:[`↓`,Wk(e.usage.output)]}),e.usage.cacheRead>0&&(0,m.jsxs)(`span`,{title:`缓存读取`,children:[`缓存读 `,Wk(e.usage.cacheRead)]}),e.usage.cacheWrite>0&&(0,m.jsxs)(`span`,{title:`缓存写入`,children:[`缓存写 `,Wk(e.usage.cacheWrite)]}),e.usage.cost>0&&(0,m.jsxs)(`span`,{title:`本轮花费`,children:[`$`,e.usage.cost.toFixed(4)]})]}),o.length>10&&(0,m.jsx)(`button`,{type:`button`,className:`subagent-collapse`,"data-subagent-collapse":e.id,"aria-expanded":n,onClick:r,children:n?`收起`:`展开全部 ${o.length} 条`})]})}function eA(e,t=[]){return Array.isArray(t)?t.filter(t=>typeof t?.id==`string`&&(mp(e,t.id)||!t.id.startsWith(`skill:`)&&typeof t.name==`string`&&mp(e,t.name))):[]}function tA(e){let t=e.deliveryMode===`steer`?`steer`:`queue`;return{type:`message.send`,conversationId:e.conversationId,content:e.content,clientId:e.clientId,...e.images?.length?{images:e.images}:{},...e.attachments?.length?{attachments:e.attachments}:{},...e.inFlight&&t===`steer`?{mode:`steer`}:{}}}function nA({mode:e,onChange:t,maintenance:n=!1}){return(0,m.jsxs)(`div`,{className:`composer-delivery-bar`,"data-delivery-mode-bar":`1`,children:[(0,m.jsxs)(`div`,{className:`delivery-mode-group`,role:`radiogroup`,"aria-label":`运行中消息投递模式`,children:[(0,m.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===`queue`,className:`delivery-mode-btn${e===`queue`?` active`:``}`,"data-delivery-mode":`queue`,title:`等待当前回合与前面排队消息完成后依次回答(默认)`,onClick:()=>t(`queue`),children:`排队`}),(0,m.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===`steer`,className:`delivery-mode-btn${e===`steer`?` active`:``}`,"data-delivery-mode":`steer`,disabled:n,title:n?`正在压缩上下文,新消息会在压缩完成后排队处理`:`在当前工具调用完成后的下一回合边界插队回复,不会强行中止正在执行的工具`,onClick:()=>t(`steer`),children:`打断`})]}),(0,m.jsx)(`span`,{className:`delivery-mode-note`,"data-delivery-mode-note":`1`,children:n?`上下文压缩期间仅支持排队,完成后依次处理新消息`:e===`steer`?`将在下一回合边界生效(等当前工具跑完,不强行中止工具)`:`默认排队:等当前回合及前面排队消息完成后回答`})]})}function rA({messages:e,running:t,pendingInterrupts:n=[],onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onCancelMany:s,onEdit:c}){let[l,u]=(0,p.useState)(!1),[d,f]=(0,p.useState)([]),h=(0,p.useMemo)(()=>e.filter(e=>e.delivery!==`sending`).map(e=>e.id),[e]),g=(0,p.useMemo)(()=>d.filter(e=>h.includes(e)),[d,h]);if(!e.length)return null;let _=e.filter(e=>e.delivery===`sending`).length,v=h.length>0&&g.length===h.length,y=e=>{f(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])};return(0,m.jsxs)(`section`,{className:`queue-dock`,"data-queue-dock":`1`,"data-interrupt-pending":n.length,"data-queue-count":e.length,"data-queue-sending":_,"aria-label":`排队等待回答的消息`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`queue-dock-head`,"data-queue-collapse":`1`,"aria-expanded":!l,onClick:()=>u(e=>!e),children:[(0,m.jsx)(`span`,{className:`chevron`,children:l?`▸`:`▾`}),(0,m.jsxs)(`strong`,{children:[e.length,` 条等待回答`]}),_>0&&(0,m.jsxs)(`span`,{className:`queue-dock-badge`,"data-queue-badge":`sending`,children:[`已交给 Agent `,_,` 条`]}),l&&(0,m.jsx)(`span`,{className:`queue-dock-preview`,children:iA(e[0])})]}),!l&&s&&(h.length>1||g.length>0)&&(0,m.jsxs)(`div`,{className:`queue-dock-toolbar`,"data-queue-bulk-toolbar":`1`,children:[(0,m.jsx)(`span`,{className:`queue-dock-selected-count`,children:g.length>0?`已选 ${g.length} 条`:`共 ${h.length} 条可多选撤回`}),(0,m.jsxs)(`div`,{className:`queue-dock-toolbar-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`queue-select-all`,"data-waiting-select-all":`1`,onClick:()=>f(v?[]:h),children:v?`取消全选`:`全选`}),(0,m.jsxs)(`button`,{type:`button`,className:`queue-cancel-selected`,"data-waiting-cancel-selected":`1`,disabled:g.length===0,onClick:()=>{g.length!==0&&(s(g),f([]))},children:[`撤回所选 (`,g.length,`)`]})]})]}),!l&&(0,m.jsx)(`ul`,{className:`queue-dock-list`,children:e.map((l,u)=>(0,m.jsx)(oA,{message:l,order:u+1,total:e.length,interrupting:n.includes(l.id),running:t,selectable:!!(s&&l.delivery!==`sending`),selected:g.includes(l.id),onToggleSelect:y,onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onEdit:c},l.id))})]})}function iA(e){return e.content||(e.images?.length?`【图片】(${e.images.length})`:``)}function aA(e){if(e.role!==`tool`)return{label:`后台回传`,state:`completed`};if(!/<task id="[^"]+" state="[^"]+"/.test(e.content))return{label:(e.content.split(`
|
|
341
|
-
`).find(e=>e.trim().length>0)??``).trim().slice(0,60)||`任务指令`,state:`running`};let t=(()=>{let t=/<summary>([\s\S]*?)<\/summary>/.exec(e.content);return t?t[1].trim():`后台回传`})(),n=/<task id="[^"]+" state="([^"]+)"/.exec(e.content);return{label:t,state:n?n[1]:`completed`}}function
|
|
342
|
-
`)??``}}function lA({question:e,index:t,expanded:n,draft:r,onDraftChange:i,onToggle:a,onAnswer:o}){return(0,m.jsxs)(`div`,{className:`call-block question-block-${e.status}`,"data-call-block":t,"data-call-tool":`question`,"data-call-detail":`提问`,"data-call-status":e.status===`answered`?`ok`:e.status===`cancelled`?`error`:`running`,"data-call-expanded":n?`true`:`false`,"data-question-block":t,children:[(0,m.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-question-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`}提问`,title:n?`折叠这段提问`:`展开这段提问`,onClick:a}),(0,m.jsxs)(`div`,{className:`call-head-row`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:a,children:[(0,m.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,m.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`answered`?`✓`:e.status===`cancelled`?`✕`:`?`}),(0,m.jsx)(`span`,{className:`call-label`,children:`提问`}),(0,m.jsxs)(`span`,{className:`call-detail`,children:[e.items.length,` 个问题`]})]}),n&&(0,m.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:a,children:`收起`})]}),n&&(0,m.jsx)(`div`,{className:`question-body`,"data-question-body":t,children:(0,m.jsx)(uA,{question:e,draft:r,onDraftChange:i,instanceId:`inline`,onAnswer:o})})]})}function uA({question:e,draft:t,onDraftChange:n,instanceId:r,onAnswer:i}){let{picked:a,note:o}=t,s=(e,r,i)=>{let o=(()=>{let t=a,n=t[e]??[];return i?{...t,[e]:n.includes(r)?n.filter(e=>e!==r):[...n,r]}:{...t,[e]:[r]}})();n({...t,picked:o})},c=()=>{i(e.items.map(e=>({id:e.id,selected:a[e.id]??[],...e.extraNote&&o.trim()?{note:o.trim()}:{}})),!1)},l=e.items.some(e=>(a[e.id]??[]).length>0);return(0,m.jsxs)(`div`,{className:`question-block question-${e.status}`,"data-question-status":e.status,children:[e.items.map(i=>(0,m.jsxs)(`div`,{className:`question-item`,children:[(0,m.jsx)(`div`,{className:`question-text`,children:i.header?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:`question-header`,children:i.header}),(0,m.jsx)(`span`,{className:`question-sep`,children:` · `}),(0,m.jsx)(ep,{source:i.question})]}):(0,m.jsx)(ep,{source:i.question})}),(0,m.jsx)(`div`,{className:`question-options`,"data-question-options":i.id,children:i.options.map(t=>{let n=e.status!==`pending`,o=(n?e.answers?.find(e=>e.id===i.id)?.selected:a[i.id])?.includes(t)??!1;return(0,m.jsxs)(`label`,{className:o?`is-chosen`:``,"data-chosen":n&&o?`1`:void 0,children:[(0,m.jsx)(`input`,{type:i.multiple?`checkbox`:`radio`,name:`q-${r}-${i.id}`,checked:o,disabled:n,onChange:()=>s(i.id,t,i.multiple)}),(0,m.jsx)(tp,{source:t}),n&&o?(0,m.jsx)(`span`,{className:`question-mark`,"aria-label":`已选择`,children:`✓`}):null]},t)})}),e.status===`pending`&&i.extraNote?(0,m.jsx)(`textarea`,{value:o,placeholder:`补充说明(可选)`,onChange:e=>n({...t,note:e.target.value})}):e.status===`answered`&&(e.answers??[]).some(e=>e.note)?(0,m.jsxs)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:[`补充:`,(e.answers??[]).map(e=>e.note).filter(Boolean).join(`;`)]}):null,e.status===`cancelled`&&(0,m.jsx)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:`已取消,没有作答。`})]},i.id)),e.status===`pending`&&(0,m.jsxs)(`div`,{className:`question-actions`,children:[(0,m.jsx)(`button`,{type:`button`,onClick:c,disabled:!l,children:`提交`}),(0,m.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:()=>i([],!0),children:`跳过`})]})]})}function dA({question:e,pendingCount:t,minimized:n,floatingRight:r,onMinimize:i,onExpand:a,onLocate:o,draft:s,onDraftChange:c,onAnswer:l}){return n?(0,Ve.createPortal)((0,m.jsxs)(`button`,{type:`button`,className:`question-floating-ball`,style:{"--question-floating-right":r},"data-question-floating-ball":e.key,onClick:a,"aria-label":`展开待回答的问题${t>1?`,还有 ${t-1} 个待处理`:``}`,title:`展开待回答的问题`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`?`}),t>1&&(0,m.jsx)(`small`,{children:t})]}),document.body):(0,Ve.createPortal)((0,m.jsxs)(`section`,{className:`question-floating-panel`,style:{"--question-floating-right":r},"data-question-floating-panel":e.key,role:`dialog`,"aria-labelledby":`question-floating-title`,children:[(0,m.jsxs)(`header`,{className:`question-floating-head`,children:[(0,m.jsx)(`span`,{className:`question-floating-mark`,"aria-hidden":`true`,children:`?`}),(0,m.jsxs)(`h2`,{id:`question-floating-title`,children:[`需要你回答`,t>1?` · 还有 ${t-1} 个`:``]}),(0,m.jsx)(`button`,{type:`button`,className:`question-floating-minimize`,onClick:o,title:`定位到消息上下文并最小化`,children:`查看上下文`}),(0,m.jsx)(`button`,{type:`button`,className:`question-floating-minimize-icon`,onClick:i,title:`最小化为悬浮球`,"aria-label":`最小化问题`,children:`−`})]}),(0,m.jsx)(`div`,{className:`question-floating-body`,children:(0,m.jsx)(uA,{question:e.value,draft:s,onDraftChange:c,instanceId:`floating`,onAnswer:l})})]}),document.body)}function fA({request:e,onAnswer:t,pending:n}){let[r,i]=(0,p.useState)(e.prefill??``),a=e.method===`input`||e.method===`editor`,o=(0,m.jsx)(`button`,{type:`button`,className:`extui-cancel`,onClick:()=>t({cancelled:!0}),children:`取消提问`});return(0,m.jsxs)(`article`,{className:`extui-card extui-${e.method}`,"data-request-id":e.requestId,"data-method":e.method,children:[(0,m.jsxs)(`div`,{className:`extui-head`,children:[(0,m.jsx)(`span`,{className:`extui-badge`,children:`扩展提问`}),e.timeoutMs!==void 0&&(0,m.jsxs)(`span`,{className:`extui-deadline`,children:[Math.ceil(Math.max(0,e.deadlineAt===void 0?e.timeoutMs:e.deadlineAt-Date.now())/1e3),`s 超时`]})]}),n&&(0,m.jsx)(`p`,{className:`extui-pending`,role:`status`,children:`提交中…`}),(0,m.jsxs)(`fieldset`,{disabled:n,style:{border:0,padding:0,margin:0},children:[(0,m.jsx)(`h3`,{className:`extui-title`,children:e.title||EA[e.method]}),e.method===`confirm`&&(0,m.jsx)(`p`,{className:`extui-body`,children:e.message}),e.method===`select`&&(0,m.jsxs)(`div`,{className:`extui-options`,children:[(e.options??[]).map(e=>(0,m.jsx)(`button`,{type:`button`,className:`extui-option`,onClick:()=>t({value:e}),children:e},e)),(e.options??[]).length===0&&(0,m.jsx)(`p`,{className:`extui-body`,children:`扩展没有提供任何选项`})]}),a&&(0,m.jsxs)(`form`,{className:`extui-form`,onSubmit:e=>{e.preventDefault(),!n&&r.trim()&&t({value:r})},children:[e.method===`input`?(0,m.jsx)(`input`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&uk(e)&&e.preventDefault()},placeholder:e.placeholder??``}):(0,m.jsx)(`textarea`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&uk(e)&&e.preventDefault()}}),(0,m.jsxs)(`div`,{className:`extui-actions`,children:[(0,m.jsx)(`button`,{type:`submit`,className:`extui-primary`,disabled:!r.trim(),children:`提交`}),o]})]}),!a&&(0,m.jsxs)(`div`,{className:`extui-actions`,children:[e.method===`confirm`&&(0,m.jsx)(`button`,{type:`button`,className:`extui-primary`,onClick:()=>t({confirmed:!0}),children:`确认`}),e.method===`confirm`&&(0,m.jsx)(`button`,{type:`button`,className:`extui-no`,onClick:()=>t({confirmed:!1}),children:`拒绝`}),o]})]})]})}function pA({initial:e,label:t,onCommit:n,onClose:r}){let[i,a]=(0,p.useState)(e),o=(0,p.useRef)(null),s=(0,p.useRef)(!1);(0,p.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]);let c=!i.trim(),l=()=>{s.current=!0,r()},u=()=>{if(c)return;let t=i.trim();(t===e||n(t))&&l()};return(0,m.jsxs)(`div`,{className:`inline-edit`,"data-editing":`1`,children:[(0,m.jsx)(`input`,{ref:o,className:`inline-edit-input`,value:i,"aria-label":t,onChange:e=>a(e.target.value),onKeyDown:e=>{if(e.key===`Enter`){if(uk(e))return;e.preventDefault(),u()}else e.key===`Escape`&&(e.preventDefault(),l())},onBlur:()=>{s.current||r()}}),(0,m.jsx)(`button`,{type:`button`,className:`inline-edit-ok`,title:`确认重命名`,"aria-label":`确认重命名`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:u,children:`✓`}),(0,m.jsx)(`button`,{type:`button`,className:`inline-edit-cancel`,title:`取消重命名`,"aria-label":`取消重命名`,onMouseDown:e=>e.preventDefault(),onClick:l,children:`✗`})]})}function mA({kind:e,label:t,value:n,detail:r,options:i,disabled:a,note:o,onChoose:s,scope:c,providerOptions:l}){let[u,d]=(0,p.useState)(!1),[f,h]=(0,p.useState)(``),[g,_]=(0,p.useState)(0),[v,y]=(0,p.useState)(`*`),b=(0,p.useRef)(null),x=(0,p.useRef)(null),S=(0,p.useRef)(null),C=(0,p.useRef)(null),w=(0,p.useRef)([]),T=i.find(e=>e.selected),E=Ik(l?i.filter(e=>v===`*`||e.key!==hA&&e.key.split(`/`)[0]===v):i,f),D=E.length===0?-1:Math.min(Math.max(g,0),E.length-1),O=D<0?void 0:E[D],k=(e=!1)=>{d(!1),e&&x.current?.focus()},A=()=>{h(``),y(`*`),_(Math.max(i.findIndex(e=>e.selected),0)),d(!0)},j=e=>_(t=>E.length?Math.min(Math.max(t+e,0),E.length-1):0);(0,p.useEffect)(()=>{if(!u)return;let e=e=>{b.current?.contains(e.target)||k()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[u]),(0,p.useEffect)(()=>{if(!u)return;let e=b.current,t=t=>{e?.contains(t.relatedTarget)||k()};return e?.addEventListener(`focusout`,t),()=>e?.removeEventListener(`focusout`,t)},[u]),(0,p.useEffect)(()=>{u&&C.current?.focus()},[u]),(0,p.useEffect)(()=>{u&&D>=0&&w.current[D]?.scrollIntoView({block:`nearest`})},[u,D]),(0,p.useLayoutEffect)(()=>{if(!u)return;let e=S.current;if(!e)return;e.style.setProperty(`--picker-nudge`,`0px`),e.style.setProperty(`--picker-drop`,`0px`);let t=e.getBoundingClientRect(),n=Math.min(window.innerWidth-8-t.right,Math.max(8-t.left,0)),r=Math.min(window.innerHeight-8-t.bottom,Math.max(8-t.top,0));e.style.setProperty(`--picker-nudge`,`${n}px`),e.style.setProperty(`--picker-drop`,`${r}px`)},[u,E.length,i.length]);let ee=e=>{if(u){if(e.key===`Escape`)e.preventDefault(),k(!0);else if(e.key===`ArrowDown`)e.preventDefault(),j(1);else if(e.key===`ArrowUp`)e.preventDefault(),j(-1);else if(e.key===`Home`)e.preventDefault(),_(0);else if(e.key===`End`)e.preventDefault(),_(Math.max(E.length-1,0));else if(e.key===`Enter`){if(uk(e))return;e.preventDefault(),O&&(s(O.key),k(!0))}}},M=`picker-list-${c??e}`,N=t=>`picker-option-${c??e}-${t}`;return(0,m.jsxs)(`div`,{className:`session-picker-item session-picker-${e}`,ref:b,onKeyDown:u?ee:void 0,children:[(0,m.jsxs)(`button`,{ref:x,type:`button`,className:`session-picker-trigger`,disabled:a,"aria-haspopup":`listbox`,"aria-expanded":u,title:o??`${Ok[e]}:${r?`${t} · ${r}`:t}`,"data-picker-trigger":e,"data-picker-value":n??t,"data-picker-selected":i.some(e=>e.selected),onClick:()=>u?k():A(),children:[(0,m.jsx)(`span`,{className:`session-picker-kind`,children:Ok[e]}),(0,m.jsx)(`span`,{className:`session-picker-name`,children:t}),r&&(0,m.jsx)(`span`,{className:`session-picker-detail`,children:r}),(0,m.jsx)(`span`,{className:`session-picker-caret`,"aria-hidden":`true`,children:`▾`})]}),u&&(0,m.jsxs)(`div`,{className:`picker-menu`,ref:S,"data-picker-menu":e,"data-picker-highlight":D,children:[l&&(0,m.jsxs)(`label`,{className:`picker-provider-filter`,children:[(0,m.jsx)(`span`,{children:`Provider`}),(0,m.jsxs)(`select`,{"data-picker-provider":e,"aria-label":`筛选模型 Provider`,value:v,onKeyDown:e=>e.stopPropagation(),onChange:e=>{y(e.target.value),_(0)},children:[(0,m.jsx)(`option`,{value:`*`,children:`全部 Provider`}),l.map(e=>(0,m.jsx)(`option`,{value:e,children:e},e))]})]}),(0,m.jsxs)(`div`,{className:`picker-filter`,children:[(0,m.jsx)(`span`,{className:`picker-filter-icon`,"aria-hidden":`true`,children:`🔍`}),(0,m.jsx)(`input`,{ref:C,className:`picker-filter-input`,"data-picker-filter":e,role:`combobox`,"aria-label":`筛选${Ak[e]}选项`,"aria-expanded":`true`,"aria-controls":M,"aria-autocomplete":`list`,"aria-activedescendant":O?N(D):void 0,value:f,placeholder:`输入以筛选…`,autoComplete:`off`,spellCheck:!1,onChange:e=>{h(e.target.value),_(0)}}),f&&(0,m.jsx)(`button`,{type:`button`,className:`picker-filter-clear`,"data-picker-filter-clear":e,title:`清空筛选`,"aria-label":`清空筛选`,onMouseDown:e=>e.preventDefault(),onClick:()=>{h(``),_(0),C.current?.focus()},children:`✕`})]}),T&&!E.some(e=>e.key===T.key)&&(0,m.jsxs)(`div`,{className:`picker-current`,"data-picker-current":e,"data-picker-current-value":T.key,children:[(0,m.jsx)(`span`,{className:`picker-current-label`,children:`当前`}),(0,m.jsx)(`span`,{className:`picker-current-value`,children:T.label})]}),(0,m.jsxs)(`div`,{className:`picker-list`,role:`listbox`,id:M,"aria-label":Mk[e],children:[E.map((e,t)=>(0,m.jsxs)(`button`,{id:N(t),type:`button`,role:`option`,"aria-selected":e.selected,ref:e=>{w.current[t]=e},className:`picker-option${e.selected?` selected`:``}${t===D&&!e.selected?` preview`:``}`,"data-picker-option":e.key,"data-picker-option-selected":e.selected,"data-picker-highlight":t===D,onClick:()=>{s(e.key),k(!0)},children:[e.color&&(0,m.jsx)(`span`,{className:`picker-option-swatch`,style:{background:e.color},"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:`picker-option-name`,children:e.label}),e.badge&&(0,m.jsx)(`span`,{className:`picker-option-badge`,"data-picker-option-badge":e.badge,children:e.badge}),e.detail&&(0,m.jsx)(`span`,{className:`picker-option-detail`,children:e.detail}),e.selected&&(0,m.jsx)(`span`,{className:`picker-option-mark`,"aria-hidden":`true`,children:`✓`})]},e.key)),E.length===0&&(0,m.jsx)(`div`,{className:`picker-empty`,"data-picker-empty":e,children:i.length===0?jk[e]:`没有匹配「${f.trim()}」的${Ak[e]}`})]})]})]})}var hA=`__pi_default__`;function gA({workspace:e,catalog:t,agents:n,onSave:r,onRename:i,onRemove:a,onClose:o}){let[s,c]=(0,p.useState)(e.defaultAgentId),[l,u]=(0,p.useState)(e.defaultModel),[d,f]=(0,p.useState)(e.defaultThinkingLevel);(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let h=t?.source===`pi`,g=[{key:hA,label:`跟随 Pi 默认`,detail:`不为新会话指定模型`,selected:l===void 0},...(t?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:[e.detail,UO(e.contextWindow)?`${UO(e.contextWindow)} 上下文`:``,WO(e.maxTokens)?`${WO(e.maxTokens)} 输出`:``].filter(Boolean).join(` · `),badge:Pk(e),selected:l?.provider===e.provider&&l.modelId===e.modelId}))],_=t?.models.find(e=>e.provider===l?.provider&&e.modelId===l?.modelId),v=_?.thinkingLevels??t?.levels??[],y=[{key:hA,label:`跟随 Pi 默认`,detail:`不为新会话指定思考等级`,selected:d===void 0},...v.map(e=>({key:e,label:e,selected:e===d}))],b=e=>{if(e===hA){u(void 0),f(void 0);return}let n=(t?.models??[]).find(t=>t.provider===e.split(`/`)[0]&&t.modelId===e.split(`/`)[1]);if(n){let e=l?.provider!==n.provider||l.modelId!==n.modelId;u({provider:n.provider,modelId:n.modelId,label:n.label}),e&&f(void 0)}},x=e=>f(e===hA?void 0:e),S=[{key:hA,label:`跟随 Pi 默认`,detail:`新会话不使用任何 agent 角色`,selected:s===void 0},...(n?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:s===e.id}))];return(0,m.jsx)(`div`,{className:`overlay`,onClick:o,children:(0,m.jsxs)(`div`,{className:`picker settings-dialog`,"data-settings-dialog":`1`,onClick:e=>e.stopPropagation(),children:[(0,m.jsx)(`h2`,{children:`工作区设置`}),(0,m.jsxs)(`div`,{className:`settings-scope`,children:[e.name,` · 默认值只影响之后新建的会话,已有会话不变`]}),(0,m.jsx)(`div`,{className:`workspace-settings-path`,children:e.path}),(0,m.jsxs)(`div`,{className:`settings-row`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认智能体`}),(0,m.jsx)(mA,{kind:`agent`,scope:`settings-agent`,label:n?.agents.find(e=>e.id===s)?.name??`跟随 Pi 默认`,value:s??hA,detail:s?`${n?.agents.find(e=>e.id===s)?.toolSummary??``}`:void 0,options:S,disabled:!n||n.source===`unavailable`,note:Uk(n),onChoose:e=>c(e===hA?void 0:e)})]}),(0,m.jsxs)(`div`,{className:`settings-row`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,m.jsx)(mA,{kind:`model`,scope:`settings-model`,label:l?.label??`跟随 Pi 默认`,value:l?`${l.provider}/${l.modelId}`:hA,detail:l?`${l.provider}/${l.modelId}`:void 0,options:g,providerOptions:[...new Set((t?.models??[]).map(e=>e.provider))],disabled:!h,note:Hk(`模型`,t),onChoose:b})]}),(0,m.jsxs)(`div`,{className:`settings-row`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`思考强度`}),(0,m.jsx)(mA,{kind:`thinking`,scope:`settings-thinking`,label:d??`跟随 Pi 默认`,value:d??hA,options:y,disabled:!h,note:Hk(`思考等级`,t),onChoose:x})]}),l&&_&&v.length===0&&(0,m.jsx)(`div`,{className:`settings-scope`,children:`Pi 未提供此模型的可选等级,使用模型默认值。`}),(0,m.jsxs)(`div`,{className:`picker-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`settings-rename`,"data-settings-rename":`1`,onClick:i,children:`重命名工作区`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-settings-cancel":`1`,onClick:o,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-ok`,"data-settings-save":`1`,onClick:()=>r(s,l,d),children:`保存`})]}),(0,m.jsx)(`button`,{type:`button`,className:`workspace-delete`,onClick:a,children:`从列表移除工作区`})]})})}var _A=[{id:`main`,label:`任务`,name:`任务与后台任务`},{id:`projects`,label:`项目`,name:`项目控制面`},{id:`tools`,label:`工具`,name:`工具 tab`},{id:`files`,label:`文件`,name:`文件 tab`},{id:`git`,label:`Git`,name:`Git tab`},{id:`rsi`,label:`RSI`,name:`RSI 观察与改进`},{id:`terminal`,label:`终端`,name:`终端 tab`}],vA=`super-pi.right-tabs.v1`;function yA(){let e=e=>_A.some(t=>t.id===e),t={tab:_A[0].id,byConversation:{}};try{let n=JSON.parse(Gn(vA)??`null`);return!n||!e(n.tab)?t:{tab:n.tab,byConversation:Object.fromEntries(Object.entries(n.byConversation??{}).filter(t=>e(t[1])))}}catch{return t}}var bA={waiting:`⋯`,running:``,failed:``,question:`?`,completed:``,unread:`•`,idle:``,awaiting_background:`⚙`,pending_report:`↑`,awaiting_subordinates:`↓`,awaiting_decision:`▲`},xA={idle:`空闲`,running:`讨论中`,awaiting_background:`后台任务进行中`,completed:`讨论已完成`,failed:`讨论未完成`},SA={waiting:`等待 LLM`,running:`进行中`,failed:`出错`,question:`等你回答`,completed:`已完成`,unread:`有未读`,idle:`空闲`,awaiting_background:`等待后台任务`,pending_report:`待汇报`,awaiting_subordinates:`等待下级`,awaiting_decision:`等上面拍板`},CA={idle:`就绪`,waiting:`等待 LLM`,running:`正在生成`,completed:`已完成`,stopped:`已停止`,failed:`运行失败`,awaiting_background:`等待后台任务`},wA=e=>e?.status===`running`||e?.status===`waiting`||e?.compaction?.status===`running`,TA={running:`运行中`,completed:`已完成`,failed:`失败`,stopped:`已停止`,cancelled:`已取消`,interrupted:`已中断`},EA={select:`请选择一项`,confirm:`请确认`,input:`请输入内容`,editor:`请输入内容`,notify:`扩展通知`,setStatus:`扩展状态`,setWidget:`扩展内容`,setTitle:`扩展标题`,set_editor_text:`扩展输入`};function DA(e,t){return t.some(t=>t.conversationId===e.id)?!0:e.messagesLoaded===!1?e.hasPendingQuestion===!0:e.messages.some(e=>(e.toolCalls??[]).some(e=>e.question?.status===`pending`))}function OA(e,t,n){let r=(t||[]).filter(t=>t.parentConversationId===e.id),i=(t||[]).find(t=>t.id===e.parentConversationId),a=n??``;return $n({conversation:e,parent:i,directChildren:r,isTopLevelUnread:e.updatedAt>a})}function kA(e,t,n,r){let i=OA(e,r,n);return er({status:e.status,reportingState:i,awaitingQuestion:t,quietWhenRead:!0})}function AA(e,t){return t===`awaiting_decision`||e===`awaiting_decision`?(0,m.jsx)(`span`,{className:`conversation-status-badge badge--warning project-status-awaiting_decision`,"data-session-status":`awaiting_decision`,"data-reporting-badge":`awaiting_decision`,title:SA.awaiting_decision,children:SA.awaiting_decision}):t===`awaiting_subordinates`||e===`awaiting_subordinates`?(0,m.jsx)(`span`,{className:`conversation-status-badge project-status-awaiting_subordinates`,"data-session-status":`awaiting_subordinates`,"data-reporting-badge":`awaiting_subordinates`,title:SA.awaiting_subordinates,children:SA.awaiting_subordinates}):t===`pending_report`||e===`pending_report`?(0,m.jsx)(`span`,{className:`conversation-status-badge project-status-pending_report`,"data-session-status":`pending_report`,"data-reporting-badge":`pending_report`,title:SA.pending_report,children:SA.pending_report}):null}function jA({state:e,label:t=SA[e]}){let n=bA[e];if(e===`idle`)return null;let r=e.replace(/_/g,`-`);return(0,m.jsx)(`i`,{className:`session-state session-state-${e} session-state-${r}`,"data-session-state":e,title:t,"aria-label":t,...e===`awaiting_background`?{style:{color:`var(--accent)`}}:{},children:(0,m.jsx)(`i`,{className:`session-state-mark`,"aria-hidden":`true`,children:n})})}function MA(e,t){return(0,m.jsxs)(m.Fragment,{children:[e.origin===`orchestrator`&&(0,m.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`orchestrator`,title:`编排会话:由上级智能体创建`,"aria-label":`编排会话:由上级智能体创建`,children:`编排`}),t&&(0,m.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`scheduled`,title:`定时任务会话:${t.name}`,"aria-label":`定时任务会话:${t.name}`,children:`定时`})]})}function NA(e,t){let n=[];return e.origin===`orchestrator`&&n.push(`编排会话`),t&&n.push(`定时任务会话:${t.name}`),n.length?`(${n.join(`;`)})`:``}var PA={pending:`未开始`,in_progress:`运行中`,completed:`已完成`},FA={pending:`○`,in_progress:`◐`,completed:`✓`},IA={high:`高`,medium:`中`,low:`低`};function LA(e){let t=e.filter(e=>e.status!==`completed`).length;return e.length?t?`${t} 个未完成 / 共 ${e.length} 个`:`全部完成:${e.length} 个`:`0 个待办任务`}function RA({todo:e,index:t}){let n=e.id??`todo_${t}`;return(0,m.jsxs)(`li`,{className:`todo-item todo-${e.status}`,"data-todo-item":n,"data-todo-status":e.status,title:`状态:${PA[e.status]}`,children:[(0,m.jsx)(`span`,{className:`todo-mark`,"aria-hidden":`true`,children:FA[e.status]}),(0,m.jsx)(`span`,{className:`todo-text`,children:e.content}),(0,m.jsx)(`span`,{className:`todo-status`,"data-todo-status-text":`1`,children:PA[e.status]}),e.priority&&(0,m.jsx)(`span`,{className:`todo-priority`,"data-todo-priority":e.priority,children:IA[e.priority]})]})}function zA(e,t){if(!e)return[];let n=t.filter(t=>t.conversationId===e.id&&t.status===`running`),r=new Set(n.map(e=>e.id));for(let t of e.messages)t.toolCalls?.forEach((i,a)=>{let o=i.backgroundTask;o&&o.status===`running`&&!r.has(o.id)&&(r.add(o.id),n.push({id:o.id,conversationId:e.id,title:i.detail?.trim()||i.label?.trim()||o.id,status:o.status,originMessageId:t.id,originCallRow:a}))});return n}function BA({tasks:e,runs:t,execOutputs:n,onStop:r}){return(0,m.jsx)(`ul`,{className:`bg-list`,"data-bg-task-count":e.length,children:e.map((e,i)=>{let a=e.id||`bg_${i}`,o=e.status?.trim()||``,s=o?TA[o]??(/[\u3400-\u9fff]/.test(o)?o:`未知状态`):`未知状态`;return(0,m.jsx)(VA,{task:e,status:s,run:t?.get(e.id),execOutputs:n,onStop:r},a)})})}function VA({task:e,status:t,run:n,execOutputs:r,onStop:i}){let[a,o]=(0,p.useState)(!1),s=Jk(e.id,r),c=n?JO(n):s?.text||e.output,l=c&&qO(c),u=n?n.outputTruncated||n.toolCalls?.some(e=>e.outputTruncated):s?.truncated??e.outputTruncated;return(0,m.jsxs)(`li`,{className:`bg-item${a?` bg-item-expanded`:``}`,"data-bg-task":e.id,"data-bg-task-status":e.status??`unknown`,title:`状态:${t}`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`bg-item-toggle`,onClick:()=>o(e=>!e),"aria-expanded":a,"aria-label":`展开后台任务详情`,children:[(0,m.jsx)(`span`,{className:`bg-title`,children:e.title?.trim()||e.id||`未命名任务`}),(0,m.jsxs)(`span`,{className:`bg-meta`,children:[e.agentId?.trim()&&(0,m.jsx)(`span`,{className:`bg-agent`,"data-bg-agent":e.agentId,children:e.agentId}),(0,m.jsx)(`span`,{className:`bg-status`,children:t})]})]}),i&&(0,m.jsx)(`button`,{type:`button`,className:`bg-stop-btn`,"data-bg-task-stop":e.id,title:`终止后台任务`,onClick:()=>i(e.id),children:`终止`}),a&&(0,m.jsx)(`pre`,{className:`bg-output`,"data-bg-output":e.id,children:[u?`日志仅保留最近一段。`:``,l].filter(Boolean).join(`
|
|
340
|
+
`)||(e.status===`running`?`等待输出…`:`任务未产生输出。`)})]})}function eA({call:e,index:t,expanded:n,onToggle:r,backgroundOutput:i,runCard:a}){let o=e.args??[];return(0,m.jsxs)(`div`,{className:`call-block call-block-${e.status??`running`}`,"data-call-block":t,"data-call-tool":e.label,"data-call-detail":e.detail??void 0,"data-call-status":e.status??`running`,"data-call-expanded":n?`true`:`false`,"data-call-arg-count":o.length,"data-thinking-at":e.thinkingAt,"data-background-exec":e.backgroundTask?.id,"data-background-status":e.backgroundTask?.status,children:[(0,m.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-call-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`} ${e.label} 调用`,title:n?`折叠这次调用`:`展开这次调用`,onClick:r}),(0,m.jsxs)(`div`,{className:`call-head-row`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:r,children:[(0,m.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,m.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,m.jsx)(`span`,{className:`call-label`,title:e.label,children:e.label}),e.detail&&(0,m.jsx)(`span`,{className:`call-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,m.jsx)(`span`,{className:`call-duration`,children:Yk(e.durationMs)}),e.backgroundTask&&(0,m.jsxs)(`span`,{className:`call-background-status`,"data-background-status-text":e.backgroundTask.status,children:[`后台任务 · `,kA[e.backgroundTask.status]??`未知状态`,e.backgroundTask.exitCode===void 0?``:` · 退出码:${e.backgroundTask.exitCode}`]}),e.preparing&&(0,m.jsx)(`span`,{className:`call-preparing`,"data-call-preparing":t,children:`生成参数中…`})]}),n&&(0,m.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:r,children:`收起`})]}),!n&&e.live&&(0,m.jsx)(`div`,{className:`call-live-preview`,"data-call-live-preview":t,title:`展开查看完整输出`,children:Zk(e.live)}),n&&(0,m.jsx)(`div`,{className:`call-args`,"data-call-args":o.length,children:o.length===0?(0,m.jsx)(`div`,{className:`call-arg call-arg-empty`,"data-call-arg-empty":t,children:`(这次调用没有可显示的参数)`}):o.map(e=>(0,m.jsxs)(`div`,{className:`call-arg`,"data-call-arg":e.key,"data-call-arg-value":e.value,children:[(0,m.jsx)(`span`,{className:`call-arg-key`,children:e.key}),(0,m.jsx)(`span`,{className:`call-arg-value`,title:e.value,children:e.value})]},e.key))}),n&&(e.result||e.live||i)&&(0,m.jsxs)(`div`,{className:`call-result`,"data-call-result":t,"data-call-result-state":e.result?`done`:`running`,children:[(e.result||e.live)&&(0,m.jsxs)(`div`,{className:`call-result-head`,children:[(0,m.jsx)(`span`,{className:`call-result-title`,children:e.result&&!e.live?`执行结果`:e.result?`执行结果 · 完整输出`:`执行中 · 输出预览`}),e.result?(0,m.jsx)(tA,{index:t,text:e.live??e.result.text}):null]}),(e.result||e.live)&&(0,m.jsx)(`pre`,{className:`call-result-body`,"data-call-result-body":t,children:e.live??e.result?.text}),e.result?.truncated&&e.live&&(0,m.jsx)(`div`,{className:`call-result-truncated`,children:`(服务端已截断到末尾 8 KB;上方显示的是执行中累积的完整输出)`}),e.result?.truncated&&!e.live&&(0,m.jsxs)(`div`,{className:`call-result-truncated`,children:[`(输出过长,已保留末尾关键内容`,e.result.droppedLines?`,省略前 ${e.result.droppedLines} 行`:``,`)`]}),i]}),!n&&i,a]})}function tA({index:e,text:t}){let[n,r]=(0,p.useState)(!1);return(0,m.jsx)(`button`,{type:`button`,className:`call-result-copy`,"data-call-result-copy":e,onClick:async()=>{await Hi(t)&&(r(!0),window.setTimeout(()=>r(!1),1600))},children:n?`已复制`:`复制`})}function nA({messageId:e,nestedCount:t,liveCall:n,liveAwaitingReader:r,liveExtra:i,preview:a,expanded:o,onToggle:s,children:c}){return(0,m.jsxs)(`section`,{className:`thinking-block`,"data-thinking-block":e,"data-thinking-expanded":o?`true`:`false`,"data-thinking-calls":t,children:[(0,m.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-thinking-fold-edge":e,"aria-expanded":o,"aria-label":`${o?`折叠`:`展开`}这段思考`,title:o?`折叠这段思考`:`展开这段思考`,onClick:s}),(0,m.jsxs)(`button`,{type:`button`,className:`thinking-head`,"data-thinking-head":e,"aria-expanded":o,title:o?`折叠这段思考`:`展开这段思考`,onClick:s,children:[(0,m.jsx)(`span`,{className:`thinking-chevron`,"aria-hidden":`true`,children:o?`▾`:`▸`}),(0,m.jsx)(`span`,{className:`thinking-label`,children:`思考`}),t>0&&(0,m.jsxs)(`span`,{className:`thinking-count`,"data-thinking-count":t,children:[t,` 次工具调用`]}),!o&&n&&(0,m.jsxs)(`span`,{className:`thinking-live${r?` thinking-live-question`:``}`,"data-thinking-live":n,"data-thinking-live-extra":i??0,"data-thinking-awaiting-reader":r?`1`:void 0,children:[(0,m.jsx)(`span`,{className:`thinking-live-glyph`,"aria-hidden":`true`,children:r?`?`:`⚙`}),r?`等你回答`:`正在执行 ${n}`,i?` 等 ${i+1} 个`:``]}),!o&&a&&(0,m.jsx)(`span`,{className:`thinking-preview`,title:a,children:a})]}),o&&(0,m.jsx)(`div`,{className:`thinking-body`,"data-thinking-body":e,children:c})]})}function rA({run:e,name:t,expanded:n,onToggle:r,onStop:i,stopping:a}){let o=e.toolCalls??[],s=n?o:o.slice(-10),c=o.length-s.length,l=e.status===`running`,u=e.partialOutput??e.output??``,d=e.dispatchedBy===`model`,[f,h]=(0,p.useState)(0);(0,p.useEffect)(()=>{if(!l)return;h(Date.now());let e=window.setInterval(()=>h(Date.now()),200);return()=>window.clearInterval(e)},[l,e.startedAt]);let g=Date.parse(e.startedAt),_=l&&f>0&&Number.isFinite(g)?f-g:void 0,v=[...o].reverse().find(e=>e.status===void 0)?.label;return(0,m.jsxs)(`article`,{className:`subagent-card subagent-${e.status}${d?` subagent-by-model`:``}`,"data-subagent-card":e.id,"data-subagent-status":e.status,"data-subagent-agent":e.agentId,"data-subagent-tools":o.length,"data-subagent-dispatched-by":d?`model`:`human`,children:[(0,m.jsxs)(`div`,{className:`subagent-head`,children:[(0,m.jsx)(`span`,{className:`subagent-badge`,children:`子智能体`}),d&&(0,m.jsxs)(`span`,{className:`subagent-source`,"data-subagent-source":`model`,title:`primary 模型自己决定派这个子智能体去干活`,children:[(0,m.jsx)(`span`,{className:`subagent-source-glyph`,"aria-hidden":`true`,children:`⚡`}),`模型自主派发`]}),(0,m.jsx)(`strong`,{className:`subagent-name`,"data-subagent-name":`1`,children:t||e.agentId}),(0,m.jsx)(`span`,{className:`subagent-status`,"data-subagent-status-text":`1`,children:l?`运行中`:e.status===`completed`?`已完成`:e.status===`stopped`?`已停止`:`失败`}),l?_!==void 0&&(0,m.jsxs)(`span`,{className:`subagent-clock`,"data-subagent-elapsed":`1`,"data-subagent-elapsed-ms":_,children:[`已运行 `,Yk(_)]}):e.durationMs!==void 0&&(0,m.jsxs)(`span`,{className:`subagent-duration`,"data-subagent-duration":`1`,"data-subagent-duration-ms":e.durationMs,children:[`用时 `,Yk(e.durationMs)]}),l&&(0,m.jsx)(`button`,{type:`button`,className:`subagent-stop`,"data-subagent-stop":e.id,disabled:a,onClick:i,children:`停止`})]}),l&&e.activity&&(0,m.jsxs)(`div`,{className:`subagent-activity`,"data-subagent-activity":e.activity.kind,"data-subagent-activity-at":e.activity.at,children:[(0,m.jsx)(`span`,{className:`subagent-activity-dot`,"aria-hidden":`true`}),e.activity.kind===`tool`?`正在调用 ${e.activity.label??`工具`}`:`正在思考…`]}),(0,m.jsxs)(`div`,{className:`subagent-task`,"data-subagent-task":`1`,children:[d&&(0,m.jsx)(`span`,{className:`subagent-task-source`,"data-subagent-model-task":`1`,children:`模型给的任务`}),e.task]}),(0,m.jsxs)(`div`,{className:`subagent-output`,"data-subagent-output":`1`,"data-live-length":u.length,children:[u||(l?`…`:`(没有输出)`),e.outputTruncated&&`(输出已截断)`]}),e.failure&&(0,m.jsxs)(`div`,{className:`subagent-failure`,"data-subagent-failure":`1`,"data-subagent-failure-stage":e.failure.stage,children:[(0,m.jsx)(`span`,{className:`subagent-failure-label`,children:`卡在`}),(0,m.jsx)(`span`,{className:`subagent-failure-stage`,"data-subagent-failure-text":`1`,children:Xk[e.failure.stage]}),e.failure.stage===`tool`&&v&&(0,m.jsxs)(`span`,{className:`subagent-failure-tool`,"data-subagent-failure-tool":`1`,children:[`· 正在跑 `,v]}),o.length>0&&(0,m.jsxs)(`span`,{className:`subagent-failure-progress`,children:[`· 死前已尝试 `,o.length,` 次工具调用`]})]}),e.error&&(0,m.jsx)(`div`,{className:`subagent-error`,"data-subagent-error":`1`,title:Br(e.error),children:zr(e.error,`这条子任务没有完成。`)}),o.length>0&&(0,m.jsxs)(`div`,{className:`subagent-tools`,"data-subagent-tool-count":o.length,children:[c>0&&!n&&(0,m.jsxs)(`button`,{type:`button`,className:`subagent-more`,"data-subagent-hidden":c,onClick:r,children:[`… 另有 `,c,` 条工具调用`]}),s.map((e,t)=>(0,m.jsxs)(`div`,{children:[(0,m.jsxs)(`div`,{className:`subagent-tool${e.status?` subagent-tool-${e.status}`:``}`,"data-subagent-tool":e.label,"data-subagent-tool-detail":e.detail??void 0,"data-subagent-tool-status":e.status??`running`,children:[(0,m.jsx)(`span`,{className:`subagent-tool-glyph`,"aria-hidden":`true`,children:e.status===`error`?`✕`:e.status===`ok`?`✓`:`·`}),(0,m.jsx)(`span`,{className:`subagent-tool-label`,title:e.label,children:e.label}),e.detail&&(0,m.jsx)(`span`,{className:`subagent-tool-detail`,title:e.detail,children:e.detail}),e.durationMs!==void 0&&(0,m.jsx)(`span`,{className:`subagent-tool-duration`,children:Yk(e.durationMs)})]}),e.output&&(0,m.jsxs)(`details`,{className:`subagent-tool-log`,children:[(0,m.jsxs)(`summary`,{children:[`命令输出`,e.outputTruncated&&`(尾部)`]}),(0,m.jsx)(`pre`,{className:`call-result-body`,"data-subagent-tool-output":!0,children:e.output})]})]},`${c&&!n?c+t:t}:${e.label}`))]}),e.usage&&(0,m.jsxs)(`div`,{className:`subagent-usage`,"data-subagent-usage":`1`,"data-subagent-turns":e.usage.turns,children:[(0,m.jsxs)(`span`,{children:[e.usage.turns,` 轮`]}),(0,m.jsxs)(`span`,{title:`输入 token`,children:[`↑`,Jk(e.usage.input)]}),(0,m.jsxs)(`span`,{title:`输出 token`,children:[`↓`,Jk(e.usage.output)]}),e.usage.cacheRead>0&&(0,m.jsxs)(`span`,{title:`缓存读取`,children:[`缓存读 `,Jk(e.usage.cacheRead)]}),e.usage.cacheWrite>0&&(0,m.jsxs)(`span`,{title:`缓存写入`,children:[`缓存写 `,Jk(e.usage.cacheWrite)]}),e.usage.cost>0&&(0,m.jsxs)(`span`,{title:`本轮花费`,children:[`$`,e.usage.cost.toFixed(4)]})]}),o.length>10&&(0,m.jsx)(`button`,{type:`button`,className:`subagent-collapse`,"data-subagent-collapse":e.id,"aria-expanded":n,onClick:r,children:n?`收起`:`展开全部 ${o.length} 条`})]})}function iA(e,t=[]){return Array.isArray(t)?t.filter(t=>typeof t?.id==`string`&&(mp(e,t.id)||!t.id.startsWith(`skill:`)&&typeof t.name==`string`&&mp(e,t.name))):[]}function aA(e){let t=e.deliveryMode===`steer`?`steer`:`queue`;return{type:`message.send`,conversationId:e.conversationId,content:e.content,clientId:e.clientId,...e.images?.length?{images:e.images}:{},...e.attachments?.length?{attachments:e.attachments}:{},...e.inFlight&&t===`steer`?{mode:`steer`}:{}}}function oA({mode:e,onChange:t,maintenance:n=!1}){return(0,m.jsxs)(`div`,{className:`composer-delivery-bar`,"data-delivery-mode-bar":`1`,children:[(0,m.jsxs)(`div`,{className:`delivery-mode-group`,role:`radiogroup`,"aria-label":`运行中消息投递模式`,children:[(0,m.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===`queue`,className:`delivery-mode-btn${e===`queue`?` active`:``}`,"data-delivery-mode":`queue`,title:`等待当前回合与前面排队消息完成后依次回答(默认)`,onClick:()=>t(`queue`),children:`排队`}),(0,m.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e===`steer`,className:`delivery-mode-btn${e===`steer`?` active`:``}`,"data-delivery-mode":`steer`,disabled:n,title:n?`正在压缩上下文,新消息会在压缩完成后排队处理`:`在当前工具调用完成后的下一回合边界插队回复,不会强行中止正在执行的工具`,onClick:()=>t(`steer`),children:`打断`})]}),(0,m.jsx)(`span`,{className:`delivery-mode-note`,"data-delivery-mode-note":`1`,children:n?`上下文压缩期间仅支持排队,完成后依次处理新消息`:e===`steer`?`将在下一回合边界生效(等当前工具跑完,不强行中止工具)`:`默认排队:等当前回合及前面排队消息完成后回答`})]})}function sA({messages:e,running:t,pendingInterrupts:n=[],onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onCancelMany:s,onEdit:c}){let[l,u]=(0,p.useState)(!1),[d,f]=(0,p.useState)([]),h=(0,p.useMemo)(()=>e.filter(e=>e.delivery!==`sending`).map(e=>e.id),[e]),g=(0,p.useMemo)(()=>d.filter(e=>h.includes(e)),[d,h]);if(!e.length)return null;let _=e.filter(e=>e.delivery===`sending`).length,v=h.length>0&&g.length===h.length,y=e=>{f(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])};return(0,m.jsxs)(`section`,{className:`queue-dock`,"data-queue-dock":`1`,"data-interrupt-pending":n.length,"data-queue-count":e.length,"data-queue-sending":_,"aria-label":`排队等待回答的消息`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`queue-dock-head`,"data-queue-collapse":`1`,"aria-expanded":!l,onClick:()=>u(e=>!e),children:[(0,m.jsx)(`span`,{className:`chevron`,children:l?`▸`:`▾`}),(0,m.jsxs)(`strong`,{children:[e.length,` 条等待回答`]}),_>0&&(0,m.jsxs)(`span`,{className:`queue-dock-badge`,"data-queue-badge":`sending`,children:[`已交给 Agent `,_,` 条`]}),l&&(0,m.jsx)(`span`,{className:`queue-dock-preview`,children:cA(e[0])})]}),!l&&s&&(h.length>1||g.length>0)&&(0,m.jsxs)(`div`,{className:`queue-dock-toolbar`,"data-queue-bulk-toolbar":`1`,children:[(0,m.jsx)(`span`,{className:`queue-dock-selected-count`,children:g.length>0?`已选 ${g.length} 条`:`共 ${h.length} 条可多选撤回`}),(0,m.jsxs)(`div`,{className:`queue-dock-toolbar-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`queue-select-all`,"data-waiting-select-all":`1`,onClick:()=>f(v?[]:h),children:v?`取消全选`:`全选`}),(0,m.jsxs)(`button`,{type:`button`,className:`queue-cancel-selected`,"data-waiting-cancel-selected":`1`,disabled:g.length===0,onClick:()=>{g.length!==0&&(s(g),f([]))},children:[`撤回所选 (`,g.length,`)`]})]})]}),!l&&(0,m.jsx)(`ul`,{className:`queue-dock-list`,children:e.map((l,u)=>(0,m.jsx)(uA,{message:l,order:u+1,total:e.length,interrupting:n.includes(l.id),running:t,selectable:!!(s&&l.delivery!==`sending`),selected:g.includes(l.id),onToggleSelect:y,onSteer:r,onInterrupt:i,onSend:a,onCancel:o,onEdit:c},l.id))})]})}function cA(e){return e.content||(e.images?.length?`【图片】(${e.images.length})`:``)}function lA(e){if(e.role!==`tool`)return{label:`后台回传`,state:`completed`};if(!/<task id="[^"]+" state="[^"]+"/.test(e.content))return{label:(e.content.split(`
|
|
341
|
+
`).find(e=>e.trim().length>0)??``).trim().slice(0,60)||`任务指令`,state:`running`};let t=(()=>{let t=/<summary>([\s\S]*?)<\/summary>/.exec(e.content);return t?t[1].trim():`后台回传`})(),n=/<task id="[^"]+" state="([^"]+)"/.exec(e.content);return{label:t,state:n?n[1]:`completed`}}function uA({message:e,order:t,total:n,running:r,interrupting:i=!1,selectable:a=!1,selected:o=!1,onToggleSelect:s,onSteer:c,onInterrupt:l,onSend:u,onCancel:d,onEdit:f}){let[h,g]=(0,p.useState)(!1),[_,v]=(0,p.useState)(e.content),y=e.delivery===`sending`,b=e.source===`session-reminder`,x=e.role===`tool`&&!b,{label:S,state:C}=x?lA(e):{label:cA(e),state:`user`},w=()=>{let t=_.trim();t&&t!==e.content&&f(e.id,t),g(!1)};return(0,m.jsxs)(`li`,{className:`queue-row ${y?`queue-row-sending`:`queue-row-queued`} ${x?`queue-row-bg-result`:``}`,"data-queue-id":e.id,"data-message-delivery":e.delivery,"data-message-role":e.role,"data-bg-result-state":x?C:void 0,"data-waiting-order":t,"data-waiting-total":n,children:[a&&(0,m.jsx)(`input`,{type:`checkbox`,className:`queue-select`,"data-waiting-select":e.id,checked:o,"aria-label":`选择「${S}」`,onChange:()=>s?.(e.id)}),(0,m.jsx)(`span`,{className:`queue-index`,"aria-hidden":`true`,children:t}),b?(0,m.jsxs)(`span`,{className:`queue-reminder`,"data-queue-reminder":!0,children:[(0,m.jsxs)(`span`,{className:`reminder-label`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`◷`}),` 定时提醒`]}),(0,m.jsx)(`span`,{className:`queue-text`,title:S,children:S})]}):x?(0,m.jsxs)(`span`,{className:`queue-bg-result`,title:S,children:[(0,m.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:C===`error`?`✕`:`↩`}),(0,m.jsx)(`span`,{className:`bg-result-label`,children:`后台回传`}),(0,m.jsx)(`span`,{className:`bg-result-summary`,children:S})]}):h?(0,m.jsxs)(`div`,{className:`queue-row-edit`,children:[(0,m.jsx)(`textarea`,{value:_,autoFocus:!0,rows:2,"aria-label":`修改这条等待中的消息`,onChange:e=>v(e.target.value),onKeyDown:t=>{t.key===`Escape`&&(t.preventDefault(),v(e.content),g(!1)),t.key===`Enter`&&(t.metaKey||t.ctrlKey)&&(t.preventDefault(),w())}}),(0,m.jsx)(`button`,{type:`button`,className:`queue-edit-save`,"data-waiting-save":e.id,onClick:w,children:`保存`}),(0,m.jsx)(`button`,{type:`button`,className:`queue-edit-cancel`,"data-waiting-cancel-edit":e.id,onClick:()=>{v(e.content),g(!1)},children:`取消`})]}):(0,m.jsx)(`span`,{className:`queue-text`,title:S,children:S}),(0,m.jsx)(`span`,{className:`queue-state`,"data-waiting-state":y?`sending`:`queued`,children:y?`已交给 Agent`:t===1?`下一条回答这条`:`等待回答 · 第 ${t} 条`}),y?(0,m.jsx)(`span`,{className:`queue-locked`,"data-waiting-locked":e.id,children:`暂时改不了`}):(0,m.jsxs)(m.Fragment,{children:[r?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`button`,{type:`button`,className:`queue-interrupt`,"data-waiting-interrupt":e.id,disabled:i,title:`停止当前任务,立即回答这条消息`,"aria-label":`停止当前任务并回答「${S}」`,onClick:()=>l(e.id),children:i?`◌ 打断中…`:`打断并回答`}),(0,m.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-steer":e.id,title:t===1?`当前工具完成后回答这条消息`:`插到最前:让它成为下一条被回答的消息`,"aria-label":t===1?`当前工具完成后回答「${S}」`:`让「${S}」插到最前`,onClick:()=>c(e.id),children:t===1?`当前工具完成后回答`:`插到最前`})]}):(0,m.jsx)(`button`,{type:`button`,className:`queue-steer`,"data-waiting-send":e.id,title:`现在就回答这条消息`,"aria-label":`现在就回答「${S}」`,onClick:()=>u(e.id),children:`现在就回答`}),e.role===`user`&&(0,m.jsx)(`button`,{type:`button`,className:`queue-edit`,"data-waiting-edit":e.id,title:`回答这条之前改字`,"aria-label":`修改「${S}」`,onClick:()=>{v(e.content),g(!0)},children:`改字`}),(0,m.jsx)(`button`,{type:`button`,className:`queue-cancel`,"data-waiting-cancel":e.id,title:`撤回这条消息,它不会被回答`,"aria-label":`撤回「${S}」`,onClick:()=>d(e.id),children:`撤回`})]})]})}function dA(e,t,n){return`${e}:${t}:${n}`}function fA(e){return{picked:Object.fromEntries((e.answers??[]).map(e=>[e.id,e.selected])),note:e.answers?.map(e=>e.note??``).join(`
|
|
342
|
+
`)??``}}function pA({question:e,index:t,expanded:n,draft:r,onDraftChange:i,onToggle:a,onAnswer:o}){return(0,m.jsxs)(`div`,{className:`call-block question-block-${e.status}`,"data-call-block":t,"data-call-tool":`question`,"data-call-detail":`提问`,"data-call-status":e.status===`answered`?`ok`:e.status===`cancelled`?`error`:`running`,"data-call-expanded":n?`true`:`false`,"data-question-block":t,children:[(0,m.jsx)(`button`,{type:`button`,className:`call-fold-edge`,"data-question-fold-edge":t,"aria-expanded":n,"aria-label":`${n?`折叠`:`展开`}提问`,title:n?`折叠这段提问`:`展开这段提问`,onClick:a}),(0,m.jsxs)(`div`,{className:`call-head-row`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`call-head`,"data-call-head":t,"aria-expanded":n,onClick:a,children:[(0,m.jsx)(`span`,{className:`call-chevron`,"aria-hidden":`true`,children:n?`▾`:`▸`}),(0,m.jsx)(`span`,{className:`call-glyph`,"aria-hidden":`true`,children:e.status===`answered`?`✓`:e.status===`cancelled`?`✕`:`?`}),(0,m.jsx)(`span`,{className:`call-label`,children:`提问`}),(0,m.jsxs)(`span`,{className:`call-detail`,children:[e.items.length,` 个问题`]})]}),n&&(0,m.jsx)(`button`,{type:`button`,className:`call-fold-top`,"data-call-fold-top":t,onClick:a,children:`收起`})]}),n&&(0,m.jsx)(`div`,{className:`question-body`,"data-question-body":t,children:(0,m.jsx)(mA,{question:e,draft:r,onDraftChange:i,instanceId:`inline`,onAnswer:o})})]})}function mA({question:e,draft:t,onDraftChange:n,instanceId:r,onAnswer:i}){let{picked:a,note:o}=t,s=(e,r,i)=>{let o=(()=>{let t=a,n=t[e]??[];return i?{...t,[e]:n.includes(r)?n.filter(e=>e!==r):[...n,r]}:{...t,[e]:[r]}})();n({...t,picked:o})},c=()=>{i(e.items.map(e=>({id:e.id,selected:a[e.id]??[],...e.extraNote&&o.trim()?{note:o.trim()}:{}})),!1)},l=e.items.some(e=>(a[e.id]??[]).length>0);return(0,m.jsxs)(`div`,{className:`question-block question-${e.status}`,"data-question-status":e.status,children:[e.items.map(i=>(0,m.jsxs)(`div`,{className:`question-item`,children:[(0,m.jsx)(`div`,{className:`question-text`,children:i.header?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`span`,{className:`question-header`,children:i.header}),(0,m.jsx)(`span`,{className:`question-sep`,children:` · `}),(0,m.jsx)(ep,{source:i.question})]}):(0,m.jsx)(ep,{source:i.question})}),(0,m.jsx)(`div`,{className:`question-options`,"data-question-options":i.id,children:i.options.map(t=>{let n=e.status!==`pending`,o=(n?e.answers?.find(e=>e.id===i.id)?.selected:a[i.id])?.includes(t)??!1;return(0,m.jsxs)(`label`,{className:o?`is-chosen`:``,"data-chosen":n&&o?`1`:void 0,children:[(0,m.jsx)(`input`,{type:i.multiple?`checkbox`:`radio`,name:`q-${r}-${i.id}`,checked:o,disabled:n,onChange:()=>s(i.id,t,i.multiple)}),(0,m.jsx)(tp,{source:t}),n&&o?(0,m.jsx)(`span`,{className:`question-mark`,"aria-label":`已选择`,children:`✓`}):null]},t)})}),e.status===`pending`&&i.extraNote?(0,m.jsx)(`textarea`,{value:o,placeholder:`补充说明(可选)`,onChange:e=>n({...t,note:e.target.value})}):e.status===`answered`&&(e.answers??[]).some(e=>e.note)?(0,m.jsxs)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:[`补充:`,(e.answers??[]).map(e=>e.note).filter(Boolean).join(`;`)]}):null,e.status===`cancelled`&&(0,m.jsx)(`div`,{className:`question-summary`,"data-question-summary":`1`,children:`已取消,没有作答。`})]},i.id)),e.status===`pending`&&(0,m.jsxs)(`div`,{className:`question-actions`,children:[(0,m.jsx)(`button`,{type:`button`,onClick:c,disabled:!l,children:`提交`}),(0,m.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:()=>i([],!0),children:`跳过`})]})]})}function hA({question:e,pendingCount:t,minimized:n,floatingRight:r,onMinimize:i,onExpand:a,onLocate:o,draft:s,onDraftChange:c,onAnswer:l}){return n?(0,Ve.createPortal)((0,m.jsxs)(`button`,{type:`button`,className:`question-floating-ball`,style:{"--question-floating-right":r},"data-question-floating-ball":e.key,onClick:a,"aria-label":`展开待回答的问题${t>1?`,还有 ${t-1} 个待处理`:``}`,title:`展开待回答的问题`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`?`}),t>1&&(0,m.jsx)(`small`,{children:t})]}),document.body):(0,Ve.createPortal)((0,m.jsxs)(`section`,{className:`question-floating-panel`,style:{"--question-floating-right":r},"data-question-floating-panel":e.key,role:`dialog`,"aria-labelledby":`question-floating-title`,children:[(0,m.jsxs)(`header`,{className:`question-floating-head`,children:[(0,m.jsx)(`span`,{className:`question-floating-mark`,"aria-hidden":`true`,children:`?`}),(0,m.jsxs)(`h2`,{id:`question-floating-title`,children:[`需要你回答`,t>1?` · 还有 ${t-1} 个`:``]}),(0,m.jsx)(`button`,{type:`button`,className:`question-floating-minimize`,onClick:o,title:`定位到消息上下文并最小化`,children:`查看上下文`}),(0,m.jsx)(`button`,{type:`button`,className:`question-floating-minimize-icon`,onClick:i,title:`最小化为悬浮球`,"aria-label":`最小化问题`,children:`−`})]}),(0,m.jsx)(`div`,{className:`question-floating-body`,children:(0,m.jsx)(mA,{question:e.value,draft:s,onDraftChange:c,instanceId:`floating`,onAnswer:l})})]}),document.body)}function gA({request:e,onAnswer:t,pending:n}){let[r,i]=(0,p.useState)(e.prefill??``),a=e.method===`input`||e.method===`editor`,o=(0,m.jsx)(`button`,{type:`button`,className:`extui-cancel`,onClick:()=>t({cancelled:!0}),children:`取消提问`});return(0,m.jsxs)(`article`,{className:`extui-card extui-${e.method}`,"data-request-id":e.requestId,"data-method":e.method,children:[(0,m.jsxs)(`div`,{className:`extui-head`,children:[(0,m.jsx)(`span`,{className:`extui-badge`,children:`扩展提问`}),e.timeoutMs!==void 0&&(0,m.jsxs)(`span`,{className:`extui-deadline`,children:[Math.ceil(Math.max(0,e.deadlineAt===void 0?e.timeoutMs:e.deadlineAt-Date.now())/1e3),`s 超时`]})]}),n&&(0,m.jsx)(`p`,{className:`extui-pending`,role:`status`,children:`提交中…`}),(0,m.jsxs)(`fieldset`,{disabled:n,style:{border:0,padding:0,margin:0},children:[(0,m.jsx)(`h3`,{className:`extui-title`,children:e.title||AA[e.method]}),e.method===`confirm`&&(0,m.jsx)(`p`,{className:`extui-body`,children:e.message}),e.method===`select`&&(0,m.jsxs)(`div`,{className:`extui-options`,children:[(e.options??[]).map(e=>(0,m.jsx)(`button`,{type:`button`,className:`extui-option`,onClick:()=>t({value:e}),children:e},e)),(e.options??[]).length===0&&(0,m.jsx)(`p`,{className:`extui-body`,children:`扩展没有提供任何选项`})]}),a&&(0,m.jsxs)(`form`,{className:`extui-form`,onSubmit:e=>{e.preventDefault(),!n&&r.trim()&&t({value:r})},children:[e.method===`input`?(0,m.jsx)(`input`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&mk(e)&&e.preventDefault()},placeholder:e.placeholder??``}):(0,m.jsx)(`textarea`,{className:`extui-field`,value:r,onChange:e=>i(e.target.value),onKeyDown:e=>{e.key===`Enter`&&mk(e)&&e.preventDefault()}}),(0,m.jsxs)(`div`,{className:`extui-actions`,children:[(0,m.jsx)(`button`,{type:`submit`,className:`extui-primary`,disabled:!r.trim(),children:`提交`}),o]})]}),!a&&(0,m.jsxs)(`div`,{className:`extui-actions`,children:[e.method===`confirm`&&(0,m.jsx)(`button`,{type:`button`,className:`extui-primary`,onClick:()=>t({confirmed:!0}),children:`确认`}),e.method===`confirm`&&(0,m.jsx)(`button`,{type:`button`,className:`extui-no`,onClick:()=>t({confirmed:!1}),children:`拒绝`}),o]})]})]})}function _A({initial:e,label:t,onCommit:n,onClose:r}){let[i,a]=(0,p.useState)(e),o=(0,p.useRef)(null),s=(0,p.useRef)(!1);(0,p.useEffect)(()=>{o.current?.focus(),o.current?.select()},[]);let c=!i.trim(),l=()=>{s.current=!0,r()},u=()=>{if(c)return;let t=i.trim();(t===e||n(t))&&l()};return(0,m.jsxs)(`div`,{className:`inline-edit`,"data-editing":`1`,children:[(0,m.jsx)(`input`,{ref:o,className:`inline-edit-input`,value:i,"aria-label":t,onChange:e=>a(e.target.value),onKeyDown:e=>{if(e.key===`Enter`){if(mk(e))return;e.preventDefault(),u()}else e.key===`Escape`&&(e.preventDefault(),l())},onBlur:()=>{s.current||r()}}),(0,m.jsx)(`button`,{type:`button`,className:`inline-edit-ok`,title:`确认重命名`,"aria-label":`确认重命名`,disabled:c,onMouseDown:e=>e.preventDefault(),onClick:u,children:`✓`}),(0,m.jsx)(`button`,{type:`button`,className:`inline-edit-cancel`,title:`取消重命名`,"aria-label":`取消重命名`,onMouseDown:e=>e.preventDefault(),onClick:l,children:`✗`})]})}function vA({kind:e,label:t,value:n,detail:r,options:i,disabled:a,note:o,onChoose:s,scope:c,providerOptions:l}){let[u,d]=(0,p.useState)(!1),[f,h]=(0,p.useState)(``),[g,_]=(0,p.useState)(0),[v,y]=(0,p.useState)(`*`),b=(0,p.useRef)(null),x=(0,p.useRef)(null),S=(0,p.useRef)(null),C=(0,p.useRef)(null),w=(0,p.useRef)([]),T=i.find(e=>e.selected),E=Bk(l?i.filter(e=>v===`*`||e.key!==yA&&e.key.split(`/`)[0]===v):i,f),D=E.length===0?-1:Math.min(Math.max(g,0),E.length-1),O=D<0?void 0:E[D],k=(e=!1)=>{d(!1),e&&x.current?.focus()},A=()=>{h(``),y(`*`),_(Math.max(i.findIndex(e=>e.selected),0)),d(!0)},j=e=>_(t=>E.length?Math.min(Math.max(t+e,0),E.length-1):0);(0,p.useEffect)(()=>{if(!u)return;let e=e=>{b.current?.contains(e.target)||k()};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[u]),(0,p.useEffect)(()=>{if(!u)return;let e=b.current,t=t=>{e?.contains(t.relatedTarget)||k()};return e?.addEventListener(`focusout`,t),()=>e?.removeEventListener(`focusout`,t)},[u]),(0,p.useEffect)(()=>{u&&C.current?.focus()},[u]),(0,p.useEffect)(()=>{u&&D>=0&&w.current[D]?.scrollIntoView({block:`nearest`})},[u,D]),(0,p.useLayoutEffect)(()=>{if(!u)return;let e=S.current;if(!e)return;e.style.setProperty(`--picker-nudge`,`0px`),e.style.setProperty(`--picker-drop`,`0px`);let t=e.getBoundingClientRect(),n=Math.min(window.innerWidth-8-t.right,Math.max(8-t.left,0)),r=Math.min(window.innerHeight-8-t.bottom,Math.max(8-t.top,0));e.style.setProperty(`--picker-nudge`,`${n}px`),e.style.setProperty(`--picker-drop`,`${r}px`)},[u,E.length,i.length]);let ee=e=>{if(u){if(e.key===`Escape`)e.preventDefault(),k(!0);else if(e.key===`ArrowDown`)e.preventDefault(),j(1);else if(e.key===`ArrowUp`)e.preventDefault(),j(-1);else if(e.key===`Home`)e.preventDefault(),_(0);else if(e.key===`End`)e.preventDefault(),_(Math.max(E.length-1,0));else if(e.key===`Enter`){if(mk(e))return;e.preventDefault(),O&&(s(O.key),k(!0))}}},M=`picker-list-${c??e}`,N=t=>`picker-option-${c??e}-${t}`;return(0,m.jsxs)(`div`,{className:`session-picker-item session-picker-${e}`,ref:b,onKeyDown:u?ee:void 0,children:[(0,m.jsxs)(`button`,{ref:x,type:`button`,className:`session-picker-trigger`,disabled:a,"aria-haspopup":`listbox`,"aria-expanded":u,title:o??`${Mk[e]}:${r?`${t} · ${r}`:t}`,"data-picker-trigger":e,"data-picker-value":n??t,"data-picker-selected":i.some(e=>e.selected),onClick:()=>u?k():A(),children:[(0,m.jsx)(`span`,{className:`session-picker-kind`,children:Mk[e]}),(0,m.jsx)(`span`,{className:`session-picker-name`,children:t}),r&&(0,m.jsx)(`span`,{className:`session-picker-detail`,children:r}),(0,m.jsx)(`span`,{className:`session-picker-caret`,"aria-hidden":`true`,children:`▾`})]}),u&&(0,m.jsxs)(`div`,{className:`picker-menu`,ref:S,"data-picker-menu":e,"data-picker-highlight":D,children:[l&&(0,m.jsxs)(`label`,{className:`picker-provider-filter`,children:[(0,m.jsx)(`span`,{children:`Provider`}),(0,m.jsxs)(`select`,{"data-picker-provider":e,"aria-label":`筛选模型 Provider`,value:v,onKeyDown:e=>e.stopPropagation(),onChange:e=>{y(e.target.value),_(0)},children:[(0,m.jsx)(`option`,{value:`*`,children:`全部 Provider`}),l.map(e=>(0,m.jsx)(`option`,{value:e,children:e},e))]})]}),(0,m.jsxs)(`div`,{className:`picker-filter`,children:[(0,m.jsx)(`span`,{className:`picker-filter-icon`,"aria-hidden":`true`,children:`🔍`}),(0,m.jsx)(`input`,{ref:C,className:`picker-filter-input`,"data-picker-filter":e,role:`combobox`,"aria-label":`筛选${Pk[e]}选项`,"aria-expanded":`true`,"aria-controls":M,"aria-autocomplete":`list`,"aria-activedescendant":O?N(D):void 0,value:f,placeholder:`输入以筛选…`,autoComplete:`off`,spellCheck:!1,onChange:e=>{h(e.target.value),_(0)}}),f&&(0,m.jsx)(`button`,{type:`button`,className:`picker-filter-clear`,"data-picker-filter-clear":e,title:`清空筛选`,"aria-label":`清空筛选`,onMouseDown:e=>e.preventDefault(),onClick:()=>{h(``),_(0),C.current?.focus()},children:`✕`})]}),T&&!E.some(e=>e.key===T.key)&&(0,m.jsxs)(`div`,{className:`picker-current`,"data-picker-current":e,"data-picker-current-value":T.key,children:[(0,m.jsx)(`span`,{className:`picker-current-label`,children:`当前`}),(0,m.jsx)(`span`,{className:`picker-current-value`,children:T.label})]}),(0,m.jsxs)(`div`,{className:`picker-list`,role:`listbox`,id:M,"aria-label":Ik[e],children:[E.map((e,t)=>(0,m.jsxs)(`button`,{id:N(t),type:`button`,role:`option`,"aria-selected":e.selected,ref:e=>{w.current[t]=e},className:`picker-option${e.selected?` selected`:``}${t===D&&!e.selected?` preview`:``}`,"data-picker-option":e.key,"data-picker-option-selected":e.selected,"data-picker-highlight":t===D,onClick:()=>{s(e.key),k(!0)},children:[e.color&&(0,m.jsx)(`span`,{className:`picker-option-swatch`,style:{background:e.color},"aria-hidden":`true`}),(0,m.jsx)(`span`,{className:`picker-option-name`,children:e.label}),e.badge&&(0,m.jsx)(`span`,{className:`picker-option-badge`,"data-picker-option-badge":e.badge,children:e.badge}),e.detail&&(0,m.jsx)(`span`,{className:`picker-option-detail`,children:e.detail}),e.selected&&(0,m.jsx)(`span`,{className:`picker-option-mark`,"aria-hidden":`true`,children:`✓`})]},e.key)),E.length===0&&(0,m.jsx)(`div`,{className:`picker-empty`,"data-picker-empty":e,children:i.length===0?Fk[e]:`没有匹配「${f.trim()}」的${Pk[e]}`})]})]})]})}var yA=`__pi_default__`;function bA({workspace:e,catalog:t,agents:n,onSave:r,onRename:i,onRemove:a,onClose:o}){let[s,c]=(0,p.useState)(e.defaultAgentId),[l,u]=(0,p.useState)(e.defaultModel),[d,f]=(0,p.useState)(e.defaultThinkingLevel);(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&!e.defaultPrevented&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]);let h=t?.source===`pi`,g=[{key:yA,label:`跟随 Pi 默认`,detail:`不为新会话指定模型`,selected:l===void 0},...(t?.models??[]).map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:[e.detail,qO(e.contextWindow)?`${qO(e.contextWindow)} 上下文`:``,JO(e.maxTokens)?`${JO(e.maxTokens)} 输出`:``].filter(Boolean).join(` · `),badge:Rk(e),selected:l?.provider===e.provider&&l.modelId===e.modelId}))],_=t?.models.find(e=>e.provider===l?.provider&&e.modelId===l?.modelId),v=_?.thinkingLevels??t?.levels??[],y=[{key:yA,label:`跟随 Pi 默认`,detail:`不为新会话指定思考等级`,selected:d===void 0},...v.map(e=>({key:e,label:e,selected:e===d}))],b=e=>{if(e===yA){u(void 0),f(void 0);return}let n=(t?.models??[]).find(t=>t.provider===e.split(`/`)[0]&&t.modelId===e.split(`/`)[1]);if(n){let e=l?.provider!==n.provider||l.modelId!==n.modelId;u({provider:n.provider,modelId:n.modelId,label:n.label}),e&&f(void 0)}},x=e=>f(e===yA?void 0:e),S=[{key:yA,label:`跟随 Pi 默认`,detail:`新会话不使用任何 agent 角色`,selected:s===void 0},...(n?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:s===e.id}))];return(0,m.jsx)(`div`,{className:`overlay`,onClick:o,children:(0,m.jsxs)(`div`,{className:`picker settings-dialog`,"data-settings-dialog":`1`,onClick:e=>e.stopPropagation(),children:[(0,m.jsx)(`h2`,{children:`工作区设置`}),(0,m.jsxs)(`div`,{className:`settings-scope`,children:[e.name,` · 默认值只影响之后新建的会话,已有会话不变`]}),(0,m.jsx)(`div`,{className:`workspace-settings-path`,children:e.path}),(0,m.jsxs)(`div`,{className:`settings-row`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认智能体`}),(0,m.jsx)(vA,{kind:`agent`,scope:`settings-agent`,label:n?.agents.find(e=>e.id===s)?.name??`跟随 Pi 默认`,value:s??yA,detail:s?`${n?.agents.find(e=>e.id===s)?.toolSummary??``}`:void 0,options:S,disabled:!n||n.source===`unavailable`,note:qk(n),onChoose:e=>c(e===yA?void 0:e)})]}),(0,m.jsxs)(`div`,{className:`settings-row`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`默认模型`}),(0,m.jsx)(vA,{kind:`model`,scope:`settings-model`,label:l?.label??`跟随 Pi 默认`,value:l?`${l.provider}/${l.modelId}`:yA,detail:l?`${l.provider}/${l.modelId}`:void 0,options:g,providerOptions:[...new Set((t?.models??[]).map(e=>e.provider))],disabled:!h,note:Kk(`模型`,t),onChoose:b})]}),(0,m.jsxs)(`div`,{className:`settings-row`,children:[(0,m.jsx)(`span`,{className:`settings-label`,children:`思考强度`}),(0,m.jsx)(vA,{kind:`thinking`,scope:`settings-thinking`,label:d??`跟随 Pi 默认`,value:d??yA,options:y,disabled:!h,note:Kk(`思考等级`,t),onChoose:x})]}),l&&_&&v.length===0&&(0,m.jsx)(`div`,{className:`settings-scope`,children:`Pi 未提供此模型的可选等级,使用模型默认值。`}),(0,m.jsxs)(`div`,{className:`picker-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`settings-rename`,"data-settings-rename":`1`,onClick:i,children:`重命名工作区`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-cancel`,"data-settings-cancel":`1`,onClick:o,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`picker-ok`,"data-settings-save":`1`,onClick:()=>r(s,l,d),children:`保存`})]}),(0,m.jsx)(`button`,{type:`button`,className:`workspace-delete`,onClick:a,children:`从列表移除工作区`})]})})}var xA=[{id:`main`,label:`任务`,name:`任务与后台任务`},{id:`projects`,label:`项目`,name:`项目控制面`},{id:`tools`,label:`工具`,name:`工具 tab`},{id:`files`,label:`文件`,name:`文件 tab`},{id:`git`,label:`Git`,name:`Git tab`},{id:`rsi`,label:`RSI`,name:`RSI 观察与改进`},{id:`terminal`,label:`终端`,name:`终端 tab`}],SA=`super-pi.right-tabs.v1`;function CA(){let e=e=>xA.some(t=>t.id===e),t={tab:xA[0].id,byConversation:{}};try{let n=JSON.parse(Gn(SA)??`null`);return!n||!e(n.tab)?t:{tab:n.tab,byConversation:Object.fromEntries(Object.entries(n.byConversation??{}).filter(t=>e(t[1])))}}catch{return t}}var wA={waiting:`⋯`,running:``,failed:``,question:`?`,completed:``,unread:`•`,idle:``,awaiting_background:`⚙`,pending_report:`↑`,awaiting_subordinates:`↓`,awaiting_decision:`▲`},TA={idle:`空闲`,running:`讨论中`,awaiting_background:`后台任务进行中`,completed:`讨论已完成`,failed:`讨论未完成`},EA={waiting:`等待 LLM`,running:`进行中`,failed:`出错`,question:`等你回答`,completed:`已完成`,unread:`有未读`,idle:`空闲`,awaiting_background:`等待后台任务`,pending_report:`待汇报`,awaiting_subordinates:`等待下级`,awaiting_decision:`等上面拍板`},DA={idle:`就绪`,waiting:`等待 LLM`,running:`正在生成`,completed:`已完成`,stopped:`已停止`,failed:`运行失败`,awaiting_background:`等待后台任务`},OA=e=>e?.status===`running`||e?.status===`waiting`||e?.compaction?.status===`running`,kA={running:`运行中`,completed:`已完成`,failed:`失败`,stopped:`已停止`,cancelled:`已取消`,interrupted:`已中断`},AA={select:`请选择一项`,confirm:`请确认`,input:`请输入内容`,editor:`请输入内容`,notify:`扩展通知`,setStatus:`扩展状态`,setWidget:`扩展内容`,setTitle:`扩展标题`,set_editor_text:`扩展输入`};function jA(e,t){return t.some(t=>t.conversationId===e.id)?!0:e.messagesLoaded===!1?e.hasPendingQuestion===!0:e.messages.some(e=>(e.toolCalls??[]).some(e=>e.question?.status===`pending`))}function MA(e,t,n){let r=(t||[]).filter(t=>t.parentConversationId===e.id),i=(t||[]).find(t=>t.id===e.parentConversationId),a=n??``;return $n({conversation:e,parent:i,directChildren:r,isTopLevelUnread:e.updatedAt>a})}function NA(e,t,n,r){let i=MA(e,r,n);return er({status:e.status,reportingState:i,awaitingQuestion:t,quietWhenRead:!0})}function PA(e,t){return t===`awaiting_decision`||e===`awaiting_decision`?(0,m.jsx)(`span`,{className:`conversation-status-badge badge--warning project-status-awaiting_decision`,"data-session-status":`awaiting_decision`,"data-reporting-badge":`awaiting_decision`,title:EA.awaiting_decision,children:EA.awaiting_decision}):t===`awaiting_subordinates`||e===`awaiting_subordinates`?(0,m.jsx)(`span`,{className:`conversation-status-badge project-status-awaiting_subordinates`,"data-session-status":`awaiting_subordinates`,"data-reporting-badge":`awaiting_subordinates`,title:EA.awaiting_subordinates,children:EA.awaiting_subordinates}):t===`pending_report`||e===`pending_report`?(0,m.jsx)(`span`,{className:`conversation-status-badge project-status-pending_report`,"data-session-status":`pending_report`,"data-reporting-badge":`pending_report`,title:EA.pending_report,children:EA.pending_report}):null}function FA({state:e,label:t=EA[e]}){let n=wA[e];if(e===`idle`)return null;let r=e.replace(/_/g,`-`);return(0,m.jsx)(`i`,{className:`session-state session-state-${e} session-state-${r}`,"data-session-state":e,title:t,"aria-label":t,...e===`awaiting_background`?{style:{color:`var(--accent)`}}:{},children:(0,m.jsx)(`i`,{className:`session-state-mark`,"aria-hidden":`true`,children:n})})}function IA(e,t){return(0,m.jsxs)(m.Fragment,{children:[e.origin===`orchestrator`&&(0,m.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`orchestrator`,title:`编排会话:由上级智能体创建`,"aria-label":`编排会话:由上级智能体创建`,children:`编排`}),t&&(0,m.jsx)(`span`,{className:`conversation-origin`,"data-conversation-origin":`scheduled`,title:`定时任务会话:${t.name}`,"aria-label":`定时任务会话:${t.name}`,children:`定时`})]})}function LA(e,t){let n=[];return e.origin===`orchestrator`&&n.push(`编排会话`),t&&n.push(`定时任务会话:${t.name}`),n.length?`(${n.join(`;`)})`:``}var RA={pending:`未开始`,in_progress:`运行中`,completed:`已完成`},zA={pending:`○`,in_progress:`◐`,completed:`✓`},BA={high:`高`,medium:`中`,low:`低`};function VA(e){let t=e.filter(e=>e.status!==`completed`).length;return e.length?t?`${t} 个未完成 / 共 ${e.length} 个`:`全部完成:${e.length} 个`:`0 个待办任务`}function HA({todo:e,index:t}){let n=e.id??`todo_${t}`;return(0,m.jsxs)(`li`,{className:`todo-item todo-${e.status}`,"data-todo-item":n,"data-todo-status":e.status,title:`状态:${RA[e.status]}`,children:[(0,m.jsx)(`span`,{className:`todo-mark`,"aria-hidden":`true`,children:zA[e.status]}),(0,m.jsx)(`span`,{className:`todo-text`,children:e.content}),(0,m.jsx)(`span`,{className:`todo-status`,"data-todo-status-text":`1`,children:RA[e.status]}),e.priority&&(0,m.jsx)(`span`,{className:`todo-priority`,"data-todo-priority":e.priority,children:BA[e.priority]})]})}function UA(e,t){if(!e)return[];let n=t.filter(t=>t.conversationId===e.id&&t.status===`running`),r=new Set(n.map(e=>e.id));for(let t of e.messages)t.toolCalls?.forEach((i,a)=>{let o=i.backgroundTask;o&&o.status===`running`&&!r.has(o.id)&&(r.add(o.id),n.push({id:o.id,conversationId:e.id,title:i.detail?.trim()||i.label?.trim()||o.id,status:o.status,originMessageId:t.id,originCallRow:a}))});return n}function WA({tasks:e,runs:t,execOutputs:n,onStop:r}){return(0,m.jsx)(`ul`,{className:`bg-list`,"data-bg-task-count":e.length,children:e.map((e,i)=>{let a=e.id||`bg_${i}`,o=e.status?.trim()||``,s=o?kA[o]??(/[\u3400-\u9fff]/.test(o)?o:`未知状态`):`未知状态`;return(0,m.jsx)(GA,{task:e,status:s,run:t?.get(e.id),execOutputs:n,onStop:r},a)})})}function GA({task:e,status:t,run:n,execOutputs:r,onStop:i}){let[a,o]=(0,p.useState)(!1),s=Qk(e.id,r),c=n?QO(n):s?.text||e.output,l=c&&ZO(c),u=n?n.outputTruncated||n.toolCalls?.some(e=>e.outputTruncated):s?.truncated??e.outputTruncated;return(0,m.jsxs)(`li`,{className:`bg-item${a?` bg-item-expanded`:``}`,"data-bg-task":e.id,"data-bg-task-status":e.status??`unknown`,title:`状态:${t}`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`bg-item-toggle`,onClick:()=>o(e=>!e),"aria-expanded":a,"aria-label":`展开后台任务详情`,children:[(0,m.jsx)(`span`,{className:`bg-title`,children:e.title?.trim()||e.id||`未命名任务`}),(0,m.jsxs)(`span`,{className:`bg-meta`,children:[e.agentId?.trim()&&(0,m.jsx)(`span`,{className:`bg-agent`,"data-bg-agent":e.agentId,children:e.agentId}),(0,m.jsx)(`span`,{className:`bg-status`,children:t})]})]}),i&&(0,m.jsx)(`button`,{type:`button`,className:`bg-stop-btn`,"data-bg-task-stop":e.id,title:`终止后台任务`,onClick:()=>i(e.id),children:`终止`}),a&&(0,m.jsx)(`pre`,{className:`bg-output`,"data-bg-output":e.id,children:[u?`日志仅保留最近一段。`:``,l].filter(Boolean).join(`
|
|
343
343
|
|
|
344
|
-
`)||`运行中,暂无输出`})]})}var
|
|
344
|
+
`)||`运行中,暂无输出`})]})}var KA=(0,p.lazy)(()=>kn(()=>import(`./GitDiffEditor-CyDiA4rj.js`),__vite__mapDeps([25,1,2,3,4,0,23,24,26])));function qA(e){let{visible:t}=ki(`projects`);return(0,m.jsx)(eD,{...e,visible:t})}function JA(e){let{visible:t}=ki(`rsi`);return(0,m.jsx)(uk,{...e,visible:t})}function YA({todos:e,tasks:t,backgroundRuns:n,execOutputs:r,scheduledTasks:i,scheduledCatalog:a,scheduledAgents:o,collapsed:s,onToggle:c,workspaceId:l,gitWorkspaceId:u=l,gitRepositoryOnly:d=!1,workspaceLabel:f,workspaceName:p,gitWorkspaceName:h=p,cwd:g=``,conversationId:_,followedWorktreeId:v,connected:y,files:b,onOpenFile:x,onOpenChanged:S,onOpenGitDiff:C,activeGitDiffUrl:w,onFileReference:T,onFilesMoved:E,onSearchFolder:D,activeTab:O,onSelectTab:k,sendCommand:A,registerTerminalSink:j,terminalShell:ee,terminalFocusRequest:M,notify:N,serverTimeZone:P,onOpenSession:F,side:I,onArrange:te,pinned:ne=!0,sharedGit:re,gitReveal:ie,rsiContext:ae,contentOwner:oe=!1,onCloseView:se,mobileViews:ce=[]}){let le=[...xA,...ce.map(e=>({id:e,label:ri[e],name:ri[e]}))],ue=Di(),de=s=>(0,m.jsxs)(m.Fragment,{children:[s.id===`main`&&(0,m.jsx)(m.Fragment,{children:(0,m.jsxs)(`div`,{className:`rail-task-sections`,children:[(0,m.jsxs)(ZT,{id:`todos`,title:`待办任务`,icon:`tasks`,count:(0,m.jsx)(`span`,{"data-todo-summary":`1`,children:VA(e)}),children:[(e.length>0||t.length>0)&&(0,m.jsxs)(`p`,{className:`rail-legend`,"data-rail-legend":`1`,children:[(0,m.jsx)(`span`,{className:`rail-legend-label`,children:`左侧竖条=状态`}),(0,m.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,m.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-pending`,"aria-hidden":`true`}),`未开始`]}),(0,m.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,m.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-running`,"aria-hidden":`true`}),`运行中`]}),(0,m.jsxs)(`span`,{className:`rail-legend-item`,children:[(0,m.jsx)(`span`,{className:`rail-legend-swatch rail-legend-swatch-done`,"aria-hidden":`true`}),`已完成`]})]}),e.length>0?(0,m.jsx)(`ol`,{className:`todo-list`,"data-todo-count":e.length,children:e.map((e,t)=>(0,m.jsx)(HA,{todo:e,index:t},e.id??`todo_${t}`))}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-todo-empty":`1`,children:`暂无待办任务。开始多步骤任务后会自动显示。`})]}),(0,m.jsx)(ZT,{id:`background`,title:`后台任务`,icon:`activity`,count:(0,m.jsx)(`span`,{"data-bg-summary":`1`,children:t.length?`${t.filter(e=>e.status===`running`).length} 个运行中 / 共 ${t.length} 个`:`0 个`}),children:t.length>0?(0,m.jsx)(WA,{tasks:t,runs:n,execOutputs:r,onStop:e=>A({type:`backgroundTask.stop`,taskId:e})}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-bg-empty":`1`,children:`当前没有正在运行的后台任务。`})}),(0,m.jsx)(dE,{tasks:i,workspaceId:l,catalog:a,agents:o,sendCommand:A,notify:N,serverTimeZone:P})]})}),s.id===`projects`&&(0,m.jsx)(qA,{workspaceId:l,notify:N,onOpenSession:F,onOpenFile:x,cwd:g},l),s.id===`rsi`&&(0,m.jsx)(JA,{context:ae,onClose:()=>se?se(ue?.placements.find(e=>e.id===`rsi`)?.view??`rsi`):c()}),s.id===`tools`&&(0,m.jsx)(XA,{workspaceId:l},l),s.id===`files`&&(0,m.jsx)(qh,{workspaceId:l,workspaceName:p,cwd:g,files:b,onOpenFile:x,onOpenChanged:S,onReference:T,onMoved:E,onSearchFolder:D}),s.id===`git`&&(0,m.jsx)(Ma,{reveal:ie,repositoryOnly:d,workspaceId:u??null,conversationId:_,cwd:u===l?g:``,followedWorktreeId:v,onOpenDiff:e=>C({...e,comparison:h?`${h} · ${e.comparison}`:e.comparison}),activeDiffUrl:w,onOpenConversation:F,sharedGit:re},JSON.stringify([u,g,_,d])),s.id===`terminal`&&(0,m.jsx)(XT,{workspaceId:l,workspaceLabel:f,cwd:g,conversationId:_,connected:y,sendCommand:A,registerSink:j,terminalShell:ee,focusRequest:M},JSON.stringify([l,_]))]});if(oe)return(0,m.jsx)(m.Fragment,{children:xA.map(e=>(0,m.jsx)(ji,{view:e.id,children:e.id===`main`?de(e):(0,m.jsx)(Mi,{id:e.id,children:de(e)})},e.id))});let fe=I&&O===`terminal`&&ue?.members(`terminal`).length===1&&ue.members(`terminal`)[0].id===`terminal`;return(0,m.jsx)(`div`,{className:`right-rail${I?` workbench-panel workbench-panel-`+I:``}${s?` right-rail-collapsed`:``}`,role:`complementary`,"aria-label":I?Jr[I]+`栏`:`右侧栏`,"data-right-rail":I&&I!==`right`?void 0:`1`,"data-right-rail-collapsed":s,"data-single-terminal":fe||void 0,"data-workbench-panel":I,hidden:I&&s?!0:void 0,children:s?!I&&(0,m.jsx)(`button`,{type:`button`,className:`right-rail-open`,"data-right-rail-open":`1`,title:`展开右侧栏`,"aria-label":`展开右侧栏`,onClick:c,children:`‹`}):(0,m.jsxs)(m.Fragment,{children:[I?(0,m.jsxs)(`div`,{className:`workbench-panel-heading`,children:[(0,m.jsx)(`h2`,{draggable:!0,title:`拖动以移动此面板`,"data-workbench-panel-drag":O,onDragStart:e=>di(e.dataTransfer,O),children:fe?(0,m.jsx)(Ni,{id:`terminal`,children:`终端`}):ri[O]}),fe&&(0,m.jsx)(Pi,{id:`terminal`}),te&&(0,m.jsx)(xi,{view:O,side:I,pinned:ne,onArrange:te}),(0,m.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-right-rail-collapse":I===`right`?`1`:void 0,title:`收起`+Jr[I]+`栏`,"aria-label":O===`rsi`?`关闭 RSI 面板`:`收起`+Jr[I]+`栏`,onClick:c,children:(0,m.jsx)(vi,{name:`close`})})]}):(0,m.jsxs)(`div`,{className:`right-rail-head`,children:[(0,m.jsx)(`div`,{className:`right-tabs`,role:`tablist`,"aria-label":`右侧栏 tab`,"data-right-tab-count":le.length,children:le.map(e=>(0,m.jsx)(`button`,{type:`button`,role:`tab`,id:`right-tab-${e.id}`,className:`right-tab${e.id===O?` right-tab-active`:``}`,"data-right-tab":e.id,"aria-selected":e.id===O,"aria-controls":`right-panel-${e.id}`,title:e.name,"aria-label":e.name,onClick:()=>k(e.id),children:e.label},e.id))}),(0,m.jsx)(`button`,{type:`button`,className:`right-rail-collapse`,"data-right-rail-collapse":`1`,title:`收起右侧栏(聊天区会变宽)`,"aria-label":O===`rsi`?`关闭 RSI 面板`:`收起右侧栏`,onClick:c,children:`›`})]}),(0,m.jsx)(`div`,{className:`right-rail-body`,role:`tabpanel`,id:`right-panel-${O}`,"aria-label":I?ri[O]:void 0,"aria-labelledby":I?void 0:`right-tab-${O}`,"data-right-panel":O,children:ue?(0,m.jsx)(z,{view:O}):xA.filter(e=>e.id===O).map(de)},O)]})})}function XA({workspaceId:e}){let{tools:t,mountedTools:n,openToolId:r,shortcuts:i}=DO(),[a,o]=(0,p.useState)(),s=async e=>{o(void 0);let t=await AO(e);t&&o(`移除工具失败:${zr(t)}`)},c=(e,t)=>t?`打开${e}(快捷键 ${eO(t)})`:`打开${e}`;return(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`rail-section-head`,children:[(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`工具`}),(0,m.jsxs)(`span`,{className:`rail-section-count`,"data-tool-summary":`1`,children:[t.length+n.length,` 个`]})]}),t.length+n.length>0?(0,m.jsxs)(`ul`,{className:`tool-grid`,"data-tool-count":t.length+n.length,children:[t.map(e=>(0,m.jsxs)(`li`,{className:`tool-slot`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-tool-icon":e.id,"data-tool-kind":e.kind,"data-tool-state":r===e.id?`open`:`idle`,title:c(e.name,i[e.id]),"aria-label":c(e.name,i[e.id]),"aria-current":r===e.id?`true`:void 0,onClick:()=>OO.toggleTool(e.id),children:[(0,m.jsx)(MD,{className:`tool-icon-glyph`,glyph:e.glyph}),(0,m.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),i[e.id]&&(0,m.jsx)(`span`,{className:`tool-key-badge`,"data-tool-key-badge":e.id,"aria-hidden":`true`,title:`快捷键 ${eO(i[e.id])}`,children:tO(i[e.id])}),e.kind===`link`&&(0,m.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>OO.removeTool(e.id),children:`✕`})]},e.id)),n.map(e=>(0,m.jsxs)(`li`,{className:`tool-slot`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`tool-icon`,"data-mounted-tool-icon":e.id,"data-tool-state":r===e.id?`open`:`idle`,title:c(e.name,i[e.id]),"aria-label":c(e.name,i[e.id]),onClick:()=>OO.toggleTool(e.id),children:[(0,m.jsx)(MD,{className:`tool-icon-glyph`,glyph:PD(e)}),(0,m.jsx)(`span`,{className:`tool-icon-name`,children:e.name})]}),i[e.id]&&(0,m.jsx)(`span`,{className:`tool-key-badge`,"data-tool-key-badge":e.id,"aria-hidden":`true`,title:`快捷键 ${eO(i[e.id])}`,children:tO(i[e.id])}),(0,m.jsx)(`button`,{type:`button`,className:`tool-remove`,"data-tool-remove":e.id,title:`移除${e.name}`,"aria-label":`移除${e.name}`,onClick:()=>void s(e.id),children:`✕`})]},e.id))]}):(0,m.jsx)(`p`,{className:`rail-empty`,"data-tool-empty":`1`,children:`还没有工具。点下面的「工具设置」添加。`}),(0,m.jsx)(`button`,{type:`button`,className:`tools-settings-btn`,"data-tool-settings-trigger":`1`,title:`添加预置工具、网址工具、快捷键与说明`,"aria-label":`打开工具设置`,onClick:()=>OO.openSettings(),children:`⚙ 工具设置`}),a&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-error":`1`,children:a})]})}function ZA({onClose:e}){let{tools:t,mountedTools:n,shortcuts:r}=DO(),[i,a]=(0,p.useState)(``),[o,s]=(0,p.useState)(``),[c,l]=(0,p.useState)(),[u,d]=(0,p.useState)(!1),[f,h]=(0,p.useState)(),[g,_]=(0,p.useState)(),[v,y]=(0,p.useState)(),[b,x]=(0,p.useState)(``),[S,C]=(0,p.useState)(),[w,T]=(0,p.useState)(),[E,D]=(0,p.useState)(!1),[O,k]=(0,p.useState)(),[A,j]=(0,p.useState)(),ee=(0,p.useRef)(null),M=(0,p.useRef)(null),[N,P]=(0,p.useState)(),[F,I]=(0,p.useState)(),te=(0,p.useRef)(null),[ne,re]=(0,p.useState)(()=>{let e=vO();return!e||typeof window>`u`?e:bO(e,window.innerWidth,window.innerHeight)}),ie=async()=>{let e=await Hi(`请为 Super Pi 开发一个全局右侧栏工具。不要启动独立 HTTP 服务器,也不要监听端口。
|
|
345
345
|
|
|
346
346
|
工具不属于当前 workspace;通过内置 tool_register 一次性提交完整文件(index.html、JS/CSS,必要时 .py),并用 glyph 提供一个易辨识的短图标(1 至 4 个字符,例如 {}、∑、◷),Super Pi 会保存为全局工具并自动出现在每个 workspace 的工具 Tab。
|
|
347
347
|
|
|
348
|
-
如需本地计算,声明 script: { path, timeoutMs, parameters }。脚本必须是 Python,参数以 JSON 从 stdin 传入,stdout 必须只输出一个 JSON 对象。在 index.html 中加载 <script src="./super-pi-tool.js"><\/script>,然后调用 SuperPiTool.run(params)、SuperPiTool.get(runId)、SuperPiTool.wait(runId) 或 SuperPiTool.cancel(runId)。这些都是已绑定本工具身份的相对接口;不要调用 /api/exec,不要猜测 toolId,也不要传 shell 命令、任意文件路径或未声明参数。页面必须实际执行一次示例任务并显示运行状态、日志和结构化结果。第三方包写进 environment.requires(必须钉死成 pkg==version),首次运行时会装进这个工具自己的虚拟环境。需要模型能力(摘要、改写、抽取、分类)时调用 SuperPiTool.llm({ prompt, system }),不要自己写模型客户端或保管密钥,并在注册时声明 permissions: { llm: true }——否则服务端会拒绝,导入页面也会提示用户。最后返回注册 id、访问地址、文件清单和验证结果。`);d(e),window.setTimeout(()=>d(!1),1800)};(0,p.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let ae=(0,p.useMemo)(()=>[...t.map(e=>({id:e.id,name:e.name,glyph:e.glyph})),...n.map(e=>({id:e.id,name:e.name,glyph:AD(e)}))],[t,n]);(0,p.useEffect)(()=>{if(!N)return;let e=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),P(void 0);return}if(qD(e.key)||nO(e.target))return;e.preventDefault(),e.stopPropagation();let t=N;if(P(void 0),e.key===`Delete`||e.key===`Backspace`){wO.clearShortcut(t).then(e=>I(e));return}let n=JD(e);if(!n){I(`没有认出这个按键,换一个试试。`);return}let i=eO(n);if(!i.ok){I(i.reason);return}let a=oO(r,n,t);if(a){let e=ae.find(e=>e.id===a)?.name;I(e?`这个组合键已经被「${e}」占用了,换一个键。`:`这个组合键已经被另一个工具占用了,换一个键。`)}else wO.setShortcut(t,n).then(e=>I(e))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[N,r,ae]);let oe=e=>{re(gO(e,window.innerWidth,window.innerHeight))},se=e=>{hO(e)},ce=()=>{re(void 0),hO(void 0)},le=(0,p.useRef)(!1),ue=n.map(e=>e.slug).filter(e=>typeof e==`string`),de=e=>{h(void 0),_(void 0),j(void 0),k({tool:e,name:PO({slug:e.slug??`tool`})})},fe=async(e,t)=>{h(void 0),_(void 0),j(void 0);let n=FO(t);if(!n.ok)j(n.reason);else try{let t=await Ie(`/api/tools/export?id=${encodeURIComponent(e.id)}`),r=await t.json();if(!t.ok||!r.bundle)throw Error(r.error??`HTTP ${t.status}`);let i=new Blob([JSON.stringify(r.bundle,null,2)],{type:`application/json`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=n.name,document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a),_(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){h(`导出失败:${zr(e)}`)}finally{k(void 0)}},pe=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;h(void 0),_(void 0),C(void 0);let n=jO(await t.text(),t.name);n.ok?(y({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),x(ue.includes(n.bundle.slug)?NO(n.bundle.slug,ue):n.bundle.slug),T(n.bundle.files[0]?.path)):h(n.reason)},L=()=>{y(void 0),x(``),C(void 0),T(void 0)},me=async()=>{if(!v)return;C(void 0);let e=MO(b);if(!e.ok)C(e.reason);else if(ue.includes(e.slug))C(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{D(!0);try{let t=await Ie(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(BO(v.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await TO(),_(`已导入「${v.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),L()}catch(e){h(`导入失败:${zr(e)}`)}finally{D(!1)}}};(0,p.useEffect)(()=>{O&&M.current?.scrollIntoView({block:`center`})},[O]);let he=()=>{let e=Qt(i);e.ok?t.length>=32?l(`工具最多 32 个,先删掉一个再加。`):(wO.setTools([...t,{id:nn(`link`,t.map(e=>e.id)),kind:`link`,name:o.trim()||XA(e.url),glyph:`↗`,url:e.url}]),a(``),s(``),l(void 0)):l(e.reason)},ge=ne?{width:`${ne.width}px`,height:`${ne.height}px`,maxWidth:`calc(100vw - 32px)`,maxHeight:`calc(100vh - 32px)`}:void 0;return(0,Ve.createPortal)((0,m.jsxs)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onPointerDown:()=>{le.current=!1},onClick:t=>{le.current?le.current=!1:t.target===t.currentTarget&&e()},children:[(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,ref:te,style:ge,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:e,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body`,children:v?(0,m.jsx)(YA,{pending:v,slugDraft:b,slugError:S,preview:w,busy:E,onSlugChange:e=>{x(e),C(void 0)},onPreviewChange:T,onCancel:L,onConfirm:()=>void me()}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,m.jsx)(`strong`,{children:`直接描述你要的工具`}),(0,m.jsx)(`p`,{className:`tool-hint`,children:`告诉 Super Pi Agent 你要创建什么,它会使用内置开发技能和 tool_register 完成注册。复制提示词仅作为备用入口。`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void ie(),children:u?`已复制`:`复制备用提示词`})]}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,m.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":Kt.length,children:Kt.map(e=>{let n=t.some(t=>t.kind===e.kind);return(0,m.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":e.kind,children:[(0,m.jsx)(OD,{className:`tool-preset-glyph`,glyph:e.glyph}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.jsx)(`small`,{children:e.blurb})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-add-preset":e.kind,disabled:n,title:n?`${e.name}已经在工具栏里了`:`添加${e.name}`,"aria-label":n?`${e.name}已添加`:`添加${e.name}`,onClick:()=>wO.setTools(rn(t,e.kind)),children:n?`已添加`:`添加`})]},e.kind)})}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,m.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,m.jsx)(`input`,{className:`tool-input`,"data-tool-url-input":`1`,value:i,maxLength:2048,placeholder:`https://example.com/工具`,"aria-label":`工具网址`,onChange:e=>{a(e.target.value),l(void 0)}}),(0,m.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:o,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>s(e.target.value)}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!i.trim(),onClick:he,children:`添加网址工具`}),c&&(0,m.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:c}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,m.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`快捷键`})}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-shortcut-hint":`1`,children:[`给每个工具绑一个组合键,按下就直接打开它,不用先找到右侧栏。`,(0,m.jsx)(`b`,{children:`弹窗打开时快捷键不生效`}),`——模态弹窗期间键盘归它自己,关掉之后再按。`]}),(0,m.jsx)(`div`,{className:`tool-shortcuts`,"data-tool-shortcut-count":ae.length,children:ae.map(e=>(0,m.jsxs)(`div`,{className:`tool-shortcut-row`,"data-tool-shortcut-row":e.id,children:[(0,m.jsx)(OD,{className:`tool-preset-glyph`,glyph:e.glyph}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.jsx)(`small`,{children:r[e.id]?`按 ${XD(r[e.id])} 打开`:`还没有快捷键`})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-shortcut-set`,"data-tool-shortcut-set":e.id,"data-tool-shortcut-capturing":N===e.id?`1`:void 0,"aria-pressed":N===e.id,title:N===e.id?`按下想用的组合键(Esc 取消,Delete 清除)`:`点一下,然后按下想用的组合键`,onClick:()=>{I(void 0),P(N===e.id?void 0:e.id)},children:N===e.id?`按下组合键…`:r[e.id]?XD(r[e.id]):`未设置`}),r[e.id]&&(0,m.jsx)(`button`,{type:`button`,className:`tool-shortcut-clear`,"data-tool-shortcut-clear":e.id,title:`清除${e.name}的快捷键`,"aria-label":`清除${e.name}的快捷键`,onClick:()=>{wO.clearShortcut(e.id),I(void 0),P(void 0)},children:`清除`})]},e.id))}),F&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-shortcut-error":`1`,children:F}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有注册全局工具。直接告诉 Agent 你想做什么即可开始。`}):(0,m.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=RO(e.environmentState);return(0,m.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,m.jsx)(OD,{className:`tool-preset-glyph`,glyph:AD(e)}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.jsx)(`small`,{"data-tool-env":e.environmentState?.state??`unknown`,children:t?`${t.warn?`⚠ `:``}${t.text}${e.environmentState?.detail?` · ${e.environmentState.detail}`:``}`:`环境未知`}),e.permissions?.llm&&(0,m.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export":e.id,title:`导出${e.name},得到一个可以发给别人导入的文件`,"aria-label":`导出${e.name}`,onClick:()=>de(e),children:`导出`})]},e.id)})}),O&&(0,m.jsxs)(`div`,{className:`tool-share-review`,ref:M,"data-tool-export-name":`1`,children:[(0,m.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,O.tool.name,`」`]}),(0,m.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,m.jsx)(`input`,{className:`tool-input`,value:O.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>k({...O,name:e.target.value})})]}),A&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:A}),(0,m.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{k(void 0),j(void 0)},children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void fe(O.tool,O.name),children:`导出`})]})]}),g&&(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:g}),f&&(0,m.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:f}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,m.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,m.jsx)(`code`,{children:DO}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,m.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>ee.current?.click(),children:`选择文件…`}),(0,m.jsx)(`input`,{ref:ee,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void pe(e)})]})})]}),(0,m.jsx)(qA,{targetRef:te,onResize:oe,onCommit:se,onDragEnd:()=>{le.current=!0},onReset:ce})]}),document.body)}var KA=18;function qA({targetRef:e,onResize:t,onCommit:n,onDragEnd:r,onReset:i}){let[a,o]=(0,p.useState)(),s=(0,p.useRef)(void 0);return(0,p.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{let e=t.getBoundingClientRect();o({left:e.right-KA,top:e.bottom-KA})};n();let r=new ResizeObserver(n);return r.observe(t),window.addEventListener(`resize`,n),window.addEventListener(`scroll`,n,!0),()=>{r.disconnect(),window.removeEventListener(`resize`,n),window.removeEventListener(`scroll`,n,!0)}},[e]),(0,m.jsx)(`div`,{className:`tool-dialog-grip`,"data-tool-settings-grip":`1`,role:`separator`,"aria-orientation":`vertical`,tabIndex:0,"aria-label":`调整工具设置弹窗大小:拖动或用方向键,Enter 恢复默认尺寸`,style:a?{left:`${a.left}px`,top:`${a.top}px`}:void 0,onPointerDown:i=>{i.preventDefault(),i.stopPropagation();let a=e.current;if(!a)return;let o=a.getBoundingClientRect(),c=o.left+o.width/2,l=o.top+o.height/2;s.current=void 0;let u=e=>{let n=gO({width:2*(e.clientX-c),height:2*(e.clientY-l)},window.innerWidth,window.innerHeight);s.current=n,t(n)},d=()=>{window.removeEventListener(`pointermove`,u),window.removeEventListener(`pointerup`,d),window.removeEventListener(`pointercancel`,d),s.current&&(n(s.current),r())};window.addEventListener(`pointermove`,u),window.addEventListener(`pointerup`,d),window.addEventListener(`pointercancel`,d)},onDoubleClick:()=>i(),onKeyDown:r=>{if(r.key===`Enter`||r.key===` `){r.preventDefault(),i();return}let a=r.shiftKey?8:24,o=e.current?.getBoundingClientRect(),c=o?.width??cO.width,l=o?.height??cO.height;if(r.key===`ArrowRight`)c+=a;else if(r.key===`ArrowLeft`)c-=a;else if(r.key===`ArrowDown`)l+=a;else if(r.key===`ArrowUp`)l-=a;else return;r.preventDefault();let u=gO({width:c,height:l},window.innerWidth,window.innerHeight);s.current=u,t(u),n(u)},onClick:e=>e.stopPropagation()})}function JA(){let{tools:e,mountedTools:t,openToolId:n,settingsOpen:r,shortcuts:i}=CO(),a=e.find(e=>e.id===n),o=t.find(e=>e.id===n);return(0,p.useEffect)(()=>{let n=n=>{if(!r&&!document.querySelector(`[aria-modal="true"]`)&&!(n.isComposing||n.defaultPrevented)){for(let[r,a]of Object.entries(i))if(rO(a,n)&&(e.some(e=>e.id===r)||t.some(e=>e.id===r))){n.preventDefault(),wO.openTool(r);return}}};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[i,e,t,r]),(0,p.useEffect)(()=>{TO();let e=()=>{TO()};return window.addEventListener(`super-pi-tools-updated`,e),window.addEventListener(`super-pi-active-server`,e),()=>{window.removeEventListener(`super-pi-tools-updated`,e),window.removeEventListener(`super-pi-active-server`,e)}},[]),(0,p.useEffect)(()=>{wO.persistTools()},[]),(0,m.jsxs)(m.Fragment,{children:[r&&(0,m.jsx)(GA,{onClose:()=>wO.closeSettings()}),a&&(0,m.jsx)(ZA,{tool:a,onClose:()=>wO.closeTool()}),o&&(0,m.jsx)(aj,{tool:o,onClose:()=>wO.closeTool()})]})}function YA({pending:e,slugDraft:t,slugError:n,preview:r,busy:i,onSlugChange:a,onPreviewChange:o,onCancel:s,onConfirm:c}){let l=e.bundle,u=l.files.reduce((e,t)=>e+new TextEncoder().encode(t.content).length,0),d=LO(l),f=IO(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,m.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,m.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,m.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,zO(u)]}),(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,m.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,m.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,m.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,m.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,m.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` · `,l.environment.fingerprint.platform||`未知平台`,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,m.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,m.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,m.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,m.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,m.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,m.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`tool-share-tab`,"aria-pressed":e.path===p?.path,"data-tool-import-file":e.path,onClick:()=>o(e.path),children:e.path},e.path))}),(0,m.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,m.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,m.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,m.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function XA(e){let t=e.replace(/^[./]+/,``).slice(0,30).trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(e))return t||e.slice(0,30);try{return new URL(e,typeof window>`u`?`http://localhost`:window.location.href).hostname||t||e.slice(0,30)}catch{return e.slice(0,30)}}function ZA({tool:e,onClose:t}){return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,m.jsx)(OD,{className:`tool-dialog-glyph`,glyph:e.glyph}),e.name]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,m.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,m.jsx)($A,{}),e.kind===`timestamp`&&(0,m.jsx)(ej,{}),e.kind===`link`&&(0,m.jsx)(tj,{tool:e})]})]})}),document.body)}function QA({image:e,onClose:t}){return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`lightbox-overlay`,"data-lightbox-overlay":`1`,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`lightbox-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`lightbox-title`,"data-lightbox-dialog":`1`,children:[(0,m.jsxs)(`div`,{className:`lightbox-head`,children:[(0,m.jsx)(`h2`,{className:`lightbox-title`,id:`lightbox-title`,children:e.name||`图片大图`}),(0,m.jsx)(`button`,{type:`button`,className:`lightbox-close`,"data-lightbox-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭大图`,onClick:t,children:`✕`})]}),(0,m.jsx)(`div`,{className:`lightbox-body`,children:(0,m.jsx)(`img`,{src:e.url,alt:e.name||`图片大图`,className:`lightbox-image`})})]})}),document.body)}function $A(){let[e,t]=(0,p.useState)(`12 * (3 + 4)`),n=vn(e),r=e=>{t(t=>t+e)};return(0,m.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,m.jsx)(`input`,{className:`tool-input tool-calc-input`,"data-calc-input":`1`,value:e,maxLength:200,"aria-label":`算式`,spellCheck:!1,autoComplete:`off`,placeholder:`例如 (12 + 8) / 4`,onChange:e=>{t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&e.preventDefault()}}),(0,m.jsx)(`div`,{className:`tool-calc-keys`,"data-calc-keys":`1`,children:[[`7`,`7`],[`8`,`8`],[`9`,`9`],[`÷`,`/`],[`(`,`(`],[`)`,`)`],[`4`,`4`],[`5`,`5`],[`6`,`6`],[`×`,`*`],[`^`,`^`],[`%`,`%`],[`1`,`1`],[`2`,`2`],[`3`,`3`],[`-`,`-`],[`←`,`back`],[`C`,`clear`],[`0`,`0`],[`.`,`.`],[`+`,`+`]].map(([e,n])=>(0,m.jsx)(`button`,{type:`button`,className:`tool-calc-key`,"data-calc-key":n,"aria-label":e===`C`?`清空`:e===`←`?`退格`:`输入 ${e}`,onClick:()=>{n===`clear`?t(``):n===`back`?t(e=>e.slice(0,-1)):r(n)},children:e},e))}),n.ok?(0,m.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:yn(n.value)}):(0,m.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function ej(){let[e,t]=(0,p.useState)(``),n=bn(e),r=n.ok?Sn(n.ms):null;return(0,m.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,m.jsx)(`input`,{className:`tool-input`,"data-stamp-input":`1`,value:e,maxLength:64,spellCheck:!1,"aria-label":`时间戳或日期`,placeholder:`1757000000 或 2026-10-08T09:00:00`,onChange:e=>t(e.target.value)}),r?(0,m.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`本地时间`}),(0,m.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`ISO(UTC)`}),(0,m.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`秒`}),(0,m.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`毫秒`}),(0,m.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,m.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function tj({tool:e}){let[t,n]=(0,p.useState)(!1),r=async()=>{let e=await Hi(`请为 Super Pi 开发一个全局右侧栏工具并自动挂载。不要启动独立 HTTP 服务器。通过内置 tool_register 提交完整的 HTML/JS/CSS 文件;工具将被 Super Pi 保存并在所有 workspace 可用。如需计算,注册一个 Python 脚本(不接受 shell 命令),参数经 JSON stdin 传入,stdout 只输出 JSON 结果。在页面里加载 ./super-pi-tool.js,使用 SuperPiTool.run(params)、wait(runId)、get(runId) 和 cancel(runId) 执行、等待、查看和取消任务。它们会自动绑定当前工具;不要调用 /api/exec,也不要猜测 toolId。`);n(e),window.setTimeout(()=>n(!1),1800)};return(0,m.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,m.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,m.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,m.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,m.jsx)(`a`,{className:`tool-link-open`,"data-tool-link-open":e.id,href:e.url,target:`_blank`,rel:`noopener noreferrer`,title:e.url,children:`在新标签页打开 ↗`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-copy-prompt":e.id,onClick:()=>void r(),children:t?`已复制`:`复制开发 Prompt`})]}),/^https?:\/\//i.test(e.url??``)&&(0,m.jsx)(`iframe`,{className:`tool-link-frame`,"data-tool-frame":e.id,src:e.url,title:e.name,sandbox:`allow-forms allow-modals allow-pointer-lock allow-popups allow-same-origin allow-scripts`,referrerPolicy:`no-referrer`})]})}var nj=`(max-width: 1100px)`,rj=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function ij(e){let t=`super-pi.mounted-tool.owner.`+e;try{let e=window.localStorage.getItem(t);if(e&&/^[0-9a-f]{32}$/.test(e))return e}catch{}let n=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``);try{window.localStorage.setItem(t,n)}catch{}return n}function aj({tool:e,onClose:t}){let n=(0,p.useRef)(null);(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let r=(0,p.useMemo)(()=>ij(e.id),[e.id]);(0,p.useLayoutEffect)(()=>Wn(()=>n.current,e.id,r),[e.id,r]);let i=e.dialogSize??{width:1100,height:780},a={width:`min(${i.width}px, calc(100vw - 32px))`,height:`min(${i.height}px, calc(100dvh - 32px))`};return(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`tool-dialog mounted-tool-dialog`,style:a,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsxs)(`h2`,{className:`tool-dialog-title`,children:[(0,m.jsx)(OD,{className:`tool-dialog-glyph`,glyph:AD(e)}),e.name]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body`,children:(0,m.jsx)(`iframe`,{ref:n,className:`tool-link-frame`,src:Fe(`/tools/${encodeURIComponent(e.id)}/#super-pi-owner=${r}`),title:e.name,sandbox:`allow-forms allow-modals allow-popups allow-scripts`,referrerPolicy:`no-referrer`})})]})}),document.body)}function oj(e,t,n){let r=Math.max(0,Math.round(n)-480),i=rj(520,180,Math.max(180,r-240)),a=rj(Math.round(e),180,i),o=rj(640,240,Math.max(240,r-a));return{sidebar:a,rail:rj(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var sj=`super-pi.rail-widths.v1`,cj=`super-pi.reader-state.v1`,lj=`super-pi.folded-groups.v1`;function uj(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.folded-groups.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t=e=>{let t={};if(e&&typeof e==`object`)for(let[n,r]of Object.entries(e))typeof r==`boolean`&&(t[n]=r);return t};return{workspaces:t(e.workspaces),archived:t(e.archived)}}catch{return{}}}function dj(e){try{typeof window<`u`&&window.localStorage.setItem(lj,JSON.stringify(e))}catch{}}var fj=e=>{let t=document.querySelector(`[data-workspace-group="${CSS.escape(e)}"]`);return t?[...t.querySelectorAll(`.conversation-row[data-session-root]`)].map(e=>({id:e.dataset.sessionRoot??``,middle:(()=>{let t=e.getBoundingClientRect();return t.top+t.height/2})()})).filter(e=>e.id!==``):[]},pj=6,mj=400,hj=32,gj=48,_j=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function vj(e,t,n=!1,r=!1){let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=n?!1:r?!0:t.followTail?i<=gj:i<=hj,o,s;if(!a){let t=e.getBoundingClientRect().top,n=[...e.querySelectorAll(`[data-transcript-key]`)].find(e=>e.getBoundingClientRect().bottom>t);o=n?.dataset.transcriptKey,s=n?n.getBoundingClientRect().top-t:void 0}return{followTail:a,scrollTop:e.scrollTop,...o?{anchorKey:o,anchorOffset:s}:{}}}function yj(){try{if(typeof window>`u`)return{conversations:{}};let e=JSON.parse(window.localStorage.getItem(`super-pi.reader-state.v1`)??`null`);if(!e||typeof e!=`object`)return{conversations:{}};let t={};if(e.conversations&&typeof e.conversations==`object`)for(let[n,r]of Object.entries(e.conversations)){let e=r;typeof e.followTail==`boolean`&&(t[n]={followTail:e.followTail,scrollTop:Number.isFinite(e.scrollTop)?Math.max(0,Number(e.scrollTop)):0,...typeof e.anchorKey==`string`?{anchorKey:e.anchorKey}:{},...Number.isFinite(e.anchorOffset)?{anchorOffset:Number(e.anchorOffset)}:{}})}let n={};if(e.readAt&&typeof e.readAt==`object`)for(let[t,r]of Object.entries(e.readAt))typeof r==`string`&&(n[t]=r);return{activeId:typeof e.activeId==`string`?e.activeId:void 0,workspaceId:typeof e.workspaceId==`string`?e.workspaceId:void 0,conversations:t,readAt:n}}catch{return{conversations:{}}}}function bj(e){try{typeof window<`u`&&window.localStorage.setItem(cj,JSON.stringify(e))}catch{}}var xj=`super-pi.session-tabs.v1`;function Sj(e,t){if(!t||e.has(t))return e;let n=new Set(e);return n.add(t),n}function Cj(e,t,n){let r=e.touched.has(t),i=e.touched;if(r){let r=new Set(e.touched);r.delete(t),n&&r.add(n),i=r}return{ids:e.ids.flatMap(e=>e===t?n?[n]:[]:[e]),previewId:e.previewId===t?n&&!r?n:void 0:e.previewId,emptied:e.emptied,touched:i}}function wj(){try{if(typeof window>`u`)return{ids:[]};let e=JSON.parse(Gn(`super-pi.session-tabs.v1`)??`null`);if(!e||typeof e!=`object`)return{ids:[]};let t=e,n=Array.isArray(t.ids)?[...new Set(t.ids.filter(e=>typeof e==`string`))]:[],r=Array.isArray(t.touched)?[...new Set(t.touched.filter(e=>typeof e==`string`))]:[],i=typeof t.previewId==`string`&&n.includes(t.previewId)&&!r.includes(t.previewId)?t.previewId:void 0;i&&i!==t.activeId&&(n=n.filter(e=>e!==i));let a=typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0,o=typeof t.workspaceLandingId==`string`?t.workspaceLandingId:void 0;return{ids:n,activeId:a,contextId:typeof t.contextId==`string`?t.contextId:void 0,workspaceLandingId:o,previewId:i===a?i:void 0,touched:r,emptied:n.length===0&&(t.emptied===!0||!!i),selectionCleared:t.selectionCleared===!0}}catch{return{ids:[]}}}function Tj(e,t,n,r=!1){try{if(typeof window>`u`)return;let{ids:i,previewId:a,touched:o,emptied:s}=e;Kn(xj,JSON.stringify({ids:i,...t&&i.includes(t)?{activeId:t}:{},...t?{contextId:t}:{},...n?{workspaceLandingId:n}:{},...a&&i.includes(a)?{previewId:a}:{},...o.size?{touched:[...o]}:{},...s?{emptied:s}:{},...r?{selectionCleared:!0}:{}}))}catch{}}function Ej(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(sj);if(e===null)return{};let t=JSON.parse(e),n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.round(e):void 0;return{sidebar:n(t.sidebar),rail:n(t.rail)}}catch{return{}}}function Dj(e){try{if(typeof window>`u`)return;window.localStorage.setItem(sj,JSON.stringify(e))}catch{}}function Oj({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,p.useState)(!1),c=e=>e.shiftKey?64:16;return(0,m.jsx)(`div`,{className:`rail-resizer rail-resizer-${e}${o?` rail-resizer-dragging`:``}`,"data-rail-resizer":e,"data-rail-resizer-dragging":o?`true`:`false`,"data-rail-resizer-width":t,role:`separator`,"aria-orientation":`vertical`,"aria-label":i,"aria-valuenow":t,"aria-valuemin":n,"aria-valuemax":r,tabIndex:0,onMouseDown:i=>{i.preventDefault(),i.currentTarget.focus();let o=i.clientX,c=t;s(!0);let l=document.body,u=l.style.cursor,d=l.style.userSelect;l.style.cursor=`col-resize`,l.style.userSelect=`none`;let f=t=>{let i=e===`left`?t.clientX-o:o-t.clientX;a(rj(c+i,n,r))},p=()=>{l.style.cursor=u,l.style.userSelect=d,s(!1),window.removeEventListener(`mousemove`,f),window.removeEventListener(`mouseup`,p)};window.addEventListener(`mousemove`,f),window.addEventListener(`mouseup`,p)},onKeyDown:i=>{let o=c(i);i.key===`ArrowLeft`?(i.preventDefault(),a(rj(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(rj(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var kj=`super-pi.composer-height.v1`,Aj=148,jj=.55,Mj=()=>Math.max(Aj,Math.round((typeof window>`u`?800:window.innerHeight)*jj)),Nj=e=>{let t=Number.isFinite(e)?e:Aj;return Math.round(Math.min(Mj(),Math.max(Aj,t)))},Pj=()=>{try{let e=window.localStorage.getItem(kj);return e===null?Aj:Nj(Number(e))}catch{return Aj}};function Fj({height:e,onHeight:t}){let[n,r]=(0,p.useState)(!1),i=e=>e.shiftKey?64:16,a=Mj();return(0,m.jsx)(`div`,{className:`composer-resize${n?` composer-resize-dragging`:``}`,"data-composer-resize":`1`,"data-composer-resize-dragging":n?`true`:`false`,"data-composer-height":e,role:`separator`,"aria-orientation":`horizontal`,"aria-label":`调整消息编辑区高度`,"aria-valuenow":e,"aria-valuemin":Aj,"aria-valuemax":a,tabIndex:0,onMouseDown:n=>{n.preventDefault(),n.currentTarget.focus();let i=n.clientY,a=e;r(!0);let o=document.documentElement,s=document.body.style.userSelect;document.body.style.cursor=`ns-resize`,document.body.style.userSelect=`none`;let c=e=>{let t=Nj(a+(i-e.clientY));o.style.setProperty(`--composer-height`,`${t}px`)},l=()=>{document.body.style.cursor=``,document.body.style.userSelect=s;let n=Number.parseFloat(o.style.getPropertyValue(`--composer-height`));r(!1),window.removeEventListener(`mousemove`,c),window.removeEventListener(`mouseup`,l),t(Number.isFinite(n)?n:e)};window.addEventListener(`mousemove`,c),window.addEventListener(`mouseup`,l)},onKeyDown:n=>{let r=i(n);n.key===`ArrowUp`?(n.preventDefault(),t(Nj(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(Nj(e-r))):n.key===`Home`?(n.preventDefault(),t(Aj)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(Nj(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(Nj(e-96)))}})}function Ij(e,t,n){if(e=e.filter(e=>!e.groupExecution),!e.length)return;let r=n?e.find(e=>e.workspaceId===n):void 0;if(r)return r;if(!(n&&t.some(e=>e.id===n)))return n?e.find(e=>y(e.workspaceId).server===y(n).server):e[0]}function Lj(e,t,n){let r=n&&e?JSON.stringify([e,t,n]):void 0,[i,a]=(0,p.useState)();(0,p.useEffect)(()=>{if(!r||!n||!e)return;let i=new AbortController;return Ie(`/api/files/diff?${new URLSearchParams({workspaceId:e,path:n,...t?{cwd:t}:{}})}`,{signal:i.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{i.signal.aborted||a({scope:r,diff:e,error:``})}).catch(e=>{i.signal.aborted||a({scope:r,diff:null,error:e instanceof Error?e.message:`读取差异失败`})}),()=>i.abort()},[r,e,t,n]);let o=i?.scope===r?i:void 0;return{diff:o?.diff??null,error:o?.error??``,loading:!!r&&!o}}function Rj(e){try{let t=`super-pi.browser-notification-events`,n=Date.now(),r=JSON.parse(window.localStorage.getItem(t)??`[]`).filter(e=>Array.isArray(e)&&typeof e[0]==`string`&&typeof e[1]==`number`&&n-e[1]<864e5);return!r.some(([t])=>t===e)&&(window.localStorage.setItem(t,JSON.stringify([...r.slice(-63),[e,n]])),!0)}catch{return!0}}function zj(){let[e,t]=(0,p.useState)(lk),[n,r]=(0,p.useState)(()=>{try{return typeof window<`u`&&window.localStorage.getItem(`super-pi.browser-notifications`)===`enabled`}catch{return!1}}),[i,a]=(0,p.useState)(()=>eo()),o=(0,p.useCallback)(()=>a(eo()),[]),s=(0,p.useRef)(new Map),c=(0,p.useRef)(!1),l=(0,p.useRef)(new Map),u=(0,p.useCallback)(e=>{t(t=>{let n=typeof e==`function`?e(t):e;return jt(n,t)})},[]),[d,f]=(0,p.useState)(()=>xm().map(e=>{let t=new Date().toISOString();return{id:e.clientId,key:`send:${e.conversationId}:${e.clientId}`,serverId:L(e.conversationId),retry:!0,command:{...e},apply:n=>Tm(n,e,t),accepted:t=>!!t.conversations.find(t=>t.id===e.conversationId)?.messages.some(t=>t.id===wm(e))}})),g=(0,p.useRef)(d),_=(0,p.useRef)(null);_.current||=yj();let x=(0,p.useRef)(null);x.current||=wj();let S=x.current,C=(0,p.useRef)(null);C.current||=qn();let w={current:C.current},T=(0,p.useRef)(null);T.current||=Jn();let E=T.current,O=d.reduce((e,t)=>t.apply(e),e),A=E.view===`file`||E.view===`diff`||E.view===`gitDiff`,[j,ee]=(0,p.useState)(S.workspaceLandingId||S.selectionCleared?void 0:S.activeId??(A?S.contextId:void 0)??(S.emptied?void 0:_.current.activeId)),[M,N]=(0,p.useState)(S.workspaceLandingId??(S.selectionCleared?w.current.kind===`workspace`?w.current.workspaceId:void 0:_.current.workspaceId)),[P,F]=(0,p.useState)(!1),I=pe(),te=P&&I.statuses.get(I.activeServer)?.state===`online`,[ne,re]=(0,p.useState)(),[ie,ae]=(0,p.useState)(()=>uj().workspaces??{}),[se,ce]=(0,p.useState)(()=>({ids:S.ids,previewId:S.previewId,touched:new Set(S.touched??[]),emptied:S.emptied})),le=se.ids,ue=se.previewId,de=(0,p.useRef)(0),[fe,Se]=(0,p.useState)(),[Ce,we]=(0,p.useState)({entries:[],index:-1}),Te=(0,p.useRef)([]),[Ee,De]=(0,p.useState)(),[Oe,ke]=(0,p.useState)(),Ae=(0,p.useRef)(new Set),je=se.emptied===!0,[Me,Ne]=(0,p.useState)(!1),[Pe,Le]=(0,p.useState)(!1),[Re,ze]=(0,p.useState)(),Ve=(0,p.useRef)(null),He=(0,p.useRef)(void 0),Ue=(0,p.useRef)(_.current.conversations),Ge=(0,p.useRef)(le);Ge.current=le;let Ke=(0,p.useRef)(_.current.readAt??{}),[qe,Je]=(0,p.useState)(0),[Ye,Xe]=(0,p.useState)(sr),[Ze,nt]=(0,p.useState)(()=>E.groups.length?E.groups:Ye?[Ye]:[]),[rt,it]=(0,p.useState)(E.view?E.view===`group`:!!Ye),[R,at]=(0,p.useState)(()=>E.view??(Ye?`group`:`session`)),{index:ot,reload:st,remember:ct,forget:ut,activities:dt,recordActivity:ft}=_r(O.workspaces,te),[pt,mt]=(0,p.useState)(()=>new Set),ht=Ye?.workspaceId??``,gt=Ye?.roomId??``,_t=ot[ht]?.rooms.find(e=>e.id===gt),vt=_t?.title;(0,p.useEffect)(()=>{cr(R===`group`?Ye:void 0)},[Ye,R]),(0,p.useEffect)(()=>{R===`group`&&Me&&!O.workspaces.some(e=>e.id===ht&&!e.closedAt)&&(it(!1),at(`session`))},[R,Me,O.workspaces,ht]);let yt=(0,p.useRef)(null),bt=(0,p.useRef)(null),xt=(0,p.useRef)(void 0),St=(0,p.useRef)(!1),Ct=(0,p.useRef)(!0),[wt,Tt]=(0,p.useState)({followTail:!0,scrollTop:0}),Et=(0,p.useRef)(!1),Dt=(0,p.useRef)(new Map),Ot=(0,p.useRef)(void 0),kt=(0,p.useRef)([]),At=(0,p.useRef)(void 0),jt=(0,p.useCallback)((e,t)=>{let n=new Map(t.conversations.map(e=>[e.id,e]));return{...e,conversations:e.conversations.map(e=>{let t=n.get(e.id);if(e.messagesLoaded===!1||!t||t.messagesLoaded===!1||t.status!==`running`)return e;let r=new Map(t.messages.map(e=>[e.id,e]));return{...e,messages:e.messages.map(e=>{let t=r.get(e.id);return!t||!(t.content.length>e.content.length||(t.thinking?.length??0)>(e.thinking?.length??0))?e:{...e,content:t.content,thinking:t.thinking,thinkingActive:t.thinkingActive,thinkingBlocks:hk(t.thinkingBlocks,e.thinkingBlocks)}})}})}},[]),Mt=(0,p.useCallback)(()=>{if(At.current!==void 0&&(cancelAnimationFrame(At.current),At.current=void 0),!kt.current.length)return;let e=kt.current;kt.current=[];let t=new Map;for(let n of e){let e=`${n.conversationId}\u0000${n.messageId}`,r=t.get(e)??[];r.push(n),t.set(e,r)}u(e=>({...e,conversations:e.conversations.map(e=>{let n=e.messages.map(n=>{let r=t.get(`${e.id}\u0000${n.id}`);if(!r)return n;let i={...n};for(let e of r){if(e.type===`message.delta`){i.content+=e.delta;continue}if(i.thinkingActive=e.active,!e.delta)continue;let t=e.at??i.content.length,n=mk(i.thinkingBlocks??[],e,t);i={...i,thinking:(i.thinking??``)+e.delta,thinkingBlocks:n}}return i});return n.every((t,n)=>t===e.messages[n])?e:{...e,messages:n}})}))},[]),Nt=(0,p.useCallback)(e=>{let t=kt.current,n=t.at(-1);n&&n.type===e.type&&n.conversationId===e.conversationId&&n.messageId===e.messageId&&(e.type!==`message.thinking`||n.type===`message.thinking`&&n.at===e.at&&n.active===e.active&&n.blockIndex===e.blockIndex)?t[t.length-1]={...e,delta:n.delta+e.delta}:t.push(e),At.current===void 0&&(At.current=requestAnimationFrame(Mt))},[Mt]),Pt=(0,p.useCallback)(e=>{Ot.current=e},[]),[Ft,It]=(0,p.useState)(()=>uj().archived??{});(0,p.useEffect)(()=>{dj({workspaces:ie,archived:Ft})},[ie,Ft]);let[Lt,Rt]=(0,p.useState)(()=>LD());(0,p.useEffect)(()=>{RD(Lt)},[Lt]);let[zt,Bt]=(0,p.useState)(),Vt=(0,p.useRef)(0),Ht=(0,p.useRef)(``),Ut=(e,t,n,r)=>{let i=(e.target instanceof Element?e.target:void 0)?.closest(`button`);if(i&&!i.classList.contains(`conversation`)||e.button!==0)return;let a=e.clientY,o=e.pointerType===`touch`,s=!1,c,l=[],u,d=!1,f=e=>{let t=l.filter(e=>e.id!==n);if(t.length===0){u=void 0,d=!1;return}let r=0;for(;r<t.length&&t[r].middle<e;)r+=1;r<t.length?(u=t[r].id,d=!1):(u=t[t.length-1].id,d=!0)},p=()=>Bt(e=>e&&e.dropRootId===u&&e.dropAfter===d?e:{workspaceId:t,conversationId:n,dropRootId:u,dropAfter:d}),m=()=>{s||(s=!0,l=fj(t),f(a),document.body.style.userSelect=`none`,p())},h=e=>{if(!s){if(o){c!==void 0&&window.clearTimeout(c),c=void 0;return}if(Math.abs(e.clientY-a)<pj)return;m()}f(e.clientY),p()},g=e=>{if(window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,_),window.removeEventListener(`pointercancel`,v),document.removeEventListener(`touchmove`,y),c!==void 0&&window.clearTimeout(c),document.body.style.userSelect=``,s&&e){let e=r.filter(e=>e!==n),i=u===void 0?e.length:d?e.indexOf(u)+1:e.indexOf(u);Rt(e=>({...e,[t]:FD(r,n,i)})),Vt.current=Date.now(),Ht.current=n}Bt(void 0)},_=()=>g(!0),v=()=>g(!1),y=e=>{s&&e.preventDefault()};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,_),window.addEventListener(`pointercancel`,v),o&&(document.addEventListener(`touchmove`,y,{passive:!1}),c=window.setTimeout(m,mj))},[Wt,Gt]=(0,p.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),Kt=e=>{let t=e.slice(0,24);Gt(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},qt=Wt.trim()||`你`,[Jt,Yt]=(0,p.useState)(),[Xt,Zt]=(0,p.useState)([]),[Qt,$t]=(0,p.useState)([]),[en,nn]=(0,p.useState)(),[rn,an]=(0,p.useState)(),[on,sn]=(0,p.useState)([]),[cn,ln]=(0,p.useState)([]),[un,dn]=(0,p.useState)(),[fn,pn]=(0,p.useState)(),[mn,hn]=(0,p.useState)(),[gn,_n]=(0,p.useState)(),[vn,yn]=(0,p.useState)(),bn=Ja(mn),xn=(0,p.useMemo)(()=>Xt.filter(e=>e.request.blocking),[Xt]),[Sn,wn]=(0,p.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[Tn,En]=(0,p.useState)(`chat`),[Dn,On]=(0,p.useState)(!1),kn=(0,p.useCallback)(()=>{En(`chat`),window.matchMedia(`(max-width: 700px)`).matches&&wn(!0)},[]),[An,jn]=(0,p.useState)(!1),[Mn,Nn]=(0,p.useState)(w.current.kind),[Fn,In]=(0,p.useState)(()=>w.current.serverId??localStorage.getItem(`super-pi.server-filter`)??`all`),[Ln,Rn]=(0,p.useState)(w.current.workspaceId??_.current.workspaceId),[zn,Vn]=(0,p.useState)(w.current.repoId??_.current.workspaceId),[Hn,Un]=(0,p.useState)(S.selectionCleared===!0);(0,p.useEffect)(()=>{try{Kn(`super-pi.sidebar-scope.v1`,JSON.stringify({kind:Mn,serverId:Fn,workspaceId:Ln,repoId:zn}))}catch{}},[Mn,Fn,Ln,zn]);let Wn=(0,p.useRef)(Hn);Wn.current=Hn;let[Gn,Qn]=(0,p.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,p.useEffect)(()=>{let e=()=>Qn(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[er,tr]=(0,p.useState)(hi),[nr]=(0,p.useState)(()=>new Ti);Oi(nr),(0,p.useEffect)(()=>gi(er),[er]);let[rr,ir]=(0,p.useState)(Ej),ar=oj(rr.sidebar??270,rr.rail??320,Gn>1100?Gn-88:Gn);(0,p.useEffect)(()=>{Dj({sidebar:rr.sidebar??270,rail:rr.rail??320})},[rr.sidebar,rr.rail]);let or=e=>ir(t=>({...t,sidebar:e})),fr=e=>ir(t=>({...t,rail:e})),[pr,vr]=(0,p.useState)(null);(0,p.useEffect)(()=>{vr(Pj())},[]),(0,p.useEffect)(()=>{pr!==null&&document.documentElement.style.setProperty(`--composer-height`,`${pr}px`)},[pr]);let br=e=>{let t=Nj(e);vr(t);try{window.localStorage.setItem(kj,String(t))}catch{}};(0,p.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(nj),t=e=>{e.matches&&wn(!0)};return e.addEventListener(`change`,t),e.matches&&wn(!0),()=>e.removeEventListener(`change`,t)},[]);let xr=Gn<=1100;(0,p.useEffect)(()=>{if(!xr||Sn)return;let e=e=>{e.key===`Escape`&&(e.defaultPrevented||document.querySelector(`.tool-overlay, .lightbox-overlay, .quick-open-backdrop, .ctx-menu, .overlay, .picker-menu, .content-search-overlay`)||(e.preventDefault(),wn(!0)))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[xr,Sn]);let[Sr,Cr]=(0,p.useState)({}),[wr,Tr]=(0,p.useState)({}),[Er,Dr]=(0,p.useState)({}),[Or,kr]=(0,p.useState)({}),[Ar,jr]=(0,p.useState)(null),[Mr,Nr]=(0,p.useState)(),[Pr,Fr]=(0,p.useState)(()=>new Set);(0,p.useEffect)(()=>{Fr(e=>{if(e.size===0)return e;let t=new Set([...e].filter(e=>{let t=O.conversations.find(t=>t.id===e);return t?wA(t):!1}));return t.size===e.size?e:t})},[O.conversations]);let[Ir,Lr]=(0,p.useState)(),[Rr,Vr]=(0,p.useState)(),Hr=(0,p.useRef)(new Map),[Ur,Wr]=(0,p.useState)(()=>{let e=Em(`super-pi.composer-drafts.v1`,{});return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,attachments:eA(t.text,t.attachments)}]))}),Gr=(0,p.useRef)(Ur),Kr=(0,p.useRef)(!1);Gr.current=Ur,(0,p.useEffect)(()=>{let e=()=>{let e=Object.entries(Gr.current).filter(([e,t])=>!e.startsWith(`pending:`)&&(t.text||t.images.length||t.attachments.length)).map(([e,{text:t,images:n,attachments:r}])=>[e,{text:t,images:n,attachments:r,uploading:0}]),t=Dm(`super-pi.composer-drafts.v1`,Object.fromEntries(e));!t&&e.length&&!Kr.current&&Sc(`浏览器无法保存聊天草稿,刷新前请先保留这段内容。`,`warning`),Kr.current=!t&&e.length>0},t=window.setTimeout(e,250);return window.addEventListener(`pagehide`,e),()=>{window.clearTimeout(t),window.removeEventListener(`pagehide`,e)}},[Ur]);let qr=(0,p.useRef)(new Set),[Jr,Yr]=(0,p.useState)([]),[Xr,Zr]=(0,p.useState)([]),[ti,ni]=(0,p.useState)(),[ri,ii]=(0,p.useState)(!1),ai=(0,p.useRef)(null),oi=(0,p.useRef)(!1),si=(0,p.useRef)(0),ci=(0,p.useRef)([]),li=(0,p.useRef)(void 0),ui=(0,p.useRef)(!1),fi=(0,p.useRef)(new Set),mi=(0,p.useRef)(new Set),_i=(0,p.useRef)(new Map),bi=(0,p.useRef)(new Map),[Si,Ci]=(0,p.useState)(()=>Date.now());(0,p.useEffect)(()=>{let e=window.setInterval(()=>Ci(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let wi=(0,p.useMemo)(()=>O.conversations.filter(e=>!e.archivedAt),[O.conversations]),Di=(0,p.useMemo)(()=>e.conversations.filter(e=>!e.archivedAt),[e.conversations]),ki=(0,p.useMemo)(()=>new Set(O.collapsedConversationIds??[]),[O.collapsedConversationIds]),z=(0,p.useMemo)(()=>{let e=wi.find(e=>e.id===j);if(e)return e;if(!(je||Hn||oe(j??M)))return Ij(wi,O.workspaces,M)},[je,Hn,j,wi,M,O.workspaces]),Ni=(0,p.useMemo)(()=>z?{workspaceId:z.workspaceId,conversationId:z.id,onImageOpen:ni}:void 0,[z?.workspaceId,z?.id]),[Pi,Fi]=(0,p.useState)(`queue`),Ii=!!(z&&wA(z));(0,p.useEffect)(()=>{Fi(`queue`)},[z?.id,Ii]);let[Li,Ri]=(0,p.useState)([]),zi=(0,p.useMemo)(()=>Zn(z?.parentConversationId,z?.parentConversationId?O.conversations.find(e=>e.id===z.parentConversationId):void 0),[z,O.conversations]),Bi=!!(z&&O.unlockedChildConversationIds?.includes(z.id)),Ui=zi&&!Bi,Wi=(0,p.useMemo)(()=>(O.conversations||[]).filter(e=>e.parentConversationId===z?.id),[O.conversations,z?.id]),Gi=(0,p.useMemo)(()=>(O.conversations||[]).find(e=>e.id===z?.parentConversationId),[O.conversations,z?.parentConversationId]),Ki=(0,p.useMemo)(()=>z?$n({conversation:z,parent:Gi,directChildren:Wi,isTopLevelUnread:!1}):null,[z,Gi,Wi]),qi=yt.current;if(qi){let e=qi.dataset.messageScrollContainer;e&&z?.id&&e!==z?.id&&qi.querySelector(`[data-transcript-key]`)&&(Ue.current[e]=vj(qi,Ue.current[e]??{followTail:!0,scrollTop:0}))}Ct.current=z?.messagesLoaded!==!1,(0,p.useEffect)(()=>{if(!Me||oe(j??M)||(je||Hn)&&!j||j&&Di.some(e=>e.id===j)||j&&g.current.some(e=>e.temporaryId===j))return;let e=Ij(wi,O.workspaces,M);je&&e||(j&&!e&&R!==`group`&&(de.current++,at(`session`)),ee(e?.id),e&&ce(t=>t.emptied||t.ids.length===0||t.ids.includes(e.id)?t:{...t,ids:[...t.ids,e.id]}))},[je,Hn,j,Di,wi,Me,M,O.workspaces,R]),(0,p.useEffect)(()=>{re(void 0)},[j,M]);let Ji=(0,p.useMemo)(()=>O.workspaces.find(e=>e.id===M)??(Hn||oe(M)?void 0:O.workspaces[0]),[O.workspaces,M,Hn]),Yi=Ji&&!wi.some(e=>e.workspaceId===Ji.id)?Ji:void 0,Xi=Ji?.id.startsWith(`pending:`)===!0,[Zi,Qi]=(0,p.useState)(``);(0,p.useEffect)(()=>{Qi(``)},[Ji?.id]);let $i=(0,p.useRef)(M);$i.current=M,(0,p.useEffect)(()=>{z&&N(z.workspaceId)},[z?.id]),(0,p.useEffect)(()=>{li.current=j},[j]),(0,p.useEffect)(()=>{xt.current=z?.id},[z?.id]);let ea=(0,p.useCallback)(e=>{let t=e.activity.lastReplyAt,n=lr({workspaceId:e.workspaceId,roomId:e.id});!t||t<=(Ke.current[n]??``)||(Ke.current[n]=t,Je(e=>e+1),bj({activeId:li.current,workspaceId:$i.current,conversations:Ue.current,readAt:Ke.current}))},[]);yr(Ke,O.conversations,()=>{Je(e=>e+1),bj({activeId:li.current,workspaceId:$i.current,conversations:Ue.current,readAt:Ke.current})}),(0,p.useEffect)(()=>{let e=z?.id;if(!e)return;let t=O.conversations.find(t=>t.id===e);if(!t||t.messagesLoaded===!1)return;let n=()=>{let n=yt.current;document.visibilityState!==`visible`||!n||n.getBoundingClientRect().height<=0||t.updatedAt<=(Ke.current[e]??``)||(Ke.current[e]=t.updatedAt,Je(e=>e+1),bj({activeId:li.current,workspaceId:z?.workspaceId??M,conversations:Ue.current,readAt:Ke.current}))},r=requestAnimationFrame(n);return document.addEventListener(`visibilitychange`,n),window.addEventListener(`focus`,n),()=>{cancelAnimationFrame(r),document.removeEventListener(`visibilitychange`,n),window.removeEventListener(`focus`,n)}},[z?.id,O.conversations,R]),(0,p.useEffect)(()=>{let e=z?.workspaceId??M;te&&Me&&e&&!e.startsWith(`pending:`)&&!z?.id.startsWith(`pending:`)&&bj({activeId:z?.id,workspaceId:e,conversations:Ue.current,readAt:Ke.current})},[z?.id,z?.workspaceId,te,Me,M]),(0,p.useEffect)(()=>{let e=yt.current;if(R!==`session`||!e||!z?.id||z.messagesLoaded===!1)return;let t=z.id;Et.current=!1;let n=Ue.current[t]??{followTail:!0,scrollTop:0};Ue.current[t]=n,Tt(n);let r=requestAnimationFrame(()=>{if(yt.current!==e)St.current=!1;else{if(n.followTail)_j(e),e.scrollTop=e.scrollHeight;else{let t=n.anchorKey?e.querySelector(`[data-transcript-key="${CSS.escape(n.anchorKey)}"]`):null;e.scrollTop=t?Math.max(0,e.scrollTop+t.getBoundingClientRect().top-(n.anchorOffset??0)-e.getBoundingClientRect().top):n.scrollTop}St.current=!1}});return()=>cancelAnimationFrame(r)},[z?.id,z?.messagesLoaded,R]),(0,p.useLayoutEffect)(()=>{St.current=!0},[z?.id,z?.messagesLoaded,R]);let ta=(0,p.useCallback)((e,t=!1,n=!1)=>{let r=xt.current;if(!r||St.current||!Ct.current)return;let i=vj(e,Ue.current[r]??{followTail:!0,scrollTop:0},t,n);Et.current=!i.followTail,Ue.current[r]=i,Tt(i),bj({activeId:r,workspaceId:$i.current,conversations:Ue.current,readAt:Ke.current})},[]),na=z?.id??``,ra=Ur[na]??{text:``,images:[],attachments:[],uploading:0},ia=ra.text,aa=ra.images,oa=ra.attachments,sa=Object.keys(ra.pendingSkills??{}).length>0,ca=ra.uploading,la=(e,t)=>Wr(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),ua=(e,t)=>({...e,text:t,attachments:eA(t,e.attachments),pendingSkills:e.pendingSkills&&Object.fromEntries(Object.entries(e.pendingSkills).filter(([e])=>mp(t,e)))}),da=e=>la(na,t=>ua(t,e)),fa=(e,t,n,r)=>{let i=tn();la(n,n=>{let r=ua(n,t);return{...r,pendingSkills:{...r.pendingSkills,[e]:i}}});let a=t=>t[n]?.pendingSkills?.[e]===i?n:n.startsWith(`pending:`)?Object.keys(t).find(n=>t[n].pendingSkills?.[e]===i):void 0,o=t=>Wr(n=>{let r=a(n);if(!r)return n;let i=n[r],o={...i.pendingSkills};delete o[e];let s=t?[...i.attachments.filter(t=>t.id!==e),t]:i.attachments;return{...n,[r]:{...i,pendingSkills:o,attachments:s}}});Ie(`/api/skills/read?${new URLSearchParams({name:e,workspaceId:r})}`,{signal:AbortSignal.timeout(1e4)}).then(async t=>{if(!t.ok)throw Error(`读取技能失败`);let n=await t.json();if(typeof n.content!=`string`)throw Error(`读取技能失败`);o({kind:`skill`,id:e,name:n.name??e.slice(6),content:n.content})}).catch(()=>{a(Gr.current)&&Sc(`读取技能失败`,`error`),o()})},ma=(e,t)=>la(z?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[ha,ga]=(0,p.useState)({visible:!1,query:``,rect:null}),_a=JSON.stringify([z?.id,z?.workspaceId,z?.cwd??``]),[va,ya]=(0,p.useState)(),ba=(0,p.useRef)(null),[xa,Sa]=(0,p.useState)(),Ca=(0,p.useRef)(void 0),wa=(0,p.useRef)(``),Ta=!Ui&&va?.scope===_a?va:void 0,Ea=e=>{let t=!oi.current&&!Ui&&z?_p(e.value,e.selectionStart,e.selectionEnd):void 0,n=JSON.stringify([_a,t]);return!t||wa.current===n?(ya(void 0),!1):(ya({scope:_a,token:t,rect:e.getBoundingClientRect()}),ga({visible:!1,query:``,rect:null}),!0)},Da=()=>{wa.current=JSON.stringify([_a,Ta?.token]),ya(void 0)};(0,p.useEffect)(()=>{ya(void 0),wa.current=``},[_a]),(0,p.useLayoutEffect)(()=>{let e=Ca.current;Ca.current=void 0,e?.scope===_a&&e.text===ia&&(bt.current?.focus(),bt.current?.setSelectionRange(e.caret,e.caret))},[ia,_a]),(0,p.useEffect)(()=>{let e=()=>{let e=bt.current;e&&ya(t=>t?{...t,rect:e.getBoundingClientRect()}:void 0)};return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let Oa=e=>la(z?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),ka=le.length>0?le:je?[]:z?[z.id]:[],Aa=(0,p.useMemo)(()=>ka.map(e=>wi.find(t=>t.id===e)).filter(e=>e!==void 0),[ka,wi]),ja=Yi?void 0:Aa.filter(e=>e.id!==ue).at(-1)?.id,Ma=Aa.some(e=>e.id===z?.id);(0,p.useEffect)(()=>{if(!Me)return;let e=new Set(wi.map(e=>e.id));ce(t=>{let n=t.ids.filter(t=>e.has(t)||oe(t)),r=t.previewId&&(e.has(t.previewId)||oe(t.previewId))?t.previewId:void 0;return n.length===t.ids.length&&r===t.previewId?t:{...t,ids:n,previewId:r}})},[Me,wi]),(0,p.useEffect)(()=>{!Me||Xi||j?.startsWith(`pending:`)||oe(j??M)||Tj(se,j,j?void 0:Yi?.id,Hn||!j&&!rt)},[j,Me,se,Xi,Yi?.id,Hn,rt]);let Na=(0,p.useCallback)(e=>{e&&ce(t=>{if(t.touched.has(e))return t;let n=t.previewId===e?void 0:t.previewId;return{...t,previewId:n,touched:Sj(t.touched,e)}})},[]),Pa=(0,p.useCallback)(e=>{xe(L(e)),Un(!1),de.current++,it(!1),ee(e);let t=O.conversations.find(t=>t.id===e)?.workspaceId;t&&N(t),at(`session`),ce(t=>{let n=t.emptied===!0,r=n?{...t,emptied:!1}:t;if(r.ids.includes(e))return r;let i=!n&&r.ids.length===0&&z?.id&&z.id!==e?[z.id]:[],a=[...r.ids,...i];if(r.touched.has(e))return{...r,ids:[...a,e]};let o=r.previewId?a.indexOf(r.previewId):-1,s=o>=0?a.map((t,n)=>n===o?e:t):[...a,e];return{...r,ids:s,previewId:e}})},[z,wi,O.conversations]);(0,p.useEffect)(()=>{let e=e=>{let t=e.detail;typeof t==`string`&&O.conversations.some(e=>e.id===t)&&Pa(t)};return window.addEventListener(`super-pi-open-execution-session`,e),()=>window.removeEventListener(`super-pi-open-execution-session`,e)},[Pa,O.conversations]),(0,p.useEffect)(()=>{if(!Me)return;let t=new Map(e.conversations.filter(e=>!e.archivedAt).map(e=>[e.id,{status:e.status,hasPendingQuestion:!!e.hasPendingQuestion,title:e.title,workspaceId:e.workspaceId,parentConversationId:e.parentConversationId}]));if(!c.current){s.current=t,c.current=!0;return}let r=document.visibilityState===`visible`&&document.hasFocus(),a=n&&[`granted`,`native`].includes(i)&&!r;for(let[n,r]of t){let t=s.current.get(n);if(!t||r.parentConversationId||!a)continue;let i=!t.hasPendingQuestion&&r.hasPendingQuestion,o=r.status===`completed`&&t.status!==`completed`&&[`waiting`,`running`,`awaiting_background`].includes(t.status);if(!i&&!o)continue;let c=i?`question`:`completed`;if(Rj(`${n}:${c}:${e.conversations.find(e=>e.id===n)?.updatedAt??``}`))try{let e=`${n}:${c}`,t=no(i?`Super Pi · 等你回答`:`Super Pi · Agent 已完成`,{body:`${be(r.workspaceId)} · ${i?`「${r.title}」需要你的回答。`:`「${r.title}」已完成。`}`,tag:`super-pi-${c}-${n}`});l.current.set(e,t),t.onclose=()=>{l.current.get(e)===t&&l.current.delete(e)},t.onclick=()=>{t.close(),l.current.delete(e),window.focus(),Pa(n)}}catch(e){console.warn(`[Super Pi] Browser notification could not be shown:`,e instanceof Error?e.message:`unknown error`)}}s.current=t},[e.conversations,Me,n,i,Pa]);let Fa=(0,p.useCallback)(e=>{e&&(Na(e),Pa(e))},[Na,Pa]),Ia=e=>{e.startsWith(`pending:`)||xe(L(e)),Un(!0),de.current++,it(!1),z&&Ma&&ce(e=>e.ids.length||e.emptied?e:{...e,ids:[z.id]}),N(e),ee(void 0),at(`session`),jn(!1),kn()},La=(0,p.useCallback)((e,t=``)=>{de.current++;let n={workspaceId:e,roomId:t};t&&nt(r=>r.some(n=>n.workspaceId===e&&n.roomId===t)?r:[...r,n]),Xe(n),it(!0),N(e),jn(!1),at(`group`),kn()},[kn]),Ra=(0,p.useCallback)((e,t)=>{ct(e,!0),t&&(ae(t=>t[e.workspaceId]?{...t,[e.workspaceId]:!1}:t),La(e.workspaceId,e.id))},[La,ct]);(0,p.useEffect)(()=>{let e=new Set;if(!n||![`granted`,`native`].includes(i))io(e);else{for(let t of Object.values(ot))for(let n of t.rooms)if(!n.archivedAt)for(let t of n.cloneRequests??[]){if(t.status!==`pending`||t.automatic)continue;let r=`group-clone:${n.id}:${t.id}`;e.add(r),ro(r,`${be(n.workspaceId)} · ${n.title} · 需要决定是否创建分身`,`群聊主持人正在等待你的决定,请打开群聊查看详情。`,R===`group`&>===n.id&&document.visibilityState===`visible`&&document.hasFocus(),()=>La(n.workspaceId,n.id))}io(e)}},[ot,R,gt,La,n,i]);let za=(0,p.useCallback)(e=>{st(),ut(e)},[ut,st]);async function Ba(e,t){if(!pt.has(e.id)&&(t!==`delete`||window.confirm(`永久删除群聊「${e.title}」及其聊天记录?删除后无法恢复。`))){mt(t=>new Set(t).add(e.id));try{let n=await mr(dr(e.workspaceId,e.id),{action:t});if(t===`delete`)za({workspaceId:e.workspaceId,roomId:e.id});else{if(!n)throw Error(`服务没有确认群聊状态。`);st(),ct(n),t===`archive`&&It(t=>({...t,[e.workspaceId]:!1}))}}catch(e){Sc(e instanceof Error?e.message:`群聊操作失败。`,`error`)}finally{mt(t=>new Set([...t].filter(t=>t!==e.id)))}}}let Va=rt&&R!==`session`,Ha=Va?ht:z?.workspaceId??M,Ua=Ha?.startsWith(`pending:`)?void 0:Ha,Wa=Ua??(Mn===`repo`?O.workspaces.find(e=>e.id===zn&&(!e.worktreeOf||!O.workspaces.some(t=>t.id===e.worktreeOf)))?.id??O.workspaces.find(e=>(Fn===`all`||y(e.id).server===Fn)&&(!e.worktreeOf||!O.workspaces.some(t=>t.id===e.worktreeOf)))?.id:void 0),Ga=Wa?.startsWith(`pending:`)?void 0:Wa,Ka=Va?``:z?.cwd??``;(0,p.useEffect)(()=>{Ua&&xe(L(Ua))},[Ua]);let qa=Mn===`repo`&&!Ua,Xa=JSON.stringify([Ua,Ka]),[Za,Qa]=(0,p.useState)(),[$a,B]=(0,p.useState)(50),ao=Za?.scope===Xa?Za:void 0,oo=!!ao,so=ao?.tabId;(0,p.useEffect)(()=>{Qa(e=>e?.scope===Xa?e:void 0)},[Xa]);let co=(0,p.useCallback)(e=>{Qa(t=>t?.scope===Xa?{...t,tabId:e}:t)},[Xa]),V=zh(Ua,Ka,{navigation:de,showingFile:R===`file`,splitFilePath:so?.startsWith(`file:`)?so.slice(5):void 0}),lo=pa(Ga,Ga===Ua?Ka:``,te&&Me),uo=(0,p.useRef)(lo.refresh);uo.current=lo.refresh;let fo=(0,p.useRef)(V.setChangedFor),po=(0,p.useRef)(V.invalidateTree);po.current=V.invalidateTree;let mo=(0,p.useRef)(Ua);mo.current=Ua,(0,p.useEffect)(()=>{fo.current=V.setChangedFor},[V.setChangedFor]);let[ho]=(0,p.useState)(yA),[go,_o]=(0,p.useState)(ho.tab),[vo,yo]=(0,p.useState)(ho.byConversation),bo=go===`rsi`?go:(z?.id?vo[z.id]:void 0)??go;(0,p.useEffect)(()=>{try{Kn(vA,JSON.stringify({tab:go,byConversation:vo}))}catch{}},[go,vo]);let[xo,So]=(0,p.useState)(),Co=(0,p.useCallback)(()=>So(e=>({request:(e?.request??0)+1,workspaceId:Ua,conversationId:Va?void 0:z?.id})),[Ua,Va,z?.id]),wo=(0,p.useCallback)(e=>{xr||tr(t=>({...t,rightView:e})),e===`terminal`&&Co(),_o(e),z?.id&&yo(t=>({...t,[z.id]:e}))},[z?.id,Co,xr]),[To,Eo]=(0,p.useState)(),Do=er.order.filter(e=>ei(e)||nr.members(e).length>0),Oo=e=>Do.filter(t=>er.sides[t]===e),ko=Oo(`left`),Ao=Oo(`right`),jo=Oo(`bottom`),Mo=ko.includes(er.leftView)?er.leftView:ko[0],No=er.rightView&&(er.rightView===`sessions`||er.rightView===`search`||!ei(er.rightView))?er.rightView:bo,Po=No&&Ao.includes(No)?No:Ao[0],Fo=er.bottomView&&jo.includes(er.bottomView)?er.bottomView:jo[0],Io=er.rightClosed||!Po,Lo={left:er.leftClosed?void 0:Mo,right:Io?void 0:Po,bottom:er.bottomClosed?void 0:Fo},Ro=To&&Do.includes(To)?To:bo,zo=e=>xr?!Sn&&(Gn>700||Tn===`rail`)&&Ro===e:Lo[er.sides[e]]===e,Bo=zo(nr.hostView(`rsi`)),Vo=xr?Gn>700||An:zo(`sessions`),Ho=e=>{e===`sessions`?(kn(),jn(!0)):(e===`search`||!ei(e)?Eo(e):(Eo(void 0),wo(e)),wn(!1),Gn<=700&&En(`rail`))},Uo=(e,t=!1)=>{if(xr){Ho(e);return}let n=er.sides[e];nr.hostView(`terminal`)===e&&(n!==`right`||e!==`terminal`)&&Co(),n===`right`&&ei(e)&&e!==`search`&&e!==`sessions`&&wo(e),tr(r=>({...r,[n+`View`]:e,[n+`Closed`]:t&&Lo[n]===e}))},Wo=(e,t=!1)=>Uo(nr.hostView(e),t),[Go,Ko]=(0,p.useState)(),qo=e=>{Wo(`git-${e}`),Ko(t=>({workspaceId:Ga,view:e,request:(t?.request??0)+1}))},Jo=(e,t,n,r=`before`)=>{e!==n&&(t===`right`&&ei(e)&&e!==`sessions`&&e!==`search`&&wo(e),tr(i=>{let a=i.order.filter(t=>t!==e),o=n?a.indexOf(n):-1;return a.splice(o<0?a.length:o+Number(r===`after`),0,e),{...i,order:a,sides:{...i.sides,[e]:t},[t+`View`]:e,[t+`Closed`]:!1,unpinned:i.unpinned.filter(t=>t!==e)}}))},Yo=(e,t)=>{if(!$r(e))return;let n=Qr(e);nr.move(e,n,void 0,!1),Jo(n,t),xr&&(Eo(n),wn(!1))},Xo=(e,t)=>{let n=er.sides[e];if(t.startsWith(`move`))Jo(e,t===`move-bottom`?`bottom`:t===`move-right`||n===`left`?`right`:`left`),requestAnimationFrame(()=>document.querySelector(`[data-workbench-view="${e}"]`)?.focus());else if(t===`pin`)tr(t=>({...t,unpinned:t.unpinned.includes(e)?t.unpinned.filter(t=>t!==e):[...t.unpinned,e]}));else{let r=Oo(n).filter(e=>!er.unpinned.includes(e)),i=r[r.indexOf(e)+(t===`up`?-1:1)];i&&Jo(e,n,i,t===`up`?`before`:`after`)}},Zo=(e,t,n,r)=>Jo(e,n??(t?er.sides[t]:er.sides[e]),t,r),Qo=JSON.stringify([Ua,Ka]),[$o,es]=(0,p.useState)(),ts=$o?.scope===Qo?$o:void 0,ns=ts?.mode===`path`;(0,p.useEffect)(()=>{es(e=>e?.scope===Qo?e:void 0)},[Qo]);let rs=(0,p.useCallback)((e,t,n,r=!1)=>{de.current++,es(i=>i?.mode===e&&i.scope===Qo&&i.directory===n?{...i,replace:r||i.replace}:{mode:e,scope:Qo,initialQuery:t,directory:n,replace:r}),jn(!1)},[Qo]),is=(0,p.useCallback)(()=>{de.current++,es(void 0)},[]),[H,as]=(0,p.useState)(),os=(0,p.useRef)(0),ss=e=>{Pa(e.conversationId),as({hit:e,request:de.current}),es(void 0),kn()};(0,p.useEffect)(()=>{if(!H||H.request===os.current||z?.id!==H.hit.conversationId||z?.messagesLoaded===!1||R!==`session`||!Ma)return;let{hit:e,request:t}=H,n=null,r,i=requestAnimationFrame(()=>{let i=yt.current;i&&de.current===t&&(n=i.querySelector(`[data-transcript-key="${CSS.escape(`m:${e.messageId}`)}"]`),n&&(os.current=t,_j(i),i.scrollTop+=n.getBoundingClientRect().top-i.getBoundingClientRect().top-24,ta(i,!0),n.dataset.sessionSearchHit=`true`,n.tabIndex=-1,n.focus({preventScroll:!0}),r=setTimeout(()=>{n&&delete n.dataset.sessionSearchHit},2400)))});return()=>{cancelAnimationFrame(i),clearTimeout(r),n&&delete n.dataset.sessionSearchHit}},[z?.id,z?.messagesLoaded,R,ta,Ma,H]);let[cs,ls]=(0,p.useState)(),[us,ds]=(0,p.useState)(),[fs,ps]=(0,p.useState)(E.diffs),ms=fs.paths,[hs,gs]=(0,p.useState)(E.gitDiffs),[_s,vs]=(0,p.useState)(E.gitDiffUrl);(0,p.useEffect)(()=>{if(!(!Me||V.restoringWorkbench||oe(j??M)))try{Yn({view:R,groups:Ze,gitDiffs:hs,gitDiffUrl:_s,diffs:fs})}catch{}},[Me,V.restoringWorkbench,j,M,R,Ze,hs,_s,fs]);let ys=R===`gitDiff`?hs.find(e=>e.target.url===_s):void 0,bs=R===`gitDiff`?`diff`:R,xs=ys?.target.path??us,Ss=(0,p.useCallback)(e=>{if(qa&&!e.commitHash)return;de.current++;let t=document.activeElement instanceof HTMLElement?document.activeElement:void 0;gs(n=>{let r=n.find(t=>t.target.url===e.url);if(!r){let r={target:e,workspaceId:Ua,reading:{},revision:0,preview:!0,origin:t},i=oo&&R===`gitDiff`?_s:void 0,a=n.find(e=>e.preview&&e.target.url!==i);return a?n.map(e=>e===a?r:e):[...n,r]}if(e.commitHash)return n;let i=r.target.label===e.label?{...r.reading,snapshot:void 0}:{};return n.map(n=>n===r?{...n,target:e,reading:i,revision:n.revision+1,origin:t}:n)}),oo?(co(`git-diff:${e.url}`),R===`gitDiff`&&_s===e.url&&at(`session`)):(vs(e.url),at(`gitDiff`)),kn()},[Ua,qa,_s,R,co,kn,oo]),Cs=(0,p.useCallback)(()=>{!Ma&&ja?Pa(ja):at(`session`)},[Ma,ja,Pa]);(0,p.useEffect)(()=>{let e=e=>{let t=ot[e.workspaceId];return!t?.loaded||t.rooms.some(t=>t.id===e.roomId)},t=Ze.filter(e);if(t.length!==Ze.length&&nt(t),R!==`group`||!Ye?.roomId||e(Ye))return;let n=t.filter(e=>e.workspaceId===Ye.workspaceId).at(-1);n?La(n.workspaceId,n.roomId):Cs()},[ot,Ye,Ze,R,La,Cs]),(0,p.useEffect)(()=>{R===`file`&&!V.active&&Cs()},[R,V.active,Cs]),(0,p.useEffect)(()=>{R===`diff`&&!us&&Cs()},[R,us,Cs]);let ws=(0,p.useRef)(`${Ua??``}:${Ka}`);(0,p.useEffect)(()=>{let e=`${Ua??``}:${Ka}`;ws.current!==e&&(ws.current=e,ps({paths:[]}),ds(void 0),at(e=>e===`gitDiff`||e===`group`?e:`session`))},[Ua,Ka]);let Ts=(0,p.useCallback)((e,t=!1)=>{de.current++;let n=oo&&!t;ps(t=>{if(t.paths.includes(e))return t;let r=n&&R===`diff`&&us===t.previewPath;return{paths:t.previewPath&&!r?t.paths.map(n=>n===t.previewPath?e:n):[...t.paths,e],previewPath:e}}),n?(co(`diff:${e}`),R===`diff`&&us===e&&at(`session`)):(ds(e),at(`diff`)),kn(),_o(`files`)},[us,R,co,kn,oo]),Es=R===`diff`?us:void 0,Ds=so?.startsWith(`diff:`)?so.slice(5):void 0,Os=Ds&&Ds!==Es&&ms.includes(Ds)?Ds:void 0,ks=Lj(Ua,Ka,Es),U=Lj(Ua,Ka,Os),[W,G]=(0,p.useState)(`server`),[K,q]=(0,p.useState)(`server`),As=e=>{let t=V.open.find(t=>t.path===e);return t?.dirty?t.content:void 0},js=(0,p.useCallback)(e=>{de.current++,V.setActivePath(e),at(`file`),_o(`files`)},[V.setActivePath]),Ms=(0,p.useCallback)(async(e,t,n=!1,r=!1,i=!1,a)=>{let o=++de.current,s=()=>de.current===o,c=oo&&!i,l=await V.openFile(e,{preview:!n,activate:!c,isCurrent:s,throwOnError:r,requireText:a!==void 0});if(l&&s())return n&&V.pinFile(l),ls(t?{scope:Qo,path:l,line:t,column:a,request:o}:void 0),c?(co(`file:${l}`),R===`file`&&V.activePath===l&&at(`session`)):at(`file`),kn(),l},[V.openFile,V.pinFile,V.activePath,Qo,R,co,kn,oo]),Ns=(0,p.useCallback)((e,t)=>{Ms(e,void 0,t)},[Ms]),Ps=z&&!Ui?(e,t)=>{let n=ia&&!/\s$/u.test(ia)?`${ia} `:ia,r=vp(n,{start:n.length,end:n.length,query:``},{path:e,kind:t?`directory`:`file`});Ca.current={scope:_a,...r},Na(z.id),Pa(z.id),kn(),da(r.text)}:void 0,Fs=(e,t)=>{de.current+=1,ps(t=>({paths:t.paths.filter(t=>!kp(t,e)),previewPath:t.previewPath&&!kp(t.previewPath,e)?t.previewPath:void 0})),us&&kp(us,e)&&ds(void 0),Qa(n=>{let r=n?.tabId?.startsWith(`file:`)?n.tabId.slice(5):void 0;return n&&r&&kp(r,e)?{...n,tabId:`file:${t}${r.slice(e.length)}`}:n}),ls(n=>n?.scope===Qo&&kp(n.path,e)?{...n,path:t+n.path.slice(e.length)}:n)};(0,p.useEffect)(()=>{let e=e=>{if(!(e.ctrlKey||e.metaKey)||e.altKey||e.isComposing)return;let t=e.key.toLowerCase();e.shiftKey&&t===`f`?(e.preventDefault(),rs(`content`)):e.shiftKey&&t===`h`?(e.preventDefault(),rs(`content`,void 0,void 0,!0)):!e.shiftKey&&t===`p`&&(e.preventDefault(),rs(`path`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[rs]);let Is=(0,p.useMemo)(()=>Aa.map(e=>({id:`session:${e.id}`,workspaceId:e.workspaceId,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:!0,preview:ue===e.id,badge:(0,m.jsx)(jA,{state:kA(e,DA(e,xn),Ke.current[e.id],O.conversations)})})),[Aa,xn,O.conversations,qe,ue]),Ls=(0,p.useMemo)(()=>V.open.map(e=>({id:`file:${e.path}`,workspaceId:V.ownerWorkspaceId,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,preview:e.preview,badge:e.dirty?(0,m.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[V.ownerWorkspaceId,V.open]),J=(0,p.useMemo)(()=>ms.map(e=>({id:`diff:${e}`,workspaceId:Ua,rawId:e,kind:`diff`,label:e.split(/[\\/]/).pop()||e,title:`${e}(改动)`,closable:!0,preview:fs.previewPath===e,icon:(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`±`})})),[Ua,ms,fs.previewPath]),Rs=(0,p.useMemo)(()=>[...Is,...[...Ze,...R===`group`&&Ye&&!gt?[Ye]:[]].flatMap(e=>{let t=O.workspaces.find(t=>t.id===e.workspaceId&&!t.closedAt);if(!t)return[];let n=ot[e.workspaceId]?.rooms.find(t=>t.id===e.roomId),r=e.roomId?n?.title??`群聊`:`新建群聊`,i=n?hr(n,dt[n.id]):`idle`,a=n?gr(n,dt[n.id],Ke.current[lr(e)]):`idle`,o=a===`completed`?`讨论已完成,有新回复未读`:a===`unread`?`有新回复未读`:xA[i],s=`${r} · ${t.name}${i===`idle`?``:` · ${o}`}`;return[{id:lr(e),workspaceId:e.workspaceId,label:r,title:s,closable:!0,icon:(0,m.jsx)(vi,{name:`group`}),badge:(0,m.jsx)(jA,{state:a,label:o})}]}),...Ls,...J,...hs.map(({target:e,preview:t,workspaceId:n})=>({id:`git-diff:${e.url}`,workspaceId:n,kind:`diff`,closable:!0,preview:t,label:`${e.path.split(/[\\/]/).pop()||e.path} (${e.label})`,title:`${e.path} · ${e.comparison}`,icon:(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`±`})}))],[Is,Ls,J,hs,Ze,ot,dt,Ye,gt,R,O.workspaces,qe]),Y=R===`group`&&Ye?lr(Ye):R===`file`&&V.activePath?`file:${V.activePath}`:R===`diff`&&us?`diff:${us}`:ys?`git-diff:${ys.target.url}`:Ma&&z?.id?`session:${z.id}`:void 0,zs=(0,p.useRef)(!1),Bs=(0,p.useRef)(void 0);(0,p.useLayoutEffect)(()=>{let e=zs.current;if(zs.current=!1,Bs.current!==V.restoredActive&&(Bs.current=V.restoredActive,!Oe&&V.restoredActive&&V.restoredActive===V.activePath&&R!==`file`&&R!==`gitDiff`&&R!==`group`)){at(`file`);return}if(!e&&Me&&ue&&Y!==`session:${ue}`&&wi.some(e=>e.id===ue)&&ce(e=>{if(e.previewId!==ue)return e;let t=e.ids.filter(e=>e!==ue);return{...e,ids:t,previewId:void 0,emptied:t.length===0}}),!e)for(let e of V.open)e.preview&&Y!==`file:${e.path}`&&so!==`file:${e.path}`&&V.discardPreview(e.path);let t=fs.previewPath;!e&&t&&Y!==`diff:${t}`&&so!==`diff:${t}`&&ps(e=>e.previewPath===t?{paths:e.paths.filter(e=>e!==t)}:e);let n=e=>{let t=`git-diff:${e.target.url}`;return!e.preview||t===Y||t===so};!e&&hs.some(e=>!n(e))&&gs(e=>e.filter(n)),Me&&R===`session`&&z&&z.id===j&&!Ma&&!V.restoringWorkbench&&ja&&Pa(ja)},[Y,Me,ue,V.open,V.activePath,V.restoredActive,V.discardPreview,fs.previewPath,R,z?.id,j,Ma,V.restoringWorkbench,ja,Pa,wi,Oe,so,hs]);let Vs=(0,p.useCallback)(e=>{if(e.startsWith(`group:`)){let t=ur(e);t&&La(t.workspaceId,t.roomId)}else if(e.startsWith(`file:`)){let t=e.slice(5);js(t)}else if(e.startsWith(`diff:`)){de.current++;let t=e.slice(5);ds(t),at(`diff`)}else if(e.startsWith(`git-diff:`))de.current++,vs(e.slice(9)),at(`gitDiff`);else if(e.startsWith(`session:`)){let t=e.slice(8);Pa(t)}},[js,Pa,La]),Hs=Rs.find(e=>e.id===Y),Us=R===`file`?V.active:void 0,Ws=(0,p.useMemo)(()=>{if(!Me||!Hs||Hs.id.startsWith(`session:pending:`))return;let{id:e,label:t}=Hs;if(R!==`group`||gt&&vt){if(R===`session`)return e.startsWith(`session:`)?{key:e,tabId:e,title:t}:void 0;if(R===`file`||R===`diff`||R===`gitDiff`){if(!Ua||V.restoringWorkbench||R===`file`&&!Us||R===`diff`&&!us)return;let n={workspaceId:Ua,cwd:Ka,conversationId:z?.id},r=Us&&{path:Us.path,name:Us.name,text:null,...Us.assetTicket||/^(?:[a-z]:[\\/]|[\\/])/i.test(Us.path)?{openLink:!0}:{}},i=R===`file`&&Ee?.scope===JSON.stringify([n.workspaceId,n.cwd,Us?.path])?{line:Ee.position.line,column:Ee.position.column}:void 0,a=!!i&&(Ee?.position.navigation||cs?.scope===Qo&&cs.path===Us?.path&&cs.line===i.line&&(cs.column??1)===i.column);return{key:JSON.stringify([n.workspaceId,n.cwd,e]),tabId:e,title:t,scope:n,file:r,position:i,explicitPosition:a,gitDiff:R===`gitDiff`&&ys?{...ys,origin:void 0,preview:!1}:void 0}}return{key:e,tabId:e,title:t}}},[Me,Hs,R,Ua,Ka,z?.id,V.restoringWorkbench,us,Us?.path,Us?.name,Us?.assetTicket,gt,vt,Ee,cs,Qo,ys]);(0,p.useEffect)(()=>{!Oe&&Ws&&(Ae.current.delete(Ws.key),we(e=>_g(e,Ws)))},[Ws,Oe]);let Gs=e=>{let t=wi.filter(t=>t.workspaceId===e.workspaceId&&(t.cwd??``)===e.cwd);return t.find(t=>t.id===e.conversationId)??t[0]},Ks=e=>{if(gg(e,Ws)||Ae.current.has(e.key))return!1;if(e.tabId.startsWith(`session:`))return wi.some(t=>`session:${t.id}`===e.tabId);let t=ur(e.tabId);if(t)return O.workspaces.some(e=>e.id===t.workspaceId&&!e.closedAt)&&!!ot[t.workspaceId]?.rooms.some(e=>e.id===t.roomId);if(!e.scope)return Rs.some(t=>t.id===e.tabId);let{scope:n}=e;return O.workspaces.some(e=>e.id===n.workspaceId)?n.workspaceId===Ua&&n.cwd===Ka||!!Gs(n)||!n.cwd&&!wi.some(e=>e.workspaceId===n.workspaceId):!1},qs=vg(Ce,Ce.index+ +!Ws,-1,Ks),Js=vg(Ce,Ce.index,1,Ks),Ys=e=>{if(Oe){Te.current.length<20&&Te.current.push(e);return}let t=e<0?qs:Js;t<0||ke({index:t,direction:e,ticket:++de.current,stage:`start`})},Xs=(0,p.useRef)(Ys);Xs.current=Ys,(0,p.useEffect)(()=>{if(Oe||!Te.current.length)return;let e=de.current,t=requestAnimationFrame(()=>{if(de.current!==e){Te.current=[];return}let t=Te.current.shift();t&&Xs.current(t)});return()=>cancelAnimationFrame(t)},[Oe,Ce.index]),(0,p.useEffect)(()=>{let e=e=>{(e.button===3||e.button===4)&&(e.preventDefault(),e.stopPropagation(),e.type===`mouseup`&&Xs.current(e.button===3?-1:1))};for(let t of[`mousedown`,`mouseup`,`auxclick`])window.addEventListener(t,e,!0);return()=>{for(let t of[`mousedown`,`mouseup`,`auxclick`])window.removeEventListener(t,e,!0)}},[]),(0,p.useEffect)(()=>{let e=Oe;if(!e)return;if(de.current!==e.ticket){Te.current=[],ke(void 0);return}let t=Ce.entries[e.index];if(gg(t,Ws)){we(t=>({...t,index:e.index})),ke(void 0);return}let n=(t=e.ticket)=>{let n=vg(Ce,e.index,e.direction,Ks);ke(n<0?void 0:{...e,index:n,ticket:t,stage:`start`})};if(!Ks(t)){n();return}let r=t.scope;if(r&&(r.workspaceId!==Ua||r.cwd!==Ka)){if(e.stage!==`start`){n();return}let t=Gs(r);t?Pa(t.id):Ia(r.workspaceId),ke({...e,stage:`scope`,ticket:de.current});return}if(t.key===Ws?.key&&t.position&&e.stage!==`position`){let n=Us?.content.split(`
|
|
349
|
-
`)??[``],r=Math.max(1,Math.min(t.position.line,n.length)),i=Math.max(1,Math.min(t.position.column,n[r-1].length+1));we(t=>({...t,entries:t.entries.map((t,n)=>n===e.index?{...t,position:{line:r,column:i}}:t)})),ls({scope:Qo,path:Us.path,line:r,column:i,request:de.current}),ke({...e,stage:`position`});return}if(e.stage===`opening`||e.stage===`position`||r&&V.restoringWorkbench)return;jn(!1),kn();let i=t.file;if(i&&!V.open.some(e=>e.path===i.path)){let r=Ms(i,t.position?.line,!1,!0,!0,t.position?.column),a=de.current;ke({...e,stage:`opening`,ticket:a}),r.then(e=>{!e&&de.current===a&&ke(void 0)}).catch(e=>{de.current===a&&(e instanceof fh&&e.status===404?(Ae.current.add(t.key),n(a)):(Sc(zr(e instanceof Error?e.message:void 0,`无法打开导航历史中的文件。`),`error`),ke(void 0)))})}else t.gitDiff&&!hs.some(e=>e.target.url===t.gitDiff.target.url)?(gs(e=>[...e,{...t.gitDiff,preview:!1}]),vs(t.gitDiff.target.url),at(`gitDiff`)):t.tabId.startsWith(`diff:`)&&!Rs.some(e=>e.id===t.tabId)?Ts(t.tabId.slice(5),!0):Vs(t.tabId),ke({...e,stage:`opening`,ticket:de.current})});let Zs=(0,p.useCallback)(e=>{if(e.startsWith(`session:`))Fa(e.slice(8));else if(e.startsWith(`file:`))V.pinFile(e.slice(5));else if(e.startsWith(`diff:`)){let t=e.slice(5);ps(e=>e.previewPath===t?{paths:e.paths}:e)}else e.startsWith(`git-diff:`)&&gs(t=>t.map(t=>t.preview&&`git-diff:${t.target.url}`===e?{...t,preview:!1}:t))},[Fa,V.pinFile]),Qs=Rs.filter(e=>e.kind===`file`||e.kind===`diff`),$s=oo&&so!==Y?Qs.find(e=>e.id===so):void 0,ec=e=>{Qs.some(t=>t.id===e)&&(de.current++,co(e),e===Y&&Cs())},tc=()=>{if(oo){de.current++,$s&&Zs($s.id),Qa(void 0);return}de.current++;let e=Qs.find(e=>e.id===Y)??Qs.at(-1);Qa({scope:Xa,tabId:e?.id}),e&&e.id===Y&&(z&&!Ma?Pa(z.id):Cs())},nc=(0,p.useCallback)(e=>{let t=ka.indexOf(e);if(t<0)return;let n=ka.filter(t=>t!==e);if(ce(t=>({...t,ids:t.ids.filter(t=>t!==e),previewId:t.previewId===e?void 0:t.previewId,emptied:n.length===0||t.emptied})),z?.id!==e||R!==`session`)return;de.current++;let r=n[Math.min(t,n.length-1)];if(r)ee(r);else if(V.open.length>0){let e=V.activePath&&V.open.some(e=>e.path===V.activePath)?V.activePath:V.open[0].path;V.setActivePath(e),at(`file`)}else ms.length>0?(ds(ms[0]),at(`diff`)):hs.length>0?(vs(hs[0].target.url),at(`gitDiff`)):ee(void 0)},[ka,z,V,ms,hs,R]),rc=(0,p.useCallback)(e=>{if(e.startsWith(`group:`)){let t=Ze.filter(t=>lr(t)!==e);if(nt(t),R===`group`&&Y===e){let e=t.filter(e=>e.workspaceId===ht).at(-1);e?La(e.workspaceId,e.roomId):Cs()}}else if(e.startsWith(`file:`)){let t=e.slice(5);V.closeFile(t),R===`file`&&V.activePath===t&&V.open.length<=1&&de.current++}else if(e.startsWith(`diff:`)){let t=e.slice(5);ps(e=>({paths:e.paths.filter(e=>e!==t),previewPath:e.previewPath===t?void 0:e.previewPath})),R===`diff`&&us===t&&(de.current++,ds(void 0),Cs())}else if(e.startsWith(`session:`)){let t=e.slice(8);nc(t)}else if(e.startsWith(`git-diff:`)){let t=e.slice(9),n=hs.findIndex(e=>e.target.url===t);if(n<0)return;let r=hs.filter(e=>e.target.url!==t);gs(r);let i=document.activeElement?.getAttribute(`data-diff-tab-close`)===e;if(ys?.target.url===t){de.current++;let e=r[Math.max(0,n-1)];vs(e?.target.url),e||Cs()}i&&requestAnimationFrame(()=>{let e=document.querySelector(`.chat-tab-strip [role="tab"][aria-selected="true"]`),t=hs[n].origin;(e??(t?.getClientRects().length?t:void 0)??document.querySelector(`[data-workspace-welcome-create]:not(:disabled)`))?.focus()})}},[V,nc,us,R,hs,ys?.target.url,Cs,ht,Ze,Y,La]),ic=V.active,ac=JSON.stringify([Ua,Ka,ic?.path]),oc=(0,p.useCallback)(e=>{De(t=>e?{scope:ac,position:e}:t?.scope===ac?void 0:t)},[ac]),sc=Ee?.scope===ac?Ee.position:void 0,[cc,lc]=(0,p.useState)(),uc=(0,p.useRef)(null),[dc,fc]=(0,p.useState)(``),[pc,mc]=(0,p.useState)({}),hc=O.workspaces.find(e=>e.id===Ua),gc=O.workspaces.find(e=>e.id===Ga),_c=(e,t)=>{let n=e&&xh(e.path),r=e&&(e.assetTicket||n?(0,m.jsx)(`span`,{className:`file-editor-path`,title:n??e.path,children:n??e.path}):(0,m.jsx)(Vi,{root:Ka.split(`/`).at(-1)||hc?.name||`工作目录`,path:e.path,reveal:(e,t)=>{Wo(`file-tree`),V.locatePath(e,t)}})),i=cs?.scope===Qo&&cs?.path===e?.path?cs:void 0,a=e&&(!e.view||e.view===`table`)&&(0,m.jsx)(Ph,{file:e,state:V.saves[e.path]?.state??`idle`,message:V.saves[e.path]?.message??``,external:V.external[e.path]===!0,jumpToLine:i,languageOverride:pc[JSON.stringify([Ua,Ka,e.path])],onChange:t=>V.updateBuffer(e.path,t),onSave:()=>void V.save(e.path,!1),onReload:()=>void V.reload(e.path),onOverwrite:()=>void V.save(e.path,!0),workspaceId:Ua,cwd:Ka,navigation:e.view?void 0:r,embedded:!!e.view,onPosition:t?oc:void 0});return(0,m.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":e?.path,"data-file-view-kind":`editor`,children:e?.view&&Ua?(0,m.jsx)(Cp,{workspaceId:Ua,cwd:n?``:Ka,path:n??e.path,name:e.name,kind:e.view,content:e.content,version:e.etag,source:a||void 0,external:V.external[e.path],navigation:r,assetTicket:e.assetTicket,onReload:()=>void V.reload(e.path),sourceRequest:i?.request},JSON.stringify([Ua,Ka,e.path])):a||(0,m.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})})},vc=e=>qa&&!e.target.commitHash?(0,m.jsx)(`div`,{className:`chat-file-view`,role:`status`,children:(0,m.jsx)(`p`,{className:`rail-empty`,children:`请选择具体 session 以确定工作区,再查看或编辑工作区差异。`})}):(0,m.jsx)(`div`,{className:`chat-file-view chat-git-diff`,"data-main-diff-view":e.target.path,"data-file-view-kind":`diff`,children:(0,m.jsx)(p.Suspense,{fallback:(0,m.jsx)(`p`,{className:`rail-empty`,role:`status`,children:`正在读取差异…`}),children:(0,m.jsx)(HA,{tab:e,dark:Jl!==`github-light`&&Jl!==`solarized-light`},JSON.stringify([e.target.url,e.revision]))})}),yc=(e,t)=>{let n=t?U:ks;return(0,m.jsx)(`div`,{className:`chat-file-view`,"data-main-diff-view":e??``,"data-file-view-kind":`diff`,children:(0,m.jsx)(Lh,{diff:n.diff,loading:n.loading,error:n.error,bufferContent:As(e),mode:t?K:W,onMode:t?q:G})})},bc=()=>{let e=$s?.id;if(!e)return null;if(e.startsWith(`file:`))return _c(V.open.find(t=>`file:${t.path}`===e),!1);if(Os)return yc(Os,!0);let t=hs.find(t=>`git-diff:${t.target.url}`===e);return t?vc(t):null},xc=z?.id;(0,p.useEffect)(()=>{xc&&!xc.startsWith(`pending:`)&&kc({type:`conversation.select`,conversationId:xc})},[xc]);let Sc=(e,t=`info`)=>{if(!e)return;let n=++si.current;$t(r=>[...r,{key:n,text:e,kind:t}]),ci.current.push(window.setTimeout(()=>$t(e=>e.filter(e=>e.key!==n)),7e3))},Cc=(e,t=``)=>{if(hc&&hc.id===e&&Ka===t)return n=>{let r=lt(n,{root:hc.path,cwd:t,origin:window.location.origin});if(r)return{title:r.artifact?r.path:`${r.path}:${r.line}${r.column?`:${r.column}`:``}`,open:()=>{let n=Zh(r.path,t);!Va&&z?.workspaceId===e&&Na(z.id),Ms(n,r.artifact?void 0:r.line,!0,!0,!1,r.artifact?void 0:r.column??1).catch(e=>Sc(`打不开「${n.name}」:${e instanceof Error?e.message:`文件不可用`}`,`error`))}}}},wc=Cc(z?.workspaceId,z?.cwd),Tc=async e=>{try{await window.superPiDesktop?.notifications?.configure?.({enabled:e})}catch(e){Sc(e instanceof Error?e.message:`无法更新桌面提醒设置`,`error`);return}if(!e){r(!1);try{window.localStorage.setItem(`super-pi.browser-notifications`,`disabled`)}catch{}}else if(typeof window>`u`||typeof Notification>`u`&&!window.superPiDesktop?.notifications)a(`unsupported`);else if(!window.isSecureContext&&!window.superPiDesktop?.notifications)a(`insecure`);else try{let e=await to();a(e);let t=e===`granted`||e===`native`;r(t);try{window.localStorage.setItem(`super-pi.browser-notifications`,t?`enabled`:`disabled`)}catch{}}catch{a(eo()),r(!1),Sc(`请求浏览器通知权限失败,请检查站点权限后重试。`,`error`)}};(0,p.useEffect)(()=>{window.superPiDesktop?.notifications?.configure?.({enabled:n}).catch(e=>Sc(e instanceof Error?e.message:`无法恢复桌面通知设置`,`error`))},[n]),(0,p.useEffect)(()=>{let e=()=>{for(let e of l.current.values())e.close();l.current.clear()},t=()=>{if(a(eo()),document.visibilityState===`visible`&&document.hasFocus()){let t=window.superPiDesktop?.notifications;t?.clearSystem?t.status().then(n=>{n.mode===`pet`||n.mode===`both`?t.clearSystem?.():e()}).catch(()=>{}):e();try{window.localStorage.setItem(`super-pi.browser-notification-focus`,String(Date.now()))}catch{}}},n=t=>{t.key===`super-pi.browser-notification-focus`&&e()};window.addEventListener(`focus`,t);let r=!1,i;return navigator.permissions?.query&&navigator.permissions.query({name:`notifications`}).then(e=>{r||(i=e,e.addEventListener(`change`,t),t())}).catch(()=>{}),window.addEventListener(`storage`,n),document.addEventListener(`visibilitychange`,t),()=>{r=!0,i?.removeEventListener(`change`,t),window.removeEventListener(`focus`,t),window.removeEventListener(`storage`,n),document.removeEventListener(`visibilitychange`,t),e()}},[]),(0,p.useEffect)(()=>{let e=z?.id,t=z?.agentNotice;e&&t&&!fi.current.has(e)&&(fi.current.add(e),Sc(t,`info`))},[z?.id,z?.agentNotice]);let Ec=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},X=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},Dc=(e,t)=>{if(t.method===`notify`)Sc(t.message||t.title,t.notifyType??`info`);else if(t.blocking||t.method===`setStatus`||t.method===`setWidget`||t.method===`setTitle`){let n=e=>e.blocking?e.requestId:e.statusKey??e.widgetKey??``,r=t.method===`setStatus`&&t.statusText===void 0||t.method===`setWidget`&&t.widgetLines===void 0||t.method===`setTitle`&&!t.title;Zt(i=>{let a=i.filter(r=>r.conversationId!==e||r.request.method!==t.method||n(r.request)!==n(t));return r?a:[...a,{conversationId:e,request:t}]})}else t.method===`set_editor_text`&&e===li.current&&da(t.text??``)},Oc=(e,t,n)=>{Zt(n=>n.filter(n=>!(n.conversationId===e&&n.request.blocking&&n.request.requestId===t)));let r=Bk[n];r&&Sc(r,`warning`)};(0,p.useEffect)(()=>{let e=!1;return(()=>{if(e)return;let t=new Be(li.current);He.current=t,t.onopen=()=>{if(!e){F(!0);for(let e of[{type:`stream.configure`,coalesce:!0},{type:`catalog.fetch`,conversationId:li.current},...$i.current?[{type:`prompt.catalog.fetch`,workspaceId:$i.current}]:[],{type:`catalog.fetchAll`},{type:`agent.catalog.fetch`},{type:`subagent.catalog.fetch`}])t.canSend(e)&&t.send(JSON.stringify(e))}},t.onserveropen=e=>{for(let n of g.current)n.retry&&n.command&&n.serverId===e&&t.canSend(n.command)&&t.send(JSON.stringify({...n.command,operationRequestId:n.id}))},t.ondisconnect=(t,n)=>{if(e)return;let r=MD(g.current.filter(e=>e.serverId===t));for(let e of r.failed)e.onFailure?.(`${ye(t)} 连接中断`);g.current=g.current.filter(e=>!r.failed.includes(e)),f(g.current),Sc(`${ye(t)} 连接中断${n?`(code ${n.code}${n.reason?` · ${n.reason}`:``})`:``},正在自动重连。`,`warning`)},t.onmessage=({data:t})=>{if(e)return;let n=JSON.parse(t);if(n.type===`group.activity`)ft(n);else if(n.type!==`message.delta`&&n.type!==`message.thinking`&&Mt(),n.type===`message.accepted`){Cm(n.conversationId,n.clientId);for(let e of g.current)e.command?.conversationId===n.conversationId&&e.command?.clientId===n.clientId&&(e.receipt=!0)}else if(n.type===`exec.output`){let e=Dt.current.get(n.sessionId),t=e?.raw??e?.text??``,r=n.offset===void 0?void 0:n.offset-n.data.length;if(!n.replace&&e?.offset!==void 0&&n.offset!==void 0&&n.offset<=e.offset)return;let i=e&&(r===void 0||e.offset!==void 0&&e.offset>=r),a=r!==void 0&&e?.offset!==void 0?Math.max(0,e.offset-r):0,o=(n.replace||!i?n.data:t+n.data.slice(a)).slice(-KO),s=qO(o);Dt.current.delete(n.sessionId),Dt.current.set(n.sessionId,{text:s.slice(-KO),raw:o,offset:n.offset,truncated:n.offset===void 0?n.truncated||o.length>128e3:n.offset>o.length}),Dt.current.size>64&&Dt.current.delete(Dt.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:n.sessionId}))}else if(n.type===`run.stopping`)Fr(e=>{let t=new Set(e);return t.add(n.conversationId),t});else if(n.type!==`exec.exit`){if(n.type.startsWith(`terminal.`))Ot.current?.(n);else if(n.type===`conversation.autoRename.result`){let e=Hr.current.get(n.conversationId);e&&(Hr.current.delete(n.conversationId),n.ok?e.resolve(n.title):e.reject(Error(n.error)))}else if(n.type===`message.thinking`)Nt(n);else if(n.type===`state`){Mt(),ui.current=!1;let e=li.current,t=!!(e&&mi.current.has(e)),r=!(!e||n.state.conversations.some(t=>t.id===e)),i=t&&r&&e&&_i.current.has(e)?{...n.state,conversations:[_i.current.get(e),...n.state.conversations]}:n.state;e&&!r&&(mi.current.delete(e),_i.current.delete(e)),g.current=g.current.filter(e=>!e.accepted?.(i)||i.sendReceipts&&e.retry&&!e.receipt?!0:(e.retry&&typeof e.command?.conversationId==`string`&&typeof e.command.clientId==`string`&&Cm(e.command.conversationId,e.command.clientId),!1)),f(g.current),Fr(e=>{let t=new Set(e);for(let e of[...t]){let n=i.conversations.find(t=>t.id===e);(!n||n.status!==`running`&&n.status!==`waiting`)&&t.delete(e)}return t}),i.extensionUi&&Zt(i.extensionUi),i.stoppingConversationIds&&Fr(new Set(i.stoppingConversationIds)),u(i),Ne(!0),F(!0);let a=g.current.filter(e=>e.key===`create-workspace`).map(e=>e.temporaryId);N(e=>{if(!e&&Wn.current)return;if(e&&(oe(e)||i.workspaces.some(t=>t.id===e)||a.includes(e)))return e;let t=_.current?.workspaceId;return t&&i.workspaces.some(e=>e.id===t)?t:i.workspaces[0]?.id})}else if(n.type===`message.delta`)Nt(n);else if(n.type===`queue.withdrawn`){Ri(e=>[...e.filter(e=>e.conversationId!==n.conversationId).slice(-9),{id:`withdrawn_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,conversationId:n.conversationId,actor:n.actor,withdrawn:n.withdrawn}]);let e=n.withdrawn.slice(0,2).map(e=>`「${e.content.replace(/\s+/g,` `).trim().slice(0,24)}」`).join(`、`),t=n.actor===`agent`?`上级 Agent 已撤回`:`已撤回`;Sc(`${t} ${n.withdrawn.length} 条排队消息:${e}${n.withdrawn.length>2?`…`:``}`,`info`)}else if(n.type===`message.revert.result`)Su(void 0),Nr(void 0),n.ok||(console.error(`[Super Pi Error] revert failed:`,n.message),re(n.message));else if(n.type===`operation.result`){let e=g.current.find(e=>e.id===n.requestId),t=e?.retry?e.command:void 0;if(t&&Cm(t.conversationId,t.clientId),g.current=g.current.filter(e=>e.id!==n.requestId),f(g.current),e?.temporaryId){let t=e.temporaryId;if(e.key===`create-workspace`&&n.ok&&n.entityId){let r=n.entityId;u(n=>{if(n.workspaces.some(e=>e.id===r))return n;let i=e.apply(n).workspaces.find(e=>e.id===t);return i?{...n,workspaces:[...n.workspaces,{...i,id:r}]}:n})}else if(n.ok&&n.entityId){let e=n.entityId,r=bi.current.get(t);if(r&&_i.current.set(e,{...r,id:e}),mi.current.add(e),r){let t={...r,id:e};u(n=>n.conversations.some(t=>t.id===e)?n:{...n,conversations:[t,...n.conversations]})}Wr(n=>{let r=n[t];if(!r)return n;let i=n[e],a={...n};return a[e]=i?{...i,text:r.text||i.text,images:r.images.length?r.images:i.images,attachments:r.text?r.attachments:i.attachments,pendingSkills:r.text?r.pendingSkills:i.pendingSkills,uploading:r.uploading+i.uploading}:r,delete a[t],a}),bi.current.delete(t)}ee(r=>r===t?n.ok?n.entityId:e.previousActiveId:r),ce(e=>Cj(e,t,n.ok&&n.entityId?n.entityId:void 0)),N(r=>r===t?n.ok?n.entityId:e.previousWorkspaceId:r),!n.ok&&e.key===`create-workspace`&&$i.current===t&&ee(t=>t??e.previousActiveId)}if(n.ok&&e?.key.startsWith(`reload:`)&&Sc(`会话资源已重新加载,历史和草稿保持不变`,`success`),!n.ok){if(console.error(`[Super Pi Error] operation failed:`,n.message),!e?.receipt){if(e?.onFailure)e.onFailure(n.message);else if(t){let e=t.images??[],r=eA(t.content,t.attachments);Yr(i=>[...i,{id:t.clientId,conversationId:t.conversationId,content:t.content,images:e,attachments:r,reason:n.message}]),la(t.conversationId,n=>n.text||n.images.length||n.attachments.length?n:{...n,text:t.content,images:e,attachments:r})}}let r=n.message??`操作失败`;re(r),e?.onFailure||Sc(zr(r),`error`)}}else n.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):n.type===`files.changed`?(fo.current(n.workspaceId,n.changes,n.dropped),n.workspaceId===mo.current&&uo.current()):n.type===`files.invalidated`?(po.current(n.workspaceId,n.paths),n.workspaceId===mo.current&&uo.current()):n.type===`error`?(console.error(`[Super Pi Error]`,n.message),n.recordedTurnFailure||(re(n.message),Sc(zr(n.message),`error`),ui.current&&=!1)):n.type===`extension.ui`?Dc(n.conversationId,n.request):n.type===`extension.ui.closed`?Oc(n.conversationId,n.requestId,n.reason):n.type===`model.catalog`?(!n.conversationId||n.conversationId===li.current)&&nn(n.catalog):n.type===`model.catalog.all`?an(n.catalog):n.type===`providers.list`?(sn(n.providers),ln(n.apis)):n.type===`agent.catalog`?((n.sourceServerId??me())===me()&&dn(n.catalog),(n.sourceServerId??me())===he()&&_n(n.catalog)):n.type===`prompt.catalog`?Yt(n.catalog):n.type===`subagent.catalog`?((n.sourceServerId??me())===me()&&pn(n.catalog),(n.sourceServerId??me())===he()&&yn(n.catalog)):n.type===`server.version`?hn(n.version):n.type===`subagent.event`?u(e=>({...e,subagentRuns:Ec(e.subagentRuns??[],n.run)})):n.type===`workflow.event`?u(e=>({...e,workflows:X(e.workflows??[],n.workflow)})):n.type===`message.tools`?u(e=>({...e,conversations:e.conversations.map(e=>e.id===n.conversationId?{...e,messages:e.messages.map(e=>e.id===n.messageId?{...e,toolCalls:n.toolCalls}:e)}:e)})):n.type===`conversation.fork.result`&&(Au(e=>e===n.conversationId?void 0:e),Sc(n.ok?`已从「${n.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${n.messagesCopied?`复制了 ${n.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${zr(n.message)}`,n.ok?`info`:`error`))}}})(),()=>{e=!0,Mt();for(let e of ci.current)window.clearTimeout(e);He.current?.close()}},[Nt,Mt,ft]);let kc=(0,p.useCallback)(e=>{if(!He.current?.canSend(e))return!1;try{return He.current.send(JSON.stringify(e)),!0}catch(e){return Sc(e instanceof Error?e.message:`服务器未连接`,`error`),!1}},[]),Ac=(0,p.useCallback)(e=>{Se({id:e,ticket:++de.current});let t=li.current;t?.startsWith(`pending:`)||kc({type:`state.subscribe`,...t?{conversationId:t}:{}}),kn()},[kc,kn]);(0,p.useEffect)(()=>{if(!fe)return;if(fe.ticket!==de.current){Se(void 0);return}let e=Di.find(e=>e.id===fe.id);e&&O.workspaces.some(t=>t.id===e.workspaceId)&&(Se(void 0),Pa(e.id),N(e.workspaceId))},[fe,Di,O.workspaces,Pa]),(0,p.useEffect)(()=>{if(!te||!Me||oe(j??M))return;let e=z?.id;e?.startsWith(`pending:`)||kc({type:`state.subscribe`,...e?{conversationId:e}:{}})},[z?.id,j,M,te,Me,kc]);let jc=(e,t,n,r,i,a,o)=>{let s=He.current?.canSend(e)===!0,c=jD(e);if(g.current.some(e=>e.key===t)||!s&&!c)return!1;if(c&&!Sm(e))return Sc(`浏览器无法保存待发消息,正文仍在输入框。`,`error`),!1;let l=tn(),u=D(e),d=[...u][0]??e._server??me(),p={id:l,key:t,serverId:d,apply:e=>u.size||me()===d?n(e):e,temporaryId:r,previousActiveId:li.current,previousWorkspaceId:$i.current,onFailure:i,accepted:a,...o?{expiresAt:Date.now()+o}:{},...c?{retry:!0,command:e}:{}};return g.current=[...g.current,p],f(g.current),s&&He.current.send(JSON.stringify({...e,operationRequestId:l})),!0},Mc=e=>kc({...e,_server:he()}),Nc=(e,...t)=>jc({...e,_server:he()},...t),Pc=(e,t)=>{kc({type:`conversation.childLock`,conversationId:e,unlocked:t})||Sc(t?`连接断开,这个子会话没有解锁,请重试`:`连接断开,这个子会话没有上锁,请重试`,`error`)},Fc=e=>{if(!e)return;let t=`message_${tn()}`;jc({type:`message.send`,conversationId:e,content:kk,clientId:t},`continue-truncated:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===e?{...t,warning:void 0}:t)}),void 0,void 0,void 0)};(0,p.useEffect)(()=>{let e=d.flatMap(e=>e.expiresAt?[e.expiresAt]:[]);if(!e.length)return;let t=window.setTimeout(()=>{let e=g.current.filter(e=>e.expiresAt&&e.expiresAt<=Date.now());if(e.length){g.current=g.current.filter(t=>!e.includes(t)),f(g.current);for(let t of e)t.onFailure?.(`打断请求超时,尚未确认是否开始回答;请检查会话状态后重试`)}},Math.max(0,Math.min(...e)-Date.now()));return()=>window.clearTimeout(t)},[d]);let Ic=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),Lc=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),Rc=z?.id.startsWith(`pending:`)===!0,zc=!!(z&&wA(z)&&(Pr.has(z.id)||d.some(e=>e.key===`stop:${z.id}`))),Bc=z?.messagesLoaded===!1||d.some(e=>e.key.startsWith(`send:${z?.id}:`)||e.key===`configuration:${z?.id}`||e.temporaryId===z?.id||e.key===`archive:${z?.id}`),Vc=(e,t,n,r,i)=>{e&&kc({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i})},Hc=(e,t)=>kr(n=>({...n,[e]:t})),Uc=(e,t,n)=>(Na(e),jc({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e)),Wc=z?.model??en?.defaultModel,Gc=z?.thinkingLevel??en?.defaultThinkingLevel,Kc=Gc&&en?.levels.includes(Gc)?Gc:void 0,qc=en?.source===`pi`,Jc=en?.models.find(e=>e.provider===Wc?.provider&&e.modelId===Wc?.modelId),Yc=!!Jc?.imageInput,Xc=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(O.modelFilterRules??[]).every(n=>{try{let r=new RegExp(n.workspacePattern,`i`),i=[t.name,t.path,t.worktreeProjectPath].filter(e=>!!e).some(e=>r.test(e.replaceAll(`\\`,`/`))),a=new RegExp(n.modelPattern,`i`);return!i||a.test(e.label)||a.test(`${e.provider}/${e.modelId}`)}catch{return!0}}))},Zc=!!z?.messages?.some(e=>e.images&&e.images.length>0),Qc=Xc(en,O.workspaces.find(e=>e.id===z?.workspaceId))?.models??[],$c=Zc?Qc.filter(e=>e.imageInput):Qc,el=$c.map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:[e.detail,UO(e.contextWindow)?`${UO(e.contextWindow)} 上下文`:``,WO(e.maxTokens)?`${WO(e.maxTokens)} 输出`:``].filter(Boolean).join(` · `),badge:Pk(e),selected:Wc?.provider===e.provider&&Wc.modelId===e.modelId})),tl=(en?.levels??[]).map(e=>({key:e,label:e,selected:e===Gc})),nl=e=>{if(!z)return;let[t,n]=e.split(`/`);t&&n&&(Na(z.id),jc({type:`conversation.model`,conversationId:z.id,provider:t,modelId:n},`configuration:${z.id}`,Ic(z.id,{model:en?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}})))},rl=e=>{z&&(Na(z.id),jc({type:`conversation.thinking`,conversationId:z.id,level:e},`configuration:${z.id}`,Ic(z.id,{thinkingLevel:e})))},il=un?.agents.find(e=>e.id===z?.agentId),al=[{key:hA,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!z?.agentId},...(un?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:z?.agentId===e.id}))],ol=il?.model,sl=!!(ol&&z?.model&&z.model.provider===ol.provider&&z.model.modelId===ol.modelId);il?.thinkingLevel&&(z?.thinkingLevel,il.thinkingLevel);let cl=e=>{if(z){let t=un?.agents.find(t=>t.id===e);jc({type:`conversation.agent`,conversationId:z.id,agentId:e===hA?null:e},`configuration:${z.id}`,Ic(z.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},ll=xn.filter(e=>e.conversationId===z?.id),ul=(0,p.useMemo)(()=>{let e=z?.id;return e?(z.messages??[]).flatMap(t=>(t.toolCalls??[]).flatMap((n,r)=>n.question?.status===`pending`?[{key:sA(e,t.id,r),messageId:t.id,index:r,value:n.question}]:[])):[]},[z?.id,z?.messages]),Z=ul[0],dl=()=>{let e=Z;e&&(jr(e.key),at(`session`),window.setTimeout(()=>{(yt.current?.querySelector(`[data-transcript-key="${CSS.escape(`m:${e.messageId}`)}"]`))?.scrollIntoView({block:`center`,behavior:`smooth`})},0))},fl=Xt.filter(e=>e.conversationId===z?.id).map(e=>e.request),pl=new Map(fl.filter(e=>e.method===`setStatus`).map(e=>[e.statusKey??``,e.statusText??``])),ml=new Map(fl.filter(e=>e.method===`setWidget`).map(e=>[e.widgetKey??``,{lines:e.widgetLines??[],placement:e.widgetPlacement??`aboveEditor`}])),hl=fl.find(e=>e.method===`setTitle`)?.title,gl=(0,p.useMemo)(()=>(O.subagentRuns??[]).filter(e=>e.conversationId===z?.id),[O.subagentRuns,z?.id]),_l=(0,p.useMemo)(()=>(O.workflows??[]).filter(e=>e.conversationId===z?.id),[O.workflows,z?.id]),vl=(0,p.useMemo)(()=>new Map(_l.map(e=>[e.id,e])),[_l]),yl=(0,p.useMemo)(()=>new Map((fn?.agents??[]).map(e=>[e.id,e.name])),[fn]),bl=(0,p.useMemo)(()=>new Map((z?.messages??[]).map(e=>[e.id,e])),[z?.messages]),xl=(0,p.useMemo)(()=>new Map(gl.map(e=>[e.id,e])),[gl]),Sl=(0,p.useMemo)(()=>{let e=new Map;for(let t of gl)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[gl]),Cl=(0,p.useMemo)(()=>{if(!z||!Ma)return[];let e=Mr?.conversationId===z.id?(()=>{let e=z.messages.find(e=>e.id===Mr.messageId);if(e)return{index:z.messages.indexOf(e),at:Date.parse(e.createdAt)||0,inclusive:!0}})():void 0,t=[];return z.messages.forEach((n,r)=>{e&&(r>e.index||e.inclusive&&r===e.index)||n.delivery||n.batchedInto||t.push({at:Date.parse(n.createdAt)||0,seq:r,key:`m:${n.id}`})}),gl.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&z?.messages.some(e=>e.id===n.originMessageId&&e.toolCalls?.[n.originCallRow])||e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`r:${n.id}`})}),_l.forEach((n,r)=>{e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`w:${n.id}`})}),Ya(t)},[z,gl,_l,Mr]),wl=(0,p.useMemo)(()=>{for(let e=Cl.length-1;e>=0;--e){let t=Cl[e];if(t.startsWith(`m:`)&&bl.get(t.slice(2))?.role===`user`)return t.slice(2)}},[Cl,bl]);(0,p.useEffect)(()=>{let e=yt.current;if(!e||!z?.id)return;let t=()=>{!Et.current&&Ue.current[z.id]?.followTail&&(_j(e),e.scrollTop=e.scrollHeight)};if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);n.observe(e);for(let t of e.children)n.observe(t);return()=>n.disconnect()},[z?.id,z?.messages,gl,_l,Ma,Cl,R]);let Tl=e=>Cr(t=>({...t,[e]:!t[e]})),El=(e,t)=>Tr(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),Dl=(e,t)=>Dr(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[Ol,kl]=(0,p.useState)({}),Al=e=>kl(t=>({...t,[e]:t[e]!==!0})),jl=e=>{jc({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||Sc(`连接断开,无法停止子智能体,请重试`,`error`)},Ml=e=>{jc({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||Sc(`连接断开,无法停止编排,请重试`,`error`)},Nl=e=>[...ml].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,m.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,Vk).map((e,t)=>(0,m.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>Vk&&(0,m.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),Pl=(e,t)=>{let n=`pending:${tn()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};jc({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(Ia(n),Le(!1))},[Fl,Il]=(0,p.useState)(),Ll=(e,t)=>Il(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),Rl=()=>Il(void 0),zl=(e,t)=>Fl?.kind===e&&Fl.id===t,Bl=(e,t,n)=>!t.startsWith(`pending:`)&&(e===`conversation`&&Na(t),jc(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?Lc(t,{name:n}):Ic(t,{title:n}))?(ui.current=!0,Rl(),!0):(Sc(`连接断开,改名未保存,请重试`,`error`),!1)),Vl=async e=>{if(e.startsWith(`pending:`)){Sc(`这个会话还在创建中,稍后再试`,`warning`);return}if(Hr.current.has(e))return;Sc(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{Hr.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{Hr.current.delete(e)&&n(Error(`模型在 ${Math.round(YO/1e3)} 秒内没有返回标题`))},YO)});if(!kc({type:`conversation.autoRename`,conversationId:e}))Hr.current.delete(e),Sc(`连接断开,无法生成标题`,`error`);else try{let n=await t;Bl(`conversation`,e,n),Sc(`已重命名为「${n}」`,`info`)}catch(e){Sc(`重命名失败:${zr(e)}`,`error`)}},Hl=e=>{if(e.id.startsWith(`pending:`))return;let t=O.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`从列表移除工作区「${e.name}」?${t?`其中的 ${t} 条会话会保留,`:``}重新添加同一个目录即可恢复,不会删除任何会话。`)&&(Wl(void 0),jc({type:`workspace.delete`,workspaceId:e.id},`delete:${e.id}`,t=>({...t,workspaces:t.workspaces.filter(t=>t.id!==e.id),conversations:t.conversations.filter(t=>t.workspaceId!==e.id)})))},[Ul,Wl]=(0,p.useState)(),[Gl,Kl]=(0,p.useState)(!1),ql=Ul?O.workspaces.find(e=>e.id===Ul):void 0,{theme:Jl,setTheme:Yl}=y_(),[Xl,Zl]=(0,p.useState)(!1),[Ql,$l]=(0,p.useState)();(0,p.useEffect)(()=>{let e=()=>{_e(),ge(`entry`),$l(`servers`),Zl(!0)};return window.addEventListener(`super-pi-open-server-management`,e),()=>window.removeEventListener(`super-pi-open-server-management`,e)},[]),(0,p.useEffect)(()=>{let e=e=>{let t=e.detail;typeof t==`string`&&O.conversations.some(e=>e.id===t)&&(Pa(t),xr&&kn())};return window.addEventListener(`super-pi-open-rsi-work`,e),()=>window.removeEventListener(`super-pi-open-rsi-work`,e)},[O.conversations,Pa,xr,kn]);let[eu,tu]=(0,p.useState)(!1),nu=(e,t,n,r)=>{e.startsWith(`pending:`)||(jc({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,Lc(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?Wl(void 0):Sc(`连接断开,设置未保存,请重试`,`error`))},ru=(e,t)=>{let n=I.activeServer;jc({type:`workspaces.settings.bulk`,model:e?{provider:e.provider,modelId:e.modelId}:null,thinkingLevel:t??null},`workspace-defaults-bulk`,r=>({...r,workspaces:r.workspaces.map(r=>{if(y(r.id).server!==n||r.closedAt||r.id.startsWith(`pending:`))return r;let i={...r};return e?i.defaultModel=e:delete i.defaultModel,t?i.defaultThinkingLevel=t:delete i.defaultThinkingLevel,i})}))?Kl(!1):Sc(`连接断开,批量设置未保存,请重试`,`error`)},iu=(e,t=``)=>{if(e.startsWith(`pending:`))return;if(g.current.some(t=>t.key===`defaults:${e}`)){Sc(`工作区设置正在保存,请稍后再新建会话`,`warning`);return}let n=`pending:${tn()}`,r={id:n,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[],...t?{cwd:t}:{}};bi.current.set(n,r),jc({type:`conversation.create`,workspaceId:e,...t?{cwd:t}:{}},`create-session:${e}:${n}`,e=>({...e,conversations:[r,...e.conversations]}),n)?(de.current++,N(e),ee(n),at(`session`),ce(e=>({...e,ids:[...e.ids.filter(e=>e!==n),n],touched:Sj(e.touched,n)}))):(bi.current.delete(n),Sc(`连接断开,会话未创建,请重试`,`error`))},au=e=>{if(e.startsWith(`pending:`))return;let t=O.conversations.find(t=>t.id===e);if(!t||t.archivedAt||t.parentConversationId&&O.conversations.some(e=>e.id===t.parentConversationId))return;let n=wk(O.conversations,e),r=n.filter(e=>!e.archivedAt),i=r.length-1,a=n.length-r.length,o=GO(O.pendingUserDecisionsByConversation,n.map(e=>e.id)),s=sk({title:t.title,activeCount:r.length,activeDescendants:i,alreadyArchived:a,pendingDecisions:o});if(ck({activeDescendants:i,pendingDecisions:o})&&!window.confirm(s))return;let c=new Date().toISOString(),l=new Set(r.map(e=>e.id));jc({type:`conversation.archive`,conversationId:e},`archive:${e}`,e=>({...e,conversations:e.conversations.map(e=>l.has(e.id)&&!e.archivedAt?{...e,archivedAt:c}:e)}))},ou=(e,t)=>jc({type:`conversation.collapse`,conversationId:e,collapsed:t},`collapse:${e}`,n=>{let r=new Set(n.collapsedConversationIds??[]);t?r.add(e):r.delete(e);let i={...n};return r.size===0?delete i.collapsedConversationIds:i.collapsedConversationIds=[...r],i}),su=e=>{let t=O.conversations.find(t=>t.id===e);if(!t?.archivedAt||(t.parentConversationId?O.conversations.find(e=>e.id===t.parentConversationId):void 0)?.archivedAt)return;let n=new Set(wk(O.conversations,e).filter(e=>e.archivedAt).map(e=>e.id));jc({type:`conversation.unarchive`,conversationId:e},`unarchive:${e}`,e=>({...e,conversations:e.conversations.map(e=>{if(!n.has(e.id)||!e.archivedAt)return e;let t={...e};return delete t.archivedAt,t})}))},cu=async e=>{if(!z){Sc(`请先选择或创建会话`,`error`);return}if(!Yc){Sc(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(Sc(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(Sc(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=z.id;la(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:tn(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));Zr(e=>[...e,...i]);for(let[e,t]of n.entries()){let n=i[e];try{let e=await new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let t=r.result,n=t.indexOf(`,`);e(n>=0?t.slice(n+1):t)},r.onerror=n,r.readAsDataURL(t)}),i=await Ie(`/api/upload`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({conversationId:r,name:t.name,mimeType:t.type,data:e})});if(!(i.headers.get(`content-type`)??``).includes(`application/json`)){Sc(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(qr.current.has(n.id))continue;Zr(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),la(r,t=>({...t,images:[...t.images,{id:b(L(r),e.id),name:e.name,mimeType:e.mimeType,bytes:e.bytes}]}))}else{let e=await i.json().catch(()=>({error:`上传失败`}));Sc(zr(e.error,`上传失败(HTTP ${i.status})`),`error`)}}catch(e){Sc(`上传失败:${zr(e,`网络或服务暂时不可用`)}`,`error`)}finally{Zr(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),la(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},lu=e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.type.startsWith(`image/`)){let e=r.getAsFile();e&&n.push(e)}}if(n.length>0){if(!Yc){Sc(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),cu(n)}},uu=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),ii(!0))},du=e=>{e.currentTarget.contains(e.relatedTarget)||ii(!1)},fu=e=>{ii(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!Yc){Sc(`当前模型不支持图片输入`,`error`);return}cu(t)}},pu=t=>{if(t.preventDefault(),!z)return;if(Ui){Sc(Xn,`warning`);return}if(Bc){Sc(Rc?`会话正在创建,请稍候再发送`:z.messagesLoaded===!1?`正在加载会话,请稍候再发送`:`正在保存配置,请稍候再发送`,`info`);return}let n=ia.trim(),r=lp(n);if(r){if(r.args||aa.length||oa.length){Sc(`/${r.id} 请单独执行,不要附加正文或附件`,`info`);return}Mu(r.id)&&(la(z.id,e=>({...e,text:``})),ga({visible:!1,query:``,rect:null}));return}if(!n&&aa.length===0)return;if(aa.length>0&&!Yc){Sc(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(ca>0){Sc(`图片正在上传中,请稍候…`,`info`);return}if(sa){Sc(`技能正在读取中,请稍候…`,`info`);return}let i=`message_${tn()}`,a=z.id,o=ia,s=aa,c=oa;Na(a),e.stoppingConversationIds||Fr(e=>{if(!e.has(a))return e;let t=new Set(e);return t.delete(a),t});let l=tA({conversationId:a,content:o,clientId:i,images:s,attachments:c,inFlight:wA(z),deliveryMode:z.compaction?.status===`running`?`queue`:Pi}),u=new Date().toISOString();jc(l,`send:${a}:${i}`,e=>Tm(e,l,u),i,e=>{Yr(t=>[...t,{id:i,conversationId:a,content:o,images:s,attachments:c,reason:e}]),la(a,e=>e.text||e.images.length||e.attachments.length?e:{...e,text:o,images:s,attachments:c})},e=>!!e.conversations.find(e=>e.id===a)?.messages.some(e=>e.id===wm(l)))&&la(a,e=>({...e,text:``,images:[],attachments:[],pendingSkills:void 0}))},mu=(0,p.useMemo)(()=>(z?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[z?.messages]),hu=e=>{jc({type:`message.cancel`,conversationId:z?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===z?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||Sc(`连接断开,撤回没有生效,请重试`,`error`)},gu=e=>{if(!z?.id||!e.length)return;let t=new Set(e),n=`queue-many:${z.id}:${e.join(`,`)}`;jc({type:`message.cancelMany`,conversationId:z.id,messageIds:e},n,e=>({...e,conversations:e.conversations.map(e=>e.id===z.id?{...e,messages:e.messages.filter(e=>!t.has(e.id))}:e)}),void 0,e=>Sc(e??`撤回所选消息失败,请重试`,`error`),t=>{let n=t.conversations.find(e=>e.id===z.id);return!!(n&&e.every(e=>!n.messages.some(t=>t.id===e&&t.delivery)))})||Sc(`连接断开,批量撤回没有生效,请重试`,`error`)},_u=e=>{jc({type:`message.steer`,conversationId:z?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===z?.id?{...t,messages:dk(t.messages,e,0)}:t)}),void 0,void 0,t=>t.conversations.find(e=>e.id===z?.id)?.messages.find(t=>t.id===e)?.delivery===`sending`)||Sc(`连接断开,插到最前没有生效,请重试`,`error`)},vu=e=>{let t=z?.id;t&&(He.current?.readyState===WebSocket.OPEN?jc({type:`message.interrupt`,conversationId:t,messageId:e},`interrupt:${t}:${e}`,e=>e,void 0,e=>Sc(e??`打断失败,请重试`,`error`),n=>{let r=n.conversations.find(e=>e.id===t)?.messages.find(t=>t.id===e);return!(!r||r.delivery)},3e4)||Sc(`正在打断,请稍候`,`info`):Sc(`连接断开,打断没有生效,请重试`,`error`))},yu=e=>{jc({type:`message.sendQueued`,conversationId:z?.id??``,messageId:e},`send-queued:${e}`,e=>e,void 0,void 0,t=>!t.conversations.find(e=>e.id===z?.id)?.messages.find(t=>t.id===e)?.delivery)||Sc(`连接断开,发送没有生效,请重试`,`error`)},bu=(e,t)=>{jc({type:`message.edit`,conversationId:z?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===z?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||Sc(`连接断开,修改没有生效,请重试`,`error`)},[xu,Su]=(0,p.useState)(),Cu=(e,t=!0)=>{if(!z||z.messagesLoaded===!1||xu)return;let n=z.messages.find(t=>t.id===e);n&&(Wr(e=>{let t=e[z.id]??{text:``,images:[],attachments:[],uploading:0};return t.text.trim()||t.images.length||t.attachments.length?e:{...e,[z.id]:{...t,text:n.content,images:n.images??[],attachments:eA(n.content,n.attachments)}}}),Nr({conversationId:z.id,messageId:e,kind:t?`withdraw`:`revert`})),kc({type:`message.revert`,conversationId:z.id,messageId:e,withdraw:t})?Su(e):(Nr(void 0),Sc(`连接断开,回退未执行,请重试`,`error`))},[wu,Tu]=(0,p.useState)(),Eu=(0,p.useRef)(void 0),Du=(0,p.useRef)(0),Ou=async(e,t)=>{let n=++Du.current,r=await Hi(t);n===Du.current&&(clearTimeout(Eu.current),Tu({id:e,kind:r?`copied`:`error`}),r||Sc(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),Eu.current=setTimeout(()=>Tu(void 0),2e3))};(0,p.useEffect)(()=>()=>{Du.current+=1,clearTimeout(Eu.current)},[]);let[ku,Au]=(0,p.useState)(),ju=e=>{ku||e.startsWith(`pending:`)||(Na(e),kc({type:`conversation.fork`,conversationId:e})?Au(e):Sc(`连接断开,分叉没有执行,请重试`,`error`))},Mu=e=>{if(!z)return!1;if(e===`reload`||e===`compact`||e===`stop`){if(g.current.some(t=>t.key===`${e}:${z.id}`))return!1;if(e!==`stop`&&(wA(z)||Pr.has(z.id)))return Sc(`请结束或停止当前任务后再执行此操作`,`info`),!1;let t=jc({type:e===`reload`?`conversation.reload`:e===`compact`?`conversation.compact`:`run.stop`,conversationId:z.id},`${e}:${z.id}`,e=>e,void 0,e=>Sc(e??`操作失败,请重试`,`error`),void 0,12e4);return t&&e===`reload`&&Sc(`正在重新加载当前会话的 Agent、技能与扩展…`,`info`),t&&e===`compact`&&(uc.current=document.querySelector(`[data-context-button]`),lc(`context`)),t||Sc(`服务器未连接,操作未执行`,`error`),t}if(e===`new`||e===`clear`)return iu(z.workspaceId,z.cwd),!0;if(e===`fork`)return wA(z)||ku?(Sc(`请结束当前任务或分叉操作后重试`,`info`),!1):(ju(z.id),!0);if(e===`help`)return tu(!0),!0;if(e===`settings`)return $l(void 0),_e(),Zl(!0),Mc({type:`catalog.fetchAll`}),Mc({type:`providers.fetch`}),!0;if(e===`model`){let e=document.querySelector(`#composer-session-options [data-picker-trigger="model"]`);return!e||e.disabled?(Sc(`模型列表尚未就绪,请稍后重试`,`info`),!1):(On(!0),e.click(),!0)}return e===`resume`?(Uo(`sessions`),!0):e===`update`?(bn.open(),!0):e===`restart`||e===`start`?e===`restart`&&!window.confirm(`确定重启此 Super Pi 服务?进行中的任务可能中断。`)?!1:kc({type:e===`restart`?`super_pi.restart`:`super_pi.start`,conversationId:z.id})?!0:(Sc(`服务器未连接,操作未执行`,`error`),!1):!1},Nu=new Map;for(let e of O.scheduledTasks??[])e.conversationId&&!Nu.has(e.conversationId)&&Nu.set(e.conversationId,e);let Pu=(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,title:`设置`,"aria-haspopup":`dialog`,"aria-expanded":Xl,onClick:()=>{$l(void 0),_e(),Zl(!0),Mc({type:`catalog.fetchAll`}),Mc({type:`providers.fetch`})},children:[(0,m.jsx)(vi,{name:`settings`}),(0,m.jsx)(`span`,{className:`workbench-action-label`,children:`设置`})]}),(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,title:`使用指南`,"aria-haspopup":`dialog`,"aria-expanded":eu,onClick:()=>tu(!0),children:[(0,m.jsx)(vi,{name:`help`}),(0,m.jsx)(`span`,{className:`workbench-action-label`,children:`使用指南`})]})]}),Fu=Va?void 0:z,Iu=de.current,Lu={onOpenSession:e=>{Iu===de.current&&Ac(e)},rsiContext:Va&>?{source:{kind:`group`,id:gt,workspaceId:ht},title:vt??`群聊`,archived:!!_t?.archivedAt}:Fu?{source:{kind:`session`,id:Fu.id,workspaceId:Fu.workspaceId},title:Fu.title,archived:!!Fu.archivedAt}:void 0,rsiCatalog:Xc(en,hc),todos:O.todosByConversation?.[Fu?.id??``]??[],tasks:zA(Fu,O.backgroundTasks??[]),backgroundRuns:Fu?xl:void 0,execOutputs:Dt.current,scheduledTasks:(O.scheduledTasks??[]).filter(e=>e.workspaceId===Ua),scheduledCatalog:Xc(en,hc),scheduledAgents:un,notify:Sc,serverTimeZone:O.serverTimeZone,workspaceId:Ua,gitWorkspaceId:Ga,gitRepositoryOnly:qa,gitWorkspaceName:gc?.name,workspaceLabel:hc?.path,workspaceName:hc?.name,conversationId:Fu?.id,followedWorktreeId:Fu?.followedWorktreeId,cwd:Ka,connected:te&&I.statuses.get(I.activeServer)?.state===`online`&&Me&&!Fu?.id.startsWith(`pending:`),files:V,onOpenFile:Ns,onOpenChanged:Ts,onOpenGitDiff:Ss,activeGitDiffUrl:ys?.target.url,onFileReference:Ps,onFilesMoved:Fs,onSearchFolder:e=>rs(`content`,void 0,[Ka,e].filter(Boolean).join(`/`)),onSelectTab:Ho,sendCommand:kc,registerTerminalSink:Pt,terminalShell:O.terminalShell,terminalFocusRequest:xo,sharedGit:lo,gitReveal:Go},Ru=e=>I.connections.some(t=>t.id===y(e).server)&&(Fn===`all`||y(e).server===Fn),zu=new Set(O.workspaces.map(e=>e.id)),Bu=O.workspaces.filter(e=>Ru(e.id)&&(!e.worktreeOf||!zu.has(e.worktreeOf))),Vu=Bu.flatMap(e=>[e,...O.workspaces.filter(t=>t.worktreeOf===e.id)]),Hu=(0,p.useMemo)(()=>{let e=new Map;for(let t of O.workspaces){if(t.closedAt)continue;let n=t.name.trim().toLowerCase();n&&e.set(n,(e.get(n)??0)+1)}return new Set([...e].filter(([,e])=>e>1).map(([e])=>e))},[O.workspaces]),Uu=Ln&&Vu.some(e=>e.id===Ln)?Ln:M&&Vu.some(e=>e.id===M)?M:Vu[0]?.id,Wu=O.workspaces.find(e=>e.id===M),Gu=Wu?.worktreeOf&&zu.has(Wu.worktreeOf)?Wu.worktreeOf:Wu?.id,Ku=zn&&Bu.some(e=>e.id===zn)?zn:Gu&&Bu.some(e=>e.id===Gu)?Gu:Bu[0]?.id,qu=Date.now()-18e6,Q=Vu.filter(e=>e.id===Ku||e.worktreeOf===Ku),Ju=e=>{let t=O.conversations.some(t=>t.workspaceId===e&&!t.archivedAt&&(Mn===`recent`?Date.parse(t.updatedAt)>=qu:t.status===`running`||t.status===`waiting`)),n=(ot[e]?.rooms??[]).some(e=>!e.archivedAt&&(Mn===`recent`?Date.parse(e.updatedAt)>=qu:[`running`,`queued`].includes(hr(e,dt[e.id]))));return t||n},Yu=Bu.flatMap(e=>{let t=Vu.filter(t=>t.worktreeOf===e.id&&Ju(t.id));return Ju(e.id)||t.length>0?[e,...t]:[]}),Xu=Mn===`all`?Vu:Mn===`workspace`?Vu.filter(e=>e.id===Uu):Mn===`repo`?Q:Yu,Zu=Mn===`all`||Mn===`workspace`||Mn===`repo`,Qu=(e,t=Mn,n=Uu,r=Ku)=>{if(!e||!Ru(e))return!1;if(t===`all`)return!0;if(t===`workspace`)return e===n;if(t===`repo`)return e===r||Vu.some(t=>t.id===e&&t.worktreeOf===r);let i=O.conversations.filter(t=>t.workspaceId===e&&!t.archivedAt).some(e=>t===`recent`?Date.parse(e.updatedAt)>=qu:e.status===`running`||e.status===`waiting`),a=(ot[e]?.rooms??[]).some(e=>!e.archivedAt&&(t===`recent`?Date.parse(e.updatedAt)>=qu:[`running`,`queued`].includes(hr(e,dt[e.id]))));return i||a},$u=(e,t=Uu,n=Ku)=>{Nn(e),t&&Rn(t),n&&Vn(n);let r=R===`group`&&ht&>?ot[ht]?.rooms.find(e=>e.id===gt):void 0,i=R===`group`?!!(ht&&r&&!r.archivedAt&&Qu(ht,e,t,n)&&(e===`all`||e===`workspace`||e===`repo`||(e===`recent`?Date.parse(r.updatedAt)>=qu:[`running`,`queued`].includes(hr(r,dt[r.id]))))):!!(z&&!z.archivedAt&&Qu(z.workspaceId,e,t,n)&&(e===`all`||e===`workspace`||e===`repo`||(e===`recent`?Date.parse(z.updatedAt)>=qu:z.status===`running`||z.status===`waiting`)));if(zs.current=!0,i){e===`workspace`&&N(t);let r=Rs.find(e=>e.id===Y)?.workspaceId;(e===`recent`||e===`running`||(e===`workspace`||e===`repo`)&&!Qu(r,e,t,n))&&at(`session`)}else Un(!0),ee(void 0),it(!1),(R===`session`||R===`group`||e===`recent`||e===`running`||(e===`workspace`||e===`repo`)&&!Qu(Rs.find(e=>e.id===Y)?.workspaceId,e,t,n))&&at(`session`),N(e===`workspace`?t:void 0)},ed=e=>{In(e),localStorage.setItem(`super-pi.server-filter`,e),e!==`all`&&xe(e);let t=R===`group`?ht:z?.workspaceId??M;if(t&&e!==`all`&&y(t).server!==e){zs.current=!0,Un(!0),ee(void 0),it(!1);let t=O.workspaces.filter(t=>y(t.id).server===e);if(Mn===`workspace`){let e=t.find(e=>e.id===Ln)?.id??t[0]?.id;Rn(e),N(e)}else N(void 0),Mn===`repo`&&Vn(t.find(e=>!e.worktreeOf)?.id);at(`session`)}};(0,p.useEffect)(()=>{Fn!==`all`&&!I.connections.some(e=>e.id===Fn)&&ed(`all`)},[Fn,I.connections]);let td=Rs.filter(e=>{if(!e.workspaceId||!Ru(e.workspaceId))return!1;if(Mn===`all`)return!0;if(Mn===`workspace`||Mn===`repo`)return Qu(e.workspaceId);if(e.id.startsWith(`session:`)){let t=O.conversations.find(t=>t.id===e.rawId);return!!(t&&!t.archivedAt&&Qu(t.workspaceId)&&(Mn===`recent`?Date.parse(t.updatedAt)>=qu:t.status===`running`||t.status===`waiting`))}if(e.id.startsWith(`group:`)){let t=ur(e.id),n=t?.roomId?ot[t.workspaceId]?.rooms.find(e=>e.id===t.roomId):void 0;return!!(t&&n&&!n.archivedAt&&Qu(t.workspaceId)&&(Mn===`recent`?Date.parse(n.updatedAt)>=qu:[`running`,`queued`].includes(hr(n,dt[n.id]))))}return e.id===Y||e.id===so||Qu(e.workspaceId)}),nd=qa?`未选工作区`:lo.status?.detached?`游离 HEAD`:lo.status?.branch,rd=!qa&&lo.status&&new Set([...lo.status.staged,...lo.status.unstaged,...lo.status.untracked].map(e=>e.path)).size,id=!qa&&lo.status&&(lo.status.ahead||lo.status.behind)?[lo.status.ahead?`↑`+lo.status.ahead:``,lo.status.behind?`↓`+lo.status.behind:``].filter(Boolean).join(` `):``,ad=()=>tr(e=>({...e,rightClosed:!0})),od=()=>tr(e=>({...e,leftClosed:!0})),sd=xr?Sn:Io;return(0,m.jsx)(Ei,{store:nr,showing:e=>e===`sessions`?Vo:zo(e),onDock:Yo,onReveal:e=>Uo(e),children:(0,m.jsxs)(`main`,{className:`shell workbench-shell${sd?` shell-rail-collapsed`:``} mobile-panel-${Tn}${An?` mobile-drawer-open`:``}`,"data-bottom-open":!xr&&!er.bottomClosed,"data-rail-collapsed":sd,"data-workbench-left-closed":!xr&&(er.leftClosed||ko.length===0),"data-selected-workspace":M??``,style:{"--bottom-height":er.bottomHeight+`px`,"--sidebar-width":`${ar.sidebar}px`,"--rail-col":sd?void 0:`${ar.rail}px`},children:[!xr&&(0,m.jsx)(yi,{side:`left`,views:ko,unpinned:er.unpinned,active:Lo.left,onSelect:e=>Uo(e,!0),onDockCard:Yo,onArrange:Xo,onReorder:Zo,children:Pu}),(0,m.jsxs)(`aside`,{className:`workbench-sessions`,id:`workbench-sessions`,"data-workbench-sessions-side":xr?`left`:er.sides.sessions,"data-workbench-session-view":Vo?`shown`:`hidden`,children:[!xr&&(0,m.jsxs)(`div`,{className:`workbench-panel-heading workbench-session-heading`,children:[(0,m.jsx)(`h2`,{draggable:!0,"data-workbench-panel-drag":`sessions`,title:`拖动以移动此面板`,onDragStart:e=>di(e.dataTransfer,`sessions`),children:`会话`}),(0,m.jsx)(xi,{view:`sessions`,side:er.sides.sessions,pinned:!er.unpinned.includes(`sessions`),onArrange:Xo})]}),(0,m.jsxs)(`div`,{className:`sidebar-actions`,children:[(0,m.jsx)(`button`,{className:`workspace-new`,onClick:()=>Le(!0),children:`+ 添加工作区`}),z&&Ma&&td.length===1&&(0,m.jsx)(`button`,{type:`button`,className:`mobile-close-session`,onClick:()=>{nc(z.id),jn(!1)},children:`关闭当前标签`})]}),(0,m.jsxs)(`div`,{className:`label label-desktop workspace-title-row`,children:[(0,m.jsx)(`span`,{children:`工作区`}),(0,m.jsx)(`button`,{type:`button`,className:`workspace-bulk-settings`,title:`批量设置所有工作区`,"aria-label":`批量设置所有工作区`,onClick:()=>Kl(!0),children:`⚙`})]}),(0,m.jsx)(`div`,{className:`label label-phone`,children:`会话`}),Gl&&(0,m.jsx)(ED,{workspaces:O.workspaces.filter(e=>y(e.id).server===I.activeServer&&!e.closedAt&&!e.id.startsWith(`pending:`)),catalog:rn??{source:`unavailable`,models:[],levels:[],fetchedAt:``},onClose:()=>Kl(!1),onSave:ru}),(0,m.jsxs)(`div`,{className:`sidebar-session-filters`,"aria-label":`会话与群聊筛选`,children:[(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`span`,{children:`服务器`}),(0,m.jsxs)(`select`,{"aria-label":`服务器范围`,value:Fn,onChange:e=>ed(e.target.value),children:[(0,m.jsx)(`option`,{value:`all`,children:`全部服务器`}),I.connections.map(e=>(0,m.jsxs)(`option`,{value:e.id,children:[e.name,I.statuses.get(e.id)?.state===`offline`?` · 离线`:``]},e.id))]})]}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`span`,{children:`显示`}),(0,m.jsxs)(`select`,{"aria-label":`会话列表筛选方式`,value:Mn,onChange:e=>$u(e.currentTarget.value),children:[(0,m.jsx)(`option`,{value:`all`,children:`全部`}),(0,m.jsx)(`option`,{value:`workspace`,children:`按工作区`}),(0,m.jsx)(`option`,{value:`repo`,children:`按仓库`}),(0,m.jsx)(`option`,{value:`recent`,children:`近期活跃 · 5 小时`}),(0,m.jsx)(`option`,{value:`running`,children:`正在运行`})]})]}),Mn===`workspace`&&(0,m.jsx)(`select`,{"aria-label":`选择工作区`,value:Uu??``,onChange:e=>$u(`workspace`,e.currentTarget.value,Ku),children:(0,m.jsx)(Bn,{workspaces:Vu})}),Mn===`repo`&&(0,m.jsx)(`select`,{"aria-label":`选择仓库`,value:Ku??``,onChange:e=>$u(`repo`,Uu,e.currentTarget.value),children:(0,m.jsx)(Bn,{workspaces:Bu})})]}),(0,m.jsx)(`nav`,{"aria-label":`工作区、会话与群聊`,children:Xu.length===0?(0,m.jsx)(`div`,{className:`sidebar-filter-empty`,children:Mn===`recent`?`近 5 小时没有活跃的会话或群聊`:`当前没有正在运行的会话或群聊`}):Xu.map((e,t)=>{let n=ot[e.id],r=(n?.rooms.filter(e=>!e.archivedAt)??[]).filter(e=>Zu||(Mn===`recent`?Date.parse(e.updatedAt)>=qu:[`running`,`queued`].includes(hr(e,dt[e.id])))),i=Zu?n?.rooms.filter(e=>e.archivedAt)??[]:[],a=O.conversations.filter(t=>t.workspaceId===e.id&&!t.groupExecution),o=a.filter(e=>!e.archivedAt&&(Zu||(Mn===`recent`?Date.parse(e.updatedAt)>=qu:e.status===`running`||e.status===`waiting`))),s=zD(o,ki,{manualRoots:Lt[e.id]}),c=s.filter(e=>e.depth===0).map(e=>e.conversation.id),l=Zu?a.filter(e=>e.archivedAt):[],u=zD(l,new Set),d=Zu?l.length+i.length:0,f=ie[e.id]??!1,p=Ft[e.id]??!0,h=Hu.has(e.name.trim().toLowerCase()),g=!e.worktreeOf||!zu.has(e.worktreeOf),_=(Mn===`recent`||Mn===`running`)&&g,v=t=>R===`group`&&ht===e.id&>===t;return(0,m.jsxs)(`section`,{className:`workspace-group${e.worktreeOf&&zu.has(e.worktreeOf)?` workspace-linked-checkout`:``}${_?` workspace-active-repo-root`:``}`,"data-workspace-parent":e.worktreeOf,"data-workspace-group":e.id,"data-sidebar-repo-root":_?e.id:void 0,"data-current-workspace":M===e.id,children:[I.connections.length>1&&(t===0||y(Xu[t-1].id).server!==y(e.id).server)&&(0,m.jsxs)(`div`,{className:`workspace-server-label`,children:[be(e.id),I.statuses.get(y(e.id).server)?.state===`offline`?` · 离线`:``]}),(0,m.jsx)(`div`,{className:`workspace-header`,children:zl(`workspace`,e.id)?(0,m.jsx)(pA,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>Bl(`workspace`,e.id,t),onClose:Rl}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`button`,{type:`button`,className:`workspace-disclosure`,"data-workspace-fold":e.id,"aria-expanded":!f,"aria-label":`${f?`展开`:`折叠`}工作区 ${e.name}`,onClick:()=>ae(t=>({...t,[e.id]:!t[e.id]})),children:(0,m.jsx)(`span`,{className:`chevron-folder`,"aria-hidden":`true`,children:f?`▸`:`▾`})}),(0,m.jsx)(`button`,{type:`button`,className:`workspace-toggle`,"aria-label":e.name,"aria-describedby":h?`workspace-name-warning-${e.id}`:void 0,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();Lr({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{Rn(e.id);let t=wi.find(t=>t.workspaceId===e.id)?.id;t?(t!==z?.id||R!==`session`||!Ma)&&Pa(t):Ia(e.id)},children:(0,m.jsxs)(`span`,{children:[(0,m.jsxs)(`span`,{className:`workspace-name-line`,children:[(0,m.jsx)(`strong`,{onDoubleClick:()=>Ll(`workspace`,e.id),children:e.name}),h&&(0,m.jsx)(`small`,{id:`workspace-name-warning-${e.id}`,className:`workspace-name-warning`,"data-workspace-name-warning":e.id,title:`请重命名其中一个工作区;名称唯一后提示会自动消失。`,children:`存在同名,易混淆`})]}),(0,m.jsx)(`small`,{children:e.path})]})}),(0,m.jsx)(`button`,{className:`workspace-add`,disabled:e.id.startsWith(`pending:`),title:`在此工作区新建会话`,onClick:t=>{Rn(e.id),Ve.current=t.currentTarget,ze({workspaceId:e.id})},children:`+`}),(0,m.jsx)(`button`,{type:`button`,className:`workspace-group-chat`,"data-open-group-chat":e.id,disabled:e.id.startsWith(`pending:`),title:`新建群聊`,"aria-label":`在 ${e.name} 新建群聊`,onClick:()=>{Rn(e.id),La(e.id)},children:(0,m.jsx)(vi,{name:`group-add`})}),(0,m.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>Wl(e.id),children:`⚙`})]})}),!f&&r.map(t=>{let n=v(t.id),r=hr(t,dt[t.id]),i=gr(t,dt[t.id],Ke.current[lr({workspaceId:e.id,roomId:t.id})]),a=i===`completed`?`讨论已完成,有新回复未读`:i===`unread`?`有新回复未读`:xA[r];return(0,m.jsxs)(`div`,{className:`conversation-row group-room-row`,children:[(0,m.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),(0,m.jsxs)(`button`,{type:`button`,className:`conversation group-room-button${n?` selected`:``}`,"data-sidebar-group-chat":t.id,"aria-current":n?`true`:void 0,"aria-label":`打开群聊 ${t.title},${a}`,title:t.title,onClick:()=>{Rn(e.id),La(e.id,t.id)},children:[(0,m.jsx)(`i`,{className:`conversation-mark`,children:(0,m.jsx)(jA,{state:i,label:a})}),(0,m.jsx)(vi,{name:`group`}),(0,m.jsx)(`span`,{className:`group-room-title`,children:t.title})]}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-archive`,"data-archive-group":t.id,title:`归档群聊`,"aria-label":`归档群聊 ${t.title}`,disabled:pt.has(t.id),onClick:()=>void Ba(t,`archive`),children:(0,m.jsx)(vi,{name:`archive`})})]},t.id)}),!f&&n?.failed&&(0,m.jsx)(`button`,{type:`button`,className:`group-rooms-retry`,onClick:st,children:`重试载入群聊`}),!f&&(s.length?s.map(({conversation:t,depth:n,childCount:r,isLastSibling:i})=>(0,m.jsxs)(`div`,{className:`conversation-row`,style:{"--tree-depth":n},"data-session-root":n===0?t.id:void 0,"data-session-dragging":zt?.conversationId===t.id?`true`:void 0,"data-session-drop":zt?.dropRootId===t.id?zt.dropAfter?`after`:`before`:void 0,onPointerDown:n===0?n=>Ut(n,e.id,t.id,c):void 0,children:[r>0?(0,m.jsxs)(`button`,{type:`button`,className:`conversation-tree-toggle`,"data-tree-toggle":t.id,"aria-expanded":!ki.has(t.id),title:ki.has(t.id)?`展开 ${r} 个子会话`:`折叠 ${r} 个子会话`,"aria-label":ki.has(t.id)?`展开会话 ${t.title} 的 ${r} 个子会话`:`折叠会话 ${t.title} 的 ${r} 个子会话`,onClick:()=>ou(t.id,!ki.has(t.id)),children:[(0,m.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:ki.has(t.id)?`▸`:`▾`}),(0,m.jsx)(`small`,{children:r})]}):(0,m.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),zl(`conversation`,t.id)?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(pA,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>Bl(`conversation`,t.id,e),onClose:Rl}),(0,m.jsx)(`small`,{className:`conversation-time`,children:Ck(t.updatedAt,Si)})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{className:`conversation ${!Va&&z?.id===t.id?`selected`:``}`,"data-conversation":t.id,"aria-current":!Va&&z?.id===t.id?`true`:void 0,"data-tree-child":n>0?`true`:void 0,"data-tree-last":n>0&&i?`true`:void 0,title:n>0?`${t.title}(由「${o.find(e=>e.id===t.parentConversationId)?.title??`已不存在的会话`}」创建)`:t.title,"aria-label":`打开会话 ${t.title}${NA(t,Nu.get(t.id))}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();Vr({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{t.id===Ht.current&&Date.now()-Vt.current<300||(Rn(e.id),Pa(t.id),N(e.id),jn(!1))},onDoubleClick:()=>{Fa(t.id)},children:[(0,m.jsx)(`i`,{className:`conversation-mark`,children:(0,m.jsx)(jA,{state:kA(t,DA(t,xn),Ke.current[t.id],O.conversations)})}),(0,m.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:e=>{e.stopPropagation(),Ll(`conversation`,t.id)},style:{flex:`0 1 auto`,minWidth:`3.5em`},children:t.title}),(0,m.jsx)(`span`,{className:`conversation-title-gap`,"aria-hidden":`true`,style:{marginLeft:`-8px`}}),AA(kA(t,DA(t,xn),Ke.current[t.id],O.conversations),OA(t,O.conversations,Ke.current[t.id])),MA(t,Nu.get(t.id)),(0,m.jsx)(`small`,{children:Ck(t.updatedAt,Si)})]}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":ku===t.id?`pending`:`idle`,disabled:!!ku,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>ju(t.id),children:`⑂`}),!(t.parentConversationId&&O.conversations.some(e=>e.id===t.parentConversationId))&&(0,m.jsx)(`button`,{className:`conversation-archive`,"data-archive-conversation":t.id,title:`归档整棵会话树`,"aria-label":`归档会话 ${t.title}`,onClick:()=>au(t.id),children:`×`})]})]},t.id)):!r.length&&(0,m.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!f&&d>0&&(0,m.jsxs)(`div`,{className:`archived-group`,"data-archived-count":d,children:[(0,m.jsxs)(`button`,{className:`archived-toggle`,title:p?`展开已归档`:`收起已归档`,"aria-expanded":!p,onClick:()=>It(t=>({...t,[e.id]:!p})),children:[(0,m.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:p?`▸`:`▾`}),(0,m.jsxs)(`span`,{className:`archived-label`,children:[`已归档 (`,d,`)`]})]}),!p&&u.map(({conversation:e,depth:t,isLastSibling:n})=>{let r=wk(l,e.id).length-1,i=!!(e.parentConversationId&&O.conversations.some(t=>t.id===e.parentConversationId&&t.archivedAt));return(0,m.jsxs)(`div`,{className:`conversation-archived`,"data-archived-conversation":e.id,"data-archived-at":e.archivedAt,"data-tree-child":t>0?`true`:void 0,"data-tree-last":t>0&&n?`true`:void 0,style:{"--tree-depth":t},children:[(0,m.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,m.jsx)(`span`,{"data-archived-title":e.id,children:e.title}),MA(e,Nu.get(e.id)),(0,m.jsx)(`small`,{children:Tk(e.archivedAt)}),!i&&(0,m.jsx)(`button`,{className:`conversation-restore`,"data-restore-conversation":e.id,title:r?`恢复这个会话和它的 ${r} 个子孙会话`:`恢复为正常会话`,"aria-label":r?`恢复会话 ${e.title} 及其 ${r} 个子孙会话`:`恢复会话 ${e.title}`,onClick:()=>su(e.id),children:`↑`})]},e.id)}),!p&&i.map(t=>{let n=v(t.id),r=pt.has(t.id);return(0,m.jsxs)(`div`,{className:`conversation-row group-room-row group-room-history`,"data-archived-group":t.id,children:[(0,m.jsxs)(`button`,{type:`button`,className:`conversation group-room-button${n?` selected`:``}`,"data-open-archived-group":t.id,"aria-current":n?`true`:void 0,"aria-label":`查看已归档群聊 ${t.title}`,title:t.title,onClick:()=>La(e.id,t.id),children:[(0,m.jsx)(vi,{name:`group`}),(0,m.jsx)(`span`,{className:`group-room-title`,children:t.title})]}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-restore`,"data-restore-group":t.id,title:`恢复群聊`,"aria-label":`恢复群聊 ${t.title}`,disabled:r,onClick:()=>void Ba(t,`restore`),children:`↑`}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-restore`,"data-delete-group":t.id,title:`永久删除群聊`,"aria-label":`永久删除群聊 ${t.title}`,disabled:r,onClick:()=>void Ba(t,`delete`),children:(0,m.jsx)(vi,{name:`delete`})})]},t.id)})]}),!f&&(()=>{let t=O.warmSessions?.filter(t=>t.workspaceId===e.id)??[];return t.length?(0,m.jsxs)(`details`,{className:`archived-group`,"data-warm-sessions":e.id,children:[(0,m.jsx)(`summary`,{className:`archived-toggle`,children:(0,m.jsxs)(`span`,{className:`archived-label`,children:[`预热会话 (`,t.length,`)`]})}),t.map(e=>(0,m.jsxs)(`div`,{className:`conversation-archived`,"data-warm-session":e.id,children:[(0,m.jsx)(`span`,{title:e.title,children:e.title}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-restore`,"aria-label":`移除预热会话 ${e.title}`,onClick:()=>{window.confirm(`移除预热会话「${e.title}」?`)&&!kc({type:`conversation.warm.delete`,conversationId:e.id})&&Sc(`连接断开,未移除预热会话`,`error`)},children:`×`})]},e.id))]}):null})()]},e.id)})}),(0,m.jsx)(Ai,{active:Vo}),xr&&(0,m.jsxs)(`footer`,{className:`workbench-mobile-utilities`,children:[(0,m.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-mobile-workbench-search":!0,"aria-label":`搜索`,title:`搜索`,onClick:()=>rs(`content`),children:(0,m.jsx)(vi,{name:`search`})}),Pu]})]}),(0,m.jsx)(ji,{view:`search`,children:(0,m.jsx)(Mi,{id:`search`,header:!1,children:(0,m.jsx)(`section`,{className:`workbench-search-panel`,"data-workbench-search-panel":!0,"aria-label":`侧栏搜索`,children:(0,m.jsx)(ng,{workspaceId:Ua,workspaceName:hc?.name,cwd:Ka,connected:te,dirtyPaths:V.open.filter(e=>e.dirty).map(e=>e.path),active:zo(nr.hostView(`search`)),onOpen:(e,t,n)=>Ms(e,t,!1,!0,!1,n),onSession:ss},Qo)})})}),!xr&&!er.leftClosed&&Mo&&Mo!==`sessions`&&(0,m.jsx)(UA,{...Lu,side:`left`,activeTab:Mo,collapsed:!1,onToggle:od,pinned:!er.unpinned.includes(Mo),onArrange:Xo}),(xr||!er.leftClosed)&&(0,m.jsx)(Oj,{side:`left`,width:ar.sidebar,min:ar.sidebarMin,max:ar.sidebarMax,label:`调整左侧栏宽度`,onWidth:or}),(0,m.jsx)(`div`,{className:`workbench-main`,children:(0,m.jsxs)(`div`,{className:`workbench-main-panes`,"data-workbench-split":oo,style:{"--split-share":`${$a}%`},children:[(0,m.jsxs)(`section`,{className:`chat`,"data-main-view":bs,"data-main-view-kind":bs,children:[td.length>0&&(0,m.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":Aa.length,"data-file-count":V.open.length,children:(0,m.jsx)(dg,{tabs:($s?td.filter(e=>e.id!==$s.id):td).map(e=>I.connections.length>1&&e.workspaceId?{...e,label:`${e.label} · ${be(e.workspaceId)}`,title:`${be(e.workspaceId)} · ${e.title??e.label}`}:e),prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:Y,onSelect:Vs,onClose:rc,onActivate:Zs,minWidth:120,maxWidth:320})}),(0,m.jsxs)(`header`,{children:[(0,m.jsx)(`button`,{type:`button`,className:`mobile-drawer-toggle`,"data-mobile-drawer-toggle":`1`,"aria-label":`打开会话列表`,title:`会话列表`,"aria-expanded":An,onClick:()=>jn(!0),children:`☰`}),(0,m.jsxs)(`div`,{className:`chat-head`,children:[(0,m.jsx)(`h1`,{children:R===`group`?gt?vt??`群聊`:`新建群聊`:z?.title??`准备开始`}),R!==`group`&&pl.size>0?[...pl].map(([e,t])=>(0,m.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):null]}),(0,m.jsxs)(`div`,{className:`workbench-history-controls`,role:`group`,"aria-label":`主区导航`,"aria-busy":!!Oe,"data-workbench-history":qs>=0||Js>=0?`available`:`empty`,children:[z&&R!==`group`&&(0,m.jsx)(ak,{id:z.id,expanded:Bo,onClick:()=>Wo(`rsi`,!0)}),z&&R!==`group`&&(0,m.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-session-actions":!0,title:`会话操作`,"aria-label":`会话操作`,"aria-haspopup":`dialog`,"aria-expanded":cc===`session`,"data-session-reload":d.some(e=>e.key===`reload:${z.id}`)?`running`:`idle`,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`session`?void 0:`session`)},children:d.some(e=>e.key===`reload:${z.id}`)?(0,m.jsx)(`span`,{className:`context-status-spinner`,"aria-label":`正在重新加载资源`}):`⋯`}),(0,m.jsx)(`button`,{type:`button`,"data-workbench-history-back":!0,"aria-label":`后退`,className:`workbench-icon-button`,title:qs<0?`后退`:`后退到 ${Ce.entries[qs].title}`,disabled:qs<0,onClick:()=>Ys(-1),children:(0,m.jsx)(vi,{name:`back`})}),(0,m.jsx)(`button`,{type:`button`,"data-workbench-history-forward":!0,"aria-label":`前进`,className:`workbench-icon-button`,title:Js<0?`前进`:`前进到 ${Ce.entries[Js].title}`,disabled:Js<0,onClick:()=>Ys(1),children:(0,m.jsx)(vi,{name:`forward`})}),Ua&&(0,m.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-toggle-workbench-split":!0,"aria-pressed":oo,"aria-label":oo?`合并主区`:`拆分主区`,title:oo?`合并主区`:`拆分主区`,onClick:tc,children:(0,m.jsx)(vi,{name:`split`})})]}),bn.entry(`workbench-status-button software-update-mobile`),(0,m.jsxs)(`span`,{className:`chat-view chat-view-${bs}`,"data-main-view-indicator":bs,"data-main-view-kind":bs,title:R===`file`?`中间主画面正在显示文件 ${V.active?.path??``}`:bs===`diff`?`中间主画面正在显示 ${xs??``} 的改动`:`中间主画面正在显示这个会话的消息流`,children:[(0,m.jsx)(`span`,{className:`chat-view-kind`,children:R===`group`?`群聊`:R===`file`?`文件`:bs===`diff`?`改动`:`会话`}),R===`file`&&V.active&&(0,m.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":V.active.name,children:V.active.name}),bs===`diff`&&xs&&(0,m.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":xs,children:xs})]}),!Va&&(0,m.jsx)(`div`,{className:`badge`,"data-workbench-header-status":Ki||z?.status===`failed`?`attention`:`routine`,"data-conversation-status":z?.status??`idle`,...Ki?{"data-reporting-status":Ki}:{},children:z?.compaction?.status===`running`?`压缩中`:Ki===`awaiting_decision`?`等上面拍板`:wA(z)?CA[z?.status??`idle`]:Ki===`awaiting_subordinates`?`等待下级`:Ki===`pending_report`?`待汇报`:CA[z?.status??`idle`]}),(0,m.jsx)(`button`,{type:`button`,className:`mobile-tools-toggle`,"data-mobile-nav":`rail`,onClick:()=>{En(`rail`),wn(!1)},children:`工具`})]}),ne&&(0,m.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,m.jsx)(`span`,{title:Br(ne),children:zr(ne)}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>re(void 0),children:`×`})]}),!Va&&z?.error&&(0,m.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,title:Br(z.error),children:zr(z.error)}),z?.warning&&(0,m.jsxs)(`div`,{className:`warning`,role:`status`,"data-role":`conversation-warning`,title:Br(z.warning),children:[(0,m.jsx)(`span`,{children:z.warning}),(0,m.jsx)(`button`,{type:`button`,"data-role":`conversation-warning-continue`,title:`让模型继续完成当前任务`,onClick:()=>Fc(z?.id??``),children:`继续任务`})]}),!Va&&z?.modelNotice&&(0,m.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-model-notice`,children:z.modelNotice}),z?.agentNotice&&(0,m.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-agent-notice`,children:z.agentNotice}),hl&&(0,m.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,hl]}),Qt.length>0&&(0,m.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":Qt.length,children:Qt.map(e=>(0,m.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),R===`group`?hc?(0,m.jsx)(CD,{workspaceId:ht,roomId:gt,onOpenRsi:()=>Wo(`rsi`,!0),rsiActive:Bo,sourceLink:Cc(ht),composerResize:pr===null?void 0:(0,m.jsx)(Fj,{height:pr,onHeight:br}),onEnableNotifications:()=>Tc(!0),agents:un?.agents??[],catalog:Xc(en,hc),userLabel:qt,archivedAt:_t?.archivedAt,restoring:pt.has(gt),onRestore:e=>void Ba(e,`restore`),onRoomSeen:ct,onRoomRead:ea,onRoomMissing:za,onCreated:Ra,onCancelCreate:()=>Ye&&rc(lr(Ye))},Ye&&lr(Ye)):(0,m.jsx)(`div`,{className:`group-empty`,children:Me?`这个群聊的工作区已不可用。`:`正在加载工作区…`}):R===`file`?_c(ic,!0):ys?vc(ys):R===`diff`?yc(us,!1):(0,m.jsxs)(m.Fragment,{children:[z&&Ma&&(0,m.jsx)(sg,{container:yt,onNavigate:e=>{Et.current=!0,ta(e,!0)}},z.id),(0,m.jsxs)(`div`,{className:`messages`,ref:yt,"data-message-scroll-container":z?.id??``,onWheel:e=>{e.deltaY<0&&Ue.current[z?.id??``]?.followTail&&(Et.current=!0,ta(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:ta(t)},children:[(!z||!Ma)&&(0,m.jsxs)(`div`,{className:`empty`,"data-workspace-welcome":Yi?.id,children:[(0,m.jsx)(`div`,{className:`orb`,children:`π`}),(0,m.jsx)(`h2`,{children:Yi?.name??`开始一个新会话`}),O.workspaces.length===0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,m.jsx)(`button`,{onClick:()=>Le(!0),children:`+ 新建工作区`})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{children:Yi?`暂无活跃会话。你可以创建会话,也可以直接使用资源管理器、Git 和终端。`:O.workspaces.length===1&&Ji?`在「${Ji.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),Yi&&(0,m.jsx)(`p`,{className:`workspace-welcome-path`,title:Yi.path,children:Yi.path}),O.workspaces.length>1&&(0,m.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,m.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,m.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:Ji?.id,onChange:e=>{e.target.value===`__new__`?Le(!0):Ia(e.target.value)},children:[(0,m.jsx)(Bn,{workspaces:O.workspaces}),(0,m.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),Ji&&(0,m.jsxs)(m.Fragment,{children:[!Xi&&(0,m.jsx)(Lk,{workspaceId:Ji.id,value:Zi,onChange:Qi}),(0,m.jsx)(`button`,{"data-workspace-welcome-create":Yi?`1`:void 0,disabled:Xi||!te,onClick:()=>iu(Ji.id,Zi),children:Xi?`正在创建工作区…`:`新建会话`})]}),(0,m.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>Le(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),Le(!0))},children:`+ 新建工作区`})]})]}),z?.messagesLoaded===!1&&(0,m.jsx)(`p`,{role:`status`,"data-conversation-loading":`1`,children:`正在加载会话…`}),Cl.map(e=>{if(e.startsWith(`m:`)){let t=bl.get(e.slice(2));if(!t||t.batchedInto)return null;if(t.backgroundBatch?.length)return(0,m.jsx)(k,{message:t,onOpenFile:e=>{Ms({path:e,name:e.split(/[/\\]/).at(-1)||e,text:!0})},onOpenSession:e=>{wi.some(t=>t.id===e)?Ac(e):Sc(`子会话已不可用。`,`info`)}},e);let n=t.id===wl,r=t.role===`user`&&z?.status!==`running`&&z?.status!==`waiting`&&xu!==t.id,i=r&&n&&!t.id.startsWith(`pending:`),a=r&&!n&&!!t.piEntryId,o=t.content?(0,m.jsx)(ep,{source:t.content,media:Ni,sourceLink:wc}):(0,m.jsx)(`span`,{className:`typing`,children:`正在思考`});if(t.source===`session-reminder`)return(0,m.jsx)(`article`,{className:`message message-reminder`,"data-transcript-key":e,"data-message-reminder":t.id,children:(0,m.jsxs)(`details`,{children:[(0,m.jsxs)(`summary`,{className:`reminder-header`,children:[(0,m.jsxs)(`span`,{className:`reminder-label`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`◷`}),` 定时提醒`]}),(0,m.jsx)(`time`,{dateTime:t.createdAt,children:gk(t.createdAt)})]}),(0,m.jsx)(`div`,{className:`content`,children:o})]})},e);let s=t.toolCalls??[],c=wu?.id===t.id?wu.kind:void 0;if(t.role===`user`){let n=t.content||(t.images?.length?`[图片]`:``),r=eA(t.content,t.attachments);return(0,m.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsxs)(`div`,{className:`bubble`,children:[(0,m.jsxs)(`div`,{className:`meta`,children:[qt,(0,m.jsx)(`time`,{children:gk(t.createdAt)})]}),t.images&&t.images.length>0&&(0,m.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>ni({url:Fe(`/api/upload/${encodeURIComponent(z?.id??``)}/${encodeURIComponent(e.id)}`),name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,m.jsx)(`img`,{src:Fe(`/api/upload/${encodeURIComponent(z?.id??``)}/${encodeURIComponent(e.id)}`),alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,m.jsx)(`div`,{className:`content`,children:o})]}),r.length>0&&(0,m.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:r.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=wr[n]??!1;return(0,m.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,m.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>Tr(e=>({...e,[n]:!r})),children:[(0,m.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,m.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,m.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,m.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,m.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,m.jsxs)(`div`,{className:`message-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":c,"aria-label":`复制这条消息:${n}`,onClick:()=>Ou(t.id,n),children:c===`copied`?`已复制`:c===`error`?`复制失败`:`复制`}),i&&(0,m.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>Cu(t.id,!0),children:`撤回`}),a&&(0,m.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退并编辑:删除这条消息及后续全部对话,将原消息恢复到输入框`,onClick:()=>Cu(t.id),children:`回退`})]})]}),(0,m.jsx)(`div`,{className:`avatar`,title:qt,children:qt})]},e)}if(t.role===`tool`){let n=HO(t.content),r=n!==void 0,i=/<task id="[^"]+" state="[^"]+"/.test(t.content),a=(()=>{if(r)return`模型不完整输出后的自动恢复`;let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():i?`后台回传`:(t.content.split(`
|
|
348
|
+
如需本地计算,声明 script: { path, timeoutMs, parameters }。脚本必须是 Python,参数以 JSON 从 stdin 传入,stdout 必须只输出一个 JSON 对象。在 index.html 中加载 <script src="./super-pi-tool.js"><\/script>,然后调用 SuperPiTool.run(params)、SuperPiTool.get(runId)、SuperPiTool.wait(runId) 或 SuperPiTool.cancel(runId)。这些都是已绑定本工具身份的相对接口;不要调用 /api/exec,不要猜测 toolId,也不要传 shell 命令、任意文件路径或未声明参数。页面必须实际执行一次示例任务并显示运行状态、日志和结构化结果。第三方包写进 environment.requires(必须钉死成 pkg==version),首次运行时会装进这个工具自己的虚拟环境。需要模型能力(摘要、改写、抽取、分类)时调用 SuperPiTool.llm({ prompt, system }),不要自己写模型客户端或保管密钥,并在注册时声明 permissions: { llm: true }——否则服务端会拒绝,导入页面也会提示用户。最后返回注册 id、访问地址、文件清单和验证结果。`);d(e),window.setTimeout(()=>d(!1),1800)};(0,p.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]);let ae=(0,p.useMemo)(()=>[...t.map(e=>({id:e.id,name:e.name,glyph:e.glyph})),...n.map(e=>({id:e.id,name:e.name,glyph:PD(e)}))],[t,n]);(0,p.useEffect)(()=>{if(!N)return;let e=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),P(void 0);return}if(ZD(e.key)||oO(e.target))return;e.preventDefault(),e.stopPropagation();let t=N;if(P(void 0),e.key===`Delete`||e.key===`Backspace`){OO.clearShortcut(t).then(e=>I(e));return}let n=QD(e);if(!n){I(`没有认出这个按键,换一个试试。`);return}let i=iO(n);if(!i.ok){I(i.reason);return}let a=uO(r,n,t);if(a){let e=ae.find(e=>e.id===a)?.name;I(e?`这个组合键已经被「${e}」占用了,换一个键。`:`这个组合键已经被另一个工具占用了,换一个键。`)}else OO.setShortcut(t,n).then(e=>I(e))};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[N,r,ae]);let oe=e=>{re(bO(e,window.innerWidth,window.innerHeight))},se=e=>{yO(e)},ce=()=>{re(void 0),yO(void 0)},le=(0,p.useRef)(!1),ue=n.map(e=>e.slug).filter(e=>typeof e==`string`),de=e=>{h(void 0),_(void 0),j(void 0),k({tool:e,name:RO({slug:e.slug??`tool`})})},fe=async(e,t)=>{h(void 0),_(void 0),j(void 0);let n=zO(t);if(!n.ok)j(n.reason);else try{let t=await Ie(`/api/tools/export?id=${encodeURIComponent(e.id)}`),r=await t.json();if(!t.ok||!r.bundle)throw Error(r.error??`HTTP ${t.status}`);let i=new Blob([JSON.stringify(r.bundle,null,2)],{type:`application/json`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=n.name,document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(a),_(r.skipped?.length?`已导出「${e.name}」,但有 ${r.skipped.length} 个文件没有包含:${r.skipped.join(`、`)}。`:`已导出「${e.name}」。`)}catch(e){h(`导出失败:${zr(e)}`)}finally{k(void 0)}},pe=async e=>{let t=e.target.files?.[0];if(e.target.value=``,!t)return;h(void 0),_(void 0),C(void 0);let n=FO(await t.text(),t.name);n.ok?(y({filename:t.name,bundle:n.bundle,unnamedFormat:n.unnamedFormat}),x(ue.includes(n.bundle.slug)?LO(n.bundle.slug,ue):n.bundle.slug),T(n.bundle.files[0]?.path)):h(n.reason)},L=()=>{y(void 0),x(``),C(void 0),T(void 0)},me=async()=>{if(!v)return;C(void 0);let e=IO(b);if(!e.ok)C(e.reason);else if(ue.includes(e.slug))C(`本机已经有 slug「${e.slug}」的工具,换一个名字再导入。`);else{D(!0);try{let t=await Ie(`/api/tools`,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(WO(v.bundle,e.slug))}),n=await t.json();if(!t.ok||!n.id)throw Error(n.error??`HTTP ${t.status}`);await kO(),_(`已导入「${v.bundle.name}」,它现在出现在工具栏里,所有工作区都能用。`),L()}catch(e){h(`导入失败:${zr(e)}`)}finally{D(!1)}}};(0,p.useEffect)(()=>{O&&M.current?.scrollIntoView({block:`center`})},[O]);let he=()=>{let e=Qt(i);e.ok?t.length>=32?l(`工具最多 32 个,先删掉一个再加。`):(OO.setTools([...t,{id:nn(`link`,t.map(e=>e.id)),kind:`link`,name:o.trim()||nj(e.url),glyph:`↗`,url:e.url}]),a(``),s(``),l(void 0)):l(e.reason)},ge=ne?{width:`${ne.width}px`,height:`${ne.height}px`,maxWidth:`calc(100vw - 32px)`,maxHeight:`calc(100vh - 32px)`}:void 0;return(0,Ve.createPortal)((0,m.jsxs)(`div`,{className:`tool-overlay`,"data-tool-settings-overlay":`1`,onPointerDown:()=>{le.current=!1},onClick:t=>{le.current?le.current=!1:t.target===t.currentTarget&&e()},children:[(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-settings-title`,"data-tool-settings":`1`,ref:te,style:ge,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsx)(`h2`,{className:`tool-dialog-title`,id:`tool-settings-title`,children:`⚙ 工具设置`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-settings-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭工具设置`,onClick:e,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body`,children:v?(0,m.jsx)(tj,{pending:v,slugDraft:b,slugError:S,preview:w,busy:E,onSlugChange:e=>{x(e),C(void 0)},onPreviewChange:T,onCancel:L,onConfirm:()=>void me()}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`div`,{className:`tool-prompt-card`,children:[(0,m.jsx)(`strong`,{children:`直接描述你要的工具`}),(0,m.jsx)(`p`,{className:`tool-hint`,children:`告诉 Super Pi Agent 你要创建什么,它会使用内置开发技能和 tool_register 完成注册。复制提示词仅作为备用入口。`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-development-prompt":`1`,onClick:()=>void ie(),children:u?`已复制`:`复制备用提示词`})]}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`从预置列表添加`})}),(0,m.jsx)(`div`,{className:`tool-presets`,"data-tool-presets":Kt.length,children:Kt.map(e=>{let n=t.some(t=>t.kind===e.kind);return(0,m.jsxs)(`div`,{className:`tool-preset`,"data-tool-preset":e.kind,children:[(0,m.jsx)(MD,{className:`tool-preset-glyph`,glyph:e.glyph}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.jsx)(`small`,{children:e.blurb})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-add-preset":e.kind,disabled:n,title:n?`${e.name}已经在工具栏里了`:`添加${e.name}`,"aria-label":n?`${e.name}已添加`:`添加${e.name}`,onClick:()=>OO.setTools(rn(t,e.kind)),children:n?`已添加`:`添加`})]},e.kind)})}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`添加网址工具`})}),(0,m.jsx)(`p`,{className:`tool-hint`,children:`填一个网址,它会变成一个图标;点开后在弹窗里用按钮在新标签页打开。网址只接受 http / https / mailto。`}),(0,m.jsx)(`input`,{className:`tool-input`,"data-tool-url-input":`1`,value:i,maxLength:2048,placeholder:`https://example.com/工具`,"aria-label":`工具网址`,onChange:e=>{a(e.target.value),l(void 0)}}),(0,m.jsx)(`input`,{className:`tool-input`,"data-tool-url-name":`1`,value:o,maxLength:40,placeholder:`名称(可留空,默认用域名)`,"aria-label":`工具名称(可选)`,onChange:e=>s(e.target.value)}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-url-add":`1`,disabled:!i.trim(),onClick:he,children:`添加网址工具`}),c&&(0,m.jsx)(`p`,{className:`tool-error`,"data-tool-error":`1`,role:`alert`,children:c}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-scope-note":`1`,children:[`能自定义到哪:从上面挑预置工具,或自己填一个网址。`,(0,m.jsx)(`b`,{children:`没有开放「写一段脚本来执行」这一档`}),`——它在浏览器里等同于任意代码执行,会拿着本应用的权限跑。计算器是手写的算术解析器,不含 eval,也认不出变量名。`]}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`快捷键`})}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-shortcut-hint":`1`,children:[`给每个工具绑一个组合键,按下就直接打开它,不用先找到右侧栏。`,(0,m.jsx)(`b`,{children:`弹窗打开时快捷键不生效`}),`——模态弹窗期间键盘归它自己,关掉之后再按。`]}),(0,m.jsx)(`div`,{className:`tool-shortcuts`,"data-tool-shortcut-count":ae.length,children:ae.map(e=>(0,m.jsxs)(`div`,{className:`tool-shortcut-row`,"data-tool-shortcut-row":e.id,children:[(0,m.jsx)(MD,{className:`tool-preset-glyph`,glyph:e.glyph}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.jsx)(`small`,{children:r[e.id]?`按 ${eO(r[e.id])} 打开`:`还没有快捷键`})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-shortcut-set`,"data-tool-shortcut-set":e.id,"data-tool-shortcut-capturing":N===e.id?`1`:void 0,"aria-pressed":N===e.id,title:N===e.id?`按下想用的组合键(Esc 取消,Delete 清除)`:`点一下,然后按下想用的组合键`,onClick:()=>{I(void 0),P(N===e.id?void 0:e.id)},children:N===e.id?`按下组合键…`:r[e.id]?eO(r[e.id]):`未设置`}),r[e.id]&&(0,m.jsx)(`button`,{type:`button`,className:`tool-shortcut-clear`,"data-tool-shortcut-clear":e.id,title:`清除${e.name}的快捷键`,"aria-label":`清除${e.name}的快捷键`,onClick:()=>{OO.clearShortcut(e.id),I(void 0),P(void 0)},children:`清除`})]},e.id))}),F&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-shortcut-error":`1`,children:F}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsxs)(`h2`,{className:`rail-section-title`,children:[`已安装的全局工具(`,n.length,`)`]})}),n.length===0?(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-mounted-empty":`1`,children:`还没有注册全局工具。直接告诉 Agent 你想做什么即可开始。`}):(0,m.jsx)(`div`,{className:`tool-presets`,"data-tool-mounted-list":n.length,children:n.map(e=>{let t=HO(e.environmentState);return(0,m.jsxs)(`div`,{className:`tool-share-row`,"data-tool-share-row":e.id,children:[(0,m.jsx)(MD,{className:`tool-preset-glyph`,glyph:PD(e)}),(0,m.jsxs)(`span`,{className:`tool-preset-text`,children:[(0,m.jsx)(`strong`,{children:e.name}),(0,m.jsx)(`small`,{"data-tool-env":e.environmentState?.state??`unknown`,children:t?`${t.warn?`⚠ `:``}${t.text}${e.environmentState?.detail?` · ${e.environmentState.detail}`:``}`:`环境未知`}),e.permissions?.llm&&(0,m.jsx)(`small`,{"data-tool-model":`1`,children:`⚠ 会调用模型`})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export":e.id,title:`导出${e.name},得到一个可以发给别人导入的文件`,"aria-label":`导出${e.name}`,onClick:()=>de(e),children:`导出`})]},e.id)})}),O&&(0,m.jsxs)(`div`,{className:`tool-share-review`,ref:M,"data-tool-export-name":`1`,children:[(0,m.jsxs)(`h3`,{className:`tool-share-title`,children:[`导出「`,O.tool.name,`」`]}),(0,m.jsxs)(`label`,{className:`tool-hint`,children:[`文件名(发给别人的就是这个文件)`,(0,m.jsx)(`input`,{className:`tool-input`,value:O.name,"aria-label":`导出文件名`,"data-tool-export-input":`1`,onChange:e=>k({...O,name:e.target.value})})]}),A&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-export-name-error":`1`,children:A}),(0,m.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-export-cancel":`1`,onClick:()=>{k(void 0),j(void 0)},children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-export-confirm":`1`,onClick:()=>void fe(O.tool,O.name),children:`导出`})]})]}),g&&(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-share-notice":`1`,children:g}),f&&(0,m.jsx)(`p`,{className:`tool-error`,"data-tool-share-error":`1`,role:`alert`,children:f}),(0,m.jsx)(`div`,{className:`rail-section-head`,children:(0,m.jsx)(`h2`,{className:`rail-section-title`,children:`从文件导入`})}),(0,m.jsxs)(`p`,{className:`tool-hint`,children:[`收到别人分享的工具文件(`,(0,m.jsx)(`code`,{children:jO}),`)?导入后它出现在工具栏里,所有工作区都能用。`,(0,m.jsx)(`b`,{children:`导入前会先给你看这个包里有什么。`})]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-pick":`1`,onClick:()=>ee.current?.click(),children:`选择文件…`}),(0,m.jsx)(`input`,{ref:ee,type:`file`,accept:`.json,application/json`,style:{display:`none`},"data-tool-import-input":`1`,onChange:e=>void pe(e)})]})})]}),(0,m.jsx)($A,{targetRef:te,onResize:oe,onCommit:se,onDragEnd:()=>{le.current=!0},onReset:ce})]}),document.body)}var QA=18;function $A({targetRef:e,onResize:t,onCommit:n,onDragEnd:r,onReset:i}){let[a,o]=(0,p.useState)(),s=(0,p.useRef)(void 0);return(0,p.useLayoutEffect)(()=>{let t=e.current;if(!t)return;let n=()=>{let e=t.getBoundingClientRect();o({left:e.right-QA,top:e.bottom-QA})};n();let r=new ResizeObserver(n);return r.observe(t),window.addEventListener(`resize`,n),window.addEventListener(`scroll`,n,!0),()=>{r.disconnect(),window.removeEventListener(`resize`,n),window.removeEventListener(`scroll`,n,!0)}},[e]),(0,m.jsx)(`div`,{className:`tool-dialog-grip`,"data-tool-settings-grip":`1`,role:`separator`,"aria-orientation":`vertical`,tabIndex:0,"aria-label":`调整工具设置弹窗大小:拖动或用方向键,Enter 恢复默认尺寸`,style:a?{left:`${a.left}px`,top:`${a.top}px`}:void 0,onPointerDown:i=>{i.preventDefault(),i.stopPropagation();let a=e.current;if(!a)return;let o=a.getBoundingClientRect(),c=o.left+o.width/2,l=o.top+o.height/2;s.current=void 0;let u=e=>{let n=bO({width:2*(e.clientX-c),height:2*(e.clientY-l)},window.innerWidth,window.innerHeight);s.current=n,t(n)},d=()=>{window.removeEventListener(`pointermove`,u),window.removeEventListener(`pointerup`,d),window.removeEventListener(`pointercancel`,d),s.current&&(n(s.current),r())};window.addEventListener(`pointermove`,u),window.addEventListener(`pointerup`,d),window.addEventListener(`pointercancel`,d)},onDoubleClick:()=>i(),onKeyDown:r=>{if(r.key===`Enter`||r.key===` `){r.preventDefault(),i();return}let a=r.shiftKey?8:24,o=e.current?.getBoundingClientRect(),c=o?.width??fO.width,l=o?.height??fO.height;if(r.key===`ArrowRight`)c+=a;else if(r.key===`ArrowLeft`)c-=a;else if(r.key===`ArrowDown`)l+=a;else if(r.key===`ArrowUp`)l-=a;else return;r.preventDefault();let u=bO({width:c,height:l},window.innerWidth,window.innerHeight);s.current=u,t(u),n(u)},onClick:e=>e.stopPropagation()})}function ej(){let{tools:e,mountedTools:t,openToolId:n,settingsOpen:r,shortcuts:i}=DO(),a=e.find(e=>e.id===n),o=t.find(e=>e.id===n);return(0,p.useEffect)(()=>{let n=n=>{if(!r&&!document.querySelector(`[aria-modal="true"]`)&&!(n.isComposing||n.defaultPrevented)){for(let[r,a]of Object.entries(i))if(sO(a,n)&&(e.some(e=>e.id===r)||t.some(e=>e.id===r))){n.preventDefault(),OO.openTool(r);return}}};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[i,e,t,r]),(0,p.useEffect)(()=>{kO();let e=()=>{kO()};return window.addEventListener(`super-pi-tools-updated`,e),window.addEventListener(`super-pi-active-server`,e),()=>{window.removeEventListener(`super-pi-tools-updated`,e),window.removeEventListener(`super-pi-active-server`,e)}},[]),(0,p.useEffect)(()=>{OO.persistTools()},[]),(0,m.jsxs)(m.Fragment,{children:[r&&(0,m.jsx)(ZA,{onClose:()=>OO.closeSettings()}),a&&(0,m.jsx)(rj,{tool:a,onClose:()=>OO.closeTool()}),o&&(0,m.jsx)(uj,{tool:o,onClose:()=>OO.closeTool()})]})}function tj({pending:e,slugDraft:t,slugError:n,preview:r,busy:i,onSlugChange:a,onPreviewChange:o,onCancel:s,onConfirm:c}){let l=e.bundle,u=l.files.reduce((e,t)=>e+new TextEncoder().encode(t.content).length,0),d=VO(l),f=BO(l),p=l.files.find(e=>e.path===r)??l.files[0];return(0,m.jsxs)(`div`,{className:`tool-share-review`,"data-tool-import-review":`1`,children:[(0,m.jsx)(`h3`,{className:`tool-share-title`,"data-tool-import-name":`1`,children:l.name}),l.description&&(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-import-desc":`1`,children:l.description}),e.unnamedFormat&&(0,m.jsx)(`p`,{className:`tool-import-note`,"data-tool-import-unbranded":`1`,children:`这个文件没有 Super Pi 的工具标记,已按内容形状读取——粘出来的 tool_register 参数也认。`}),(0,m.jsxs)(`p`,{className:`tool-hint`,"data-tool-import-files":`1`,children:[l.files.length,` 个文件 · 共 `,UO(u)]}),(0,m.jsx)(`p`,{className:`tool-hint`,"data-tool-import-paths":`1`,children:l.files.map(e=>e.path).join(` · `)}),l.script&&(0,m.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-script":l.script.path,children:[(0,m.jsxs)(`b`,{children:[`⚠ 含 Python 脚本 `,l.script.path]}),(0,m.jsx)(`br`,{}),`导入后运行这个工具时,这段代码会在本机上执行,权限和你自己的 Python 一样(能读你的文件、能联网)。 可以先展开下面的文件列表把它读完。`]}),(0,m.jsxs)(`p`,{className:d.tone===`warn`?`tool-import-warn`:`tool-import-note`,"data-tool-import-env":d.tone,children:[(0,m.jsxs)(`b`,{children:[d.tone===`warn`?`⚠ `:`✓ `,d.text]}),l.environment?.fingerprint?.python&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`br`,{}),`导出方环境:Python `,l.environment.fingerprint.python,` · `,l.environment.fingerprint.platform||`未知平台`,`。版本对不上时会标出来,但不会拦住你运行。`]})]}),f&&(0,m.jsxs)(`p`,{className:`tool-import-warn`,"data-tool-import-model":`1`,children:[(0,m.jsx)(`b`,{children:`⚠ 这个工具可以调用模型`}),(0,m.jsx)(`br`,{}),f.text,`。模型由 Super Pi 通过 Pi 调用(凭据和模型选择都在 Super Pi 这边),工具只拿到文字。`]}),(0,m.jsxs)(`details`,{className:`tool-import-files`,"data-tool-import-filebox":l.files.length,children:[(0,m.jsxs)(`summary`,{children:[`查看文件(`,l.files.length,`)`]}),(0,m.jsx)(`div`,{className:`tool-share-tabs`,children:l.files.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`tool-share-tab`,"aria-pressed":e.path===p?.path,"data-tool-import-file":e.path,onClick:()=>o(e.path),children:e.path},e.path))}),(0,m.jsx)(`pre`,{className:`tool-import-code`,"data-tool-import-code":p?.path,children:p?.content??``})]}),(0,m.jsxs)(`label`,{className:`tool-hint`,"data-tool-import-slug":`1`,children:[`导入后的 slug(工具的短名字,也是它在磁盘上的目录名)`,(0,m.jsx)(`input`,{className:`tool-input`,value:t,"aria-label":`导入后的 slug`,onChange:e=>a(e.target.value)})]}),n&&(0,m.jsx)(`p`,{className:`tool-error`,role:`alert`,"data-tool-import-slug-error":`1`,children:n}),(0,m.jsxs)(`div`,{className:`tool-share-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`tool-preset-add`,"data-tool-import-cancel":`1`,onClick:s,children:`取消`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-url-add`,"data-tool-import-confirm":`1`,disabled:i,onClick:c,children:i?`导入中…`:`导入`})]})]})}function nj(e){let t=e.replace(/^[./]+/,``).slice(0,30).trim();if(!/^[a-z][a-z0-9+.-]*:/i.test(e))return t||e.slice(0,30);try{return new URL(e,typeof window>`u`?`http://localhost`:window.location.href).hostname||t||e.slice(0,30)}catch{return e.slice(0,30)}}function rj({tool:e,onClose:t}){return(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]),(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`tool-dialog`,role:`dialog`,"aria-modal":`true`,"aria-labelledby":`tool-dialog-title`,"data-tool-dialog":e.id,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsxs)(`h2`,{className:`tool-dialog-title`,id:`tool-dialog-title`,children:[(0,m.jsx)(MD,{className:`tool-dialog-glyph`,glyph:e.glyph}),e.name]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,"data-tool-close":`1`,title:`关闭(Esc)`,"aria-label":`关闭${e.name}`,onClick:t,children:`✕`})]}),(0,m.jsxs)(`div`,{className:`tool-dialog-body`,children:[e.kind===`calculator`&&(0,m.jsx)(ij,{}),e.kind===`timestamp`&&(0,m.jsx)(aj,{}),e.kind===`link`&&(0,m.jsx)(oj,{tool:e})]})]})}),document.body)}function ij(){let[e,t]=(0,p.useState)(`12 * (3 + 4)`),n=vn(e),r=e=>{t(t=>t+e)};return(0,m.jsxs)(`div`,{className:`tool-calc`,"data-tool-calc":`1`,children:[(0,m.jsx)(`input`,{className:`tool-input tool-calc-input`,"data-calc-input":`1`,value:e,maxLength:200,"aria-label":`算式`,spellCheck:!1,autoComplete:`off`,placeholder:`例如 (12 + 8) / 4`,onChange:e=>{t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&e.preventDefault()}}),(0,m.jsx)(`div`,{className:`tool-calc-keys`,"data-calc-keys":`1`,children:[[`7`,`7`],[`8`,`8`],[`9`,`9`],[`÷`,`/`],[`(`,`(`],[`)`,`)`],[`4`,`4`],[`5`,`5`],[`6`,`6`],[`×`,`*`],[`^`,`^`],[`%`,`%`],[`1`,`1`],[`2`,`2`],[`3`,`3`],[`-`,`-`],[`←`,`back`],[`C`,`clear`],[`0`,`0`],[`.`,`.`],[`+`,`+`]].map(([e,n])=>(0,m.jsx)(`button`,{type:`button`,className:`tool-calc-key`,"data-calc-key":n,"aria-label":e===`C`?`清空`:e===`←`?`退格`:`输入 ${e}`,onClick:()=>{n===`clear`?t(``):n===`back`?t(e=>e.slice(0,-1)):r(n)},children:e},e))}),n.ok?(0,m.jsx)(`p`,{className:`tool-calc-result`,"data-calc-result":`1`,"data-calc-value":String(n.value),children:yn(n.value)}):(0,m.jsx)(`p`,{className:`tool-calc-error`,"data-calc-error":`1`,role:`alert`,children:n.reason})]})}function aj(){let[e,t]=(0,p.useState)(``),n=bn(e),r=n.ok?Sn(n.ms):null;return(0,m.jsxs)(`div`,{className:`tool-stamp`,"data-tool-stamp":`1`,children:[(0,m.jsx)(`input`,{className:`tool-input`,"data-stamp-input":`1`,value:e,maxLength:64,spellCheck:!1,"aria-label":`时间戳或日期`,placeholder:`1757000000 或 2026-10-08T09:00:00`,onChange:e=>t(e.target.value)}),r?(0,m.jsxs)(`dl`,{className:`tool-stamp-out`,"data-stamp-result":`1`,children:[(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`本地时间`}),(0,m.jsx)(`dd`,{"data-stamp-local":`1`,children:r.local})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`ISO(UTC)`}),(0,m.jsx)(`dd`,{"data-stamp-iso":`1`,children:r.iso})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`秒`}),(0,m.jsx)(`dd`,{"data-stamp-seconds":`1`,children:r.seconds})]}),(0,m.jsxs)(`div`,{children:[(0,m.jsx)(`dt`,{children:`毫秒`}),(0,m.jsx)(`dd`,{"data-stamp-ms":`1`,children:r.milliseconds})]})]}):(0,m.jsx)(`p`,{className:`tool-stamp-error`,"data-stamp-error":`1`,role:`alert`,children:n.ok?`这个日期无法显示。`:n.reason})]})}function oj({tool:e}){let[t,n]=(0,p.useState)(!1),r=async()=>{let e=await Hi(`请为 Super Pi 开发一个全局右侧栏工具并自动挂载。不要启动独立 HTTP 服务器。通过内置 tool_register 提交完整的 HTML/JS/CSS 文件;工具将被 Super Pi 保存并在所有 workspace 可用。如需计算,注册一个 Python 脚本(不接受 shell 命令),参数经 JSON stdin 传入,stdout 只输出 JSON 结果。在页面里加载 ./super-pi-tool.js,使用 SuperPiTool.run(params)、wait(runId)、get(runId) 和 cancel(runId) 执行、等待、查看和取消任务。它们会自动绑定当前工具;不要调用 /api/exec,也不要猜测 toolId。`);n(e),window.setTimeout(()=>n(!1),1800)};return(0,m.jsxs)(`div`,{className:`tool-link`,"data-tool-link":e.id,children:[(0,m.jsx)(`p`,{className:`tool-hint`,children:`这是旧版外部网页链接;新工具由 Super Pi 统一托管,并可选绑定受控 Python 脚本。`}),(0,m.jsx)(`code`,{className:`tool-link-url`,"data-tool-link-url":e.id,children:e.url}),(0,m.jsxs)(`div`,{className:`tool-link-actions`,children:[(0,m.jsx)(`a`,{className:`tool-link-open`,"data-tool-link-open":e.id,href:e.url,target:`_blank`,rel:`noopener noreferrer`,title:e.url,children:`在新标签页打开 ↗`}),(0,m.jsx)(`button`,{type:`button`,className:`tool-link-copy-prompt`,"data-tool-copy-prompt":e.id,onClick:()=>void r(),children:t?`已复制`:`复制开发 Prompt`})]}),/^https?:\/\//i.test(e.url??``)&&(0,m.jsx)(`iframe`,{className:`tool-link-frame`,"data-tool-frame":e.id,src:e.url,title:e.name,sandbox:`allow-forms allow-modals allow-pointer-lock allow-popups allow-same-origin allow-scripts`,referrerPolicy:`no-referrer`})]})}var sj=`(max-width: 1100px)`,cj=(e,t,n)=>Math.min(Math.max(e,t),Math.max(t,n));function lj(e){let t=`super-pi.mounted-tool.owner.`+e;try{let e=window.localStorage.getItem(t);if(e&&/^[0-9a-f]{32}$/.test(e))return e}catch{}let n=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``);try{window.localStorage.setItem(t,n)}catch{}return n}function uj({tool:e,onClose:t}){let n=(0,p.useRef)(null);(0,p.useEffect)(()=>{let e=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[t]);let r=(0,p.useMemo)(()=>lj(e.id),[e.id]);(0,p.useLayoutEffect)(()=>Wn(()=>n.current,e.id,r),[e.id,r]);let i=e.dialogSize??{width:1100,height:780},a={width:`min(${i.width}px, calc(100vw - 32px))`,height:`min(${i.height}px, calc(100dvh - 32px))`};return(0,Ve.createPortal)((0,m.jsx)(`div`,{className:`tool-overlay`,"data-mounted-tool-overlay":e.id,onClick:e=>{e.target===e.currentTarget&&t()},children:(0,m.jsxs)(`div`,{className:`tool-dialog mounted-tool-dialog`,style:a,"data-mounted-tool-dialog":e.id,role:`dialog`,"aria-modal":`true`,children:[(0,m.jsxs)(`div`,{className:`tool-dialog-head`,children:[(0,m.jsxs)(`h2`,{className:`tool-dialog-title`,children:[(0,m.jsx)(MD,{className:`tool-dialog-glyph`,glyph:PD(e)}),e.name]}),(0,m.jsx)(`button`,{type:`button`,className:`tool-dialog-close`,onClick:t,children:`✕`})]}),(0,m.jsx)(`div`,{className:`tool-dialog-body`,children:(0,m.jsx)(`iframe`,{ref:n,className:`tool-link-frame`,src:Fe(`/tools/${encodeURIComponent(e.id)}/#super-pi-owner=${r}`),title:e.name,sandbox:`allow-forms allow-modals allow-popups allow-scripts`,referrerPolicy:`no-referrer`})})]})}),document.body)}function dj(e,t,n){let r=Math.max(0,Math.round(n)-480),i=cj(520,180,Math.max(180,r-240)),a=cj(Math.round(e),180,i),o=cj(640,240,Math.max(240,r-a));return{sidebar:a,rail:cj(Math.round(t),240,o),sidebarMin:180,sidebarMax:i,railMin:240,railMax:o,sumCap:r}}var fj=`super-pi.rail-widths.v1`,pj=`super-pi.reader-state.v1`,mj=`super-pi.folded-groups.v1`;function hj(){try{if(typeof window>`u`)return{};let e=JSON.parse(window.localStorage.getItem(`super-pi.folded-groups.v1`)??`null`);if(!e||typeof e!=`object`)return{};let t=e=>{let t={};if(e&&typeof e==`object`)for(let[n,r]of Object.entries(e))typeof r==`boolean`&&(t[n]=r);return t};return{workspaces:t(e.workspaces),archived:t(e.archived)}}catch{return{}}}function gj(e){try{typeof window<`u`&&window.localStorage.setItem(mj,JSON.stringify(e))}catch{}}var _j=e=>{let t=document.querySelector(`[data-workspace-group="${CSS.escape(e)}"]`);return t?[...t.querySelectorAll(`.conversation-row[data-session-root]`)].map(e=>({id:e.dataset.sessionRoot??``,middle:(()=>{let t=e.getBoundingClientRect();return t.top+t.height/2})()})).filter(e=>e.id!==``):[]},vj=6,yj=400,bj=32,xj=48,Sj=e=>{e.dataset.programmaticScroll=`true`,window.setTimeout(()=>{delete e.dataset.programmaticScroll},0)};function Cj(e,t,n=!1,r=!1){let i=e.scrollHeight-e.clientHeight-e.scrollTop,a=n?!1:r?!0:t.followTail?i<=xj:i<=bj,o,s;if(!a){let t=e.getBoundingClientRect().top,n=[...e.querySelectorAll(`[data-transcript-key]`)].find(e=>e.getBoundingClientRect().bottom>t);o=n?.dataset.transcriptKey,s=n?n.getBoundingClientRect().top-t:void 0}return{followTail:a,scrollTop:e.scrollTop,...o?{anchorKey:o,anchorOffset:s}:{}}}function wj(){try{if(typeof window>`u`)return{conversations:{}};let e=JSON.parse(window.localStorage.getItem(`super-pi.reader-state.v1`)??`null`);if(!e||typeof e!=`object`)return{conversations:{}};let t={};if(e.conversations&&typeof e.conversations==`object`)for(let[n,r]of Object.entries(e.conversations)){let e=r;typeof e.followTail==`boolean`&&(t[n]={followTail:e.followTail,scrollTop:Number.isFinite(e.scrollTop)?Math.max(0,Number(e.scrollTop)):0,...typeof e.anchorKey==`string`?{anchorKey:e.anchorKey}:{},...Number.isFinite(e.anchorOffset)?{anchorOffset:Number(e.anchorOffset)}:{}})}let n={};if(e.readAt&&typeof e.readAt==`object`)for(let[t,r]of Object.entries(e.readAt))typeof r==`string`&&(n[t]=r);return{activeId:typeof e.activeId==`string`?e.activeId:void 0,workspaceId:typeof e.workspaceId==`string`?e.workspaceId:void 0,conversations:t,readAt:n}}catch{return{conversations:{}}}}function Tj(e){try{typeof window<`u`&&window.localStorage.setItem(pj,JSON.stringify(e))}catch{}}var Ej=`super-pi.session-tabs.v1`;function Dj(e,t){if(!t||e.has(t))return e;let n=new Set(e);return n.add(t),n}function Oj(e,t,n){let r=e.touched.has(t),i=e.touched;if(r){let r=new Set(e.touched);r.delete(t),n&&r.add(n),i=r}return{ids:e.ids.flatMap(e=>e===t?n?[n]:[]:[e]),previewId:e.previewId===t?n&&!r?n:void 0:e.previewId,emptied:e.emptied,touched:i}}function kj(){try{if(typeof window>`u`)return{ids:[]};let e=JSON.parse(Gn(`super-pi.session-tabs.v1`)??`null`);if(!e||typeof e!=`object`)return{ids:[]};let t=e,n=Array.isArray(t.ids)?[...new Set(t.ids.filter(e=>typeof e==`string`))]:[],r=Array.isArray(t.touched)?[...new Set(t.touched.filter(e=>typeof e==`string`))]:[],i=typeof t.previewId==`string`&&n.includes(t.previewId)&&!r.includes(t.previewId)?t.previewId:void 0;i&&i!==t.activeId&&(n=n.filter(e=>e!==i));let a=typeof t.activeId==`string`&&n.includes(t.activeId)?t.activeId:void 0,o=typeof t.workspaceLandingId==`string`?t.workspaceLandingId:void 0;return{ids:n,activeId:a,contextId:typeof t.contextId==`string`?t.contextId:void 0,workspaceLandingId:o,previewId:i===a?i:void 0,touched:r,emptied:n.length===0&&(t.emptied===!0||!!i),selectionCleared:t.selectionCleared===!0}}catch{return{ids:[]}}}function Aj(e,t,n,r=!1){try{if(typeof window>`u`)return;let{ids:i,previewId:a,touched:o,emptied:s}=e;Kn(Ej,JSON.stringify({ids:i,...t&&i.includes(t)?{activeId:t}:{},...t?{contextId:t}:{},...n?{workspaceLandingId:n}:{},...a&&i.includes(a)?{previewId:a}:{},...o.size?{touched:[...o]}:{},...s?{emptied:s}:{},...r?{selectionCleared:!0}:{}}))}catch{}}function jj(){try{if(typeof window>`u`)return{};let e=window.localStorage.getItem(fj);if(e===null)return{};let t=JSON.parse(e),n=e=>typeof e==`number`&&Number.isFinite(e)&&e>0?Math.round(e):void 0;return{sidebar:n(t.sidebar),rail:n(t.rail)}}catch{return{}}}function Mj(e){try{if(typeof window>`u`)return;window.localStorage.setItem(fj,JSON.stringify(e))}catch{}}function Nj({side:e,width:t,min:n,max:r,label:i,onWidth:a}){let[o,s]=(0,p.useState)(!1),c=e=>e.shiftKey?64:16;return(0,m.jsx)(`div`,{className:`rail-resizer rail-resizer-${e}${o?` rail-resizer-dragging`:``}`,"data-rail-resizer":e,"data-rail-resizer-dragging":o?`true`:`false`,"data-rail-resizer-width":t,role:`separator`,"aria-orientation":`vertical`,"aria-label":i,"aria-valuenow":t,"aria-valuemin":n,"aria-valuemax":r,tabIndex:0,onMouseDown:i=>{i.preventDefault(),i.currentTarget.focus();let o=i.clientX,c=t;s(!0);let l=document.body,u=l.style.cursor,d=l.style.userSelect;l.style.cursor=`col-resize`,l.style.userSelect=`none`;let f=t=>{let i=e===`left`?t.clientX-o:o-t.clientX;a(cj(c+i,n,r))},p=()=>{l.style.cursor=u,l.style.userSelect=d,s(!1),window.removeEventListener(`mousemove`,f),window.removeEventListener(`mouseup`,p)};window.addEventListener(`mousemove`,f),window.addEventListener(`mouseup`,p)},onKeyDown:i=>{let o=c(i);i.key===`ArrowLeft`?(i.preventDefault(),a(cj(e===`left`?t-o:t+o,n,r))):i.key===`ArrowRight`?(i.preventDefault(),a(cj(e===`left`?t+o:t-o,n,r))):i.key===`Home`?(i.preventDefault(),a(n)):i.key===`End`&&(i.preventDefault(),a(r))}})}var Pj=`super-pi.composer-height.v1`,Fj=148,Ij=.55,Lj=()=>Math.max(Fj,Math.round((typeof window>`u`?800:window.innerHeight)*Ij)),Rj=e=>{let t=Number.isFinite(e)?e:Fj;return Math.round(Math.min(Lj(),Math.max(Fj,t)))},zj=()=>{try{let e=window.localStorage.getItem(Pj);return e===null?Fj:Rj(Number(e))}catch{return Fj}};function Bj({height:e,onHeight:t}){let[n,r]=(0,p.useState)(!1),i=e=>e.shiftKey?64:16,a=Lj();return(0,m.jsx)(`div`,{className:`composer-resize${n?` composer-resize-dragging`:``}`,"data-composer-resize":`1`,"data-composer-resize-dragging":n?`true`:`false`,"data-composer-height":e,role:`separator`,"aria-orientation":`horizontal`,"aria-label":`调整消息编辑区高度`,"aria-valuenow":e,"aria-valuemin":Fj,"aria-valuemax":a,tabIndex:0,onMouseDown:n=>{n.preventDefault(),n.currentTarget.focus();let i=n.clientY,a=e;r(!0);let o=document.documentElement,s=document.body.style.userSelect;document.body.style.cursor=`ns-resize`,document.body.style.userSelect=`none`;let c=e=>{let t=Rj(a+(i-e.clientY));o.style.setProperty(`--composer-height`,`${t}px`)},l=()=>{document.body.style.cursor=``,document.body.style.userSelect=s;let n=Number.parseFloat(o.style.getPropertyValue(`--composer-height`));r(!1),window.removeEventListener(`mousemove`,c),window.removeEventListener(`mouseup`,l),t(Number.isFinite(n)?n:e)};window.addEventListener(`mousemove`,c),window.addEventListener(`mouseup`,l)},onKeyDown:n=>{let r=i(n);n.key===`ArrowUp`?(n.preventDefault(),t(Rj(e+r))):n.key===`ArrowDown`?(n.preventDefault(),t(Rj(e-r))):n.key===`Home`?(n.preventDefault(),t(Fj)):n.key===`End`?(n.preventDefault(),t(a)):n.key===`PageUp`?(n.preventDefault(),t(Rj(e+96))):n.key===`PageDown`&&(n.preventDefault(),t(Rj(e-96)))}})}function Vj(e,t,n){if(e=e.filter(e=>!e.groupExecution),!e.length)return;let r=n?e.find(e=>e.workspaceId===n):void 0;if(r)return r;if(!(n&&t.some(e=>e.id===n)))return n?e.find(e=>y(e.workspaceId).server===y(n).server):e[0]}function Hj(e,t,n){let r=n&&e?JSON.stringify([e,t,n]):void 0,[i,a]=(0,p.useState)();(0,p.useEffect)(()=>{if(!r||!n||!e)return;let i=new AbortController;return Ie(`/api/files/diff?${new URLSearchParams({workspaceId:e,path:n,...t?{cwd:t}:{}})}`,{signal:i.signal}).then(async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error??`HTTP ${e.status}`);return t}).then(e=>{i.signal.aborted||a({scope:r,diff:e,error:``})}).catch(e=>{i.signal.aborted||a({scope:r,diff:null,error:e instanceof Error?e.message:`读取差异失败`})}),()=>i.abort()},[r,e,t,n]);let o=i?.scope===r?i:void 0;return{diff:o?.diff??null,error:o?.error??``,loading:!!r&&!o}}function Uj(e){try{let t=`super-pi.browser-notification-events`,n=Date.now(),r=JSON.parse(window.localStorage.getItem(t)??`[]`).filter(e=>Array.isArray(e)&&typeof e[0]==`string`&&typeof e[1]==`number`&&n-e[1]<864e5);return!r.some(([t])=>t===e)&&(window.localStorage.setItem(t,JSON.stringify([...r.slice(-63),[e,n]])),!0)}catch{return!0}}function Wj(){let[e,t]=(0,p.useState)(pk),[n,r]=(0,p.useState)(()=>{try{return typeof window<`u`&&window.localStorage.getItem(`super-pi.browser-notifications`)===`enabled`}catch{return!1}}),[i,a]=(0,p.useState)(()=>eo()),o=(0,p.useCallback)(()=>a(eo()),[]),s=(0,p.useRef)(new Map),c=(0,p.useRef)(!1),l=(0,p.useRef)(new Map),u=(0,p.useCallback)(e=>{t(t=>{let n=typeof e==`function`?e(t):e;return jt(n,t)})},[]),[d,f]=(0,p.useState)(()=>xm().map(e=>{let t=new Date().toISOString();return{id:e.clientId,key:`send:${e.conversationId}:${e.clientId}`,serverId:L(e.conversationId),retry:!0,command:{...e},apply:n=>Tm(n,e,t),accepted:t=>!!t.conversations.find(t=>t.id===e.conversationId)?.messages.some(t=>t.id===wm(e))}})),g=(0,p.useRef)(d),_=(0,p.useRef)(null);_.current||=wj();let x=(0,p.useRef)(null);x.current||=kj();let S=x.current,C=(0,p.useRef)(null);C.current||=qn();let w={current:C.current},T=(0,p.useRef)(null);T.current||=Jn();let E=T.current,O=d.reduce((e,t)=>t.apply(e),e),A=E.view===`file`||E.view===`diff`||E.view===`gitDiff`,[j,ee]=(0,p.useState)(S.workspaceLandingId||S.selectionCleared?void 0:S.activeId??(A?S.contextId:void 0)??(S.emptied?void 0:_.current.activeId)),[M,N]=(0,p.useState)(S.workspaceLandingId??(S.selectionCleared?w.current.kind===`workspace`?w.current.workspaceId:void 0:_.current.workspaceId)),[P,F]=(0,p.useState)(!1),I=pe(),te=P&&I.statuses.get(I.activeServer)?.state===`online`,[ne,re]=(0,p.useState)(),[ie,ae]=(0,p.useState)(()=>hj().workspaces??{}),[se,ce]=(0,p.useState)(()=>({ids:S.ids,previewId:S.previewId,touched:new Set(S.touched??[]),emptied:S.emptied})),le=se.ids,ue=se.previewId,de=(0,p.useRef)(0),[fe,Se]=(0,p.useState)(),[Ce,we]=(0,p.useState)({entries:[],index:-1}),Te=(0,p.useRef)([]),[Ee,De]=(0,p.useState)(),[Oe,ke]=(0,p.useState)(),Ae=(0,p.useRef)(new Set),je=se.emptied===!0,[Me,Ne]=(0,p.useState)(!1),[Pe,Le]=(0,p.useState)(!1),[Re,ze]=(0,p.useState)(),Ve=(0,p.useRef)(null),He=(0,p.useRef)(void 0),Ue=(0,p.useRef)(_.current.conversations),Ge=(0,p.useRef)(le);Ge.current=le;let Ke=(0,p.useRef)(_.current.readAt??{}),[qe,Je]=(0,p.useState)(0),[Ye,Xe]=(0,p.useState)(sr),[Ze,nt]=(0,p.useState)(()=>E.groups.length?E.groups:Ye?[Ye]:[]),[rt,it]=(0,p.useState)(E.view?E.view===`group`:!!Ye),[R,at]=(0,p.useState)(()=>E.view??(Ye?`group`:`session`)),{index:ot,reload:st,remember:ct,forget:ut,activities:dt,recordActivity:ft}=_r(O.workspaces,te),[pt,mt]=(0,p.useState)(()=>new Set),ht=Ye?.workspaceId??``,gt=Ye?.roomId??``,_t=ot[ht]?.rooms.find(e=>e.id===gt),vt=_t?.title;(0,p.useEffect)(()=>{cr(R===`group`?Ye:void 0)},[Ye,R]),(0,p.useEffect)(()=>{R===`group`&&Me&&!O.workspaces.some(e=>e.id===ht&&!e.closedAt)&&(it(!1),at(`session`))},[R,Me,O.workspaces,ht]);let yt=(0,p.useRef)(null),bt=(0,p.useRef)(null),xt=(0,p.useRef)(void 0),St=(0,p.useRef)(!1),Ct=(0,p.useRef)(!0),[wt,Tt]=(0,p.useState)({followTail:!0,scrollTop:0}),Et=(0,p.useRef)(!1),Dt=(0,p.useRef)(new Map),Ot=(0,p.useRef)(void 0),kt=(0,p.useRef)([]),At=(0,p.useRef)(void 0),jt=(0,p.useCallback)((e,t)=>{let n=new Map(t.conversations.map(e=>[e.id,e]));return{...e,conversations:e.conversations.map(e=>{let t=n.get(e.id);if(e.messagesLoaded===!1||!t||t.messagesLoaded===!1||t.status!==`running`)return e;let r=new Map(t.messages.map(e=>[e.id,e]));return{...e,messages:e.messages.map(e=>{let t=r.get(e.id);return!t||!(t.content.length>e.content.length||(t.thinking?.length??0)>(e.thinking?.length??0))?e:{...e,content:t.content,thinking:t.thinking,thinkingActive:t.thinkingActive,thinkingBlocks:yk(t.thinkingBlocks,e.thinkingBlocks)}})}})}},[]),Mt=(0,p.useCallback)(()=>{if(At.current!==void 0&&(cancelAnimationFrame(At.current),At.current=void 0),!kt.current.length)return;let e=kt.current;kt.current=[];let t=new Map;for(let n of e){let e=`${n.conversationId}\u0000${n.messageId}`,r=t.get(e)??[];r.push(n),t.set(e,r)}u(e=>({...e,conversations:e.conversations.map(e=>{let n=e.messages.map(n=>{let r=t.get(`${e.id}\u0000${n.id}`);if(!r)return n;let i={...n};for(let e of r){if(e.type===`message.delta`){i.content+=e.delta;continue}if(i.thinkingActive=e.active,!e.delta)continue;let t=e.at??i.content.length,n=vk(i.thinkingBlocks??[],e,t);i={...i,thinking:(i.thinking??``)+e.delta,thinkingBlocks:n}}return i});return n.every((t,n)=>t===e.messages[n])?e:{...e,messages:n}})}))},[]),Nt=(0,p.useCallback)(e=>{let t=kt.current,n=t.at(-1);n&&n.type===e.type&&n.conversationId===e.conversationId&&n.messageId===e.messageId&&(e.type!==`message.thinking`||n.type===`message.thinking`&&n.at===e.at&&n.active===e.active&&n.blockIndex===e.blockIndex)?t[t.length-1]={...e,delta:n.delta+e.delta}:t.push(e),At.current===void 0&&(At.current=requestAnimationFrame(Mt))},[Mt]),Pt=(0,p.useCallback)(e=>{Ot.current=e},[]),[Ft,It]=(0,p.useState)(()=>hj().archived??{});(0,p.useEffect)(()=>{gj({workspaces:ie,archived:Ft})},[ie,Ft]);let[Lt,Rt]=(0,p.useState)(()=>VD());(0,p.useEffect)(()=>{HD(Lt)},[Lt]);let[zt,Bt]=(0,p.useState)(),Vt=(0,p.useRef)(0),Ht=(0,p.useRef)(``),Ut=(e,t,n,r)=>{let i=(e.target instanceof Element?e.target:void 0)?.closest(`button`);if(i&&!i.classList.contains(`conversation`)||e.button!==0)return;let a=e.clientY,o=e.pointerType===`touch`,s=!1,c,l=[],u,d=!1,f=e=>{let t=l.filter(e=>e.id!==n);if(t.length===0){u=void 0,d=!1;return}let r=0;for(;r<t.length&&t[r].middle<e;)r+=1;r<t.length?(u=t[r].id,d=!1):(u=t[t.length-1].id,d=!0)},p=()=>Bt(e=>e&&e.dropRootId===u&&e.dropAfter===d?e:{workspaceId:t,conversationId:n,dropRootId:u,dropAfter:d}),m=()=>{s||(s=!0,l=_j(t),f(a),document.body.style.userSelect=`none`,p())},h=e=>{if(!s){if(o){c!==void 0&&window.clearTimeout(c),c=void 0;return}if(Math.abs(e.clientY-a)<vj)return;m()}f(e.clientY),p()},g=e=>{if(window.removeEventListener(`pointermove`,h),window.removeEventListener(`pointerup`,_),window.removeEventListener(`pointercancel`,v),document.removeEventListener(`touchmove`,y),c!==void 0&&window.clearTimeout(c),document.body.style.userSelect=``,s&&e){let e=r.filter(e=>e!==n),i=u===void 0?e.length:d?e.indexOf(u)+1:e.indexOf(u);Rt(e=>({...e,[t]:zD(r,n,i)})),Vt.current=Date.now(),Ht.current=n}Bt(void 0)},_=()=>g(!0),v=()=>g(!1),y=e=>{s&&e.preventDefault()};window.addEventListener(`pointermove`,h),window.addEventListener(`pointerup`,_),window.addEventListener(`pointercancel`,v),o&&(document.addEventListener(`touchmove`,y,{passive:!1}),c=window.setTimeout(m,yj))},[Wt,Gt]=(0,p.useState)(()=>{if(typeof window>`u`)return``;try{return window.localStorage.getItem(`super-pi.user-nickname`)??``}catch{return``}}),Kt=e=>{let t=e.slice(0,24);Gt(t);try{window.localStorage.setItem(`super-pi.user-nickname`,t)}catch{}},qt=Wt.trim()||`你`,[Jt,Yt]=(0,p.useState)(),[Xt,Zt]=(0,p.useState)([]),[Qt,$t]=(0,p.useState)([]),[en,nn]=(0,p.useState)(),[rn,an]=(0,p.useState)(),[on,sn]=(0,p.useState)([]),[cn,ln]=(0,p.useState)([]),[un,dn]=(0,p.useState)(),[fn,pn]=(0,p.useState)(),[mn,hn]=(0,p.useState)(),[gn,_n]=(0,p.useState)(),[vn,yn]=(0,p.useState)(),bn=Ja(mn),xn=(0,p.useMemo)(()=>Xt.filter(e=>e.request.blocking),[Xt]),[Sn,wn]=(0,p.useState)(()=>typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(max-width: 1100px)`).matches),[Tn,En]=(0,p.useState)(`chat`),[Dn,On]=(0,p.useState)(!1),kn=(0,p.useCallback)(()=>{En(`chat`),window.matchMedia(`(max-width: 700px)`).matches&&wn(!0)},[]),[An,jn]=(0,p.useState)(!1),[Mn,Nn]=(0,p.useState)(w.current.kind),[Fn,In]=(0,p.useState)(()=>w.current.serverId??localStorage.getItem(`super-pi.server-filter`)??`all`),[Ln,Rn]=(0,p.useState)(w.current.workspaceId??_.current.workspaceId),[zn,Vn]=(0,p.useState)(w.current.repoId??_.current.workspaceId),[Hn,Un]=(0,p.useState)(S.selectionCleared===!0);(0,p.useEffect)(()=>{try{Kn(`super-pi.sidebar-scope.v1`,JSON.stringify({kind:Mn,serverId:Fn,workspaceId:Ln,repoId:zn}))}catch{}},[Mn,Fn,Ln,zn]);let Wn=(0,p.useRef)(Hn);Wn.current=Hn;let[Gn,Qn]=(0,p.useState)(()=>typeof window>`u`?1440:window.innerWidth);(0,p.useEffect)(()=>{let e=()=>Qn(window.innerWidth);return window.addEventListener(`resize`,e),e(),()=>window.removeEventListener(`resize`,e)},[]);let[er,tr]=(0,p.useState)(hi),[nr]=(0,p.useState)(()=>new Ti);Oi(nr),(0,p.useEffect)(()=>gi(er),[er]);let[rr,ir]=(0,p.useState)(jj),ar=dj(rr.sidebar??270,rr.rail??320,Gn>1100?Gn-88:Gn);(0,p.useEffect)(()=>{Mj({sidebar:rr.sidebar??270,rail:rr.rail??320})},[rr.sidebar,rr.rail]);let or=e=>ir(t=>({...t,sidebar:e})),fr=e=>ir(t=>({...t,rail:e})),[pr,vr]=(0,p.useState)(null);(0,p.useEffect)(()=>{vr(zj())},[]),(0,p.useEffect)(()=>{pr!==null&&document.documentElement.style.setProperty(`--composer-height`,`${pr}px`)},[pr]);let br=e=>{let t=Rj(e);vr(t);try{window.localStorage.setItem(Pj,String(t))}catch{}};(0,p.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(sj),t=e=>{e.matches&&wn(!0)};return e.addEventListener(`change`,t),e.matches&&wn(!0),()=>e.removeEventListener(`change`,t)},[]);let xr=Gn<=1100;(0,p.useEffect)(()=>{if(!xr||Sn)return;let e=e=>{e.key===`Escape`&&(e.defaultPrevented||document.querySelector(`.tool-overlay, .lightbox-overlay, .quick-open-backdrop, .ctx-menu, .overlay, .picker-menu, .content-search-overlay`)||(e.preventDefault(),wn(!0)))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[xr,Sn]);let[Sr,Cr]=(0,p.useState)({}),[wr,Tr]=(0,p.useState)({}),[Er,Dr]=(0,p.useState)({}),[Or,kr]=(0,p.useState)({}),[Ar,jr]=(0,p.useState)(null),[Mr,Nr]=(0,p.useState)(),[Pr,Fr]=(0,p.useState)(()=>new Set);(0,p.useEffect)(()=>{Fr(e=>{if(e.size===0)return e;let t=new Set([...e].filter(e=>{let t=O.conversations.find(t=>t.id===e);return t?OA(t):!1}));return t.size===e.size?e:t})},[O.conversations]);let[Ir,Lr]=(0,p.useState)(),[Rr,Vr]=(0,p.useState)(),Hr=(0,p.useRef)(new Map),[Ur,Wr]=(0,p.useState)(()=>{let e=Em(`super-pi.composer-drafts.v1`,{});return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{...t,attachments:iA(t.text,t.attachments)}]))}),Gr=(0,p.useRef)(Ur),Kr=(0,p.useRef)(!1);Gr.current=Ur,(0,p.useEffect)(()=>{let e=()=>{let e=Object.entries(Gr.current).filter(([e,t])=>!e.startsWith(`pending:`)&&(t.text||t.images.length||t.attachments.length)).map(([e,{text:t,images:n,attachments:r}])=>[e,{text:t,images:n,attachments:r,uploading:0}]),t=Dm(`super-pi.composer-drafts.v1`,Object.fromEntries(e));!t&&e.length&&!Kr.current&&Sc(`浏览器无法保存聊天草稿,刷新前请先保留这段内容。`,`warning`),Kr.current=!t&&e.length>0},t=window.setTimeout(e,250);return window.addEventListener(`pagehide`,e),()=>{window.clearTimeout(t),window.removeEventListener(`pagehide`,e)}},[Ur]);let qr=(0,p.useRef)(new Set),[Jr,Yr]=(0,p.useState)([]),[Xr,Zr]=(0,p.useState)([]),[ti,ni]=(0,p.useState)(),[ri,ii]=(0,p.useState)(!1),ai=(0,p.useRef)(null),oi=(0,p.useRef)(!1),si=(0,p.useRef)(0),ci=(0,p.useRef)([]),li=(0,p.useRef)(void 0),ui=(0,p.useRef)(!1),fi=(0,p.useRef)(new Set),mi=(0,p.useRef)(new Set),_i=(0,p.useRef)(new Map),bi=(0,p.useRef)(new Map),[Si,Ci]=(0,p.useState)(()=>Date.now());(0,p.useEffect)(()=>{let e=window.setInterval(()=>Ci(Date.now()),3e4);return()=>window.clearInterval(e)},[]);let wi=(0,p.useMemo)(()=>O.conversations.filter(e=>!e.archivedAt),[O.conversations]),Di=(0,p.useMemo)(()=>e.conversations.filter(e=>!e.archivedAt),[e.conversations]),ki=(0,p.useMemo)(()=>new Set(O.collapsedConversationIds??[]),[O.collapsedConversationIds]),z=(0,p.useMemo)(()=>{let e=wi.find(e=>e.id===j);if(e)return e;if(!(je||Hn||oe(j??M)))return Vj(wi,O.workspaces,M)},[je,Hn,j,wi,M,O.workspaces]),Ni=(0,p.useMemo)(()=>z?{workspaceId:z.workspaceId,conversationId:z.id,onImageOpen:ni}:void 0,[z?.workspaceId,z?.id]),[Pi,Fi]=(0,p.useState)(`queue`),Ii=!!(z&&OA(z));(0,p.useEffect)(()=>{Fi(`queue`)},[z?.id,Ii]);let[Li,Ri]=(0,p.useState)([]),zi=(0,p.useMemo)(()=>Zn(z?.parentConversationId,z?.parentConversationId?O.conversations.find(e=>e.id===z.parentConversationId):void 0),[z,O.conversations]),Bi=!!(z&&O.unlockedChildConversationIds?.includes(z.id)),Ui=zi&&!Bi,Wi=(0,p.useMemo)(()=>(O.conversations||[]).filter(e=>e.parentConversationId===z?.id),[O.conversations,z?.id]),Gi=(0,p.useMemo)(()=>(O.conversations||[]).find(e=>e.id===z?.parentConversationId),[O.conversations,z?.parentConversationId]),Ki=(0,p.useMemo)(()=>z?$n({conversation:z,parent:Gi,directChildren:Wi,isTopLevelUnread:!1}):null,[z,Gi,Wi]),qi=yt.current;if(qi){let e=qi.dataset.messageScrollContainer;e&&z?.id&&e!==z?.id&&qi.querySelector(`[data-transcript-key]`)&&(Ue.current[e]=Cj(qi,Ue.current[e]??{followTail:!0,scrollTop:0}))}Ct.current=z?.messagesLoaded!==!1,(0,p.useEffect)(()=>{if(!Me||oe(j??M)||(je||Hn)&&!j||j&&Di.some(e=>e.id===j)||j&&g.current.some(e=>e.temporaryId===j))return;let e=Vj(wi,O.workspaces,M);je&&e||(j&&!e&&R!==`group`&&(de.current++,at(`session`)),ee(e?.id),e&&ce(t=>t.emptied||t.ids.length===0||t.ids.includes(e.id)?t:{...t,ids:[...t.ids,e.id]}))},[je,Hn,j,Di,wi,Me,M,O.workspaces,R]),(0,p.useEffect)(()=>{re(void 0)},[j,M]);let Ji=(0,p.useMemo)(()=>O.workspaces.find(e=>e.id===M)??(Hn||oe(M)?void 0:O.workspaces[0]),[O.workspaces,M,Hn]),Yi=Ji&&!wi.some(e=>e.workspaceId===Ji.id)?Ji:void 0,Xi=Ji?.id.startsWith(`pending:`)===!0,[Zi,Qi]=(0,p.useState)(``);(0,p.useEffect)(()=>{Qi(``)},[Ji?.id]);let $i=(0,p.useRef)(M);$i.current=M,(0,p.useEffect)(()=>{z&&N(z.workspaceId)},[z?.id]),(0,p.useEffect)(()=>{li.current=j},[j]),(0,p.useEffect)(()=>{xt.current=z?.id},[z?.id]);let ea=(0,p.useCallback)(e=>{let t=e.activity.lastReplyAt,n=lr({workspaceId:e.workspaceId,roomId:e.id});!t||t<=(Ke.current[n]??``)||(Ke.current[n]=t,Je(e=>e+1),Tj({activeId:li.current,workspaceId:$i.current,conversations:Ue.current,readAt:Ke.current}))},[]);yr(Ke,O.conversations,()=>{Je(e=>e+1),Tj({activeId:li.current,workspaceId:$i.current,conversations:Ue.current,readAt:Ke.current})}),(0,p.useEffect)(()=>{let e=z?.id;if(!e)return;let t=O.conversations.find(t=>t.id===e);if(!t||t.messagesLoaded===!1)return;let n=()=>{let n=yt.current;document.visibilityState!==`visible`||!n||n.getBoundingClientRect().height<=0||t.updatedAt<=(Ke.current[e]??``)||(Ke.current[e]=t.updatedAt,Je(e=>e+1),Tj({activeId:li.current,workspaceId:z?.workspaceId??M,conversations:Ue.current,readAt:Ke.current}))},r=requestAnimationFrame(n);return document.addEventListener(`visibilitychange`,n),window.addEventListener(`focus`,n),()=>{cancelAnimationFrame(r),document.removeEventListener(`visibilitychange`,n),window.removeEventListener(`focus`,n)}},[z?.id,O.conversations,R]),(0,p.useEffect)(()=>{let e=z?.workspaceId??M;te&&Me&&e&&!e.startsWith(`pending:`)&&!z?.id.startsWith(`pending:`)&&Tj({activeId:z?.id,workspaceId:e,conversations:Ue.current,readAt:Ke.current})},[z?.id,z?.workspaceId,te,Me,M]),(0,p.useEffect)(()=>{let e=yt.current;if(R!==`session`||!e||!z?.id||z.messagesLoaded===!1)return;let t=z.id;Et.current=!1;let n=Ue.current[t]??{followTail:!0,scrollTop:0};Ue.current[t]=n,Tt(n);let r=requestAnimationFrame(()=>{if(yt.current!==e)St.current=!1;else{if(n.followTail)Sj(e),e.scrollTop=e.scrollHeight;else{let t=n.anchorKey?e.querySelector(`[data-transcript-key="${CSS.escape(n.anchorKey)}"]`):null;e.scrollTop=t?Math.max(0,e.scrollTop+t.getBoundingClientRect().top-(n.anchorOffset??0)-e.getBoundingClientRect().top):n.scrollTop}St.current=!1}});return()=>cancelAnimationFrame(r)},[z?.id,z?.messagesLoaded,R]),(0,p.useLayoutEffect)(()=>{St.current=!0},[z?.id,z?.messagesLoaded,R]);let ta=(0,p.useCallback)((e,t=!1,n=!1)=>{let r=xt.current;if(!r||St.current||!Ct.current)return;let i=Cj(e,Ue.current[r]??{followTail:!0,scrollTop:0},t,n);Et.current=!i.followTail,Ue.current[r]=i,Tt(i),Tj({activeId:r,workspaceId:$i.current,conversations:Ue.current,readAt:Ke.current})},[]),na=z?.id??``,ra=Ur[na]??{text:``,images:[],attachments:[],uploading:0},ia=ra.text,aa=ra.images,oa=ra.attachments,sa=Object.keys(ra.pendingSkills??{}).length>0,ca=ra.uploading,la=(e,t)=>Wr(n=>({...n,[e]:t(n[e]??{text:``,images:[],attachments:[],uploading:0})})),ua=(e,t)=>({...e,text:t,attachments:iA(t,e.attachments),pendingSkills:e.pendingSkills&&Object.fromEntries(Object.entries(e.pendingSkills).filter(([e])=>mp(t,e)))}),da=e=>la(na,t=>ua(t,e)),fa=(e,t,n,r)=>{let i=tn();la(n,n=>{let r=ua(n,t);return{...r,pendingSkills:{...r.pendingSkills,[e]:i}}});let a=t=>t[n]?.pendingSkills?.[e]===i?n:n.startsWith(`pending:`)?Object.keys(t).find(n=>t[n].pendingSkills?.[e]===i):void 0,o=t=>Wr(n=>{let r=a(n);if(!r)return n;let i=n[r],o={...i.pendingSkills};delete o[e];let s=t?[...i.attachments.filter(t=>t.id!==e),t]:i.attachments;return{...n,[r]:{...i,pendingSkills:o,attachments:s}}});Ie(`/api/skills/read?${new URLSearchParams({name:e,workspaceId:r})}`,{signal:AbortSignal.timeout(1e4)}).then(async t=>{if(!t.ok)throw Error(`读取技能失败`);let n=await t.json();if(typeof n.content!=`string`)throw Error(`读取技能失败`);o({kind:`skill`,id:e,name:n.name??e.slice(6),content:n.content})}).catch(()=>{a(Gr.current)&&Sc(`读取技能失败`,`error`),o()})},ma=(e,t)=>la(z?.id??``,n=>({...n,attachments:n.attachments.filter(n=>n.kind!==e||n.id!==t)})),[ha,ga]=(0,p.useState)({visible:!1,query:``,rect:null}),_a=JSON.stringify([z?.id,z?.workspaceId,z?.cwd??``]),[va,ya]=(0,p.useState)(),ba=(0,p.useRef)(null),[xa,Sa]=(0,p.useState)(),Ca=(0,p.useRef)(void 0),wa=(0,p.useRef)(``),Ta=!Ui&&va?.scope===_a?va:void 0,Ea=e=>{let t=!oi.current&&!Ui&&z?_p(e.value,e.selectionStart,e.selectionEnd):void 0,n=JSON.stringify([_a,t]);return!t||wa.current===n?(ya(void 0),!1):(ya({scope:_a,token:t,rect:e.getBoundingClientRect()}),ga({visible:!1,query:``,rect:null}),!0)},Da=()=>{wa.current=JSON.stringify([_a,Ta?.token]),ya(void 0)};(0,p.useEffect)(()=>{ya(void 0),wa.current=``},[_a]),(0,p.useLayoutEffect)(()=>{let e=Ca.current;Ca.current=void 0,e?.scope===_a&&e.text===ia&&(bt.current?.focus(),bt.current?.setSelectionRange(e.caret,e.caret))},[ia,_a]),(0,p.useEffect)(()=>{let e=()=>{let e=bt.current;e&&ya(t=>t?{...t,rect:e.getBoundingClientRect()}:void 0)};return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);let Oa=e=>la(z?.id??``,t=>({...t,images:typeof e==`function`?e(t.images):e})),ka=le.length>0?le:je?[]:z?[z.id]:[],Aa=(0,p.useMemo)(()=>ka.map(e=>wi.find(t=>t.id===e)).filter(e=>e!==void 0),[ka,wi]),ja=Yi?void 0:Aa.filter(e=>e.id!==ue).at(-1)?.id,Ma=Aa.some(e=>e.id===z?.id);(0,p.useEffect)(()=>{if(!Me)return;let e=new Set(wi.map(e=>e.id));ce(t=>{let n=t.ids.filter(t=>e.has(t)||oe(t)),r=t.previewId&&(e.has(t.previewId)||oe(t.previewId))?t.previewId:void 0;return n.length===t.ids.length&&r===t.previewId?t:{...t,ids:n,previewId:r}})},[Me,wi]),(0,p.useEffect)(()=>{!Me||Xi||j?.startsWith(`pending:`)||oe(j??M)||Aj(se,j,j?void 0:Yi?.id,Hn||!j&&!rt)},[j,Me,se,Xi,Yi?.id,Hn,rt]);let Na=(0,p.useCallback)(e=>{e&&ce(t=>{if(t.touched.has(e))return t;let n=t.previewId===e?void 0:t.previewId;return{...t,previewId:n,touched:Dj(t.touched,e)}})},[]),Pa=(0,p.useCallback)(e=>{xe(L(e)),Un(!1),de.current++,it(!1),ee(e);let t=O.conversations.find(t=>t.id===e)?.workspaceId;t&&N(t),at(`session`),ce(t=>{let n=t.emptied===!0,r=n?{...t,emptied:!1}:t;if(r.ids.includes(e))return r;let i=!n&&r.ids.length===0&&z?.id&&z.id!==e?[z.id]:[],a=[...r.ids,...i];if(r.touched.has(e))return{...r,ids:[...a,e]};let o=r.previewId?a.indexOf(r.previewId):-1,s=o>=0?a.map((t,n)=>n===o?e:t):[...a,e];return{...r,ids:s,previewId:e}})},[z,wi,O.conversations]);(0,p.useEffect)(()=>{let e=e=>{let t=e.detail;typeof t==`string`&&O.conversations.some(e=>e.id===t)&&Pa(t)};return window.addEventListener(`super-pi-open-execution-session`,e),()=>window.removeEventListener(`super-pi-open-execution-session`,e)},[Pa,O.conversations]),(0,p.useEffect)(()=>{if(!Me)return;let t=new Map(e.conversations.filter(e=>!e.archivedAt).map(e=>[e.id,{status:e.status,hasPendingQuestion:!!e.hasPendingQuestion,title:e.title,workspaceId:e.workspaceId,parentConversationId:e.parentConversationId}]));if(!c.current){s.current=t,c.current=!0;return}let r=document.visibilityState===`visible`&&document.hasFocus(),a=n&&[`granted`,`native`].includes(i)&&!r;for(let[n,r]of t){let t=s.current.get(n);if(!t||r.parentConversationId||!a)continue;let i=!t.hasPendingQuestion&&r.hasPendingQuestion,o=r.status===`completed`&&t.status!==`completed`&&[`waiting`,`running`,`awaiting_background`].includes(t.status);if(!i&&!o)continue;let c=i?`question`:`completed`;if(Uj(`${n}:${c}:${e.conversations.find(e=>e.id===n)?.updatedAt??``}`))try{let e=`${n}:${c}`,t=no(i?`Super Pi · 等你回答`:`Super Pi · Agent 已完成`,{body:`${be(r.workspaceId)} · ${i?`「${r.title}」需要你的回答。`:`「${r.title}」已完成。`}`,tag:`super-pi-${c}-${n}`});l.current.set(e,t),t.onclose=()=>{l.current.get(e)===t&&l.current.delete(e)},t.onclick=()=>{t.close(),l.current.delete(e),window.focus(),Pa(n)}}catch(e){console.warn(`[Super Pi] Browser notification could not be shown:`,e instanceof Error?e.message:`unknown error`)}}s.current=t},[e.conversations,Me,n,i,Pa]);let Fa=(0,p.useCallback)(e=>{e&&(Na(e),Pa(e))},[Na,Pa]),Ia=e=>{e.startsWith(`pending:`)||xe(L(e)),Un(!0),de.current++,it(!1),z&&Ma&&ce(e=>e.ids.length||e.emptied?e:{...e,ids:[z.id]}),N(e),ee(void 0),at(`session`),jn(!1),kn()},La=(0,p.useCallback)((e,t=``)=>{de.current++;let n={workspaceId:e,roomId:t};t&&nt(r=>r.some(n=>n.workspaceId===e&&n.roomId===t)?r:[...r,n]),Xe(n),it(!0),N(e),jn(!1),at(`group`),kn()},[kn]),Ra=(0,p.useCallback)((e,t)=>{ct(e,!0),t&&(ae(t=>t[e.workspaceId]?{...t,[e.workspaceId]:!1}:t),La(e.workspaceId,e.id))},[La,ct]);(0,p.useEffect)(()=>{let e=new Set;if(!n||![`granted`,`native`].includes(i))io(e);else{for(let t of Object.values(ot))for(let n of t.rooms)if(!n.archivedAt)for(let t of n.cloneRequests??[]){if(t.status!==`pending`||t.automatic)continue;let r=`group-clone:${n.id}:${t.id}`;e.add(r),ro(r,`${be(n.workspaceId)} · ${n.title} · 需要决定是否创建分身`,`群聊主持人正在等待你的决定,请打开群聊查看详情。`,R===`group`&>===n.id&&document.visibilityState===`visible`&&document.hasFocus(),()=>La(n.workspaceId,n.id))}io(e)}},[ot,R,gt,La,n,i]);let za=(0,p.useCallback)(e=>{st(),ut(e)},[ut,st]);async function Ba(e,t){if(!pt.has(e.id)&&(t!==`delete`||window.confirm(`永久删除群聊「${e.title}」及其聊天记录?删除后无法恢复。`))){mt(t=>new Set(t).add(e.id));try{let n=await mr(dr(e.workspaceId,e.id),{action:t});if(t===`delete`)za({workspaceId:e.workspaceId,roomId:e.id});else{if(!n)throw Error(`服务没有确认群聊状态。`);st(),ct(n),t===`archive`&&It(t=>({...t,[e.workspaceId]:!1}))}}catch(e){Sc(e instanceof Error?e.message:`群聊操作失败。`,`error`)}finally{mt(t=>new Set([...t].filter(t=>t!==e.id)))}}}let Va=rt&&R!==`session`,Ha=Va?ht:z?.workspaceId??M,Ua=Ha?.startsWith(`pending:`)?void 0:Ha,Wa=Ua??(Mn===`repo`?O.workspaces.find(e=>e.id===zn&&(!e.worktreeOf||!O.workspaces.some(t=>t.id===e.worktreeOf)))?.id??O.workspaces.find(e=>(Fn===`all`||y(e.id).server===Fn)&&(!e.worktreeOf||!O.workspaces.some(t=>t.id===e.worktreeOf)))?.id:void 0),Ga=Wa?.startsWith(`pending:`)?void 0:Wa,Ka=Va?``:z?.cwd??``;(0,p.useEffect)(()=>{Ua&&xe(L(Ua))},[Ua]);let qa=Mn===`repo`&&!Ua,Xa=JSON.stringify([Ua,Ka]),[Za,Qa]=(0,p.useState)(),[$a,B]=(0,p.useState)(50),ao=Za?.scope===Xa?Za:void 0,oo=!!ao,so=ao?.tabId;(0,p.useEffect)(()=>{Qa(e=>e?.scope===Xa?e:void 0)},[Xa]);let co=(0,p.useCallback)(e=>{Qa(t=>t?.scope===Xa?{...t,tabId:e}:t)},[Xa]),V=zh(Ua,Ka,{navigation:de,showingFile:R===`file`,splitFilePath:so?.startsWith(`file:`)?so.slice(5):void 0}),lo=pa(Ga,Ga===Ua?Ka:``,te&&Me),uo=(0,p.useRef)(lo.refresh);uo.current=lo.refresh;let fo=(0,p.useRef)(V.setChangedFor),po=(0,p.useRef)(V.invalidateTree);po.current=V.invalidateTree;let mo=(0,p.useRef)(Ua);mo.current=Ua,(0,p.useEffect)(()=>{fo.current=V.setChangedFor},[V.setChangedFor]);let[ho]=(0,p.useState)(CA),[go,_o]=(0,p.useState)(ho.tab),[vo,yo]=(0,p.useState)(ho.byConversation),bo=go===`rsi`?go:(z?.id?vo[z.id]:void 0)??go;(0,p.useEffect)(()=>{try{Kn(SA,JSON.stringify({tab:go,byConversation:vo}))}catch{}},[go,vo]);let[xo,So]=(0,p.useState)(),Co=(0,p.useCallback)(()=>So(e=>({request:(e?.request??0)+1,workspaceId:Ua,conversationId:Va?void 0:z?.id})),[Ua,Va,z?.id]),wo=(0,p.useCallback)(e=>{xr||tr(t=>({...t,rightView:e})),e===`terminal`&&Co(),_o(e),z?.id&&yo(t=>({...t,[z.id]:e}))},[z?.id,Co,xr]),[To,Eo]=(0,p.useState)(),Do=er.order.filter(e=>ei(e)||nr.members(e).length>0),Oo=e=>Do.filter(t=>er.sides[t]===e),ko=Oo(`left`),Ao=Oo(`right`),jo=Oo(`bottom`),Mo=ko.includes(er.leftView)?er.leftView:ko[0],No=er.rightView&&(er.rightView===`sessions`||er.rightView===`search`||!ei(er.rightView))?er.rightView:bo,Po=No&&Ao.includes(No)?No:Ao[0],Fo=er.bottomView&&jo.includes(er.bottomView)?er.bottomView:jo[0],Io=er.rightClosed||!Po,Lo={left:er.leftClosed?void 0:Mo,right:Io?void 0:Po,bottom:er.bottomClosed?void 0:Fo},Ro=To&&Do.includes(To)?To:bo,zo=e=>xr?!Sn&&(Gn>700||Tn===`rail`)&&Ro===e:Lo[er.sides[e]]===e,Bo=zo(nr.hostView(`rsi`)),Vo=xr?Gn>700||An:zo(`sessions`),Ho=e=>{e===`sessions`?(kn(),jn(!0)):(e===`search`||!ei(e)?Eo(e):(Eo(void 0),wo(e)),wn(!1),Gn<=700&&En(`rail`))},Uo=(e,t=!1)=>{if(xr){Ho(e);return}let n=er.sides[e];nr.hostView(`terminal`)===e&&(n!==`right`||e!==`terminal`)&&Co(),n===`right`&&ei(e)&&e!==`search`&&e!==`sessions`&&wo(e),tr(r=>({...r,[n+`View`]:e,[n+`Closed`]:t&&Lo[n]===e}))},Wo=(e,t=!1)=>Uo(nr.hostView(e),t),[Go,Ko]=(0,p.useState)(),qo=e=>{Wo(`git-${e}`),Ko(t=>({workspaceId:Ga,view:e,request:(t?.request??0)+1}))},Jo=(e,t,n,r=`before`)=>{e!==n&&(t===`right`&&ei(e)&&e!==`sessions`&&e!==`search`&&wo(e),tr(i=>{let a=i.order.filter(t=>t!==e),o=n?a.indexOf(n):-1;return a.splice(o<0?a.length:o+Number(r===`after`),0,e),{...i,order:a,sides:{...i.sides,[e]:t},[t+`View`]:e,[t+`Closed`]:!1,unpinned:i.unpinned.filter(t=>t!==e)}}))},Yo=(e,t)=>{if(!$r(e))return;let n=Qr(e);nr.move(e,n,void 0,!1),Jo(n,t),xr&&(Eo(n),wn(!1))},Xo=(e,t)=>{let n=er.sides[e];if(t.startsWith(`move`))Jo(e,t===`move-bottom`?`bottom`:t===`move-right`||n===`left`?`right`:`left`),requestAnimationFrame(()=>document.querySelector(`[data-workbench-view="${e}"]`)?.focus());else if(t===`pin`)tr(t=>({...t,unpinned:t.unpinned.includes(e)?t.unpinned.filter(t=>t!==e):[...t.unpinned,e]}));else{let r=Oo(n).filter(e=>!er.unpinned.includes(e)),i=r[r.indexOf(e)+(t===`up`?-1:1)];i&&Jo(e,n,i,t===`up`?`before`:`after`)}},Zo=(e,t,n,r)=>Jo(e,n??(t?er.sides[t]:er.sides[e]),t,r),Qo=JSON.stringify([Ua,Ka]),[$o,es]=(0,p.useState)(),ts=$o?.scope===Qo?$o:void 0,ns=ts?.mode===`path`;(0,p.useEffect)(()=>{es(e=>e?.scope===Qo?e:void 0)},[Qo]);let rs=(0,p.useCallback)((e,t,n,r=!1)=>{de.current++,es(i=>i?.mode===e&&i.scope===Qo&&i.directory===n?{...i,replace:r||i.replace}:{mode:e,scope:Qo,initialQuery:t,directory:n,replace:r}),jn(!1)},[Qo]),is=(0,p.useCallback)(()=>{de.current++,es(void 0)},[]),[H,as]=(0,p.useState)(),os=(0,p.useRef)(0),ss=e=>{Pa(e.conversationId),as({hit:e,request:de.current}),es(void 0),kn()};(0,p.useEffect)(()=>{if(!H||H.request===os.current||z?.id!==H.hit.conversationId||z?.messagesLoaded===!1||R!==`session`||!Ma)return;let{hit:e,request:t}=H,n=null,r,i=requestAnimationFrame(()=>{let i=yt.current;i&&de.current===t&&(n=i.querySelector(`[data-transcript-key="${CSS.escape(`m:${e.messageId}`)}"]`),n&&(os.current=t,Sj(i),i.scrollTop+=n.getBoundingClientRect().top-i.getBoundingClientRect().top-24,ta(i,!0),n.dataset.sessionSearchHit=`true`,n.tabIndex=-1,n.focus({preventScroll:!0}),r=setTimeout(()=>{n&&delete n.dataset.sessionSearchHit},2400)))});return()=>{cancelAnimationFrame(i),clearTimeout(r),n&&delete n.dataset.sessionSearchHit}},[z?.id,z?.messagesLoaded,R,ta,Ma,H]);let[cs,ls]=(0,p.useState)(),[us,ds]=(0,p.useState)(),[fs,ps]=(0,p.useState)(E.diffs),ms=fs.paths,[hs,gs]=(0,p.useState)(E.gitDiffs),[_s,vs]=(0,p.useState)(E.gitDiffUrl);(0,p.useEffect)(()=>{if(!(!Me||V.restoringWorkbench||oe(j??M)))try{Yn({view:R,groups:Ze,gitDiffs:hs,gitDiffUrl:_s,diffs:fs})}catch{}},[Me,V.restoringWorkbench,j,M,R,Ze,hs,_s,fs]);let ys=R===`gitDiff`?hs.find(e=>e.target.url===_s):void 0,bs=R===`gitDiff`?`diff`:R,xs=ys?.target.path??us,Ss=(0,p.useCallback)(e=>{if(qa&&!e.commitHash)return;de.current++;let t=document.activeElement instanceof HTMLElement?document.activeElement:void 0;gs(n=>{let r=n.find(t=>t.target.url===e.url);if(!r){let r={target:e,workspaceId:Ua,reading:{},revision:0,preview:!0,origin:t},i=oo&&R===`gitDiff`?_s:void 0,a=n.find(e=>e.preview&&e.target.url!==i);return a?n.map(e=>e===a?r:e):[...n,r]}if(e.commitHash)return n;let i=r.target.label===e.label?{...r.reading,snapshot:void 0}:{};return n.map(n=>n===r?{...n,target:e,reading:i,revision:n.revision+1,origin:t}:n)}),oo?(co(`git-diff:${e.url}`),R===`gitDiff`&&_s===e.url&&at(`session`)):(vs(e.url),at(`gitDiff`)),kn()},[Ua,qa,_s,R,co,kn,oo]),Cs=(0,p.useCallback)(()=>{!Ma&&ja?Pa(ja):at(`session`)},[Ma,ja,Pa]);(0,p.useEffect)(()=>{let e=e=>{let t=ot[e.workspaceId];return!t?.loaded||t.rooms.some(t=>t.id===e.roomId)},t=Ze.filter(e);if(t.length!==Ze.length&&nt(t),R!==`group`||!Ye?.roomId||e(Ye))return;let n=t.filter(e=>e.workspaceId===Ye.workspaceId).at(-1);n?La(n.workspaceId,n.roomId):Cs()},[ot,Ye,Ze,R,La,Cs]),(0,p.useEffect)(()=>{R===`file`&&!V.active&&Cs()},[R,V.active,Cs]),(0,p.useEffect)(()=>{R===`diff`&&!us&&Cs()},[R,us,Cs]);let ws=(0,p.useRef)(`${Ua??``}:${Ka}`);(0,p.useEffect)(()=>{let e=`${Ua??``}:${Ka}`;ws.current!==e&&(ws.current=e,ps({paths:[]}),ds(void 0),at(e=>e===`gitDiff`||e===`group`?e:`session`))},[Ua,Ka]);let Ts=(0,p.useCallback)((e,t=!1)=>{de.current++;let n=oo&&!t;ps(t=>{if(t.paths.includes(e))return t;let r=n&&R===`diff`&&us===t.previewPath;return{paths:t.previewPath&&!r?t.paths.map(n=>n===t.previewPath?e:n):[...t.paths,e],previewPath:e}}),n?(co(`diff:${e}`),R===`diff`&&us===e&&at(`session`)):(ds(e),at(`diff`)),kn(),_o(`files`)},[us,R,co,kn,oo]),Es=R===`diff`?us:void 0,Ds=so?.startsWith(`diff:`)?so.slice(5):void 0,Os=Ds&&Ds!==Es&&ms.includes(Ds)?Ds:void 0,ks=Hj(Ua,Ka,Es),U=Hj(Ua,Ka,Os),[W,G]=(0,p.useState)(`server`),[K,q]=(0,p.useState)(`server`),As=e=>{let t=V.open.find(t=>t.path===e);return t?.dirty?t.content:void 0},js=(0,p.useCallback)(e=>{de.current++,V.setActivePath(e),at(`file`),_o(`files`)},[V.setActivePath]),Ms=(0,p.useCallback)(async(e,t,n=!1,r=!1,i=!1,a)=>{let o=++de.current,s=()=>de.current===o,c=oo&&!i,l=await V.openFile(e,{preview:!n,activate:!c,isCurrent:s,throwOnError:r,requireText:a!==void 0});if(l&&s())return n&&V.pinFile(l),ls(t?{scope:Qo,path:l,line:t,column:a,request:o}:void 0),c?(co(`file:${l}`),R===`file`&&V.activePath===l&&at(`session`)):at(`file`),kn(),l},[V.openFile,V.pinFile,V.activePath,Qo,R,co,kn,oo]),Ns=(0,p.useCallback)((e,t)=>{Ms(e,void 0,t)},[Ms]),Ps=z&&!Ui?(e,t)=>{let n=ia&&!/\s$/u.test(ia)?`${ia} `:ia,r=vp(n,{start:n.length,end:n.length,query:``},{path:e,kind:t?`directory`:`file`});Ca.current={scope:_a,...r},Na(z.id),Pa(z.id),kn(),da(r.text)}:void 0,Fs=(e,t)=>{de.current+=1,ps(t=>({paths:t.paths.filter(t=>!kp(t,e)),previewPath:t.previewPath&&!kp(t.previewPath,e)?t.previewPath:void 0})),us&&kp(us,e)&&ds(void 0),Qa(n=>{let r=n?.tabId?.startsWith(`file:`)?n.tabId.slice(5):void 0;return n&&r&&kp(r,e)?{...n,tabId:`file:${t}${r.slice(e.length)}`}:n}),ls(n=>n?.scope===Qo&&kp(n.path,e)?{...n,path:t+n.path.slice(e.length)}:n)};(0,p.useEffect)(()=>{let e=e=>{if(!(e.ctrlKey||e.metaKey)||e.altKey||e.isComposing)return;let t=e.key.toLowerCase();e.shiftKey&&t===`f`?(e.preventDefault(),rs(`content`)):e.shiftKey&&t===`h`?(e.preventDefault(),rs(`content`,void 0,void 0,!0)):!e.shiftKey&&t===`p`&&(e.preventDefault(),rs(`path`))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[rs]);let Is=(0,p.useMemo)(()=>Aa.map(e=>({id:`session:${e.id}`,workspaceId:e.workspaceId,rawId:e.id,kind:`session`,label:e.title,title:e.title,closable:!0,preview:ue===e.id,badge:(0,m.jsx)(FA,{state:NA(e,jA(e,xn),Ke.current[e.id],O.conversations)})})),[Aa,xn,O.conversations,qe,ue]),Ls=(0,p.useMemo)(()=>V.open.map(e=>({id:`file:${e.path}`,workspaceId:V.ownerWorkspaceId,rawId:e.path,kind:`file`,label:e.name,title:e.path,closable:!0,preview:e.preview,badge:e.dirty?(0,m.jsx)(`span`,{className:`file-tab-badge`,"data-file-tab-dirty":e.path,"aria-label":`未保存`,children:`●`}):void 0})),[V.ownerWorkspaceId,V.open]),J=(0,p.useMemo)(()=>ms.map(e=>({id:`diff:${e}`,workspaceId:Ua,rawId:e,kind:`diff`,label:e.split(/[\\/]/).pop()||e,title:`${e}(改动)`,closable:!0,preview:fs.previewPath===e,icon:(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`±`})})),[Ua,ms,fs.previewPath]),Rs=(0,p.useMemo)(()=>[...Is,...[...Ze,...R===`group`&&Ye&&!gt?[Ye]:[]].flatMap(e=>{let t=O.workspaces.find(t=>t.id===e.workspaceId&&!t.closedAt);if(!t)return[];let n=ot[e.workspaceId]?.rooms.find(t=>t.id===e.roomId),r=e.roomId?n?.title??`群聊`:`新建群聊`,i=n?hr(n,dt[n.id]):`idle`,a=n?gr(n,dt[n.id],Ke.current[lr(e)]):`idle`,o=a===`completed`?`讨论已完成,有新回复未读`:a===`unread`?`有新回复未读`:TA[i],s=`${r} · ${t.name}${i===`idle`?``:` · ${o}`}`;return[{id:lr(e),workspaceId:e.workspaceId,label:r,title:s,closable:!0,icon:(0,m.jsx)(vi,{name:`group`}),badge:(0,m.jsx)(FA,{state:a,label:o})}]}),...Ls,...J,...hs.map(({target:e,preview:t,workspaceId:n})=>({id:`git-diff:${e.url}`,workspaceId:n,kind:`diff`,closable:!0,preview:t,label:`${e.path.split(/[\\/]/).pop()||e.path} (${e.label})`,title:`${e.path} · ${e.comparison}`,icon:(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`±`})}))],[Is,Ls,J,hs,Ze,ot,dt,Ye,gt,R,O.workspaces,qe]),Y=R===`group`&&Ye?lr(Ye):R===`file`&&V.activePath?`file:${V.activePath}`:R===`diff`&&us?`diff:${us}`:ys?`git-diff:${ys.target.url}`:Ma&&z?.id?`session:${z.id}`:void 0,zs=(0,p.useRef)(!1),Bs=(0,p.useRef)(void 0);(0,p.useLayoutEffect)(()=>{let e=zs.current;if(zs.current=!1,Bs.current!==V.restoredActive&&(Bs.current=V.restoredActive,!Oe&&V.restoredActive&&V.restoredActive===V.activePath&&R!==`file`&&R!==`gitDiff`&&R!==`group`)){at(`file`);return}if(!e&&Me&&ue&&Y!==`session:${ue}`&&wi.some(e=>e.id===ue)&&ce(e=>{if(e.previewId!==ue)return e;let t=e.ids.filter(e=>e!==ue);return{...e,ids:t,previewId:void 0,emptied:t.length===0}}),!e)for(let e of V.open)e.preview&&Y!==`file:${e.path}`&&so!==`file:${e.path}`&&V.discardPreview(e.path);let t=fs.previewPath;!e&&t&&Y!==`diff:${t}`&&so!==`diff:${t}`&&ps(e=>e.previewPath===t?{paths:e.paths.filter(e=>e!==t)}:e);let n=e=>{let t=`git-diff:${e.target.url}`;return!e.preview||t===Y||t===so};!e&&hs.some(e=>!n(e))&&gs(e=>e.filter(n)),Me&&R===`session`&&z&&z.id===j&&!Ma&&!V.restoringWorkbench&&ja&&Pa(ja)},[Y,Me,ue,V.open,V.activePath,V.restoredActive,V.discardPreview,fs.previewPath,R,z?.id,j,Ma,V.restoringWorkbench,ja,Pa,wi,Oe,so,hs]);let Vs=(0,p.useCallback)(e=>{if(e.startsWith(`group:`)){let t=ur(e);t&&La(t.workspaceId,t.roomId)}else if(e.startsWith(`file:`)){let t=e.slice(5);js(t)}else if(e.startsWith(`diff:`)){de.current++;let t=e.slice(5);ds(t),at(`diff`)}else if(e.startsWith(`git-diff:`))de.current++,vs(e.slice(9)),at(`gitDiff`);else if(e.startsWith(`session:`)){let t=e.slice(8);Pa(t)}},[js,Pa,La]),Hs=Rs.find(e=>e.id===Y),Us=R===`file`?V.active:void 0,Ws=(0,p.useMemo)(()=>{if(!Me||!Hs||Hs.id.startsWith(`session:pending:`))return;let{id:e,label:t}=Hs;if(R!==`group`||gt&&vt){if(R===`session`)return e.startsWith(`session:`)?{key:e,tabId:e,title:t}:void 0;if(R===`file`||R===`diff`||R===`gitDiff`){if(!Ua||V.restoringWorkbench||R===`file`&&!Us||R===`diff`&&!us)return;let n={workspaceId:Ua,cwd:Ka,conversationId:z?.id},r=Us&&{path:Us.path,name:Us.name,text:null,...Us.assetTicket||/^(?:[a-z]:[\\/]|[\\/])/i.test(Us.path)?{openLink:!0}:{}},i=R===`file`&&Ee?.scope===JSON.stringify([n.workspaceId,n.cwd,Us?.path])?{line:Ee.position.line,column:Ee.position.column}:void 0,a=!!i&&(Ee?.position.navigation||cs?.scope===Qo&&cs.path===Us?.path&&cs.line===i.line&&(cs.column??1)===i.column);return{key:JSON.stringify([n.workspaceId,n.cwd,e]),tabId:e,title:t,scope:n,file:r,position:i,explicitPosition:a,gitDiff:R===`gitDiff`&&ys?{...ys,origin:void 0,preview:!1}:void 0}}return{key:e,tabId:e,title:t}}},[Me,Hs,R,Ua,Ka,z?.id,V.restoringWorkbench,us,Us?.path,Us?.name,Us?.assetTicket,gt,vt,Ee,cs,Qo,ys]);(0,p.useEffect)(()=>{!Oe&&Ws&&(Ae.current.delete(Ws.key),we(e=>_g(e,Ws)))},[Ws,Oe]);let Gs=e=>{let t=wi.filter(t=>t.workspaceId===e.workspaceId&&(t.cwd??``)===e.cwd);return t.find(t=>t.id===e.conversationId)??t[0]},Ks=e=>{if(gg(e,Ws)||Ae.current.has(e.key))return!1;if(e.tabId.startsWith(`session:`))return wi.some(t=>`session:${t.id}`===e.tabId);let t=ur(e.tabId);if(t)return O.workspaces.some(e=>e.id===t.workspaceId&&!e.closedAt)&&!!ot[t.workspaceId]?.rooms.some(e=>e.id===t.roomId);if(!e.scope)return Rs.some(t=>t.id===e.tabId);let{scope:n}=e;return O.workspaces.some(e=>e.id===n.workspaceId)?n.workspaceId===Ua&&n.cwd===Ka||!!Gs(n)||!n.cwd&&!wi.some(e=>e.workspaceId===n.workspaceId):!1},qs=vg(Ce,Ce.index+ +!Ws,-1,Ks),Js=vg(Ce,Ce.index,1,Ks),Ys=e=>{if(Oe){Te.current.length<20&&Te.current.push(e);return}let t=e<0?qs:Js;t<0||ke({index:t,direction:e,ticket:++de.current,stage:`start`})},Xs=(0,p.useRef)(Ys);Xs.current=Ys,(0,p.useEffect)(()=>{if(Oe||!Te.current.length)return;let e=de.current,t=requestAnimationFrame(()=>{if(de.current!==e){Te.current=[];return}let t=Te.current.shift();t&&Xs.current(t)});return()=>cancelAnimationFrame(t)},[Oe,Ce.index]),(0,p.useEffect)(()=>{let e=e=>{(e.button===3||e.button===4)&&(e.preventDefault(),e.stopPropagation(),e.type===`mouseup`&&Xs.current(e.button===3?-1:1))};for(let t of[`mousedown`,`mouseup`,`auxclick`])window.addEventListener(t,e,!0);return()=>{for(let t of[`mousedown`,`mouseup`,`auxclick`])window.removeEventListener(t,e,!0)}},[]),(0,p.useEffect)(()=>{let e=Oe;if(!e)return;if(de.current!==e.ticket){Te.current=[],ke(void 0);return}let t=Ce.entries[e.index];if(gg(t,Ws)){we(t=>({...t,index:e.index})),ke(void 0);return}let n=(t=e.ticket)=>{let n=vg(Ce,e.index,e.direction,Ks);ke(n<0?void 0:{...e,index:n,ticket:t,stage:`start`})};if(!Ks(t)){n();return}let r=t.scope;if(r&&(r.workspaceId!==Ua||r.cwd!==Ka)){if(e.stage!==`start`){n();return}let t=Gs(r);t?Pa(t.id):Ia(r.workspaceId),ke({...e,stage:`scope`,ticket:de.current});return}if(t.key===Ws?.key&&t.position&&e.stage!==`position`){let n=Us?.content.split(`
|
|
349
|
+
`)??[``],r=Math.max(1,Math.min(t.position.line,n.length)),i=Math.max(1,Math.min(t.position.column,n[r-1].length+1));we(t=>({...t,entries:t.entries.map((t,n)=>n===e.index?{...t,position:{line:r,column:i}}:t)})),ls({scope:Qo,path:Us.path,line:r,column:i,request:de.current}),ke({...e,stage:`position`});return}if(e.stage===`opening`||e.stage===`position`||r&&V.restoringWorkbench)return;jn(!1),kn();let i=t.file;if(i&&!V.open.some(e=>e.path===i.path)){let r=Ms(i,t.position?.line,!1,!0,!0,t.position?.column),a=de.current;ke({...e,stage:`opening`,ticket:a}),r.then(e=>{!e&&de.current===a&&ke(void 0)}).catch(e=>{de.current===a&&(e instanceof fh&&e.status===404?(Ae.current.add(t.key),n(a)):(Sc(zr(e instanceof Error?e.message:void 0,`无法打开导航历史中的文件。`),`error`),ke(void 0)))})}else t.gitDiff&&!hs.some(e=>e.target.url===t.gitDiff.target.url)?(gs(e=>[...e,{...t.gitDiff,preview:!1}]),vs(t.gitDiff.target.url),at(`gitDiff`)):t.tabId.startsWith(`diff:`)&&!Rs.some(e=>e.id===t.tabId)?Ts(t.tabId.slice(5),!0):Vs(t.tabId),ke({...e,stage:`opening`,ticket:de.current})});let Zs=(0,p.useCallback)(e=>{if(e.startsWith(`session:`))Fa(e.slice(8));else if(e.startsWith(`file:`))V.pinFile(e.slice(5));else if(e.startsWith(`diff:`)){let t=e.slice(5);ps(e=>e.previewPath===t?{paths:e.paths}:e)}else e.startsWith(`git-diff:`)&&gs(t=>t.map(t=>t.preview&&`git-diff:${t.target.url}`===e?{...t,preview:!1}:t))},[Fa,V.pinFile]),Qs=Rs.filter(e=>e.kind===`file`||e.kind===`diff`),$s=oo&&so!==Y?Qs.find(e=>e.id===so):void 0,ec=e=>{Qs.some(t=>t.id===e)&&(de.current++,co(e),e===Y&&Cs())},tc=()=>{if(oo){de.current++,$s&&Zs($s.id),Qa(void 0);return}de.current++;let e=Qs.find(e=>e.id===Y)??Qs.at(-1);Qa({scope:Xa,tabId:e?.id}),e&&e.id===Y&&(z&&!Ma?Pa(z.id):Cs())},nc=(0,p.useCallback)(e=>{let t=ka.indexOf(e);if(t<0)return;let n=ka.filter(t=>t!==e);if(ce(t=>({...t,ids:t.ids.filter(t=>t!==e),previewId:t.previewId===e?void 0:t.previewId,emptied:n.length===0||t.emptied})),z?.id!==e||R!==`session`)return;de.current++;let r=n[Math.min(t,n.length-1)];if(r)ee(r);else if(V.open.length>0){let e=V.activePath&&V.open.some(e=>e.path===V.activePath)?V.activePath:V.open[0].path;V.setActivePath(e),at(`file`)}else ms.length>0?(ds(ms[0]),at(`diff`)):hs.length>0?(vs(hs[0].target.url),at(`gitDiff`)):ee(void 0)},[ka,z,V,ms,hs,R]),rc=(0,p.useCallback)(e=>{if(e.startsWith(`group:`)){let t=Ze.filter(t=>lr(t)!==e);if(nt(t),R===`group`&&Y===e){let e=t.filter(e=>e.workspaceId===ht).at(-1);e?La(e.workspaceId,e.roomId):Cs()}}else if(e.startsWith(`file:`)){let t=e.slice(5);V.closeFile(t),R===`file`&&V.activePath===t&&V.open.length<=1&&de.current++}else if(e.startsWith(`diff:`)){let t=e.slice(5);ps(e=>({paths:e.paths.filter(e=>e!==t),previewPath:e.previewPath===t?void 0:e.previewPath})),R===`diff`&&us===t&&(de.current++,ds(void 0),Cs())}else if(e.startsWith(`session:`)){let t=e.slice(8);nc(t)}else if(e.startsWith(`git-diff:`)){let t=e.slice(9),n=hs.findIndex(e=>e.target.url===t);if(n<0)return;let r=hs.filter(e=>e.target.url!==t);gs(r);let i=document.activeElement?.getAttribute(`data-diff-tab-close`)===e;if(ys?.target.url===t){de.current++;let e=r[Math.max(0,n-1)];vs(e?.target.url),e||Cs()}i&&requestAnimationFrame(()=>{let e=document.querySelector(`.chat-tab-strip [role="tab"][aria-selected="true"]`),t=hs[n].origin;(e??(t?.getClientRects().length?t:void 0)??document.querySelector(`[data-workspace-welcome-create]:not(:disabled)`))?.focus()})}},[V,nc,us,R,hs,ys?.target.url,Cs,ht,Ze,Y,La]),ic=V.active,ac=JSON.stringify([Ua,Ka,ic?.path]),oc=(0,p.useCallback)(e=>{De(t=>e?{scope:ac,position:e}:t?.scope===ac?void 0:t)},[ac]),sc=Ee?.scope===ac?Ee.position:void 0,[cc,lc]=(0,p.useState)(),uc=(0,p.useRef)(null),[dc,fc]=(0,p.useState)(``),[pc,mc]=(0,p.useState)({}),hc=O.workspaces.find(e=>e.id===Ua),gc=O.workspaces.find(e=>e.id===Ga),_c=(e,t)=>{let n=e&&xh(e.path),r=e&&(e.assetTicket||n?(0,m.jsx)(`span`,{className:`file-editor-path`,title:n??e.path,children:n??e.path}):(0,m.jsx)(Vi,{root:Ka.split(`/`).at(-1)||hc?.name||`工作目录`,path:e.path,reveal:(e,t)=>{Wo(`file-tree`),V.locatePath(e,t)}})),i=cs?.scope===Qo&&cs?.path===e?.path?cs:void 0,a=e&&(!e.view||e.view===`table`)&&(0,m.jsx)(Ph,{file:e,state:V.saves[e.path]?.state??`idle`,message:V.saves[e.path]?.message??``,external:V.external[e.path]===!0,jumpToLine:i,languageOverride:pc[JSON.stringify([Ua,Ka,e.path])],onChange:t=>V.updateBuffer(e.path,t),onSave:()=>void V.save(e.path,!1),onReload:()=>void V.reload(e.path),onOverwrite:()=>void V.save(e.path,!0),workspaceId:Ua,cwd:Ka,navigation:e.view?void 0:r,embedded:!!e.view,onPosition:t?oc:void 0});return(0,m.jsx)(`div`,{className:`chat-file-view`,"data-main-file-view":e?.path,"data-file-view-kind":`editor`,children:e?.view&&Ua?(0,m.jsx)(Cp,{workspaceId:Ua,cwd:n?``:Ka,path:n??e.path,name:e.name,kind:e.view,content:e.content,version:e.etag,source:a||void 0,external:V.external[e.path],navigation:r,assetTicket:e.assetTicket,onReload:()=>void V.reload(e.path),sourceRequest:i?.request},JSON.stringify([Ua,Ka,e.path])):a||(0,m.jsx)(`p`,{className:`rail-empty`,"data-main-file-empty":`1`,children:`没有选中的文件。`})})},vc=e=>qa&&!e.target.commitHash?(0,m.jsx)(`div`,{className:`chat-file-view`,role:`status`,children:(0,m.jsx)(`p`,{className:`rail-empty`,children:`请选择具体 session 以确定工作区,再查看或编辑工作区差异。`})}):(0,m.jsx)(`div`,{className:`chat-file-view chat-git-diff`,"data-main-diff-view":e.target.path,"data-file-view-kind":`diff`,children:(0,m.jsx)(p.Suspense,{fallback:(0,m.jsx)(`p`,{className:`rail-empty`,role:`status`,children:`正在读取差异…`}),children:(0,m.jsx)(KA,{tab:e,dark:Jl!==`github-light`&&Jl!==`solarized-light`},JSON.stringify([e.target.url,e.revision]))})}),yc=(e,t)=>{let n=t?U:ks;return(0,m.jsx)(`div`,{className:`chat-file-view`,"data-main-diff-view":e??``,"data-file-view-kind":`diff`,children:(0,m.jsx)(Lh,{diff:n.diff,loading:n.loading,error:n.error,bufferContent:As(e),mode:t?K:W,onMode:t?q:G})})},bc=()=>{let e=$s?.id;if(!e)return null;if(e.startsWith(`file:`))return _c(V.open.find(t=>`file:${t.path}`===e),!1);if(Os)return yc(Os,!0);let t=hs.find(t=>`git-diff:${t.target.url}`===e);return t?vc(t):null},xc=z?.id;(0,p.useEffect)(()=>{xc&&!xc.startsWith(`pending:`)&&kc({type:`conversation.select`,conversationId:xc})},[xc]);let Sc=(e,t=`info`)=>{if(!e)return;let n=++si.current;$t(r=>[...r,{key:n,text:e,kind:t}]),ci.current.push(window.setTimeout(()=>$t(e=>e.filter(e=>e.key!==n)),7e3))},Cc=(e,t=``)=>{if(hc&&hc.id===e&&Ka===t)return n=>{let r=lt(n,{root:hc.path,cwd:t,origin:window.location.origin});if(r)return{title:r.artifact?r.path:`${r.path}:${r.line}${r.column?`:${r.column}`:``}`,open:()=>{let n=Zh(r.path,t);!Va&&z?.workspaceId===e&&Na(z.id),Ms(n,r.artifact?void 0:r.line,!0,!0,!1,r.artifact?void 0:r.column??1).catch(e=>Sc(`打不开「${n.name}」:${e instanceof Error?e.message:`文件不可用`}`,`error`))}}}},wc=Cc(z?.workspaceId,z?.cwd),Tc=async e=>{try{await window.superPiDesktop?.notifications?.configure?.({enabled:e})}catch(e){Sc(e instanceof Error?e.message:`无法更新桌面提醒设置`,`error`);return}if(!e){r(!1);try{window.localStorage.setItem(`super-pi.browser-notifications`,`disabled`)}catch{}}else if(typeof window>`u`||typeof Notification>`u`&&!window.superPiDesktop?.notifications)a(`unsupported`);else if(!window.isSecureContext&&!window.superPiDesktop?.notifications)a(`insecure`);else try{let e=await to();a(e);let t=e===`granted`||e===`native`;r(t);try{window.localStorage.setItem(`super-pi.browser-notifications`,t?`enabled`:`disabled`)}catch{}}catch{a(eo()),r(!1),Sc(`请求浏览器通知权限失败,请检查站点权限后重试。`,`error`)}};(0,p.useEffect)(()=>{window.superPiDesktop?.notifications?.configure?.({enabled:n}).catch(e=>Sc(e instanceof Error?e.message:`无法恢复桌面通知设置`,`error`))},[n]),(0,p.useEffect)(()=>{let e=()=>{for(let e of l.current.values())e.close();l.current.clear()},t=()=>{if(a(eo()),document.visibilityState===`visible`&&document.hasFocus()){let t=window.superPiDesktop?.notifications;t?.clearSystem?t.status().then(n=>{n.mode===`pet`||n.mode===`both`?t.clearSystem?.():e()}).catch(()=>{}):e();try{window.localStorage.setItem(`super-pi.browser-notification-focus`,String(Date.now()))}catch{}}},n=t=>{t.key===`super-pi.browser-notification-focus`&&e()};window.addEventListener(`focus`,t);let r=!1,i;return navigator.permissions?.query&&navigator.permissions.query({name:`notifications`}).then(e=>{r||(i=e,e.addEventListener(`change`,t),t())}).catch(()=>{}),window.addEventListener(`storage`,n),document.addEventListener(`visibilitychange`,t),()=>{r=!0,i?.removeEventListener(`change`,t),window.removeEventListener(`focus`,t),window.removeEventListener(`storage`,n),document.removeEventListener(`visibilitychange`,t),e()}},[]),(0,p.useEffect)(()=>{let e=z?.id,t=z?.agentNotice;e&&t&&!fi.current.has(e)&&(fi.current.add(e),Sc(t,`info`))},[z?.id,z?.agentNotice]);let Ec=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},X=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);if(n<0)return[t,...e];let r=[...e];return r[n]=t,r},Dc=(e,t)=>{if(t.method===`notify`)Sc(t.message||t.title,t.notifyType??`info`);else if(t.blocking||t.method===`setStatus`||t.method===`setWidget`||t.method===`setTitle`){let n=e=>e.blocking?e.requestId:e.statusKey??e.widgetKey??``,r=t.method===`setStatus`&&t.statusText===void 0||t.method===`setWidget`&&t.widgetLines===void 0||t.method===`setTitle`&&!t.title;Zt(i=>{let a=i.filter(r=>r.conversationId!==e||r.request.method!==t.method||n(r.request)!==n(t));return r?a:[...a,{conversationId:e,request:t}]})}else t.method===`set_editor_text`&&e===li.current&&da(t.text??``)},Oc=(e,t,n)=>{Zt(n=>n.filter(n=>!(n.conversationId===e&&n.request.blocking&&n.request.requestId===t)));let r=Wk[n];r&&Sc(r,`warning`)};(0,p.useEffect)(()=>{let e=!1;return(()=>{if(e)return;let t=new Be(li.current);He.current=t,t.onopen=()=>{if(!e){F(!0);for(let e of[{type:`stream.configure`,coalesce:!0},{type:`catalog.fetch`,conversationId:li.current},...$i.current?[{type:`prompt.catalog.fetch`,workspaceId:$i.current}]:[],{type:`catalog.fetchAll`},{type:`agent.catalog.fetch`},{type:`subagent.catalog.fetch`}])t.canSend(e)&&t.send(JSON.stringify(e))}},t.onserveropen=e=>{for(let n of g.current)n.retry&&n.command&&n.serverId===e&&t.canSend(n.command)&&t.send(JSON.stringify({...n.command,operationRequestId:n.id}))},t.ondisconnect=(t,n)=>{if(e)return;let r=ID(g.current.filter(e=>e.serverId===t));for(let e of r.failed)e.onFailure?.(`${ye(t)} 连接中断`);g.current=g.current.filter(e=>!r.failed.includes(e)),f(g.current),Sc(`${ye(t)} 连接中断${n?`(code ${n.code}${n.reason?` · ${n.reason}`:``})`:``},正在自动重连。`,`warning`)},t.onmessage=({data:t})=>{if(e)return;let n=JSON.parse(t);if(n.type===`group.activity`)ft(n);else if(n.type!==`message.delta`&&n.type!==`message.thinking`&&Mt(),n.type===`message.accepted`){Cm(n.conversationId,n.clientId);for(let e of g.current)e.command?.conversationId===n.conversationId&&e.command?.clientId===n.clientId&&(e.receipt=!0)}else if(n.type===`exec.output`){let e=Dt.current.get(n.sessionId),t=e?.raw??e?.text??``,r=n.offset===void 0?void 0:n.offset-n.data.length;if(!n.replace&&e?.offset!==void 0&&n.offset!==void 0&&n.offset<=e.offset)return;let i=e&&(r===void 0||e.offset!==void 0&&e.offset>=r),a=r!==void 0&&e?.offset!==void 0?Math.max(0,e.offset-r):0,o=(n.replace||!i?n.data:t+n.data.slice(a)).slice(-XO),s=ZO(o);Dt.current.delete(n.sessionId),Dt.current.set(n.sessionId,{text:s.slice(-XO),raw:o,offset:n.offset,truncated:n.offset===void 0?n.truncated||o.length>128e3:n.offset>o.length}),Dt.current.size>64&&Dt.current.delete(Dt.current.keys().next().value),window.dispatchEvent(new CustomEvent(`super-pi-exec-output`,{detail:n.sessionId}))}else if(n.type===`run.stopping`)Fr(e=>{let t=new Set(e);return t.add(n.conversationId),t});else if(n.type!==`exec.exit`){if(n.type.startsWith(`terminal.`))Ot.current?.(n);else if(n.type===`conversation.autoRename.result`){let e=Hr.current.get(n.conversationId);e&&(Hr.current.delete(n.conversationId),n.ok?e.resolve(n.title):e.reject(Error(n.error)))}else if(n.type===`message.thinking`)Nt(n);else if(n.type===`state`){Mt(),ui.current=!1;let e=li.current,t=!!(e&&mi.current.has(e)),r=!(!e||n.state.conversations.some(t=>t.id===e)),i=t&&r&&e&&_i.current.has(e)?{...n.state,conversations:[_i.current.get(e),...n.state.conversations]}:n.state;e&&!r&&(mi.current.delete(e),_i.current.delete(e)),g.current=g.current.filter(e=>!e.accepted?.(i)||i.sendReceipts&&e.retry&&!e.receipt?!0:(e.retry&&typeof e.command?.conversationId==`string`&&typeof e.command.clientId==`string`&&Cm(e.command.conversationId,e.command.clientId),!1)),f(g.current),Fr(e=>{let t=new Set(e);for(let e of[...t]){let n=i.conversations.find(t=>t.id===e);(!n||n.status!==`running`&&n.status!==`waiting`)&&t.delete(e)}return t}),i.extensionUi&&Zt(i.extensionUi),i.stoppingConversationIds&&Fr(new Set(i.stoppingConversationIds)),u(i),Ne(!0),F(!0);let a=g.current.filter(e=>e.key===`create-workspace`).map(e=>e.temporaryId);N(e=>{if(!e&&Wn.current)return;if(e&&(oe(e)||i.workspaces.some(t=>t.id===e)||a.includes(e)))return e;let t=_.current?.workspaceId;return t&&i.workspaces.some(e=>e.id===t)?t:i.workspaces[0]?.id})}else if(n.type===`message.delta`)Nt(n);else if(n.type===`queue.withdrawn`){Ri(e=>[...e.filter(e=>e.conversationId!==n.conversationId).slice(-9),{id:`withdrawn_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,conversationId:n.conversationId,actor:n.actor,withdrawn:n.withdrawn}]);let e=n.withdrawn.slice(0,2).map(e=>`「${e.content.replace(/\s+/g,` `).trim().slice(0,24)}」`).join(`、`),t=n.actor===`agent`?`上级 Agent 已撤回`:`已撤回`;Sc(`${t} ${n.withdrawn.length} 条排队消息:${e}${n.withdrawn.length>2?`…`:``}`,`info`)}else if(n.type===`message.revert.result`)Su(void 0),Nr(void 0),n.ok||(console.error(`[Super Pi Error] revert failed:`,n.message),re(n.message));else if(n.type===`operation.result`){let e=g.current.find(e=>e.id===n.requestId),t=e?.retry?e.command:void 0;if(t&&Cm(t.conversationId,t.clientId),g.current=g.current.filter(e=>e.id!==n.requestId),f(g.current),e?.temporaryId){let t=e.temporaryId;if(e.key===`create-workspace`&&n.ok&&n.entityId){let r=n.entityId;u(n=>{if(n.workspaces.some(e=>e.id===r))return n;let i=e.apply(n).workspaces.find(e=>e.id===t);return i?{...n,workspaces:[...n.workspaces,{...i,id:r}]}:n})}else if(n.ok&&n.entityId){let e=n.entityId,r=bi.current.get(t);if(r&&_i.current.set(e,{...r,id:e}),mi.current.add(e),r){let t={...r,id:e};u(n=>n.conversations.some(t=>t.id===e)?n:{...n,conversations:[t,...n.conversations]})}Wr(n=>{let r=n[t];if(!r)return n;let i=n[e],a={...n};return a[e]=i?{...i,text:r.text||i.text,images:r.images.length?r.images:i.images,attachments:r.text?r.attachments:i.attachments,pendingSkills:r.text?r.pendingSkills:i.pendingSkills,uploading:r.uploading+i.uploading}:r,delete a[t],a}),bi.current.delete(t)}ee(r=>r===t?n.ok?n.entityId:e.previousActiveId:r),ce(e=>Oj(e,t,n.ok&&n.entityId?n.entityId:void 0)),N(r=>r===t?n.ok?n.entityId:e.previousWorkspaceId:r),!n.ok&&e.key===`create-workspace`&&$i.current===t&&ee(t=>t??e.previousActiveId)}if(n.ok&&e?.key.startsWith(`reload:`)&&Sc(`会话资源已重新加载,历史和草稿保持不变`,`success`),!n.ok){if(console.error(`[Super Pi Error] operation failed:`,n.message),!e?.receipt){if(e?.onFailure)e.onFailure(n.message);else if(t){let e=t.images??[],r=iA(t.content,t.attachments);Yr(i=>[...i,{id:t.clientId,conversationId:t.conversationId,content:t.content,images:e,attachments:r,reason:n.message}]),la(t.conversationId,n=>n.text||n.images.length||n.attachments.length?n:{...n,text:t.content,images:e,attachments:r})}}let r=n.message??`操作失败`;re(r),e?.onFailure||Sc(zr(r),`error`)}}else n.type===`tools.updated`?window.dispatchEvent(new Event(`super-pi-tools-updated`)):n.type===`files.changed`?(fo.current(n.workspaceId,n.changes,n.dropped),n.workspaceId===mo.current&&uo.current()):n.type===`files.invalidated`?(po.current(n.workspaceId,n.paths),n.workspaceId===mo.current&&uo.current()):n.type===`error`?(console.error(`[Super Pi Error]`,n.message),n.recordedTurnFailure||(re(n.message),Sc(zr(n.message),`error`),ui.current&&=!1)):n.type===`extension.ui`?Dc(n.conversationId,n.request):n.type===`extension.ui.closed`?Oc(n.conversationId,n.requestId,n.reason):n.type===`model.catalog`?(!n.conversationId||n.conversationId===li.current)&&nn(n.catalog):n.type===`model.catalog.all`?an(n.catalog):n.type===`providers.list`?(sn(n.providers),ln(n.apis)):n.type===`agent.catalog`?((n.sourceServerId??me())===me()&&dn(n.catalog),(n.sourceServerId??me())===he()&&_n(n.catalog)):n.type===`prompt.catalog`?Yt(n.catalog):n.type===`subagent.catalog`?((n.sourceServerId??me())===me()&&pn(n.catalog),(n.sourceServerId??me())===he()&&yn(n.catalog)):n.type===`server.version`?hn(n.version):n.type===`subagent.event`?u(e=>({...e,subagentRuns:Ec(e.subagentRuns??[],n.run)})):n.type===`workflow.event`?u(e=>({...e,workflows:X(e.workflows??[],n.workflow)})):n.type===`message.tools`?u(e=>({...e,conversations:e.conversations.map(e=>e.id===n.conversationId?{...e,messages:e.messages.map(e=>e.id===n.messageId?{...e,toolCalls:n.toolCalls}:e)}:e)})):n.type===`conversation.fork.result`&&(Au(e=>e===n.conversationId?void 0:e),Sc(n.ok?`已从「${n.title}」分叉出新会话,放在侧边栏最上面;没有切换过去。${n.messagesCopied?`复制了 ${n.messagesCopied} 条消息。`:`原会话还没有消息,只复制了会话本身。`}`:`分叉失败:${zr(n.message)}`,n.ok?`info`:`error`))}}})(),()=>{e=!0,Mt();for(let e of ci.current)window.clearTimeout(e);He.current?.close()}},[Nt,Mt,ft]);let kc=(0,p.useCallback)(e=>{if(!He.current?.canSend(e))return!1;try{return He.current.send(JSON.stringify(e)),!0}catch(e){return Sc(e instanceof Error?e.message:`服务器未连接`,`error`),!1}},[]),Ac=(0,p.useCallback)(e=>{Se({id:e,ticket:++de.current});let t=li.current;t?.startsWith(`pending:`)||kc({type:`state.subscribe`,...t?{conversationId:t}:{}}),kn()},[kc,kn]);(0,p.useEffect)(()=>{if(!fe)return;if(fe.ticket!==de.current){Se(void 0);return}let e=Di.find(e=>e.id===fe.id);e&&O.workspaces.some(t=>t.id===e.workspaceId)&&(Se(void 0),Pa(e.id),N(e.workspaceId))},[fe,Di,O.workspaces,Pa]),(0,p.useEffect)(()=>{if(!te||!Me||oe(j??M))return;let e=z?.id;e?.startsWith(`pending:`)||kc({type:`state.subscribe`,...e?{conversationId:e}:{}})},[z?.id,j,M,te,Me,kc]);let jc=(e,t,n,r,i,a,o)=>{let s=He.current?.canSend(e)===!0,c=FD(e);if(g.current.some(e=>e.key===t)||!s&&!c)return!1;if(c&&!Sm(e))return Sc(`浏览器无法保存待发消息,正文仍在输入框。`,`error`),!1;let l=tn(),u=D(e),d=[...u][0]??e._server??me(),p={id:l,key:t,serverId:d,apply:e=>u.size||me()===d?n(e):e,temporaryId:r,previousActiveId:li.current,previousWorkspaceId:$i.current,onFailure:i,accepted:a,...o?{expiresAt:Date.now()+o}:{},...c?{retry:!0,command:e}:{}};return g.current=[...g.current,p],f(g.current),s&&He.current.send(JSON.stringify({...e,operationRequestId:l})),!0},Mc=e=>kc({...e,_server:he()}),Nc=(e,...t)=>jc({...e,_server:he()},...t),Pc=(e,t)=>{kc({type:`conversation.childLock`,conversationId:e,unlocked:t})||Sc(t?`连接断开,这个子会话没有解锁,请重试`:`连接断开,这个子会话没有上锁,请重试`,`error`)},Fc=e=>{if(!e)return;let t=`message_${tn()}`;jc({type:`message.send`,conversationId:e,content:Nk,clientId:t},`continue-truncated:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===e?{...t,warning:void 0}:t)}),void 0,void 0,void 0)};(0,p.useEffect)(()=>{let e=d.flatMap(e=>e.expiresAt?[e.expiresAt]:[]);if(!e.length)return;let t=window.setTimeout(()=>{let e=g.current.filter(e=>e.expiresAt&&e.expiresAt<=Date.now());if(e.length){g.current=g.current.filter(t=>!e.includes(t)),f(g.current);for(let t of e)t.onFailure?.(`打断请求超时,尚未确认是否开始回答;请检查会话状态后重试`)}},Math.max(0,Math.min(...e)-Date.now()));return()=>window.clearTimeout(t)},[d]);let Ic=(e,t)=>n=>({...n,conversations:n.conversations.map(n=>n.id===e?{...n,...t}:n)}),Lc=(e,t)=>n=>({...n,workspaces:n.workspaces.map(n=>n.id===e?{...n,...t}:n)}),Rc=z?.id.startsWith(`pending:`)===!0,zc=!!(z&&OA(z)&&(Pr.has(z.id)||d.some(e=>e.key===`stop:${z.id}`))),Bc=z?.messagesLoaded===!1||d.some(e=>e.key.startsWith(`send:${z?.id}:`)||e.key===`configuration:${z?.id}`||e.temporaryId===z?.id||e.key===`archive:${z?.id}`),Vc=(e,t,n,r,i)=>{e&&kc({type:`question.answer`,conversationId:e,messageId:t,callIndex:n,answers:r,cancelled:i})},Hc=(e,t)=>kr(n=>({...n,[e]:t})),Uc=(e,t,n)=>(Na(e),jc({type:`extension.ui.answer`,conversationId:e,requestId:t,...n},`answer:${e}:${t}`,e=>e)),Wc=z?.model??en?.defaultModel,Gc=z?.thinkingLevel??en?.defaultThinkingLevel,Kc=Gc&&en?.levels.includes(Gc)?Gc:void 0,qc=en?.source===`pi`,Jc=en?.models.find(e=>e.provider===Wc?.provider&&e.modelId===Wc?.modelId),Yc=!!Jc?.imageInput,Xc=(e,t)=>!e||!t?e:{...e,models:e.models.filter(e=>(O.modelFilterRules??[]).every(n=>{try{let r=new RegExp(n.workspacePattern,`i`),i=[t.name,t.path,t.worktreeProjectPath].filter(e=>!!e).some(e=>r.test(e.replaceAll(`\\`,`/`))),a=new RegExp(n.modelPattern,`i`);return!i||a.test(e.label)||a.test(`${e.provider}/${e.modelId}`)}catch{return!0}}))},Zc=!!z?.messages?.some(e=>e.images&&e.images.length>0),Qc=Xc(en,O.workspaces.find(e=>e.id===z?.workspaceId))?.models??[],$c=Zc?Qc.filter(e=>e.imageInput):Qc,el=$c.map(e=>({key:`${e.provider}/${e.modelId}`,label:e.label,detail:[e.detail,qO(e.contextWindow)?`${qO(e.contextWindow)} 上下文`:``,JO(e.maxTokens)?`${JO(e.maxTokens)} 输出`:``].filter(Boolean).join(` · `),badge:Rk(e),selected:Wc?.provider===e.provider&&Wc.modelId===e.modelId})),tl=(en?.levels??[]).map(e=>({key:e,label:e,selected:e===Gc})),nl=e=>{if(!z)return;let[t,n]=e.split(`/`);t&&n&&(Na(z.id),jc({type:`conversation.model`,conversationId:z.id,provider:t,modelId:n},`configuration:${z.id}`,Ic(z.id,{model:en?.models.find(e=>e.provider===t&&e.modelId===n)??{provider:t,modelId:n,label:n}})))},rl=e=>{z&&(Na(z.id),jc({type:`conversation.thinking`,conversationId:z.id,level:e},`configuration:${z.id}`,Ic(z.id,{thinkingLevel:e})))},il=un?.agents.find(e=>e.id===z?.agentId),al=[{key:yA,label:`跟随 Pi 默认`,detail:`不使用任何 agent 角色`,selected:!z?.agentId},...(un?.agents??[]).map(e=>({key:e.id,label:e.name,detail:e.toolSummary,color:e.color,selected:z?.agentId===e.id}))],ol=il?.model,sl=!!(ol&&z?.model&&z.model.provider===ol.provider&&z.model.modelId===ol.modelId);il?.thinkingLevel&&(z?.thinkingLevel,il.thinkingLevel);let cl=e=>{if(z){let t=un?.agents.find(t=>t.id===e);jc({type:`conversation.agent`,conversationId:z.id,agentId:e===yA?null:e},`configuration:${z.id}`,Ic(z.id,{agentId:t?.id,...t?.model?{model:{...t.model,label:t.model.modelId}}:{},...t?.thinkingLevel?{thinkingLevel:t.thinkingLevel}:{}}))}},ll=xn.filter(e=>e.conversationId===z?.id),ul=(0,p.useMemo)(()=>{let e=z?.id;return e?(z.messages??[]).flatMap(t=>(t.toolCalls??[]).flatMap((n,r)=>n.question?.status===`pending`?[{key:dA(e,t.id,r),messageId:t.id,index:r,value:n.question}]:[])):[]},[z?.id,z?.messages]),Z=ul[0],dl=()=>{let e=Z;e&&(jr(e.key),at(`session`),window.setTimeout(()=>{(yt.current?.querySelector(`[data-transcript-key="${CSS.escape(`m:${e.messageId}`)}"]`))?.scrollIntoView({block:`center`,behavior:`smooth`})},0))},fl=Xt.filter(e=>e.conversationId===z?.id).map(e=>e.request),pl=new Map(fl.filter(e=>e.method===`setStatus`).map(e=>[e.statusKey??``,e.statusText??``])),ml=new Map(fl.filter(e=>e.method===`setWidget`).map(e=>[e.widgetKey??``,{lines:e.widgetLines??[],placement:e.widgetPlacement??`aboveEditor`}])),hl=fl.find(e=>e.method===`setTitle`)?.title,gl=(0,p.useMemo)(()=>(O.subagentRuns??[]).filter(e=>e.conversationId===z?.id),[O.subagentRuns,z?.id]),_l=(0,p.useMemo)(()=>(O.workflows??[]).filter(e=>e.conversationId===z?.id),[O.workflows,z?.id]),vl=(0,p.useMemo)(()=>new Map(_l.map(e=>[e.id,e])),[_l]),yl=(0,p.useMemo)(()=>new Map((fn?.agents??[]).map(e=>[e.id,e.name])),[fn]),bl=(0,p.useMemo)(()=>new Map((z?.messages??[]).map(e=>[e.id,e])),[z?.messages]),xl=(0,p.useMemo)(()=>new Map(gl.map(e=>[e.id,e])),[gl]),Sl=(0,p.useMemo)(()=>{let e=new Map;for(let t of gl)t.originMessageId!==void 0&&t.originCallRow!==void 0&&e.set(`${t.originMessageId}:${t.originCallRow}`,t);return e},[gl]),Cl=(0,p.useMemo)(()=>{if(!z||!Ma)return[];let e=Mr?.conversationId===z.id?(()=>{let e=z.messages.find(e=>e.id===Mr.messageId);if(e)return{index:z.messages.indexOf(e),at:Date.parse(e.createdAt)||0,inclusive:!0}})():void 0,t=[];return z.messages.forEach((n,r)=>{e&&(r>e.index||e.inclusive&&r===e.index)||n.delivery||n.batchedInto||t.push({at:Date.parse(n.createdAt)||0,seq:r,key:`m:${n.id}`})}),gl.forEach((n,r)=>{n.originMessageId&&n.originCallRow!==void 0&&z?.messages.some(e=>e.id===n.originMessageId&&e.toolCalls?.[n.originCallRow])||e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`r:${n.id}`})}),_l.forEach((n,r)=>{e&&(Date.parse(n.startedAt)||0)>e.at||t.push({at:Date.parse(n.startedAt)||0,seq:t.length+r,key:`w:${n.id}`})}),Ya(t)},[z,gl,_l,Mr]),wl=(0,p.useMemo)(()=>{for(let e=Cl.length-1;e>=0;--e){let t=Cl[e];if(t.startsWith(`m:`)&&bl.get(t.slice(2))?.role===`user`)return t.slice(2)}},[Cl,bl]);(0,p.useEffect)(()=>{let e=yt.current;if(!e||!z?.id)return;let t=()=>{!Et.current&&Ue.current[z.id]?.followTail&&(Sj(e),e.scrollTop=e.scrollHeight)};if(t(),typeof ResizeObserver>`u`)return;let n=new ResizeObserver(t);n.observe(e);for(let t of e.children)n.observe(t);return()=>n.disconnect()},[z?.id,z?.messages,gl,_l,Ma,Cl,R]);let Tl=e=>Cr(t=>({...t,[e]:!t[e]})),El=(e,t)=>Tr(n=>({...n,[`${e}:${t}`]:!n[`${e}:${t}`]})),Dl=(e,t)=>Dr(n=>({...n,[`${e}:${t}`]:n[`${e}:${t}`]!==!1})),[Ol,kl]=(0,p.useState)({}),Al=e=>kl(t=>({...t,[e]:t[e]!==!0})),jl=e=>{jc({type:`subagent.stop`,runId:e},`stop:${e}`,e=>e)||Sc(`连接断开,无法停止子智能体,请重试`,`error`)},Ml=e=>{jc({type:`workflow.stop`,workflowId:e},`stop:${e}`,e=>e)||Sc(`连接断开,无法停止编排,请重试`,`error`)},Nl=e=>[...ml].filter(([,t])=>t.placement===e).map(([e,t])=>{let n=t.lines;return(0,m.jsxs)(`div`,{className:`extui-widget`,"data-widget-key":e,"data-widget-lines":n.length,children:[n.slice(0,Gk).map((e,t)=>(0,m.jsx)(`div`,{children:e},`${t}:${e}`)),n.length>Gk&&(0,m.jsx)(`div`,{children:`… (widget truncated)`})]},e)}),Pl=(e,t)=>{let n=`pending:${tn()}`,r={id:n,name:e,path:t,updatedAt:new Date().toISOString()};jc({type:`workspace.create`,name:e,path:t},`create-workspace`,e=>({...e,workspaces:[...e.workspaces,r]}),n)&&(Ia(n),Le(!1))},[Fl,Il]=(0,p.useState)(),Ll=(e,t)=>Il(n=>n?.kind===e&&n.id===t?n:{kind:e,id:t}),Rl=()=>Il(void 0),zl=(e,t)=>Fl?.kind===e&&Fl.id===t,Bl=(e,t,n)=>!t.startsWith(`pending:`)&&(e===`conversation`&&Na(t),jc(e===`workspace`?{type:`workspace.rename`,workspaceId:t,name:n}:{type:`conversation.rename`,conversationId:t,name:n},`rename:${t}`,e===`workspace`?Lc(t,{name:n}):Ic(t,{title:n}))?(ui.current=!0,Rl(),!0):(Sc(`连接断开,改名未保存,请重试`,`error`),!1)),Vl=async e=>{if(e.startsWith(`pending:`)){Sc(`这个会话还在创建中,稍后再试`,`warning`);return}if(Hr.current.has(e))return;Sc(`正在根据对话内容生成标题…`,`info`);let t=new Promise((t,n)=>{Hr.current.set(e,{resolve:t,reject:n}),window.setTimeout(()=>{Hr.current.delete(e)&&n(Error(`模型在 ${Math.round($O/1e3)} 秒内没有返回标题`))},$O)});if(!kc({type:`conversation.autoRename`,conversationId:e}))Hr.current.delete(e),Sc(`连接断开,无法生成标题`,`error`);else try{let n=await t;Bl(`conversation`,e,n),Sc(`已重命名为「${n}」`,`info`)}catch(e){Sc(`重命名失败:${zr(e)}`,`error`)}},Hl=e=>{if(e.id.startsWith(`pending:`))return;let t=O.conversations.filter(t=>t.workspaceId===e.id).length;window.confirm(`从列表移除工作区「${e.name}」?${t?`其中的 ${t} 条会话会保留,`:``}重新添加同一个目录即可恢复,不会删除任何会话。`)&&(Wl(void 0),jc({type:`workspace.delete`,workspaceId:e.id},`delete:${e.id}`,t=>({...t,workspaces:t.workspaces.filter(t=>t.id!==e.id),conversations:t.conversations.filter(t=>t.workspaceId!==e.id)})))},[Ul,Wl]=(0,p.useState)(),[Gl,Kl]=(0,p.useState)(!1),ql=Ul?O.workspaces.find(e=>e.id===Ul):void 0,{theme:Jl,setTheme:Yl}=y_(),[Xl,Zl]=(0,p.useState)(!1),[Ql,$l]=(0,p.useState)();(0,p.useEffect)(()=>{let e=()=>{_e(),ge(`entry`),$l(`servers`),Zl(!0)};return window.addEventListener(`super-pi-open-server-management`,e),()=>window.removeEventListener(`super-pi-open-server-management`,e)},[]),(0,p.useEffect)(()=>{let e=e=>{let t=e.detail;typeof t==`string`&&O.conversations.some(e=>e.id===t)&&(Pa(t),xr&&kn())};return window.addEventListener(`super-pi-open-rsi-work`,e),()=>window.removeEventListener(`super-pi-open-rsi-work`,e)},[O.conversations,Pa,xr,kn]);let[eu,tu]=(0,p.useState)(!1),nu=(e,t,n,r)=>{e.startsWith(`pending:`)||(jc({type:`workspace.settings`,workspaceId:e,model:n?{provider:n.provider,modelId:n.modelId}:null,thinkingLevel:r??null,agentId:t??null},`defaults:${e}`,Lc(e,{defaultModel:n,defaultThinkingLevel:r,defaultAgentId:t}))?Wl(void 0):Sc(`连接断开,设置未保存,请重试`,`error`))},ru=(e,t)=>{let n=I.activeServer;jc({type:`workspaces.settings.bulk`,model:e?{provider:e.provider,modelId:e.modelId}:null,thinkingLevel:t??null},`workspace-defaults-bulk`,r=>({...r,workspaces:r.workspaces.map(r=>{if(y(r.id).server!==n||r.closedAt||r.id.startsWith(`pending:`))return r;let i={...r};return e?i.defaultModel=e:delete i.defaultModel,t?i.defaultThinkingLevel=t:delete i.defaultThinkingLevel,i})}))?Kl(!1):Sc(`连接断开,批量设置未保存,请重试`,`error`)},iu=(e,t=``)=>{if(e.startsWith(`pending:`))return;if(g.current.some(t=>t.key===`defaults:${e}`)){Sc(`工作区设置正在保存,请稍后再新建会话`,`warning`);return}let n=`pending:${tn()}`,r={id:n,workspaceId:e,title:`新会话`,status:`idle`,updatedAt:new Date().toISOString(),messages:[],...t?{cwd:t}:{}};bi.current.set(n,r),jc({type:`conversation.create`,workspaceId:e,...t?{cwd:t}:{}},`create-session:${e}:${n}`,e=>({...e,conversations:[r,...e.conversations]}),n)?(de.current++,N(e),ee(n),at(`session`),ce(e=>({...e,ids:[...e.ids.filter(e=>e!==n),n],touched:Dj(e.touched,n)}))):(bi.current.delete(n),Sc(`连接断开,会话未创建,请重试`,`error`))},au=e=>{if(e.startsWith(`pending:`))return;let t=O.conversations.find(t=>t.id===e);if(!t||t.archivedAt||t.parentConversationId&&O.conversations.some(e=>e.id===t.parentConversationId))return;let n=Ok(O.conversations,e),r=n.filter(e=>!e.archivedAt),i=r.length-1,a=n.length-r.length,o=YO(O.pendingUserDecisionsByConversation,n.map(e=>e.id)),s=dk({title:t.title,activeCount:r.length,activeDescendants:i,alreadyArchived:a,pendingDecisions:o});if(fk({activeDescendants:i,pendingDecisions:o})&&!window.confirm(s))return;let c=new Date().toISOString(),l=new Set(r.map(e=>e.id));jc({type:`conversation.archive`,conversationId:e},`archive:${e}`,e=>({...e,conversations:e.conversations.map(e=>l.has(e.id)&&!e.archivedAt?{...e,archivedAt:c}:e)}))},ou=(e,t)=>jc({type:`conversation.collapse`,conversationId:e,collapsed:t},`collapse:${e}`,n=>{let r=new Set(n.collapsedConversationIds??[]);t?r.add(e):r.delete(e);let i={...n};return r.size===0?delete i.collapsedConversationIds:i.collapsedConversationIds=[...r],i}),su=e=>{let t=O.conversations.find(t=>t.id===e);if(!t?.archivedAt||(t.parentConversationId?O.conversations.find(e=>e.id===t.parentConversationId):void 0)?.archivedAt)return;let n=new Set(Ok(O.conversations,e).filter(e=>e.archivedAt).map(e=>e.id));jc({type:`conversation.unarchive`,conversationId:e},`unarchive:${e}`,e=>({...e,conversations:e.conversations.map(e=>{if(!n.has(e.id)||!e.archivedAt)return e;let t={...e};return delete t.archivedAt,t})}))},cu=async e=>{if(!z){Sc(`请先选择或创建会话`,`error`);return}if(!Yc){Sc(`当前模型不支持图片输入`,`error`);return}let t=[`image/png`,`image/jpeg`,`image/gif`,`image/webp`],n=e.filter(e=>t.includes(e.type)?e.size>5242880?(Sc(`图片「${e.name}」超过 5MB 上限`,`error`),!1):!0:(Sc(`不支持的文件格式「${e.name}」,仅支持 PNG/JPEG/GIF/WebP`,`error`),!1));if(n.length===0)return;let r=z.id;la(r,e=>({...e,uploading:e.uploading+n.length}));let i=n.map(e=>({id:tn(),conversationId:r,name:e.name,url:URL.createObjectURL(e)}));Zr(e=>[...e,...i]);for(let[e,t]of n.entries()){let n=i[e];try{let e=await new Promise((e,n)=>{let r=new FileReader;r.onload=()=>{let t=r.result,n=t.indexOf(`,`);e(n>=0?t.slice(n+1):t)},r.onerror=n,r.readAsDataURL(t)}),i=await Ie(`/api/upload`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({conversationId:r,name:t.name,mimeType:t.type,data:e})});if(!(i.headers.get(`content-type`)??``).includes(`application/json`)){Sc(`服务器未返回 JSON 响应,请刷新或重启服务`,`error`);continue}if(i.ok){let e=await i.json();if(qr.current.has(n.id))continue;Zr(e=>e.filter(e=>e.id!==n.id)),URL.revokeObjectURL(n.url),la(r,t=>({...t,images:[...t.images,{id:b(L(r),e.id),name:e.name,mimeType:e.mimeType,bytes:e.bytes}]}))}else{let e=await i.json().catch(()=>({error:`上传失败`}));Sc(zr(e.error,`上传失败(HTTP ${i.status})`),`error`)}}catch(e){Sc(`上传失败:${zr(e,`网络或服务暂时不可用`)}`,`error`)}finally{Zr(e=>e.map(e=>e.id===n.id?{...e,failed:!0}:e)),la(r,e=>({...e,uploading:Math.max(0,e.uploading-1)}))}}},lu=e=>{let t=e.clipboardData?.items;if(!t)return;let n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.type.startsWith(`image/`)){let e=r.getAsFile();e&&n.push(e)}}if(n.length>0){if(!Yc){Sc(`当前模型不支持图片输入`,`error`);return}e.preventDefault(),cu(n)}},uu=e=>{e.dataTransfer?.types?.includes(`Files`)&&(e.preventDefault(),ii(!0))},du=e=>{e.currentTarget.contains(e.relatedTarget)||ii(!1)},fu=e=>{ii(!1);let t=Array.from(e.dataTransfer?.files??[]).filter(e=>e.type.startsWith(`image/`));if(t.length>0){if(e.preventDefault(),!Yc){Sc(`当前模型不支持图片输入`,`error`);return}cu(t)}},pu=t=>{if(t.preventDefault(),!z)return;if(Ui){Sc(Xn,`warning`);return}if(Bc){Sc(Rc?`会话正在创建,请稍候再发送`:z.messagesLoaded===!1?`正在加载会话,请稍候再发送`:`正在保存配置,请稍候再发送`,`info`);return}let n=ia.trim(),r=lp(n);if(r){if(r.args||aa.length||oa.length){Sc(`/${r.id} 请单独执行,不要附加正文或附件`,`info`);return}Mu(r.id)&&(la(z.id,e=>({...e,text:``})),ga({visible:!1,query:``,rect:null}));return}if(!n&&aa.length===0)return;if(aa.length>0&&!Yc){Sc(`当前模型不支持图片输入,请移除图片或切换至支持图文的模型`,`error`);return}if(ca>0){Sc(`图片正在上传中,请稍候…`,`info`);return}if(sa){Sc(`技能正在读取中,请稍候…`,`info`);return}let i=`message_${tn()}`,a=z.id,o=ia,s=aa,c=oa;Na(a),e.stoppingConversationIds||Fr(e=>{if(!e.has(a))return e;let t=new Set(e);return t.delete(a),t});let l=aA({conversationId:a,content:o,clientId:i,images:s,attachments:c,inFlight:OA(z),deliveryMode:z.compaction?.status===`running`?`queue`:Pi}),u=new Date().toISOString();jc(l,`send:${a}:${i}`,e=>Tm(e,l,u),i,e=>{Yr(t=>[...t,{id:i,conversationId:a,content:o,images:s,attachments:c,reason:e}]),la(a,e=>e.text||e.images.length||e.attachments.length?e:{...e,text:o,images:s,attachments:c})},e=>!!e.conversations.find(e=>e.id===a)?.messages.some(e=>e.id===wm(l)))&&la(a,e=>({...e,text:``,images:[],attachments:[],pendingSkills:void 0}))},mu=(0,p.useMemo)(()=>(z?.messages??[]).filter(e=>(e.role===`user`||e.role===`tool`)&&e.delivery),[z?.messages]),hu=e=>{jc({type:`message.cancel`,conversationId:z?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===z?.id?{...t,messages:t.messages.filter(t=>t.id!==e)}:t)}))||Sc(`连接断开,撤回没有生效,请重试`,`error`)},gu=e=>{if(!z?.id||!e.length)return;let t=new Set(e),n=`queue-many:${z.id}:${e.join(`,`)}`;jc({type:`message.cancelMany`,conversationId:z.id,messageIds:e},n,e=>({...e,conversations:e.conversations.map(e=>e.id===z.id?{...e,messages:e.messages.filter(e=>!t.has(e.id))}:e)}),void 0,e=>Sc(e??`撤回所选消息失败,请重试`,`error`),t=>{let n=t.conversations.find(e=>e.id===z.id);return!!(n&&e.every(e=>!n.messages.some(t=>t.id===e&&t.delivery)))})||Sc(`连接断开,批量撤回没有生效,请重试`,`error`)},_u=e=>{jc({type:`message.steer`,conversationId:z?.id??``,messageId:e},`queue:${e}`,t=>({...t,conversations:t.conversations.map(t=>t.id===z?.id?{...t,messages:hk(t.messages,e,0)}:t)}),void 0,void 0,t=>t.conversations.find(e=>e.id===z?.id)?.messages.find(t=>t.id===e)?.delivery===`sending`)||Sc(`连接断开,插到最前没有生效,请重试`,`error`)},vu=e=>{let t=z?.id;t&&(He.current?.readyState===WebSocket.OPEN?jc({type:`message.interrupt`,conversationId:t,messageId:e},`interrupt:${t}:${e}`,e=>e,void 0,e=>Sc(e??`打断失败,请重试`,`error`),n=>{let r=n.conversations.find(e=>e.id===t)?.messages.find(t=>t.id===e);return!(!r||r.delivery)},3e4)||Sc(`正在打断,请稍候`,`info`):Sc(`连接断开,打断没有生效,请重试`,`error`))},yu=e=>{jc({type:`message.sendQueued`,conversationId:z?.id??``,messageId:e},`send-queued:${e}`,e=>e,void 0,void 0,t=>!t.conversations.find(e=>e.id===z?.id)?.messages.find(t=>t.id===e)?.delivery)||Sc(`连接断开,发送没有生效,请重试`,`error`)},bu=(e,t)=>{jc({type:`message.edit`,conversationId:z?.id??``,messageId:e,content:t},`edit:${e}`,n=>({...n,conversations:n.conversations.map(n=>n.id===z?.id?{...n,messages:n.messages.map(n=>n.id===e?{...n,content:t}:n)}:n)}))||Sc(`连接断开,修改没有生效,请重试`,`error`)},[xu,Su]=(0,p.useState)(),Cu=(e,t=!0)=>{if(!z||z.messagesLoaded===!1||xu)return;let n=z.messages.find(t=>t.id===e);n&&(Wr(e=>{let t=e[z.id]??{text:``,images:[],attachments:[],uploading:0};return t.text.trim()||t.images.length||t.attachments.length?e:{...e,[z.id]:{...t,text:n.content,images:n.images??[],attachments:iA(n.content,n.attachments)}}}),Nr({conversationId:z.id,messageId:e,kind:t?`withdraw`:`revert`})),kc({type:`message.revert`,conversationId:z.id,messageId:e,withdraw:t})?Su(e):(Nr(void 0),Sc(`连接断开,回退未执行,请重试`,`error`))},[wu,Tu]=(0,p.useState)(),Eu=(0,p.useRef)(void 0),Du=(0,p.useRef)(0),Ou=async(e,t)=>{let n=++Du.current,r=await Hi(t);n===Du.current&&(clearTimeout(Eu.current),Tu({id:e,kind:r?`copied`:`error`}),r||Sc(`复制失败:浏览器拒绝了剪贴板写入,可以手动选中这条消息的文字复制`,`error`),Eu.current=setTimeout(()=>Tu(void 0),2e3))};(0,p.useEffect)(()=>()=>{Du.current+=1,clearTimeout(Eu.current)},[]);let[ku,Au]=(0,p.useState)(),ju=e=>{ku||e.startsWith(`pending:`)||(Na(e),kc({type:`conversation.fork`,conversationId:e})?Au(e):Sc(`连接断开,分叉没有执行,请重试`,`error`))},Mu=e=>{if(!z)return!1;if(e===`reload`||e===`compact`||e===`stop`){if(g.current.some(t=>t.key===`${e}:${z.id}`))return!1;if(e!==`stop`&&(OA(z)||Pr.has(z.id)))return Sc(`请结束或停止当前任务后再执行此操作`,`info`),!1;let t=jc({type:e===`reload`?`conversation.reload`:e===`compact`?`conversation.compact`:`run.stop`,conversationId:z.id},`${e}:${z.id}`,e=>e,void 0,e=>Sc(e??`操作失败,请重试`,`error`),void 0,12e4);return t&&e===`reload`&&Sc(`正在重新加载当前会话的 Agent、技能与扩展…`,`info`),t&&e===`compact`&&(uc.current=document.querySelector(`[data-context-button]`),lc(`context`)),t||Sc(`服务器未连接,操作未执行`,`error`),t}if(e===`new`||e===`clear`)return iu(z.workspaceId,z.cwd),!0;if(e===`fork`)return OA(z)||ku?(Sc(`请结束当前任务或分叉操作后重试`,`info`),!1):(ju(z.id),!0);if(e===`help`)return tu(!0),!0;if(e===`settings`)return $l(void 0),_e(),Zl(!0),Mc({type:`catalog.fetchAll`}),Mc({type:`providers.fetch`}),!0;if(e===`model`){let e=document.querySelector(`#composer-session-options [data-picker-trigger="model"]`);return!e||e.disabled?(Sc(`模型列表尚未就绪,请稍后重试`,`info`),!1):(On(!0),e.click(),!0)}return e===`resume`?(Uo(`sessions`),!0):e===`update`?(bn.open(),!0):e===`restart`||e===`start`?e===`restart`&&!window.confirm(`确定重启此 Super Pi 服务?进行中的任务可能中断。`)?!1:kc({type:e===`restart`?`super_pi.restart`:`super_pi.start`,conversationId:z.id})?!0:(Sc(`服务器未连接,操作未执行`,`error`),!1):!1},Nu=new Map;for(let e of O.scheduledTasks??[])e.conversationId&&!Nu.has(e.conversationId)&&Nu.set(e.conversationId,e);let Pu=(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-theme-open":`1`,title:`设置`,"aria-haspopup":`dialog`,"aria-expanded":Xl,onClick:()=>{$l(void 0),_e(),Zl(!0),Mc({type:`catalog.fetchAll`}),Mc({type:`providers.fetch`})},children:[(0,m.jsx)(vi,{name:`settings`}),(0,m.jsx)(`span`,{className:`workbench-action-label`,children:`设置`})]}),(0,m.jsxs)(`button`,{type:`button`,className:`theme-settings-trigger`,"data-help-open":`1`,title:`使用指南`,"aria-haspopup":`dialog`,"aria-expanded":eu,onClick:()=>tu(!0),children:[(0,m.jsx)(vi,{name:`help`}),(0,m.jsx)(`span`,{className:`workbench-action-label`,children:`使用指南`})]})]}),Fu=Va?void 0:z,Iu=de.current,Lu={onOpenSession:e=>{Iu===de.current&&Ac(e)},rsiContext:Va&>?{source:{kind:`group`,id:gt,workspaceId:ht},title:vt??`群聊`,archived:!!_t?.archivedAt}:Fu?{source:{kind:`session`,id:Fu.id,workspaceId:Fu.workspaceId},title:Fu.title,archived:!!Fu.archivedAt}:void 0,todos:O.todosByConversation?.[Fu?.id??``]??[],tasks:UA(Fu,O.backgroundTasks??[]),backgroundRuns:Fu?xl:void 0,execOutputs:Dt.current,scheduledTasks:(O.scheduledTasks??[]).filter(e=>e.workspaceId===Ua),scheduledCatalog:Xc(en,hc),scheduledAgents:un,notify:Sc,serverTimeZone:O.serverTimeZone,workspaceId:Ua,gitWorkspaceId:Ga,gitRepositoryOnly:qa,gitWorkspaceName:gc?.name,workspaceLabel:hc?.path,workspaceName:hc?.name,conversationId:Fu?.id,followedWorktreeId:Fu?.followedWorktreeId,cwd:Ka,connected:te&&I.statuses.get(I.activeServer)?.state===`online`&&Me&&!Fu?.id.startsWith(`pending:`),files:V,onOpenFile:Ns,onOpenChanged:Ts,onOpenGitDiff:Ss,activeGitDiffUrl:ys?.target.url,onFileReference:Ps,onFilesMoved:Fs,onSearchFolder:e=>rs(`content`,void 0,[Ka,e].filter(Boolean).join(`/`)),onSelectTab:Ho,sendCommand:kc,registerTerminalSink:Pt,terminalShell:O.terminalShell,terminalFocusRequest:xo,sharedGit:lo,gitReveal:Go},Ru=e=>I.connections.some(t=>t.id===y(e).server)&&(Fn===`all`||y(e).server===Fn),zu=new Set(O.workspaces.map(e=>e.id)),Bu=O.workspaces.filter(e=>Ru(e.id)&&(!e.worktreeOf||!zu.has(e.worktreeOf))),Vu=Bu.flatMap(e=>[e,...O.workspaces.filter(t=>t.worktreeOf===e.id)]),Hu=(0,p.useMemo)(()=>{let e=new Map;for(let t of O.workspaces){if(t.closedAt)continue;let n=t.name.trim().toLowerCase();n&&e.set(n,(e.get(n)??0)+1)}return new Set([...e].filter(([,e])=>e>1).map(([e])=>e))},[O.workspaces]),Uu=Ln&&Vu.some(e=>e.id===Ln)?Ln:M&&Vu.some(e=>e.id===M)?M:Vu[0]?.id,Wu=O.workspaces.find(e=>e.id===M),Gu=Wu?.worktreeOf&&zu.has(Wu.worktreeOf)?Wu.worktreeOf:Wu?.id,Ku=zn&&Bu.some(e=>e.id===zn)?zn:Gu&&Bu.some(e=>e.id===Gu)?Gu:Bu[0]?.id,qu=Date.now()-18e6,Q=Vu.filter(e=>e.id===Ku||e.worktreeOf===Ku),Ju=e=>{let t=O.conversations.some(t=>t.workspaceId===e&&!t.archivedAt&&(Mn===`recent`?Date.parse(t.updatedAt)>=qu:t.status===`running`||t.status===`waiting`)),n=(ot[e]?.rooms??[]).some(e=>!e.archivedAt&&(Mn===`recent`?Date.parse(e.updatedAt)>=qu:[`running`,`queued`].includes(hr(e,dt[e.id]))));return t||n},Yu=Bu.flatMap(e=>{let t=Vu.filter(t=>t.worktreeOf===e.id&&Ju(t.id));return Ju(e.id)||t.length>0?[e,...t]:[]}),Xu=Mn===`all`?Vu:Mn===`workspace`?Vu.filter(e=>e.id===Uu):Mn===`repo`?Q:Yu,Zu=Mn===`all`||Mn===`workspace`||Mn===`repo`,Qu=(e,t=Mn,n=Uu,r=Ku)=>{if(!e||!Ru(e))return!1;if(t===`all`)return!0;if(t===`workspace`)return e===n;if(t===`repo`)return e===r||Vu.some(t=>t.id===e&&t.worktreeOf===r);let i=O.conversations.filter(t=>t.workspaceId===e&&!t.archivedAt).some(e=>t===`recent`?Date.parse(e.updatedAt)>=qu:e.status===`running`||e.status===`waiting`),a=(ot[e]?.rooms??[]).some(e=>!e.archivedAt&&(t===`recent`?Date.parse(e.updatedAt)>=qu:[`running`,`queued`].includes(hr(e,dt[e.id]))));return i||a},$u=(e,t=Uu,n=Ku)=>{Nn(e),t&&Rn(t),n&&Vn(n);let r=R===`group`&&ht&>?ot[ht]?.rooms.find(e=>e.id===gt):void 0,i=R===`group`?!!(ht&&r&&!r.archivedAt&&Qu(ht,e,t,n)&&(e===`all`||e===`workspace`||e===`repo`||(e===`recent`?Date.parse(r.updatedAt)>=qu:[`running`,`queued`].includes(hr(r,dt[r.id]))))):!!(z&&!z.archivedAt&&Qu(z.workspaceId,e,t,n)&&(e===`all`||e===`workspace`||e===`repo`||(e===`recent`?Date.parse(z.updatedAt)>=qu:z.status===`running`||z.status===`waiting`)));if(zs.current=!0,i){e===`workspace`&&N(t);let r=Rs.find(e=>e.id===Y)?.workspaceId;(e===`recent`||e===`running`||(e===`workspace`||e===`repo`)&&!Qu(r,e,t,n))&&at(`session`)}else Un(!0),ee(void 0),it(!1),(R===`session`||R===`group`||e===`recent`||e===`running`||(e===`workspace`||e===`repo`)&&!Qu(Rs.find(e=>e.id===Y)?.workspaceId,e,t,n))&&at(`session`),N(e===`workspace`?t:void 0)},ed=e=>{In(e),localStorage.setItem(`super-pi.server-filter`,e),e!==`all`&&xe(e);let t=R===`group`?ht:z?.workspaceId??M;if(t&&e!==`all`&&y(t).server!==e){zs.current=!0,Un(!0),ee(void 0),it(!1);let t=O.workspaces.filter(t=>y(t.id).server===e);if(Mn===`workspace`){let e=t.find(e=>e.id===Ln)?.id??t[0]?.id;Rn(e),N(e)}else N(void 0),Mn===`repo`&&Vn(t.find(e=>!e.worktreeOf)?.id);at(`session`)}};(0,p.useEffect)(()=>{Fn!==`all`&&!I.connections.some(e=>e.id===Fn)&&ed(`all`)},[Fn,I.connections]);let td=Rs.filter(e=>{if(!e.workspaceId||!Ru(e.workspaceId))return!1;if(Mn===`all`)return!0;if(Mn===`workspace`||Mn===`repo`)return Qu(e.workspaceId);if(e.id.startsWith(`session:`)){let t=O.conversations.find(t=>t.id===e.rawId);return!!(t&&!t.archivedAt&&Qu(t.workspaceId)&&(Mn===`recent`?Date.parse(t.updatedAt)>=qu:t.status===`running`||t.status===`waiting`))}if(e.id.startsWith(`group:`)){let t=ur(e.id),n=t?.roomId?ot[t.workspaceId]?.rooms.find(e=>e.id===t.roomId):void 0;return!!(t&&n&&!n.archivedAt&&Qu(t.workspaceId)&&(Mn===`recent`?Date.parse(n.updatedAt)>=qu:[`running`,`queued`].includes(hr(n,dt[n.id]))))}return e.id===Y||e.id===so||Qu(e.workspaceId)}),nd=qa?`未选工作区`:lo.status?.detached?`游离 HEAD`:lo.status?.branch,rd=!qa&&lo.status&&new Set([...lo.status.staged,...lo.status.unstaged,...lo.status.untracked].map(e=>e.path)).size,id=!qa&&lo.status&&(lo.status.ahead||lo.status.behind)?[lo.status.ahead?`↑`+lo.status.ahead:``,lo.status.behind?`↓`+lo.status.behind:``].filter(Boolean).join(` `):``,ad=()=>tr(e=>({...e,rightClosed:!0})),od=()=>tr(e=>({...e,leftClosed:!0})),sd=xr?Sn:Io;return(0,m.jsx)(Ei,{store:nr,showing:e=>e===`sessions`?Vo:zo(e),onDock:Yo,onReveal:e=>Uo(e),children:(0,m.jsxs)(`main`,{className:`shell workbench-shell${sd?` shell-rail-collapsed`:``} mobile-panel-${Tn}${An?` mobile-drawer-open`:``}`,"data-bottom-open":!xr&&!er.bottomClosed,"data-rail-collapsed":sd,"data-workbench-left-closed":!xr&&(er.leftClosed||ko.length===0),"data-selected-workspace":M??``,style:{"--bottom-height":er.bottomHeight+`px`,"--sidebar-width":`${ar.sidebar}px`,"--rail-col":sd?void 0:`${ar.rail}px`},children:[!xr&&(0,m.jsx)(yi,{side:`left`,views:ko,unpinned:er.unpinned,active:Lo.left,onSelect:e=>Uo(e,!0),onDockCard:Yo,onArrange:Xo,onReorder:Zo,children:Pu}),(0,m.jsxs)(`aside`,{className:`workbench-sessions`,id:`workbench-sessions`,"data-workbench-sessions-side":xr?`left`:er.sides.sessions,"data-workbench-session-view":Vo?`shown`:`hidden`,children:[!xr&&(0,m.jsxs)(`div`,{className:`workbench-panel-heading workbench-session-heading`,children:[(0,m.jsx)(`h2`,{draggable:!0,"data-workbench-panel-drag":`sessions`,title:`拖动以移动此面板`,onDragStart:e=>di(e.dataTransfer,`sessions`),children:`会话`}),(0,m.jsx)(xi,{view:`sessions`,side:er.sides.sessions,pinned:!er.unpinned.includes(`sessions`),onArrange:Xo})]}),(0,m.jsxs)(`div`,{className:`sidebar-actions`,children:[(0,m.jsx)(`button`,{className:`workspace-new`,onClick:()=>Le(!0),children:`+ 添加工作区`}),z&&Ma&&td.length===1&&(0,m.jsx)(`button`,{type:`button`,className:`mobile-close-session`,onClick:()=>{nc(z.id),jn(!1)},children:`关闭当前标签`})]}),(0,m.jsxs)(`div`,{className:`label label-desktop workspace-title-row`,children:[(0,m.jsx)(`span`,{children:`工作区`}),(0,m.jsx)(`button`,{type:`button`,className:`workspace-bulk-settings`,title:`批量设置所有工作区`,"aria-label":`批量设置所有工作区`,onClick:()=>Kl(!0),children:`⚙`})]}),(0,m.jsx)(`div`,{className:`label label-phone`,children:`会话`}),Gl&&(0,m.jsx)(AD,{workspaces:O.workspaces.filter(e=>y(e.id).server===I.activeServer&&!e.closedAt&&!e.id.startsWith(`pending:`)),catalog:rn??{source:`unavailable`,models:[],levels:[],fetchedAt:``},onClose:()=>Kl(!1),onSave:ru}),(0,m.jsxs)(`div`,{className:`sidebar-session-filters`,"aria-label":`会话与群聊筛选`,children:[(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`span`,{children:`服务器`}),(0,m.jsxs)(`select`,{"aria-label":`服务器范围`,value:Fn,onChange:e=>ed(e.target.value),children:[(0,m.jsx)(`option`,{value:`all`,children:`全部服务器`}),I.connections.map(e=>(0,m.jsxs)(`option`,{value:e.id,children:[e.name,I.statuses.get(e.id)?.state===`offline`?` · 离线`:``]},e.id))]})]}),(0,m.jsxs)(`label`,{children:[(0,m.jsx)(`span`,{children:`显示`}),(0,m.jsxs)(`select`,{"aria-label":`会话列表筛选方式`,value:Mn,onChange:e=>$u(e.currentTarget.value),children:[(0,m.jsx)(`option`,{value:`all`,children:`全部`}),(0,m.jsx)(`option`,{value:`workspace`,children:`按工作区`}),(0,m.jsx)(`option`,{value:`repo`,children:`按仓库`}),(0,m.jsx)(`option`,{value:`recent`,children:`近期活跃 · 5 小时`}),(0,m.jsx)(`option`,{value:`running`,children:`正在运行`})]})]}),Mn===`workspace`&&(0,m.jsx)(`select`,{"aria-label":`选择工作区`,value:Uu??``,onChange:e=>$u(`workspace`,e.currentTarget.value,Ku),children:(0,m.jsx)(Bn,{workspaces:Vu})}),Mn===`repo`&&(0,m.jsx)(`select`,{"aria-label":`选择仓库`,value:Ku??``,onChange:e=>$u(`repo`,Uu,e.currentTarget.value),children:(0,m.jsx)(Bn,{workspaces:Bu})})]}),(0,m.jsx)(`nav`,{"aria-label":`工作区、会话与群聊`,children:Xu.length===0?(0,m.jsx)(`div`,{className:`sidebar-filter-empty`,children:Mn===`recent`?`近 5 小时没有活跃的会话或群聊`:`当前没有正在运行的会话或群聊`}):Xu.map((e,t)=>{let n=ot[e.id],r=(n?.rooms.filter(e=>!e.archivedAt)??[]).filter(e=>Zu||(Mn===`recent`?Date.parse(e.updatedAt)>=qu:[`running`,`queued`].includes(hr(e,dt[e.id])))),i=Zu?n?.rooms.filter(e=>e.archivedAt)??[]:[],a=O.conversations.filter(t=>t.workspaceId===e.id&&!t.groupExecution),o=a.filter(e=>!e.archivedAt&&(Zu||(Mn===`recent`?Date.parse(e.updatedAt)>=qu:e.status===`running`||e.status===`waiting`))),s=UD(o,ki,{manualRoots:Lt[e.id]}),c=s.filter(e=>e.depth===0).map(e=>e.conversation.id),l=Zu?a.filter(e=>e.archivedAt):[],u=UD(l,new Set),d=Zu?l.length+i.length:0,f=ie[e.id]??!1,p=Ft[e.id]??!0,h=Hu.has(e.name.trim().toLowerCase()),g=!e.worktreeOf||!zu.has(e.worktreeOf),_=(Mn===`recent`||Mn===`running`)&&g,v=t=>R===`group`&&ht===e.id&>===t;return(0,m.jsxs)(`section`,{className:`workspace-group${e.worktreeOf&&zu.has(e.worktreeOf)?` workspace-linked-checkout`:``}${_?` workspace-active-repo-root`:``}`,"data-workspace-parent":e.worktreeOf,"data-workspace-group":e.id,"data-sidebar-repo-root":_?e.id:void 0,"data-current-workspace":M===e.id,children:[I.connections.length>1&&(t===0||y(Xu[t-1].id).server!==y(e.id).server)&&(0,m.jsxs)(`div`,{className:`workspace-server-label`,children:[be(e.id),I.statuses.get(y(e.id).server)?.state===`offline`?` · 离线`:``]}),(0,m.jsx)(`div`,{className:`workspace-header`,children:zl(`workspace`,e.id)?(0,m.jsx)(_A,{initial:e.name,label:`重命名工作区 ${e.name}`,onCommit:t=>Bl(`workspace`,e.id,t),onClose:Rl}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`button`,{type:`button`,className:`workspace-disclosure`,"data-workspace-fold":e.id,"aria-expanded":!f,"aria-label":`${f?`展开`:`折叠`}工作区 ${e.name}`,onClick:()=>ae(t=>({...t,[e.id]:!t[e.id]})),children:(0,m.jsx)(`span`,{className:`chevron-folder`,"aria-hidden":`true`,children:f?`▸`:`▾`})}),(0,m.jsx)(`button`,{type:`button`,className:`workspace-toggle`,"aria-label":e.name,"aria-describedby":h?`workspace-name-warning-${e.id}`:void 0,title:e.path,onContextMenu:t=>{t.preventDefault();let n=t.currentTarget.getBoundingClientRect();Lr({workspace:e,x:t.clientX||n.left+24,y:t.clientY||n.top+n.height})},onClick:()=>{Rn(e.id);let t=wi.find(t=>t.workspaceId===e.id)?.id;t?(t!==z?.id||R!==`session`||!Ma)&&Pa(t):Ia(e.id)},children:(0,m.jsxs)(`span`,{children:[(0,m.jsxs)(`span`,{className:`workspace-name-line`,children:[(0,m.jsx)(`strong`,{onDoubleClick:()=>Ll(`workspace`,e.id),children:e.name}),h&&(0,m.jsx)(`small`,{id:`workspace-name-warning-${e.id}`,className:`workspace-name-warning`,"data-workspace-name-warning":e.id,title:`请重命名其中一个工作区;名称唯一后提示会自动消失。`,children:`存在同名,易混淆`})]}),(0,m.jsx)(`small`,{children:e.path})]})}),(0,m.jsx)(`button`,{className:`workspace-add`,disabled:e.id.startsWith(`pending:`),title:`在此工作区新建会话`,onClick:t=>{Rn(e.id),Ve.current=t.currentTarget,ze({workspaceId:e.id})},children:`+`}),(0,m.jsx)(`button`,{type:`button`,className:`workspace-group-chat`,"data-open-group-chat":e.id,disabled:e.id.startsWith(`pending:`),title:`新建群聊`,"aria-label":`在 ${e.name} 新建群聊`,onClick:()=>{Rn(e.id),La(e.id)},children:(0,m.jsx)(vi,{name:`group-add`})}),(0,m.jsx)(`button`,{className:`workspace-settings`,title:`工作区设置(默认智能体 / 模型 / 思考强度)`,"aria-label":`工作区设置 ${e.name}`,onClick:()=>Wl(e.id),children:`⚙`})]})}),!f&&r.map(t=>{let n=v(t.id),r=hr(t,dt[t.id]),i=gr(t,dt[t.id],Ke.current[lr({workspaceId:e.id,roomId:t.id})]),a=i===`completed`?`讨论已完成,有新回复未读`:i===`unread`?`有新回复未读`:TA[r];return(0,m.jsxs)(`div`,{className:`conversation-row group-room-row`,children:[(0,m.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),(0,m.jsxs)(`button`,{type:`button`,className:`conversation group-room-button${n?` selected`:``}`,"data-sidebar-group-chat":t.id,"aria-current":n?`true`:void 0,"aria-label":`打开群聊 ${t.title},${a}`,title:t.title,onClick:()=>{Rn(e.id),La(e.id,t.id)},children:[(0,m.jsx)(`i`,{className:`conversation-mark`,children:(0,m.jsx)(FA,{state:i,label:a})}),(0,m.jsx)(vi,{name:`group`}),(0,m.jsx)(`span`,{className:`group-room-title`,children:t.title})]}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-archive`,"data-archive-group":t.id,title:`归档群聊`,"aria-label":`归档群聊 ${t.title}`,disabled:pt.has(t.id),onClick:()=>void Ba(t,`archive`),children:(0,m.jsx)(vi,{name:`archive`})})]},t.id)}),!f&&n?.failed&&(0,m.jsx)(`button`,{type:`button`,className:`group-rooms-retry`,onClick:st,children:`重试载入群聊`}),!f&&(s.length?s.map(({conversation:t,depth:n,childCount:r,isLastSibling:i})=>(0,m.jsxs)(`div`,{className:`conversation-row`,style:{"--tree-depth":n},"data-session-root":n===0?t.id:void 0,"data-session-dragging":zt?.conversationId===t.id?`true`:void 0,"data-session-drop":zt?.dropRootId===t.id?zt.dropAfter?`after`:`before`:void 0,onPointerDown:n===0?n=>Ut(n,e.id,t.id,c):void 0,children:[r>0?(0,m.jsxs)(`button`,{type:`button`,className:`conversation-tree-toggle`,"data-tree-toggle":t.id,"aria-expanded":!ki.has(t.id),title:ki.has(t.id)?`展开 ${r} 个子会话`:`折叠 ${r} 个子会话`,"aria-label":ki.has(t.id)?`展开会话 ${t.title} 的 ${r} 个子会话`:`折叠会话 ${t.title} 的 ${r} 个子会话`,onClick:()=>ou(t.id,!ki.has(t.id)),children:[(0,m.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:ki.has(t.id)?`▸`:`▾`}),(0,m.jsx)(`small`,{children:r})]}):(0,m.jsx)(`span`,{className:`conversation-tree-spacer`,"aria-hidden":`true`}),zl(`conversation`,t.id)?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(_A,{initial:t.title,label:`重命名会话 ${t.title}`,onCommit:e=>Bl(`conversation`,t.id,e),onClose:Rl}),(0,m.jsx)(`small`,{className:`conversation-time`,children:Dk(t.updatedAt,Si)})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{className:`conversation ${!Va&&z?.id===t.id?`selected`:``}`,"data-conversation":t.id,"aria-current":!Va&&z?.id===t.id?`true`:void 0,"data-tree-child":n>0?`true`:void 0,"data-tree-last":n>0&&i?`true`:void 0,title:n>0?`${t.title}(由「${o.find(e=>e.id===t.parentConversationId)?.title??`已不存在的会话`}」创建)`:t.title,"aria-label":`打开会话 ${t.title}${LA(t,Nu.get(t.id))}`,onContextMenu:e=>{e.preventDefault();let n=e.currentTarget.getBoundingClientRect();Vr({conversation:t,x:e.clientX||n.left+24,y:e.clientY||n.top+n.height})},onClick:()=>{t.id===Ht.current&&Date.now()-Vt.current<300||(Rn(e.id),Pa(t.id),N(e.id),jn(!1))},onDoubleClick:()=>{Fa(t.id)},children:[(0,m.jsx)(`i`,{className:`conversation-mark`,children:(0,m.jsx)(FA,{state:NA(t,jA(t,xn),Ke.current[t.id],O.conversations)})}),(0,m.jsx)(`span`,{"data-conversation-title":t.id,onDoubleClick:e=>{e.stopPropagation(),Ll(`conversation`,t.id)},style:{flex:`0 1 auto`,minWidth:`3.5em`},children:t.title}),(0,m.jsx)(`span`,{className:`conversation-title-gap`,"aria-hidden":`true`,style:{marginLeft:`-8px`}}),PA(NA(t,jA(t,xn),Ke.current[t.id],O.conversations),MA(t,O.conversations,Ke.current[t.id])),IA(t,Nu.get(t.id)),(0,m.jsx)(`small`,{children:Dk(t.updatedAt,Si)})]}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-fork`,"data-fork-conversation":t.id,"data-fork-state":ku===t.id?`pending`:`idle`,disabled:!!ku,title:`从此会话分叉出一个新会话`,"aria-label":`从会话 ${t.title} 分叉出一个新会话`,onClick:()=>ju(t.id),children:`⑂`}),!(t.parentConversationId&&O.conversations.some(e=>e.id===t.parentConversationId))&&(0,m.jsx)(`button`,{className:`conversation-archive`,"data-archive-conversation":t.id,title:`归档整棵会话树`,"aria-label":`归档会话 ${t.title}`,onClick:()=>au(t.id),children:`×`})]})]},t.id)):!r.length&&(0,m.jsx)(`div`,{className:`conversation-empty`,children:`暂无会话`})),!f&&d>0&&(0,m.jsxs)(`div`,{className:`archived-group`,"data-archived-count":d,children:[(0,m.jsxs)(`button`,{className:`archived-toggle`,title:p?`展开已归档`:`收起已归档`,"aria-expanded":!p,onClick:()=>It(t=>({...t,[e.id]:!p})),children:[(0,m.jsx)(`span`,{className:`chevron`,"aria-hidden":`true`,children:p?`▸`:`▾`}),(0,m.jsxs)(`span`,{className:`archived-label`,children:[`已归档 (`,d,`)`]})]}),!p&&u.map(({conversation:e,depth:t,isLastSibling:n})=>{let r=Ok(l,e.id).length-1,i=!!(e.parentConversationId&&O.conversations.some(t=>t.id===e.parentConversationId&&t.archivedAt));return(0,m.jsxs)(`div`,{className:`conversation-archived`,"data-archived-conversation":e.id,"data-archived-at":e.archivedAt,"data-tree-child":t>0?`true`:void 0,"data-tree-last":t>0&&n?`true`:void 0,style:{"--tree-depth":t},children:[(0,m.jsx)(`i`,{className:`conversation-mark`,"aria-hidden":`true`}),(0,m.jsx)(`span`,{"data-archived-title":e.id,children:e.title}),IA(e,Nu.get(e.id)),(0,m.jsx)(`small`,{children:kk(e.archivedAt)}),!i&&(0,m.jsx)(`button`,{className:`conversation-restore`,"data-restore-conversation":e.id,title:r?`恢复这个会话和它的 ${r} 个子孙会话`:`恢复为正常会话`,"aria-label":r?`恢复会话 ${e.title} 及其 ${r} 个子孙会话`:`恢复会话 ${e.title}`,onClick:()=>su(e.id),children:`↑`})]},e.id)}),!p&&i.map(t=>{let n=v(t.id),r=pt.has(t.id);return(0,m.jsxs)(`div`,{className:`conversation-row group-room-row group-room-history`,"data-archived-group":t.id,children:[(0,m.jsxs)(`button`,{type:`button`,className:`conversation group-room-button${n?` selected`:``}`,"data-open-archived-group":t.id,"aria-current":n?`true`:void 0,"aria-label":`查看已归档群聊 ${t.title}`,title:t.title,onClick:()=>La(e.id,t.id),children:[(0,m.jsx)(vi,{name:`group`}),(0,m.jsx)(`span`,{className:`group-room-title`,children:t.title})]}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-restore`,"data-restore-group":t.id,title:`恢复群聊`,"aria-label":`恢复群聊 ${t.title}`,disabled:r,onClick:()=>void Ba(t,`restore`),children:`↑`}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-restore`,"data-delete-group":t.id,title:`永久删除群聊`,"aria-label":`永久删除群聊 ${t.title}`,disabled:r,onClick:()=>void Ba(t,`delete`),children:(0,m.jsx)(vi,{name:`delete`})})]},t.id)})]}),!f&&(()=>{let t=O.warmSessions?.filter(t=>t.workspaceId===e.id)??[];return t.length?(0,m.jsxs)(`details`,{className:`archived-group`,"data-warm-sessions":e.id,children:[(0,m.jsx)(`summary`,{className:`archived-toggle`,children:(0,m.jsxs)(`span`,{className:`archived-label`,children:[`预热会话 (`,t.length,`)`]})}),t.map(e=>(0,m.jsxs)(`div`,{className:`conversation-archived`,"data-warm-session":e.id,children:[(0,m.jsx)(`span`,{title:e.title,children:e.title}),(0,m.jsx)(`button`,{type:`button`,className:`conversation-restore`,"aria-label":`移除预热会话 ${e.title}`,onClick:()=>{window.confirm(`移除预热会话「${e.title}」?`)&&!kc({type:`conversation.warm.delete`,conversationId:e.id})&&Sc(`连接断开,未移除预热会话`,`error`)},children:`×`})]},e.id))]}):null})()]},e.id)})}),(0,m.jsx)(Ai,{active:Vo}),xr&&(0,m.jsxs)(`footer`,{className:`workbench-mobile-utilities`,children:[(0,m.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-mobile-workbench-search":!0,"aria-label":`搜索`,title:`搜索`,onClick:()=>rs(`content`),children:(0,m.jsx)(vi,{name:`search`})}),Pu]})]}),(0,m.jsx)(ji,{view:`search`,children:(0,m.jsx)(Mi,{id:`search`,header:!1,children:(0,m.jsx)(`section`,{className:`workbench-search-panel`,"data-workbench-search-panel":!0,"aria-label":`侧栏搜索`,children:(0,m.jsx)(ng,{workspaceId:Ua,workspaceName:hc?.name,cwd:Ka,connected:te,dirtyPaths:V.open.filter(e=>e.dirty).map(e=>e.path),onOpen:(e,t,n)=>Ms(e,t,!1,!0,!1,n),onSession:ss},Qo)})})}),!xr&&!er.leftClosed&&Mo&&Mo!==`sessions`&&(0,m.jsx)(YA,{...Lu,side:`left`,activeTab:Mo,collapsed:!1,onToggle:od,pinned:!er.unpinned.includes(Mo),onArrange:Xo}),(xr||!er.leftClosed)&&(0,m.jsx)(Nj,{side:`left`,width:ar.sidebar,min:ar.sidebarMin,max:ar.sidebarMax,label:`调整左侧栏宽度`,onWidth:or}),(0,m.jsx)(`div`,{className:`workbench-main`,children:(0,m.jsxs)(`div`,{className:`workbench-main-panes`,"data-workbench-split":oo,style:{"--split-share":`${$a}%`},children:[(0,m.jsxs)(`section`,{className:`chat`,"data-main-view":bs,"data-main-view-kind":bs,children:[td.length>0&&(0,m.jsx)(`div`,{className:`chat-tab-strip`,"data-chat-tab-strip":`1`,"data-session-count":Aa.length,"data-file-count":V.open.length,children:(0,m.jsx)(dg,{tabs:($s?td.filter(e=>e.id!==$s.id):td).map(e=>I.connections.length>1&&e.workspaceId?{...e,label:`${e.label} · ${be(e.workspaceId)}`,title:`${be(e.workspaceId)} · ${e.title??e.label}`}:e),prefix:`workspace-tab`,ariaLabel:`工作区标签页`,activeId:Y,onSelect:Vs,onClose:rc,onActivate:Zs,minWidth:120,maxWidth:320})}),(0,m.jsxs)(`header`,{children:[(0,m.jsx)(`button`,{type:`button`,className:`mobile-drawer-toggle`,"data-mobile-drawer-toggle":`1`,"aria-label":`打开会话列表`,title:`会话列表`,"aria-expanded":An,onClick:()=>jn(!0),children:`☰`}),(0,m.jsxs)(`div`,{className:`chat-head`,children:[(0,m.jsx)(`h1`,{children:R===`group`?gt?vt??`群聊`:`新建群聊`:z?.title??`准备开始`}),R!==`group`&&pl.size>0?[...pl].map(([e,t])=>(0,m.jsx)(`p`,{"data-role":`run-status`,"data-status-key":e,children:`扩展状态:${e?`${e} · `:``}${t}`},e)):null]}),(0,m.jsxs)(`div`,{className:`workbench-history-controls`,role:`group`,"aria-label":`主区导航`,"aria-busy":!!Oe,"data-workbench-history":qs>=0||Js>=0?`available`:`empty`,children:[z&&R!==`group`&&(0,m.jsx)(lk,{id:z.id,expanded:Bo,onClick:()=>Wo(`rsi`,!0)}),z&&R!==`group`&&(0,m.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-session-actions":!0,title:`会话操作`,"aria-label":`会话操作`,"aria-haspopup":`dialog`,"aria-expanded":cc===`session`,"data-session-reload":d.some(e=>e.key===`reload:${z.id}`)?`running`:`idle`,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`session`?void 0:`session`)},children:d.some(e=>e.key===`reload:${z.id}`)?(0,m.jsx)(`span`,{className:`context-status-spinner`,"aria-label":`正在重新加载资源`}):`⋯`}),(0,m.jsx)(`button`,{type:`button`,"data-workbench-history-back":!0,"aria-label":`后退`,className:`workbench-icon-button`,title:qs<0?`后退`:`后退到 ${Ce.entries[qs].title}`,disabled:qs<0,onClick:()=>Ys(-1),children:(0,m.jsx)(vi,{name:`back`})}),(0,m.jsx)(`button`,{type:`button`,"data-workbench-history-forward":!0,"aria-label":`前进`,className:`workbench-icon-button`,title:Js<0?`前进`:`前进到 ${Ce.entries[Js].title}`,disabled:Js<0,onClick:()=>Ys(1),children:(0,m.jsx)(vi,{name:`forward`})}),Ua&&(0,m.jsx)(`button`,{type:`button`,className:`workbench-icon-button`,"data-toggle-workbench-split":!0,"aria-pressed":oo,"aria-label":oo?`合并主区`:`拆分主区`,title:oo?`合并主区`:`拆分主区`,onClick:tc,children:(0,m.jsx)(vi,{name:`split`})})]}),bn.entry(`workbench-status-button software-update-mobile`),(0,m.jsxs)(`span`,{className:`chat-view chat-view-${bs}`,"data-main-view-indicator":bs,"data-main-view-kind":bs,title:R===`file`?`中间主画面正在显示文件 ${V.active?.path??``}`:bs===`diff`?`中间主画面正在显示 ${xs??``} 的改动`:`中间主画面正在显示这个会话的消息流`,children:[(0,m.jsx)(`span`,{className:`chat-view-kind`,children:R===`group`?`群聊`:R===`file`?`文件`:bs===`diff`?`改动`:`会话`}),R===`file`&&V.active&&(0,m.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":V.active.name,children:V.active.name}),bs===`diff`&&xs&&(0,m.jsx)(`span`,{className:`chat-view-name`,"data-main-view-name":xs,children:xs})]}),!Va&&(0,m.jsx)(`div`,{className:`badge`,"data-workbench-header-status":Ki||z?.status===`failed`?`attention`:`routine`,"data-conversation-status":z?.status??`idle`,...Ki?{"data-reporting-status":Ki}:{},children:z?.compaction?.status===`running`?`压缩中`:Ki===`awaiting_decision`?`等上面拍板`:OA(z)?DA[z?.status??`idle`]:Ki===`awaiting_subordinates`?`等待下级`:Ki===`pending_report`?`待汇报`:DA[z?.status??`idle`]}),(0,m.jsx)(`button`,{type:`button`,className:`mobile-tools-toggle`,"data-mobile-nav":`rail`,onClick:()=>{En(`rail`),wn(!1)},children:`工具`})]}),ne&&(0,m.jsxs)(`div`,{className:`error`,role:`alert`,"data-global-error":!0,children:[(0,m.jsx)(`span`,{title:Br(ne),children:zr(ne)}),(0,m.jsx)(`button`,{type:`button`,"aria-label":`关闭错误提示`,title:`关闭错误提示`,onClick:()=>re(void 0),children:`×`})]}),!Va&&z?.error&&(0,m.jsx)(`div`,{className:`error`,"data-role":`conversation-error`,title:Br(z.error),children:zr(z.error)}),z?.warning&&(0,m.jsxs)(`div`,{className:`warning`,role:`status`,"data-role":`conversation-warning`,title:Br(z.warning),children:[(0,m.jsx)(`span`,{children:z.warning}),(0,m.jsx)(`button`,{type:`button`,"data-role":`conversation-warning-continue`,title:`让模型继续完成当前任务`,onClick:()=>Fc(z?.id??``),children:`继续任务`})]}),!Va&&z?.modelNotice&&(0,m.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-model-notice`,children:z.modelNotice}),z?.agentNotice&&(0,m.jsx)(`div`,{className:`model-notice`,"data-role":`conversation-agent-notice`,children:z.agentNotice}),hl&&(0,m.jsxs)(`div`,{className:`extui-title-note`,children:[`扩展建议标题:`,hl]}),Qt.length>0&&(0,m.jsx)(`div`,{className:`toasts`,role:`status`,"aria-live":`polite`,"data-toast-count":Qt.length,children:Qt.map(e=>(0,m.jsx)(`div`,{className:`toast toast-${e.kind}`,"data-toast-kind":e.kind,children:e.text},e.key))}),R===`group`?hc?(0,m.jsx)(DD,{workspaceId:ht,roomId:gt,onImageOpen:ni,onOpenRsi:()=>Wo(`rsi`,!0),rsiActive:Bo,sourceLink:Cc(ht),composerResize:pr===null?void 0:(0,m.jsx)(Bj,{height:pr,onHeight:br}),onEnableNotifications:()=>Tc(!0),agents:un?.agents??[],catalog:Xc(en,hc),userLabel:qt,archivedAt:_t?.archivedAt,restoring:pt.has(gt),onRestore:e=>void Ba(e,`restore`),onRoomSeen:ct,onRoomRead:ea,onRoomMissing:za,onCreated:Ra,onCancelCreate:()=>Ye&&rc(lr(Ye))},Ye&&lr(Ye)):(0,m.jsx)(`div`,{className:`group-empty`,children:Me?`这个群聊的工作区已不可用。`:`正在加载工作区…`}):R===`file`?_c(ic,!0):ys?vc(ys):R===`diff`?yc(us,!1):(0,m.jsxs)(m.Fragment,{children:[z&&Ma&&(0,m.jsx)(sg,{container:yt,onNavigate:e=>{Et.current=!0,ta(e,!0)}},z.id),(0,m.jsxs)(`div`,{className:`messages`,ref:yt,"data-message-scroll-container":z?.id??``,onWheel:e=>{e.deltaY<0&&Ue.current[z?.id??``]?.followTail&&(Et.current=!0,ta(e.currentTarget,!0))},onScroll:e=>{let t=e.currentTarget;t.dataset.programmaticScroll===`true`?delete t.dataset.programmaticScroll:ta(t)},children:[(!z||!Ma)&&(0,m.jsxs)(`div`,{className:`empty`,"data-workspace-welcome":Yi?.id,children:[(0,m.jsx)(`div`,{className:`orb`,children:`π`}),(0,m.jsx)(`h2`,{children:Yi?.name??`开始一个新会话`}),O.workspaces.length===0?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{children:`先创建一个工作区,再开始会话。`}),(0,m.jsx)(`button`,{onClick:()=>Le(!0),children:`+ 新建工作区`})]}):(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`p`,{children:Yi?`暂无活跃会话。你可以创建会话,也可以直接使用资源管理器、Git 和终端。`:O.workspaces.length===1&&Ji?`在「${Ji.name}」中创建会话,即可向 Super Pi 发送任务。`:`选择工作区即可开始会话,向 Super Pi 发送任务。`}),Yi&&(0,m.jsx)(`p`,{className:`workspace-welcome-path`,title:Yi.path,children:Yi.path}),O.workspaces.length>1&&(0,m.jsxs)(`div`,{className:`empty-workspace-select`,children:[(0,m.jsx)(`label`,{htmlFor:`empty-workspace-choice`,children:`工作区:`}),(0,m.jsxs)(`select`,{id:`empty-workspace-choice`,"aria-label":`选择工作区`,value:Ji?.id,onChange:e=>{e.target.value===`__new__`?Le(!0):Ia(e.target.value)},children:[(0,m.jsx)(Bn,{workspaces:O.workspaces}),(0,m.jsx)(`option`,{value:`__new__`,children:`+ 新建工作区…`})]})]}),Ji&&(0,m.jsxs)(m.Fragment,{children:[!Xi&&(0,m.jsx)(Vk,{workspaceId:Ji.id,value:Zi,onChange:Qi}),(0,m.jsx)(`button`,{"data-workspace-welcome-create":Yi?`1`:void 0,disabled:Xi||!te,onClick:()=>iu(Ji.id,Zi),children:Xi?`正在创建工作区…`:`新建会话`})]}),(0,m.jsx)(`span`,{className:`empty-secondary-action`,role:`button`,tabIndex:0,onClick:()=>Le(!0),onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),Le(!0))},children:`+ 新建工作区`})]})]}),z?.messagesLoaded===!1&&(0,m.jsx)(`p`,{role:`status`,"data-conversation-loading":`1`,children:`正在加载会话…`}),Cl.map(e=>{if(e.startsWith(`m:`)){let t=bl.get(e.slice(2));if(!t||t.batchedInto)return null;if(t.backgroundBatch?.length)return(0,m.jsx)(k,{message:t,onOpenFile:e=>{Ms({path:e,name:e.split(/[/\\]/).at(-1)||e,text:!0})},onOpenSession:e=>{wi.some(t=>t.id===e)?Ac(e):Sc(`子会话已不可用。`,`info`)}},e);let n=t.id===wl,r=t.role===`user`&&z?.status!==`running`&&z?.status!==`waiting`&&xu!==t.id,i=r&&n&&!t.id.startsWith(`pending:`),a=r&&!n&&!!t.piEntryId,o=t.content?(0,m.jsx)(ep,{source:t.content,media:Ni,sourceLink:wc}):(0,m.jsx)(`span`,{className:`typing`,children:`正在思考`});if(t.source===`session-reminder`)return(0,m.jsx)(`article`,{className:`message message-reminder`,"data-transcript-key":e,"data-message-reminder":t.id,children:(0,m.jsxs)(`details`,{children:[(0,m.jsxs)(`summary`,{className:`reminder-header`,children:[(0,m.jsxs)(`span`,{className:`reminder-label`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`◷`}),` 定时提醒`]}),(0,m.jsx)(`time`,{dateTime:t.createdAt,children:bk(t.createdAt)})]}),(0,m.jsx)(`div`,{className:`content`,children:o})]})},e);let s=t.toolCalls??[],c=wu?.id===t.id?wu.kind:void 0;if(t.role===`user`){let n=t.content||(t.images?.length?`[图片]`:``),r=iA(t.content,t.attachments);return(0,m.jsxs)(`article`,{className:`message user`,"data-transcript-key":e,children:[(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsxs)(`div`,{className:`bubble`,children:[(0,m.jsxs)(`div`,{className:`meta`,children:[qt,(0,m.jsx)(`time`,{children:bk(t.createdAt)})]}),t.images&&t.images.length>0&&(0,m.jsx)(`div`,{className:`message-images`,"data-message-images":`1`,children:t.images.map(e=>(0,m.jsx)(`button`,{type:`button`,className:`message-image-btn`,"data-message-image-id":e.id,onClick:()=>ni({url:Fe(`/api/upload/${encodeURIComponent(z?.id??``)}/${encodeURIComponent(e.id)}`),name:e.name,bytes:e.bytes}),title:e.name?`查看大图:${e.name}`:`查看大图`,children:(0,m.jsx)(`img`,{src:Fe(`/api/upload/${encodeURIComponent(z?.id??``)}/${encodeURIComponent(e.id)}`),alt:e.name||`图片`,className:`message-image-thumb`,loading:`lazy`})},e.id))}),(0,m.jsx)(`div`,{className:`content`,children:o})]}),r.length>0&&(0,m.jsx)(`div`,{className:`message-attachments`,"data-message-attachments":`1`,children:r.map(e=>{let n=`att:${t.id}:${e.kind}:${e.id}`,r=wr[n]??!1;return(0,m.jsxs)(`div`,{className:`message-attachment`,"data-message-attachment":e.kind,children:[(0,m.jsxs)(`button`,{type:`button`,className:`message-attachment-head`,"data-message-attachment-toggle":e.id,"aria-expanded":r,onClick:()=>Tr(e=>({...e,[n]:!r})),children:[(0,m.jsx)(`span`,{className:`message-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,m.jsx)(`span`,{className:`message-attachment-label`,children:`技能`}),(0,m.jsx)(`span`,{className:`message-attachment-name`,title:e.name,children:e.name}),(0,m.jsx)(`span`,{className:`message-attachment-chevron`,"aria-hidden":`true`,children:r?`▾`:`▸`})]}),r&&(0,m.jsx)(`pre`,{className:`message-attachment-body`,"data-message-attachment-body":e.id,children:e.content})]},n)})}),(0,m.jsxs)(`div`,{className:`message-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":c,"aria-label":`复制这条消息:${n}`,onClick:()=>Ou(t.id,n),children:c===`copied`?`已复制`:c===`error`?`复制失败`:`复制`}),i&&(0,m.jsx)(`button`,{type:`button`,className:`message-revert`,"data-withdraw-message":t.id,title:`撤回并编辑:删除这条消息并将文字恢复到输入框继续编辑`,onClick:()=>Cu(t.id,!0),children:`撤回`}),a&&(0,m.jsx)(`button`,{type:`button`,className:`message-revert`,"data-revert-message":t.id,title:`回退并编辑:删除这条消息及后续全部对话,将原消息恢复到输入框`,onClick:()=>Cu(t.id),children:`回退`})]})]}),(0,m.jsx)(`div`,{className:`avatar`,title:qt,children:qt})]},e)}if(t.role===`tool`){let n=KO(t.content),r=n!==void 0,i=/<task id="[^"]+" state="[^"]+"/.test(t.content),a=(()=>{if(r)return`模型不完整输出后的自动恢复`;let e=/<summary>([\s\S]*?)<\/summary>/.exec(t.content);return e?e[1].trim():i?`后台回传`:(t.content.split(`
|
|
350
350
|
`).find(e=>e.trim().length>0)??``).trim().slice(0,60)||`任务指令`})(),o=(()=>{let e=/<task id="[^"]+" state="([^"]+)"/.exec(t.content);return e?e[1]:`completed`})(),s=(()=>{let e=/<task_(?:result|error)>\n?([\s\S]*?)\n?<\/(?:task_result|task_error)>/.exec(t.content);return e?e[1]:n??t.content})(),c=t.backgroundTask,l=c?.output===void 0?s:[c.reason,c.outputTruncated?`日志仅保留最近一段。`:``,c.output||`任务未产生输出。`].filter(Boolean).join(`
|
|
351
351
|
|
|
352
|
-
`),u=(()=>{let e=/<result_file>([\s\S]*?)<\/result_file>/.exec(t.content);return e&&e[1].trim()?e[1].trim():void 0})(),d=(()=>{let e=/<task id="([^"]+)"/.exec(t.content);return e?v(y(t.id).server,y(e[1]).id):void 0})(),f=!!(d&&wi.some(e=>e.id===d)),p=`tool:${t.id}`,h=wr[p]??!1,g=r?`自动恢复`:i?`后台回传`:`智能体下发`;return(0,m.jsx)(`article`,{className:`message tool${i?``:` tool-order`}`,"data-transcript-key":e,"data-tool-state":o,"data-tool-kind":r?`recovery`:i?`delivery`:`order`,children:(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsxs)(`div`,{className:`bg-result-head`,"data-bg-result-head":t.id,children:[(0,m.jsxs)(`button`,{type:`button`,className:`bg-result-toggle`,"data-bg-result-toggle":t.id,"aria-expanded":h,title:h?`折叠${g}`:`展开${g}`,onClick:()=>Tr(e=>({...e,[p]:!h})),children:[(0,m.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:o===`error`?`✕`:i?`↩`:`↓`}),(0,m.jsx)(`span`,{className:`bg-result-label`,children:c&&(c.status===`cancelled`||c.status===`interrupted`)?
|
|
353
|
-
`).map(e=>e.trim()).find(Boolean)??``,expanded:Ol[`${t.id}:${e}`]===!0,onToggle:()=>Al(`${t.id}:${e}`),children:a},`${t.id}:thinking:${e}`)};return(0,m.jsxs)(`article`,{className:`message assistant`,"data-transcript-key":e,children:[(0,m.jsx)(`div`,{className:`avatar`,children:`π`}),(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsxs)(`div`,{className:`meta`,children:[t.agentIdentity?.name??`Super Pi`,(0,m.jsx)(`time`,{children:
|
|
354
|
-
`),children:e.withdrawn.map(e=>`「${e.content.replace(/\s+/g,` `).trim().slice(0,48)}」`).join(` · `)})]}),(0,m.jsx)(`div`,{className:`composer-notice-actions`,children:(0,m.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-queue-withdrawn-dismiss":`1`,onClick:()=>Ri(t=>t.filter(t=>t.id!==e.id)),children:`知道了`})})]},e.id)),Jr.filter(e=>e.conversationId===z?.id).map(e=>(0,m.jsxs)(`div`,{className:`composer-notice`,"data-failed-send":e.id,role:`alert`,children:[(0,m.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`!`}),(0,m.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,m.jsx)(`p`,{className:`composer-notice-title`,"data-failed-send-reason":`1`,title:Br(e.reason),children:e.reason?.trim()?zr(e.reason):`服务端没有接受这条消息。`}),(0,m.jsx)(`p`,{className:`composer-notice-text`,title:e.content,children:e.content})]}),(0,m.jsxs)(`div`,{className:`composer-notice-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`composer-notice-action`,"data-failed-send-restore":`1`,disabled:!!(ia||aa.length||oa.length),title:ia||aa.length||oa.length?`输入框里已经有内容,先把这条留在下面`:`放回输入框,改完再发`,onClick:()=>{la(e.conversationId,t=>({...t,text:e.content,images:e.images,attachments:e.attachments})),Yr(t=>t.filter(t=>t.id!==e.id))},children:`放回输入框`}),(0,m.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-failed-send-dismiss":`1`,onClick:()=>Yr(t=>t.filter(t=>t.id!==e.id)),children:`丢弃`})]})]},e.id)),Xr.filter(e=>e.conversationId===z?.id).map(e=>(0,m.jsxs)(`div`,{className:`composer-upload-preview${e.failed?` composer-upload-preview-failed`:``}`,"data-upload-preview":e.id,children:[(0,m.jsx)(`img`,{src:e.url,alt:e.name,width:44,height:44,className:`composer-upload-thumb`}),(0,m.jsx)(`span`,{className:`composer-upload-state`,"data-upload-preview-state":e.failed?`failed`:`uploading`,children:e.failed?`上传失败`:`上传中…`}),(0,m.jsx)(`button`,{type:`button`,className:`composer-upload-remove`,"aria-label":`移除 ${e.name}`,title:`移除这张图片`,onClick:()=>{qr.current.add(e.id),URL.revokeObjectURL(e.url),Zr(t=>t.filter(t=>t.id!==e.id))},children:`移除`})]},e.id)),(aa.length>0||ca>0||oa.length>0||sa)&&(0,m.jsxs)(`div`,{className:`composer-attachments`,"data-composer-attachments":`1`,children:[aa.map((e,t)=>(0,m.jsxs)(`div`,{className:`composer-attachment-item`,"data-composer-attachment-id":e.id,children:[(0,m.jsx)(`img`,{src:Fe(`/api/upload/${encodeURIComponent(z?.id??``)}/${encodeURIComponent(e.id)}`),alt:e.name||`已附图片`,className:`composer-attachment-thumb`,onClick:()=>ni({url:Fe(`/api/upload/${encodeURIComponent(z?.id??``)}/${encodeURIComponent(e.id)}`),name:e.name,bytes:e.bytes}),title:`点击查看大图`}),(0,m.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name||`图片`}),(0,m.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-attachment-remove":e.id,onClick:()=>Oa(e=>e.filter((e,n)=>n!==t)),"aria-label":`移除 ${e.name||`图片`}`,title:`移除图片`,children:`✕`})]},e.id)),ca>0&&(0,m.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,children:(0,m.jsxs)(`span`,{children:[`图片上传中 (`,ca,`)…`]})}),sa&&(0,m.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,"data-composer-skill-loading":!0,role:`status`,children:`读取技能中…`}),oa.map(e=>(0,m.jsxs)(`div`,{className:`composer-attachment-item composer-attachment-skill`,"data-composer-skill-id":e.id,children:[(0,m.jsx)(`span`,{className:`composer-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,m.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name}),(0,m.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-skill-remove":e.id,onClick:()=>ma(e.kind,e.id),"aria-label":`移除 ${e.name}`,title:`移除技能`,children:`✕`})]},`${e.kind}:${e.id}`))]}),z&&wA(z)&&(0,m.jsx)(nA,{mode:z?.compaction?.status===`running`?`queue`:Pi,maintenance:z?.compaction?.status===`running`,onChange:Fi}),(0,m.jsxs)(`div`,{className:`composer`,children:[(0,m.jsxs)(`div`,{className:`session-picker`,id:`composer-session-options`,"data-session-picker":`1`,"data-mobile-expanded":Dn,children:[(0,m.jsx)(mA,{kind:`agent`,label:il?.name??`跟随 Pi 默认`,value:z?.agentId??hA,options:al,disabled:!un||un.source===`unavailable`||Bc,note:Uk(un),onChoose:cl}),(0,m.jsx)(mA,{kind:`model`,label:Wc?.label??(en?`Pi 默认`:`读取中…`),value:Wc?`${Wc.provider}/${Wc.modelId}`:void 0,detail:sl?`来自 ${il?.name}`:Wc&&en?.source===`pi`&&!z?.model?`Pi 默认模型`:Wc?`${Wc.provider}/${Wc.modelId}`:void 0,options:el,providerOptions:[...new Set($c.map(e=>e.provider))],disabled:!qc||Bc,note:Hk(`模型`,en,Zc),onChoose:nl}),(0,m.jsx)(mA,{kind:`thinking`,label:Kc??(en?en.levels.length?`Pi 默认`:`无可用等级`:`读取中…`),value:Gc,options:tl,disabled:!qc||Bc,note:Hk(`思考等级`,en),onChoose:rl})]}),(0,m.jsx)(`button`,{type:`button`,className:`mobile-composer-options`,"aria-controls":`composer-session-options`,"aria-expanded":Dn,onClick:()=>On(e=>!e),children:`会话选项`}),(0,m.jsxs)(`div`,{className:`composer-hints`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`composer-attach-btn`,"data-composer-attach":`1`,onClick:()=>ai.current?.click(),disabled:!z||!Yc||ca>0,title:z?Yc?`添加图片(支持剪贴板粘贴与拖拽)`:`当前模型不支持图片输入`:`请先创建或选择会话`,"aria-label":`添加图片`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),(0,m.jsx)(`span`,{className:`composer-attach-label`,children:` 图片`})]}),(0,m.jsx)(`input`,{ref:ai,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,style:{display:`none`},onChange:e=>{e.target.files?.length&&(cu(Array.from(e.target.files)),e.target.value=``)}}),Zc&&(0,m.jsx)(`span`,{"data-image-session-hint":`1`,title:`此会话历史已包含图片,仅显示支持图文的模型`,children:`图文会话`}),(0,m.jsx)(`span`,{children:`Enter 发送 · Shift + Enter 换行`})]}),(0,m.jsxs)(`div`,{className:`composer-actions`,children:[zi&&!Ui&&(0,m.jsx)(`button`,{type:`button`,className:`composer-relock`,"data-child-session-relock":`1`,title:`重新给这个子会话上锁`,onClick:()=>Pc(z?.id??``,!1),children:`重新上锁`}),z&&z.compaction?.status!==`running`&&(wA(z)||z.status===`awaiting_background`)&&(0,m.jsx)(h,{conversationId:z.id,pending:d.some(e=>e.key===`stop:${z.id}`),stopping:Pr.has(z.id),onStop:()=>jc({type:`run.stop`,conversationId:z.id},`stop:${z.id}`,e=>e,void 0,()=>Sc(`停止尚未确认,请检查后台任务或重试停止`,`error`),void 0,15e3)}),(0,m.jsx)(`button`,{className:`send ${wA(z)?z?.compaction?.status!==`running`&&Pi===`steer`?`send-steer`:`send-queued`:``}`,"data-send-mode":z?.compaction?.status===`running`?`queued`:wA(z)?Pi===`steer`?`steer`:`queued`:`direct`,disabled:!ia.trim()&&aa.length===0||!z||ca>0||sa||!!xu||Bc||Ui,title:z?Ui?`汇报线只允许逐级上升,子会话默认不能直接对话;确有特殊情况可解锁。`:Rc?`正在创建会话,请稍候再发送`:z.messagesLoaded===!1?`正在加载会话,请稍候再发送`:xu?`正在撤回:Pi 的历史还没截断完成,撤回结束后即可发送`:!ia.trim()&&aa.length===0?`请输入消息或添加图片后发送`:ca>0?`图片上传中…`:sa?`技能正在读取中,请稍候…`:wA(z)?Pi===`steer`?`当前工具完成后在下一回合边界插队回答(不会强行中止正在执行的工具)`:`这一轮结束后发送(发送后可在上面的排队区取消或插队)`:void 0:`请先创建或选择会话`,children:z?.compaction?.status===`running`?`排队发送 ↑`:xu?`撤回中…`:wA(z)?Pi===`steer`?`打断发送 ↑`:`排队发送 ↑`:`发送 ↑`})]})]})]}),Nl(`belowEditor`)]})]})]}),oo&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(mg,{share:$a,onShare:B}),(0,m.jsx)(hg,{tabs:Qs,selected:$s?.id,onSelect:ec,onPin:Zs,onCloseTab:rc,onClose:tc,children:bc()})]})]})}),(xr||!sd)&&(0,m.jsx)(Oj,{side:`right`,width:Sn&&xr?30:ar.rail,min:ar.railMin,max:ar.railMax,label:`调整右侧栏宽度`,onWidth:fr}),ns&&(0,m.jsx)(tg,{workspaceId:Ua,cwd:Ka,connected:te,initialQuery:ts.initialQuery,onOpen:e=>Ms(e,void 0,!1,!0),onClose:is,onMode:rs},Qo),ts?.mode===`content`&&(0,m.jsx)(eg,{workspaceId:Ua,cwd:Ka,initialReplace:ts.replace,dirtyPaths:V.open.filter(e=>e.dirty).map(e=>e.path),directory:ts.directory,initialQuery:ts.initialQuery,onOpen:(e,t,n)=>Ms(e,t,!1,!0,!1,n),onClose:is,onMode:rs},JSON.stringify([Qo,ts.directory])),ts?.mode===`session`&&(0,m.jsx)(Rp,{workspaceId:Ua,initialQuery:ts.initialQuery,onOpen:ss,onClose:is,onMode:rs},Qo),(0,m.jsx)(JA,{}),An&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`button`,{type:`button`,className:`mobile-drawer-backdrop`,"data-mobile-drawer-backdrop":`1`,"aria-label":`关闭会话列表`,onClick:()=>jn(!1)}),(0,m.jsx)(`button`,{type:`button`,className:`mobile-drawer-close`,"data-mobile-drawer-close":`1`,"aria-label":`关闭会话列表`,title:`关闭`,onClick:()=>jn(!1),children:`×`})]}),Tn===`rail`&&(0,m.jsx)(`button`,{type:`button`,className:`mobile-rail-back`,"data-mobile-nav":`chat`,onClick:kn,children:`‹ 返回对话`}),Ir&&(0,m.jsx)(Ek,{workspace:Ir.workspace,x:Ir.x,y:Ir.y,notify:Sc,onClose:()=>Lr(void 0)}),Rr&&(0,m.jsx)(Dk,{conversation:Rr.conversation,x:Rr.x,y:Rr.y,notify:Sc,onRename:()=>void Vl(Rr.conversation.id),onClose:()=>Vr(void 0),sendCommand:kc,orchestrated:Rr.conversation.origin===`orchestrator`,childCount:wi.filter(e=>e.parentConversationId===Rr.conversation.id).length}),Pe&&(0,m.jsx)(zk,{onClose:()=>Le(!1),onCreate:Pl}),Re&&(()=>{let e=O.workspaces.find(e=>e.id===Re.workspaceId);return e?(0,m.jsx)(Rk,{workspace:e,onClose:()=>{ze(void 0),Ve.current?.focus()},onCreate:e=>{iu(Re.workspaceId,e),ze(void 0),Ve.current?.focus()}}):null})(),Xl&&(0,m.jsx)(I_,{initialCategory:Ql,workspaceId:M,theme:Jl,onChooseTheme:e=>Yl(e),onClose:()=>{Zl(!1),ve()},agentCatalog:gn,subagentCatalog:vn,modelFilterRules:I.settingsSnapshot?.modelFilterRules??[],pendingSettings:d.some(e=>e.key===`model-rules`||e.key===`agent-directories`||e.key===`default-model`),onSetModelRules:e=>Nc({type:`model.rules.set`,rules:e},`model-rules`,t=>({...t,modelFilterRules:e})),defaultModel:I.settingsSnapshot?.defaultModel,modelCatalog:rn,onSetDefaultModel:e=>Nc({type:`settings.defaultModel`,model:e?{provider:e.provider,modelId:e.modelId}:null},`default-model`,t=>{let n={...t};return e?n.defaultModel=e:delete n.defaultModel,n}),providers:on,providerApis:cn,onSetProvider:e=>{Mc({type:`providers.set`,provider:e})},onRemoveProvider:e=>{Mc({type:`providers.remove`,providerId:e})},onRepairProviders:()=>{Mc({type:`providers.repair`}),Sc(`正在清理 Pi 不接受的空字段并重新读取模型清单`,`info`)},onToggleProvider:(e,t)=>{Mc(t?{type:`providers.enable`,providerId:e}:{type:`providers.disable`,providerId:e}),Sc(t?`已启用供应商「${e}」,它的模型重新出现在选择器里`:`已停用供应商「${e}」:配置已从 Pi 的文件里拿掉并保存在这里,模型不再出现在选择器里`,`info`)},onRemoveProviderModel:(e,t)=>{Mc({type:`providers.removeModel`,providerId:e,modelId:t})},customAgentDirs:I.settingsSnapshot?.customAgentDirs??[],onSetCustomAgentDirs:e=>Nc({type:`agents.setCustomDirs`,dirs:e},`agent-directories`,t=>({...t,customAgentDirs:e})),onRescanAgents:()=>Mc({type:`agents.rescan`}),userNickname:Wt,onSetUserNickname:Kt,terminalShell:I.settingsSnapshot?.terminalShell,onSetTerminalShell:e=>{Mc({type:`terminal.shell.set`,command:e})},onCheckBrowserNotifications:o,browserNotificationsEnabled:n,browserNotificationPermission:i,onSetBrowserNotifications:Tc}),eu&&(0,m.jsx)(kg,{onClose:()=>tu(!1)}),ql&&(0,m.jsx)(gA,{workspace:ql,onRemove:()=>Hl(ql),catalog:Xc(en,ql),agents:un,onClose:()=>Wl(void 0),onRename:()=>{let e=ql.id;Wl(void 0),Ll(`workspace`,e)},onSave:(e,t,n)=>nu(ql.id,e,t,n)}),ti&&(0,m.jsx)(QA,{image:ti,onClose:()=>ni(void 0)}),xr&&!Sn&&(0,m.jsx)(`div`,{className:`rail-backdrop`,role:`presentation`,"aria-hidden":`true`,onClick:()=>wn(!0)}),xr?(0,m.jsx)(UA,{...Lu,activeTab:Ro,mobileViews:Do.filter(e=>!ei(e)||e===`search`),collapsed:Sn,onToggle:()=>wn(e=>!e)}):(0,m.jsxs)(m.Fragment,{children:[Po&&Po!==`sessions`&&(0,m.jsx)(UA,{...Lu,side:`right`,activeTab:Po,collapsed:Io,onToggle:ad,pinned:!er.unpinned.includes(Po),onArrange:Xo}),(0,m.jsx)(yi,{side:`right`,views:Ao,unpinned:er.unpinned,previous:Po,active:Io?void 0:Po,onSelect:e=>Uo(e,!0),onDockCard:Yo,onArrange:Xo,onReorder:Zo}),(0,m.jsx)(yi,{side:`bottom`,views:jo,active:Lo.bottom,unpinned:er.unpinned,onSelect:e=>Uo(e,!0),onDockCard:Yo,onArrange:Xo,onReorder:Zo,children:(0,m.jsx)(`button`,{type:`button`,className:`workbench-bottom-toggle`,"data-bottom-toggle":!0,"aria-expanded":!er.bottomClosed,onClick:()=>tr(e=>({...e,bottomClosed:!e.bottomClosed})),children:`底部面板`})}),!er.bottomClosed&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(DD,{height:er.bottomHeight,onHeight:e=>tr(t=>({...t,bottomHeight:e}))}),Fo?Fo!==`sessions`&&(0,m.jsx)(UA,{...Lu,side:`bottom`,activeTab:Fo,collapsed:!1,onToggle:()=>tr(e=>({...e,bottomClosed:!0})),pinned:!er.unpinned.includes(Fo),onArrange:Xo}):(0,m.jsxs)(`section`,{className:`workbench-bottom-empty`,...pi(`bottom`,Jo,Yo),children:[(0,m.jsx)(`p`,{children:`将活动图标或功能区标题拖到底部栏。`}),(0,m.jsx)(`button`,{type:`button`,"data-bottom-terminal":!0,onClick:()=>Jo(`terminal`,`bottom`),children:`将终端移到底部`})]})]})]}),bn.panel,R!==`group`&&Z&&z&&(()=>{let e=Z.key,t=Z.value,n=Or[e]??cA(t);return(0,m.jsx)(dA,{question:{key:e,messageId:Z.messageId,index:Z.index,value:t},pendingCount:ul.length,minimized:Ar===e,floatingRight:xr?`12px`:Sn?`24px`:`calc(var(--rail-width, 320px) + 24px)`,onMinimize:()=>jr(e),onExpand:()=>jr(null),onLocate:dl,draft:n,onDraftChange:t=>Hc(e,t),onAnswer:(e,t)=>Vc(z.id,Z.messageId,Z.index,e,t)})})(),cc===`context`&&!Va&&z&&(0,m.jsx)(tt,{anchor:uc.current,title:`上下文`,onClose:()=>lc(void 0),children:(0,m.jsx)(et,{conversation:z,contextWindow:Jc?.contextWindow,connected:te&&I.statuses.get(L(z.id))?.state===`online`,onCompact:()=>kc({type:`conversation.compact`,conversationId:z.id}),onCancel:()=>kc({type:`conversation.compact.cancel`,conversationId:z.id})},z.id)}),cc===`session`&&!Va&&z&&(0,m.jsx)(tt,{anchor:uc.current,title:`会话操作`,searchable:!1,onClose:()=>lc(void 0),choices:[{id:`reload`,label:d.some(e=>e.key===`reload:${z.id}`)?`正在重新加载资源…`:`重新加载资源`,detail:wA(z)?`请先结束或停止当前任务`:`重新读取 Agent、技能和扩展;保留历史与草稿,无需重启服务`,disabled:!te||wA(z)||d.some(e=>e.key===`reload:${z.id}`)},{id:`new`,label:`新建空白会话`,detail:`在同一目录开始新对话;保留当前会话历史与草稿`},{id:`fork`,label:`分叉当前会话`,detail:`从现有上下文继续另一条路线`,disabled:wA(z)||!!ku},{id:`context`,label:`查看与压缩上下文`,detail:z.compaction?.status===`running`?`正在压缩,可查看进度或停止`:`查看用量、压缩进度与最近结果`},{id:`split`,label:oo?`合并主区`:`拆分主区`,detail:`并排或上下阅读会话与文件`,disabled:!Ua},{id:`update`,label:`软件更新`,detail:`检查版本、选择更新目标与查看进度`}],onChoose:e=>{e===`split`?(tc(),lc(void 0)):e===`update`?(lc(void 0),bn.open()):e===`context`?(uc.current=document.querySelector(`[data-context-button]`),lc(`context`)):Mu(e)&&lc(void 0)}}),cc===`workspaces`&&(0,m.jsx)(tt,{anchor:uc.current,title:`进入工作区`,onClose:()=>lc(void 0),choices:O.workspaces.filter(e=>!e.closedAt&&!e.id.startsWith(`pending:`)).sort((e,t)=>be(e.id).localeCompare(be(t.id))||(e.worktreeOf??e.id).localeCompare(t.worktreeOf??t.id)||Number(!!e.worktreeOf)-Number(!!t.worktreeOf)).map(e=>({id:e.id,label:e.name+(e.id===Ua?` · 当前`:``),detail:e.path,group:be(e.id)+` · `+(O.workspaces.find(t=>t.id===e.worktreeOf)?.name??e.name)})),onChoose:e=>{ed(L(e)),$u(`workspace`,e),Ia(e),lc(void 0)},children:(0,m.jsx)(`button`,{type:`button`,onClick:()=>{lc(void 0),Le(!0)},children:`添加工作区`})}),cc===`worktrees`&&Ga&&(0,m.jsx)(Cn,{anchor:uc.current,workspaceId:Ga,summaries:O.workspaces.filter(e=>L(e.id)===L(Ga)).map(e=>({path:e.path,running:O.conversations.filter(t=>t.workspaceId===e.id&&[`running`,`waiting`,`awaiting_background`].includes(t.status)).length})),onClose:()=>lc(void 0),onEnter:e=>{ed(L(e)),$u(`workspace`,e),Ia(e),lc(void 0)},onBranches:()=>{lc(void 0),qo(`branches`)}}),cc===`line`&&ic&&(0,m.jsx)(tt,{anchor:uc.current,title:`跳转到行与列`,onClose:()=>lc(void 0),children:(0,m.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=/^(\d+)(?::(\d+))?$/.exec(dc.trim());!t||Number(t[1])<1||t[2]&&Number(t[2])<1||(ls({scope:Qo,path:ic.path,line:Number(t[1]),column:Number(t[2]??1),request:++de.current}),lc(void 0))},children:[(0,m.jsxs)(`label`,{children:[`行号或 行号:列号`,(0,m.jsx)(`input`,{autoFocus:!0,"aria-label":`跳转位置`,value:dc,onChange:e=>fc(e.target.value),pattern:`[1-9][0-9]*(:[1-9][0-9]*)?`,required:!0})]}),(0,m.jsx)(`button`,{type:`submit`,children:`跳转`})]})}),cc===`language`&&(0,m.jsx)(tt,{anchor:uc.current,title:`文件语言与语法高亮`,onClose:()=>lc(void 0),choices:[{id:`auto`,label:`自动识别`},{id:`plain`,label:`纯文本`},...[`cpp`,`c`,`js`,`ts`,`tsx`,`py`,`go`,`rs`,`java`,`json`,`md`,`sh`,`css`,`html`,`yaml`,`sql`].map(e=>({id:e,label:Pn(e)||e}))],onChoose:e=>{mc(t=>({...t,[ac]:e===`auto`?void 0:e})),lc(void 0)}}),cc===`diff`&&(0,m.jsxs)(tt,{anchor:uc.current,title:`当前文件差异`,onClose:()=>lc(void 0),children:[(0,m.jsxs)(`p`,{children:[ys?.target.comparison,` · `,xs]}),[-1,1].map(e=>(0,m.jsx)(`button`,{type:`button`,onClick:()=>{lc(void 0),window.dispatchEvent(new CustomEvent(`super-pi-status-diff-jump`,{detail:{url:ys?.target.url,direction:e}}))},children:e<0?`上一处改动`:`下一处改动`},e))]}),(0,m.jsxs)(`footer`,{className:`workbench-status`,"data-workbench-status":`1`,"aria-label":`工作台状态`,children:[(0,m.jsxs)(`div`,{className:`workbench-status-group`,children:[(0,m.jsx)(We,{connected:te,onSelectServer:e=>ed(e),onSettings:()=>{_e(),$l(`servers`),Zl(!0)}}),nd&&te&&(0,m.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-branch`,"data-workbench-branch":nd,title:`进入其他工作树或管理分支`,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`worktrees`?void 0:`worktrees`)},children:[(0,m.jsx)(vi,{name:`git`}),(0,m.jsx)(`code`,{children:nd}),id&&(0,m.jsx)(`code`,{children:id})]}),!!rd&&(0,m.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-changes`,"data-workbench-changes":rd,onClick:()=>{qo(`changes`)},children:[rd,` 个改动`]}),(0,m.jsxs)(`button`,{type:`button`,className:`workbench-status-scope workbench-status-button`,title:hc?.path??`选择工作区`,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`workspaces`?void 0:`workspaces`)},children:[(0,m.jsx)(vi,{name:`files`}),(0,m.jsxs)(`span`,{children:[hc?.name??`选择工作区`,Ka?` / `+Ka:``]})]})]}),(0,m.jsxs)(`div`,{className:`workbench-status-group workbench-status-context`,children:[!Va&&z&&(0,m.jsx)(Qe,{conversation:z,contextWindow:Jc?.contextWindow,expanded:cc===`context`,onOpen:e=>{uc.current=e.currentTarget,lc(e=>e===`context`?void 0:`context`)}}),R===`session`&&z&&(0,m.jsx)(mA,{kind:`model`,label:Jc?.label??Wc?.modelId??`选择模型`,value:Wc?`${Wc.provider}/${Wc.modelId}`:void 0,options:el,providerOptions:[...new Set($c.map(e=>e.provider))],disabled:!qc||Bc,onChoose:nl}),R===`session`&&z&&(0,m.jsx)(mA,{kind:`thinking`,label:Kc??`思考等级`,value:Gc,options:tl,disabled:!qc||Bc,onChoose:rl}),R===`group`&>&&(0,m.jsx)(`button`,{type:`button`,className:`workbench-status-button`,onClick:()=>window.dispatchEvent(new CustomEvent(`super-pi-status-group-models`,{detail:{roomId:gt}})),children:`群成员模型`}),R===`file`&&ic&&(sc?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-editor-cursor`,"data-workbench-editor-position":`1`,onClick:e=>{uc.current=e.currentTarget,fc(`${sc.line}:${sc.column}`),lc(`line`)},children:[`第 `,sc.line,` 行,第 `,sc.column,` 列`]}),(0,m.jsx)(`button`,{type:`button`,className:`workbench-status-button`,"data-file-highlight-status":sc.highlight,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`language`?void 0:`language`)},children:sc.language})]}):(0,m.jsx)(`span`,{title:ic.path,children:ic.name})),bs===`diff`&&xs&&(0,m.jsx)(`button`,{type:`button`,className:`workbench-status-button`,title:xs,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`diff`?void 0:`diff`)},children:xs}),bn.entry(`workbench-status-button software-update-desktop`),(0,m.jsxs)(`button`,{type:`button`,className:`workbench-version workbench-status-button`,"data-super-pi-version":(bn.status??mn)?.runningVersion??``,title:`查看版本与软件更新`,onClick:bn.open,children:[`v`,(bn.status??mn)?.runningVersion??`…`]})]})]}),(0,m.jsx)(UA,{...Lu,contentOwner:!0,activeTab:bo,collapsed:!1,onToggle:ad,onCloseView:e=>{xr?(kn(),wn(!0)):tr(t=>({...t,[er.sides[e]+`Closed`]:!0}))}})]})})}v_(__()),(0,f.createRoot)(document.getElementById(`root`)).render((0,m.jsx)(p.StrictMode,{children:(0,m.jsx)(zj,{})}));export{kn as _,nm as a,$p as c,Zi as d,ea as f,Nn as g,Pn as h,eh as i,Vp as l,zr as m,lh as n,Qp as o,Br as p,Zm as r,em as s,sg as t,Hp as u,d as v,r as y};
|
|
352
|
+
`),u=(()=>{let e=/<result_file>([\s\S]*?)<\/result_file>/.exec(t.content);return e&&e[1].trim()?e[1].trim():void 0})(),d=(()=>{let e=/<task id="([^"]+)"/.exec(t.content);return e?v(y(t.id).server,y(e[1]).id):void 0})(),f=!!(d&&wi.some(e=>e.id===d)),p=`tool:${t.id}`,h=wr[p]??!1,g=r?`自动恢复`:i?`后台回传`:`智能体下发`;return(0,m.jsx)(`article`,{className:`message tool${i?``:` tool-order`}`,"data-transcript-key":e,"data-tool-state":o,"data-tool-kind":r?`recovery`:i?`delivery`:`order`,children:(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsxs)(`div`,{className:`bg-result-head`,"data-bg-result-head":t.id,children:[(0,m.jsxs)(`button`,{type:`button`,className:`bg-result-toggle`,"data-bg-result-toggle":t.id,"aria-expanded":h,title:h?`折叠${g}`:`展开${g}`,onClick:()=>Tr(e=>({...e,[p]:!h})),children:[(0,m.jsx)(`span`,{className:`bg-result-glyph`,"aria-hidden":`true`,children:o===`error`?`✕`:i?`↩`:`↓`}),(0,m.jsx)(`span`,{className:`bg-result-label`,children:c&&(c.status===`cancelled`||c.status===`interrupted`)?kA[c.status]:g}),(0,m.jsx)(`span`,{className:`bg-result-summary`,title:a,children:a}),!h&&(0,m.jsx)(`span`,{className:`bg-result-preview`,"data-bg-result-preview":t.id,title:`展开查看任务输出`,children:c?.reason||Zk(l)}),(0,m.jsx)(`span`,{className:`bg-result-chevron`,"aria-hidden":`true`,children:h?`▾`:`▸`})]}),(u||f&&d)&&(0,m.jsxs)(`div`,{className:`bg-result-actions`,"data-bg-result-actions":t.id,children:[u&&(0,m.jsxs)(`button`,{type:`button`,className:`bg-result-action`,"data-result-file-link":u,title:`在主区域打开产物文件:${u}`,onClick:e=>{e.stopPropagation();let t=u.split(/[/\\]/).pop()||u;Ms({path:u,name:t,text:!0}).catch(e=>{console.warn(`打开产物文件失败:`,e)})},children:[(0,m.jsx)(`span`,{className:`bg-result-action-glyph`,"aria-hidden":`true`,children:`📄`}),(0,m.jsx)(`span`,{children:`查看产物文件`})]}),f&&d&&(0,m.jsxs)(`button`,{type:`button`,className:`bg-result-action`,"data-result-session-link":d,title:`跳转到子会话:${d}`,onClick:e=>{e.stopPropagation(),Pa(d)},children:[(0,m.jsx)(`span`,{className:`bg-result-action-glyph`,"aria-hidden":`true`,children:`↗`}),(0,m.jsx)(`span`,{children:`跳转到子会话`})]})]})]}),h&&(0,m.jsx)(`div`,{className:`bg-result-body`,"data-bg-result-body":t.id,children:(0,m.jsx)(`pre`,{className:`bg-result-pre`,"data-bg-result-pre":t.id,children:l})})]})},e)}let l=t.thinking?.trim()?t.thinking:``,u=t.thinkingBlocks?.length?t.thinkingBlocks:l?[{at:0,text:l}]:[],f=(e,n)=>{let r=typeof e.at==`number`&&Number.isFinite(e.at)?e.at:n;return Math.max(0,Math.min(r,t.content.length))},p=e=>e.thinkingBlock===void 0?typeof e.thinkingAt!=`number`||!(e.thinkingAt<l.length||t.thinkingActive)?-1:u.findIndex((t,n)=>(e.at??0)>=t.at&&(u[n+1]===void 0||(e.at??0)<u[n+1].at)):e.thinkingBlock??-1,h=e=>s.map((e,t)=>({call:e,index:t})).filter(({call:t})=>p(t)===e),g=[],_=[...u.map((e,t)=>({at:e.at,order:u.slice(0,t).reduce((e,t)=>e+t.text.length,0)*2+1,segment:{blockIndex:t}})),...s.map((e,t)=>({at:f(e,t),order:(e.thinkingAt??0)*2,segment:{call:e,index:t}})).filter(({segment:e})=>`call`in e&&p(e.call)<0)].sort((e,t)=>e.at-t.at||e.order-t.order),b=0;for(let e of _){let n=Math.max(b,Math.min(e.at,t.content.length));n>b&&g.push({text:t.content.slice(b,n)}),g.push(e.segment),b=n}b<t.content.length&&g.push({text:t.content.slice(b)});let x=e=>{let t=Sl.get(e);if(t)return(0,m.jsx)(`div`,{className:`call-anchored-run`,"data-call-anchored-run":t.id,"data-call-anchored-site":e,children:(0,m.jsx)(rA,{run:t,name:yl.get(t.agentId)??``,expanded:!!Sr[t.id],onToggle:()=>Tl(t.id),onStop:()=>jl(t.id),stopping:d.some(e=>e.key===`stop:${t.id}`)})})},S=e=>e.call.question?(()=>{let n=dA(z?.id??``,t.id,e.index),r=Or[n]??fA(e.call.question);return(0,m.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,m.jsx)(pA,{question:e.call.question,index:e.index,draft:r,onDraftChange:e=>Hc(n,e),expanded:`${t.id}:${e.index}`in Er?!!Er[`${t.id}:${e.index}`]:!0,onToggle:()=>Dl(t.id,e.index),onAnswer:(n,r)=>Vc(z?.id??``,t.id,e.index,n,r)})},`c${e.index}`)})():(0,m.jsx)(`div`,{className:`call-blocks`,"data-call-block-index":e.index,children:(0,m.jsx)(eA,{call:e.call,index:e.index,expanded:`${t.id}:${e.index}`in wr&&!!wr[`${t.id}:${e.index}`],onToggle:()=>El(t.id,e.index),backgroundOutput:e.call.backgroundTask&&(0,m.jsx)($k,{task:e.call.backgroundTask,execOutputs:Dt.current,expanded:`${t.id}:${e.index}`in wr&&!!wr[`${t.id}:${e.index}`]}),runCard:x(`${t.id}:${e.index}`)})},`c${e.index}`),C=e=>{let n=u[e],r=u.slice(0,e).reduce((e,t)=>e+t.text.length,0),i=0,a=[];for(let{call:t,index:o}of h(e).sort((e,t)=>(e.call.thinkingAt??r)-(t.call.thinkingAt??r)||e.index-t.index)){let e=Math.max(i,Math.min(n.text.length,(t.thinkingAt??r)-r));e>i&&a.push((0,m.jsx)(`div`,{className:`content thinking-text`,children:(0,m.jsx)(ep,{source:n.text.slice(i,e),media:Ni})},`t${o}`)),a.push(S({call:t,index:o})),i=e}i<n.text.length&&a.push((0,m.jsx)(`div`,{className:`content thinking-text`,children:(0,m.jsx)(ep,{source:n.text.slice(i),media:Ni})},`tail`));let o=h(e).filter(e=>e.call.status===void 0),s=o.find(e=>e.call.question?.status===`pending`);return(0,m.jsx)(nA,{liveCall:s?`question`:o.at(-1)?.call.label,liveAwaitingReader:!!s,liveExtra:o.length>1?o.length-1:void 0,messageId:`${t.id}:${e}`,nestedCount:h(e).length,preview:n.text.split(`
|
|
353
|
+
`).map(e=>e.trim()).find(Boolean)??``,expanded:Ol[`${t.id}:${e}`]===!0,onToggle:()=>Al(`${t.id}:${e}`),children:a},`${t.id}:thinking:${e}`)};return(0,m.jsxs)(`article`,{className:`message assistant`,"data-transcript-key":e,children:[(0,m.jsx)(`div`,{className:`avatar`,children:`π`}),(0,m.jsxs)(`div`,{className:`message-body`,children:[(0,m.jsxs)(`div`,{className:`meta`,children:[t.agentIdentity?.name??`Super Pi`,(0,m.jsx)(`time`,{children:bk(t.createdAt)})]}),g.length===0&&(z?.status===`running`||z?.status===`waiting`)?(0,m.jsx)(`div`,{className:`content`,children:(0,m.jsx)(`span`,{className:`typing`,children:`正在思考`})}):g.map((e,t)=>`blockIndex`in e?C(e.blockIndex):`text`in e?e.text?(0,m.jsx)(`div`,{className:`content`,children:(0,m.jsx)(ep,{source:e.text,media:Ni,sourceLink:wc})},`t${t}`):null:S(e)),t.content.trim()&&(0,m.jsx)(`div`,{className:`message-actions`,children:(0,m.jsx)(`button`,{type:`button`,className:`message-copy`,"data-copy-message":t.id,"data-copy-state":c,"aria-label":`复制智能体回复`,onClick:()=>void Ou(t.id,t.content),children:(0,m.jsx)(`span`,{"aria-live":`polite`,children:c===`copied`?`已复制`:c===`error`?`复制失败`:`复制`})})})]})]},e)}if(e.startsWith(`w:`)){let t=vl.get(e.slice(2));return t?(0,m.jsxs)(`div`,{"data-transcript-key":e,children:[d.some(e=>e.key===`stop:${t.id}`)&&(0,m.jsx)(`span`,{children:`停止中…`}),(0,m.jsx)(Dg,{workflow:t,names:yl,stopping:d.some(e=>e.key===`stop:${t.id}`),onStop:()=>Ml(t.id)},e)]},e):null}let t=xl.get(e.slice(2));return t?(0,m.jsxs)(`div`,{"data-transcript-key":e,children:[d.some(e=>e.key===`stop:${t.id}`)&&(0,m.jsx)(`span`,{children:`停止中…`}),(0,m.jsx)(rA,{run:t,stopping:d.some(e=>e.key===`stop:${t.id}`),name:yl.get(t.agentId)??``,expanded:!!Sr[t.id],onToggle:()=>Tl(t.id),onStop:()=>jl(t.id)},e)]},e):null})]}),!Yi&&(0,m.jsxs)(m.Fragment,{children:[z&&(0,m.jsx)($e,{conversation:z,connected:te,onCancel:()=>kc({type:`conversation.compact.cancel`,conversationId:z.id})},z.id),(0,m.jsx)(sA,{messages:mu,pendingInterrupts:d.filter(e=>e.key.startsWith(`interrupt:${z?.id}:`)).map(e=>e.key.slice(`interrupt:${z?.id}:`.length)),running:z?.status===`running`,onSteer:_u,onInterrupt:vu,onSend:yu,onCancel:hu,onCancelMany:gu,onEdit:bu}),(0,m.jsxs)(`div`,{className:`stream-tail`,"data-stream-tail":`1`,"data-follow-tail":wt.followTail?`true`:`false`,children:[pr!==null&&(0,m.jsx)(Bj,{height:pr,onHeight:br}),(0,m.jsx)(`span`,{className:`stream-tail-status`,"data-run-status":z?.status??`idle`,"data-stream-state":z?.compaction?.status===`running`?`compacting`:te?zc?`stopping`:z&&jA(z,xn)?`question`:z?.status===`waiting`?`waiting`:z?.status===`running`?`streaming`:z?.status===`awaiting_background`||mu.length?`waiting`:z?.status===`failed`?`failed`:Ki===`awaiting_decision`?`awaiting_decision`:Ki===`awaiting_subordinates`?`awaiting_subordinates`:Ki===`pending_report`?`pending_report`:`ready`:`waiting`,children:z?.compaction?.status===`running`?`正在压缩上下文 · 新消息等待压缩完成`:te?Rc?`正在创建会话…`:zc?`正在停止…`:z&&jA(z,xn)?`等你回答 · Agent 在等你的回复`:z?.messagesLoaded===!1?`正在加载会话…`:z?.status===`waiting`?`等待 LLM 返回`:z?.status===`running`?`Streaming · 正在生成`:z?.status===`awaiting_background`?`等待后台任务 · 任务在后台运行中`:mu.length?`Waiting · 消息排队中`:z?.status===`failed`?`运行失败`:z?.status===`stopped`?`已停止`:Ki===`awaiting_decision`?`等待上级处理例外…`:Ki===`awaiting_subordinates`?`等待下级汇报…`:Ki===`pending_report`?`已完成,待向父会话汇报`:`就绪`:`连接中 / 等待连接`}),!wt.followTail&&(0,m.jsx)(`button`,{type:`button`,className:`stream-tail-jump`,"data-jump-to-bottom":`1`,onClick:()=>{let e=yt.current;e&&(Sj(e),e.scrollTop=e.scrollHeight,ta(e,!1,!0))},children:`↓ 跳到底部`}),(0,m.jsx)(`span`,{className:`stream-tail-mode`,"data-follow-tail":wt.followTail?`true`:`false`,children:wt.followTail?`贴底`:`自由浏览`})]}),(ll.length>0||[...ml.values()].some(e=>e.placement===`aboveEditor`))&&(0,m.jsxs)(`div`,{className:`extui`,"data-extui-count":ll.length,children:[ll.map(e=>(0,m.jsx)(gA,{request:e.request,pending:d.some(t=>t.key===`answer:${e.conversationId}:${e.request.requestId}`),onAnswer:t=>Uc(e.conversationId,e.request.requestId,t)},e.request.requestId)),Nl(`aboveEditor`)]}),(0,m.jsxs)(`form`,{onSubmit:pu,onPaste:lu,onDragOver:uu,onDragLeave:du,onDrop:fu,className:ri?`composer-dropzone-active`:void 0,children:[(0,m.jsxs)(`div`,{className:`composer-input`,"data-composer-input":`1`,children:[(0,m.jsx)(`textarea`,{ref:bt,value:ia,onCompositionStart:()=>{oi.current=!0,ya(void 0)},onCompositionEnd:e=>{oi.current=!1,wa.current=``,Ea(e.currentTarget)},onSelect:e=>{e.currentTarget===document.activeElement&&Ea(e.currentTarget)},"aria-autocomplete":Ta?`list`:void 0,"aria-controls":Ta?`file-mention-menu`:void 0,"aria-activedescendant":Ta?xa:void 0,onChange:e=>{da(e.target.value),e.target.value!==ia&&Na(z?.id??``);let t=e.target.value;if(wa.current=``,Ea(e.currentTarget))return;let n=e.target.selectionStart??t.length,r=t.slice(0,n),i=r.lastIndexOf(`/`),a=r.slice(i+1),o=i>0?r[i-1]:``;i>=0&&(i===0||/\s/.test(o))&&/^[\w:-]*$/u.test(a)?ga({visible:!0,query:a,rect:e.currentTarget.getBoundingClientRect()}):ga({visible:!1,query:``,rect:null})},placeholder:z?Yc?`描述你要完成的任务(支持粘贴/拖放图片)…`:`描述你要完成的任务…`:`先创建会话`,disabled:!z,readOnly:Ui,"aria-describedby":Ui?`child-session-lock-reason`:void 0,onKeyDown:e=>{if(!(oi.current||mk(e))&&!(Ta&&ba.current?.handleKey(e))){if(ha.visible){if(e.key===`Escape`){e.preventDefault(),ga({visible:!1,query:``,rect:null});return}if([`ArrowDown`,`ArrowUp`,`Enter`].includes(e.key)){e.preventDefault();return}}e.key===`Enter`&&!e.shiftKey&&(e.preventDefault(),e.currentTarget.form?.requestSubmit())}}}),Ui&&(0,m.jsxs)(`div`,{className:`composer-lock`,"data-child-session-lock":`1`,role:`note`,"aria-labelledby":`child-session-lock-title`,children:[(0,m.jsx)(`span`,{className:`composer-lock-glyph`,"data-child-session-lock-glyph":`1`,"aria-hidden":`true`,children:(0,m.jsxs)(`svg`,{viewBox:`0 0 24 24`,width:`30`,height:`30`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,focusable:`false`,children:[(0,m.jsx)(`rect`,{x:`4`,y:`10`,width:`16`,height:`11`,rx:`2.5`}),(0,m.jsx)(`path`,{d:`M8 10V7a4 4 0 0 1 8 0v3`}),(0,m.jsx)(`path`,{d:`M12 14.5v2.5`})]})}),(0,m.jsxs)(`span`,{className:`composer-lock-text`,children:[(0,m.jsx)(`span`,{className:`composer-lock-title`,"data-child-session-lock-title":`1`,id:`child-session-lock-title`,children:`子会话输入框已上锁`}),(0,m.jsx)(`span`,{className:`composer-lock-reason`,"data-child-session-lock-reason":`1`,id:`child-session-lock-reason`,children:`汇报线只允许逐级上升,子会话默认不能直接对话;确有特殊情况可解锁。`})]}),(0,m.jsx)(`button`,{type:`button`,className:`composer-lock-action`,"data-child-session-unlock":`1`,onClick:()=>Pc(z?.id??``,!0),children:`临时解锁`})]})]}),Ta&&z?.workspaceId&&(0,m.jsx)(gp,{ref:ba,workspaceId:z.workspaceId,cwd:z.cwd??``,query:Ta.token.query,anchor:Ta.rect,onClose:Da,onActive:Sa,onChoose:e=>{let t=bt.current,n=t?.value??ia,r=t?_p(n,t.selectionStart,t.selectionEnd):void 0;if(!r||r.start!==Ta.token.start||r.query!==Ta.token.query){Da();return}let i=vp(n,r,e);Ca.current={scope:_a,...i},da(i.text),ya(void 0)}},_a),!Ta&&ha.visible&&ha.rect&&(0,m.jsx)(hp,{query:ha.query,anchorRect:ha.rect,workspaceId:z?.workspaceId,promptCatalog:Jt,command:kc,onSelect:e=>{let t=bt.current?.selectionStart??ia.length,n=ia.slice(0,t),r=n.lastIndexOf(`/`),i=fp(e,ha.query),a=`${n.slice(0,r)}/${i} ${ia.slice(t)}`;e.id.startsWith(`skill:`)&&z?fa(e.id,a,z.id,z.workspaceId):da(a),ga({visible:!1,query:``,rect:null})},onClose:()=>ga({visible:!1,query:``,rect:null})}),Li.filter(e=>e.conversationId===z?.id).map(e=>(0,m.jsxs)(`div`,{className:`composer-notice queue-withdrawn-notice`,"data-queue-withdrawn-notice":`1`,role:`status`,children:[(0,m.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`↺`}),(0,m.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,m.jsx)(`p`,{className:`composer-notice-title`,children:e.actor===`agent`?`上级 Agent 已撤回 ${e.withdrawn.length} 条排队消息(不会再被回答)`:`已撤回 ${e.withdrawn.length} 条排队消息(不会再被回答)`}),(0,m.jsx)(`p`,{className:`composer-notice-text`,title:e.withdrawn.map(e=>e.content).join(`
|
|
354
|
+
`),children:e.withdrawn.map(e=>`「${e.content.replace(/\s+/g,` `).trim().slice(0,48)}」`).join(` · `)})]}),(0,m.jsx)(`div`,{className:`composer-notice-actions`,children:(0,m.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-queue-withdrawn-dismiss":`1`,onClick:()=>Ri(t=>t.filter(t=>t.id!==e.id)),children:`知道了`})})]},e.id)),Jr.filter(e=>e.conversationId===z?.id).map(e=>(0,m.jsxs)(`div`,{className:`composer-notice`,"data-failed-send":e.id,role:`alert`,children:[(0,m.jsx)(`span`,{className:`composer-notice-mark`,"aria-hidden":`true`,children:`!`}),(0,m.jsxs)(`div`,{className:`composer-notice-body`,children:[(0,m.jsx)(`p`,{className:`composer-notice-title`,"data-failed-send-reason":`1`,title:Br(e.reason),children:e.reason?.trim()?zr(e.reason):`服务端没有接受这条消息。`}),(0,m.jsx)(`p`,{className:`composer-notice-text`,title:e.content,children:e.content})]}),(0,m.jsxs)(`div`,{className:`composer-notice-actions`,children:[(0,m.jsx)(`button`,{type:`button`,className:`composer-notice-action`,"data-failed-send-restore":`1`,disabled:!!(ia||aa.length||oa.length),title:ia||aa.length||oa.length?`输入框里已经有内容,先把这条留在下面`:`放回输入框,改完再发`,onClick:()=>{la(e.conversationId,t=>({...t,text:e.content,images:e.images,attachments:e.attachments})),Yr(t=>t.filter(t=>t.id!==e.id))},children:`放回输入框`}),(0,m.jsx)(`button`,{type:`button`,className:`composer-notice-dismiss`,"data-failed-send-dismiss":`1`,onClick:()=>Yr(t=>t.filter(t=>t.id!==e.id)),children:`丢弃`})]})]},e.id)),Xr.filter(e=>e.conversationId===z?.id).map(e=>(0,m.jsxs)(`div`,{className:`composer-upload-preview${e.failed?` composer-upload-preview-failed`:``}`,"data-upload-preview":e.id,children:[(0,m.jsx)(`img`,{src:e.url,alt:e.name,width:44,height:44,className:`composer-upload-thumb`}),(0,m.jsx)(`span`,{className:`composer-upload-state`,"data-upload-preview-state":e.failed?`failed`:`uploading`,children:e.failed?`上传失败`:`上传中…`}),(0,m.jsx)(`button`,{type:`button`,className:`composer-upload-remove`,"aria-label":`移除 ${e.name}`,title:`移除这张图片`,onClick:()=>{qr.current.add(e.id),URL.revokeObjectURL(e.url),Zr(t=>t.filter(t=>t.id!==e.id))},children:`移除`})]},e.id)),(aa.length>0||ca>0||oa.length>0||sa)&&(0,m.jsxs)(`div`,{className:`composer-attachments`,"data-composer-attachments":`1`,children:[aa.map((e,t)=>(0,m.jsxs)(`div`,{className:`composer-attachment-item`,"data-composer-attachment-id":e.id,children:[(0,m.jsx)(`img`,{src:Fe(`/api/upload/${encodeURIComponent(z?.id??``)}/${encodeURIComponent(e.id)}`),alt:e.name||`已附图片`,className:`composer-attachment-thumb`,onClick:()=>ni({url:Fe(`/api/upload/${encodeURIComponent(z?.id??``)}/${encodeURIComponent(e.id)}`),name:e.name,bytes:e.bytes}),title:`点击查看大图`}),(0,m.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name||`图片`}),(0,m.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-attachment-remove":e.id,onClick:()=>Oa(e=>e.filter((e,n)=>n!==t)),"aria-label":`移除 ${e.name||`图片`}`,title:`移除图片`,children:`✕`})]},e.id)),ca>0&&(0,m.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,children:(0,m.jsxs)(`span`,{children:[`图片上传中 (`,ca,`)…`]})}),sa&&(0,m.jsx)(`div`,{className:`composer-attachment-item composer-attachment-uploading`,"data-composer-skill-loading":!0,role:`status`,children:`读取技能中…`}),oa.map(e=>(0,m.jsxs)(`div`,{className:`composer-attachment-item composer-attachment-skill`,"data-composer-skill-id":e.id,children:[(0,m.jsx)(`span`,{className:`composer-attachment-glyph`,"aria-hidden":`true`,children:`▤`}),(0,m.jsx)(`span`,{className:`composer-attachment-name`,title:e.name,children:e.name}),(0,m.jsx)(`button`,{type:`button`,className:`composer-attachment-remove`,"data-composer-skill-remove":e.id,onClick:()=>ma(e.kind,e.id),"aria-label":`移除 ${e.name}`,title:`移除技能`,children:`✕`})]},`${e.kind}:${e.id}`))]}),z&&OA(z)&&(0,m.jsx)(oA,{mode:z?.compaction?.status===`running`?`queue`:Pi,maintenance:z?.compaction?.status===`running`,onChange:Fi}),(0,m.jsxs)(`div`,{className:`composer`,children:[(0,m.jsxs)(`div`,{className:`session-picker`,id:`composer-session-options`,"data-session-picker":`1`,"data-mobile-expanded":Dn,children:[(0,m.jsx)(vA,{kind:`agent`,label:il?.name??`跟随 Pi 默认`,value:z?.agentId??yA,options:al,disabled:!un||un.source===`unavailable`||Bc,note:qk(un),onChoose:cl}),(0,m.jsx)(vA,{kind:`model`,label:Wc?.label??(en?`Pi 默认`:`读取中…`),value:Wc?`${Wc.provider}/${Wc.modelId}`:void 0,detail:sl?`来自 ${il?.name}`:Wc&&en?.source===`pi`&&!z?.model?`Pi 默认模型`:Wc?`${Wc.provider}/${Wc.modelId}`:void 0,options:el,providerOptions:[...new Set($c.map(e=>e.provider))],disabled:!qc||Bc,note:Kk(`模型`,en,Zc),onChoose:nl}),(0,m.jsx)(vA,{kind:`thinking`,label:Kc??(en?en.levels.length?`Pi 默认`:`无可用等级`:`读取中…`),value:Gc,options:tl,disabled:!qc||Bc,note:Kk(`思考等级`,en),onChoose:rl})]}),(0,m.jsx)(`button`,{type:`button`,className:`mobile-composer-options`,"aria-controls":`composer-session-options`,"aria-expanded":Dn,onClick:()=>On(e=>!e),children:`会话选项`}),(0,m.jsxs)(`div`,{className:`composer-hints`,children:[(0,m.jsxs)(`button`,{type:`button`,className:`composer-attach-btn`,"data-composer-attach":`1`,onClick:()=>ai.current?.click(),disabled:!z||!Yc||ca>0,title:z?Yc?`添加图片(支持剪贴板粘贴与拖拽)`:`当前模型不支持图片输入`:`请先创建或选择会话`,"aria-label":`添加图片`,children:[(0,m.jsx)(`span`,{"aria-hidden":`true`,children:`+`}),(0,m.jsx)(`span`,{className:`composer-attach-label`,children:` 图片`})]}),(0,m.jsx)(`input`,{ref:ai,type:`file`,accept:`image/png,image/jpeg,image/gif,image/webp`,multiple:!0,style:{display:`none`},onChange:e=>{e.target.files?.length&&(cu(Array.from(e.target.files)),e.target.value=``)}}),Zc&&(0,m.jsx)(`span`,{"data-image-session-hint":`1`,title:`此会话历史已包含图片,仅显示支持图文的模型`,children:`图文会话`}),(0,m.jsx)(`span`,{children:`Enter 发送 · Shift + Enter 换行`})]}),(0,m.jsxs)(`div`,{className:`composer-actions`,children:[zi&&!Ui&&(0,m.jsx)(`button`,{type:`button`,className:`composer-relock`,"data-child-session-relock":`1`,title:`重新给这个子会话上锁`,onClick:()=>Pc(z?.id??``,!1),children:`重新上锁`}),z&&z.compaction?.status!==`running`&&(OA(z)||z.status===`awaiting_background`)&&(0,m.jsx)(h,{conversationId:z.id,pending:d.some(e=>e.key===`stop:${z.id}`),stopping:Pr.has(z.id),onStop:()=>jc({type:`run.stop`,conversationId:z.id},`stop:${z.id}`,e=>e,void 0,()=>Sc(`停止尚未确认,请检查后台任务或重试停止`,`error`),void 0,15e3)}),(0,m.jsx)(`button`,{className:`send ${OA(z)?z?.compaction?.status!==`running`&&Pi===`steer`?`send-steer`:`send-queued`:``}`,"data-send-mode":z?.compaction?.status===`running`?`queued`:OA(z)?Pi===`steer`?`steer`:`queued`:`direct`,disabled:!ia.trim()&&aa.length===0||!z||ca>0||sa||!!xu||Bc||Ui,title:z?Ui?`汇报线只允许逐级上升,子会话默认不能直接对话;确有特殊情况可解锁。`:Rc?`正在创建会话,请稍候再发送`:z.messagesLoaded===!1?`正在加载会话,请稍候再发送`:xu?`正在撤回:Pi 的历史还没截断完成,撤回结束后即可发送`:!ia.trim()&&aa.length===0?`请输入消息或添加图片后发送`:ca>0?`图片上传中…`:sa?`技能正在读取中,请稍候…`:OA(z)?Pi===`steer`?`当前工具完成后在下一回合边界插队回答(不会强行中止正在执行的工具)`:`这一轮结束后发送(发送后可在上面的排队区取消或插队)`:void 0:`请先创建或选择会话`,children:z?.compaction?.status===`running`?`排队发送 ↑`:xu?`撤回中…`:OA(z)?Pi===`steer`?`打断发送 ↑`:`排队发送 ↑`:`发送 ↑`})]})]})]}),Nl(`belowEditor`)]})]})]}),oo&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(mg,{share:$a,onShare:B}),(0,m.jsx)(hg,{tabs:Qs,selected:$s?.id,onSelect:ec,onPin:Zs,onCloseTab:rc,onClose:tc,children:bc()})]})]})}),(xr||!sd)&&(0,m.jsx)(Nj,{side:`right`,width:Sn&&xr?30:ar.rail,min:ar.railMin,max:ar.railMax,label:`调整右侧栏宽度`,onWidth:fr}),ns&&(0,m.jsx)(tg,{workspaceId:Ua,cwd:Ka,connected:te,initialQuery:ts.initialQuery,onOpen:e=>Ms(e,void 0,!1,!0),onClose:is,onMode:rs},Qo),ts?.mode===`content`&&(0,m.jsx)(eg,{workspaceId:Ua,cwd:Ka,initialReplace:ts.replace,dirtyPaths:V.open.filter(e=>e.dirty).map(e=>e.path),directory:ts.directory,initialQuery:ts.initialQuery,onOpen:(e,t,n)=>Ms(e,t,!1,!0,!1,n),onClose:is,onMode:rs},JSON.stringify([Qo,ts.directory])),ts?.mode===`session`&&(0,m.jsx)(Rp,{workspaceId:Ua,initialQuery:ts.initialQuery,onOpen:ss,onClose:is,onMode:rs},Qo),(0,m.jsx)(ej,{}),An&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(`button`,{type:`button`,className:`mobile-drawer-backdrop`,"data-mobile-drawer-backdrop":`1`,"aria-label":`关闭会话列表`,onClick:()=>jn(!1)}),(0,m.jsx)(`button`,{type:`button`,className:`mobile-drawer-close`,"data-mobile-drawer-close":`1`,"aria-label":`关闭会话列表`,title:`关闭`,onClick:()=>jn(!1),children:`×`})]}),Tn===`rail`&&(0,m.jsx)(`button`,{type:`button`,className:`mobile-rail-back`,"data-mobile-nav":`chat`,onClick:kn,children:`‹ 返回对话`}),Ir&&(0,m.jsx)(Ak,{workspace:Ir.workspace,x:Ir.x,y:Ir.y,notify:Sc,onClose:()=>Lr(void 0)}),Rr&&(0,m.jsx)(jk,{conversation:Rr.conversation,x:Rr.x,y:Rr.y,notify:Sc,onRename:()=>void Vl(Rr.conversation.id),onClose:()=>Vr(void 0),sendCommand:kc,orchestrated:Rr.conversation.origin===`orchestrator`,childCount:wi.filter(e=>e.parentConversationId===Rr.conversation.id).length}),Pe&&(0,m.jsx)(Uk,{onClose:()=>Le(!1),onCreate:Pl}),Re&&(()=>{let e=O.workspaces.find(e=>e.id===Re.workspaceId);return e?(0,m.jsx)(Hk,{workspace:e,onClose:()=>{ze(void 0),Ve.current?.focus()},onCreate:e=>{iu(Re.workspaceId,e),ze(void 0),Ve.current?.focus()}}):null})(),Xl&&(0,m.jsx)(I_,{initialCategory:Ql,workspaceId:M,theme:Jl,onChooseTheme:e=>Yl(e),onClose:()=>{Zl(!1),ve()},agentCatalog:gn,subagentCatalog:vn,modelFilterRules:I.settingsSnapshot?.modelFilterRules??[],pendingSettings:d.some(e=>e.key===`model-rules`||e.key===`agent-directories`||e.key===`default-model`),onSetModelRules:e=>Nc({type:`model.rules.set`,rules:e},`model-rules`,t=>({...t,modelFilterRules:e})),defaultModel:I.settingsSnapshot?.defaultModel,modelCatalog:rn,onSetDefaultModel:e=>Nc({type:`settings.defaultModel`,model:e?{provider:e.provider,modelId:e.modelId}:null},`default-model`,t=>{let n={...t};return e?n.defaultModel=e:delete n.defaultModel,n}),providers:on,providerApis:cn,onSetProvider:e=>{Mc({type:`providers.set`,provider:e})},onRemoveProvider:e=>{Mc({type:`providers.remove`,providerId:e})},onRepairProviders:()=>{Mc({type:`providers.repair`}),Sc(`正在清理 Pi 不接受的空字段并重新读取模型清单`,`info`)},onToggleProvider:(e,t)=>{Mc(t?{type:`providers.enable`,providerId:e}:{type:`providers.disable`,providerId:e}),Sc(t?`已启用供应商「${e}」,它的模型重新出现在选择器里`:`已停用供应商「${e}」:配置已从 Pi 的文件里拿掉并保存在这里,模型不再出现在选择器里`,`info`)},onRemoveProviderModel:(e,t)=>{Mc({type:`providers.removeModel`,providerId:e,modelId:t})},customAgentDirs:I.settingsSnapshot?.customAgentDirs??[],onSetCustomAgentDirs:e=>Nc({type:`agents.setCustomDirs`,dirs:e},`agent-directories`,t=>({...t,customAgentDirs:e})),onRescanAgents:()=>Mc({type:`agents.rescan`}),userNickname:Wt,onSetUserNickname:Kt,terminalShell:I.settingsSnapshot?.terminalShell,onSetTerminalShell:e=>{Mc({type:`terminal.shell.set`,command:e})},onCheckBrowserNotifications:o,browserNotificationsEnabled:n,browserNotificationPermission:i,onSetBrowserNotifications:Tc}),eu&&(0,m.jsx)(kg,{onClose:()=>tu(!1)}),ql&&(0,m.jsx)(bA,{workspace:ql,onRemove:()=>Hl(ql),catalog:Xc(en,ql),agents:un,onClose:()=>Wl(void 0),onRename:()=>{let e=ql.id;Wl(void 0),Ll(`workspace`,e)},onSave:(e,t,n)=>nu(ql.id,e,t,n)}),ti&&(0,m.jsx)(yE,{image:ti,onClose:()=>ni(void 0)},ti.url),xr&&!Sn&&(0,m.jsx)(`div`,{className:`rail-backdrop`,role:`presentation`,"aria-hidden":`true`,onClick:()=>wn(!0)}),xr?(0,m.jsx)(YA,{...Lu,activeTab:Ro,mobileViews:Do.filter(e=>!ei(e)||e===`search`),collapsed:Sn,onToggle:()=>wn(e=>!e)}):(0,m.jsxs)(m.Fragment,{children:[Po&&Po!==`sessions`&&(0,m.jsx)(YA,{...Lu,side:`right`,activeTab:Po,collapsed:Io,onToggle:ad,pinned:!er.unpinned.includes(Po),onArrange:Xo}),(0,m.jsx)(yi,{side:`right`,views:Ao,unpinned:er.unpinned,previous:Po,active:Io?void 0:Po,onSelect:e=>Uo(e,!0),onDockCard:Yo,onArrange:Xo,onReorder:Zo}),(0,m.jsx)(yi,{side:`bottom`,views:jo,active:Lo.bottom,unpinned:er.unpinned,onSelect:e=>Uo(e,!0),onDockCard:Yo,onArrange:Xo,onReorder:Zo,children:(0,m.jsx)(`button`,{type:`button`,className:`workbench-bottom-toggle`,"data-bottom-toggle":!0,"aria-expanded":!er.bottomClosed,onClick:()=>tr(e=>({...e,bottomClosed:!e.bottomClosed})),children:`底部面板`})}),!er.bottomClosed&&(0,m.jsxs)(m.Fragment,{children:[(0,m.jsx)(jD,{height:er.bottomHeight,onHeight:e=>tr(t=>({...t,bottomHeight:e}))}),Fo?Fo!==`sessions`&&(0,m.jsx)(YA,{...Lu,side:`bottom`,activeTab:Fo,collapsed:!1,onToggle:()=>tr(e=>({...e,bottomClosed:!0})),pinned:!er.unpinned.includes(Fo),onArrange:Xo}):(0,m.jsxs)(`section`,{className:`workbench-bottom-empty`,...pi(`bottom`,Jo,Yo),children:[(0,m.jsx)(`p`,{children:`将活动图标或功能区标题拖到底部栏。`}),(0,m.jsx)(`button`,{type:`button`,"data-bottom-terminal":!0,onClick:()=>Jo(`terminal`,`bottom`),children:`将终端移到底部`})]})]})]}),bn.panel,R!==`group`&&Z&&z&&(()=>{let e=Z.key,t=Z.value,n=Or[e]??fA(t);return(0,m.jsx)(hA,{question:{key:e,messageId:Z.messageId,index:Z.index,value:t},pendingCount:ul.length,minimized:Ar===e,floatingRight:xr?`12px`:Sn?`24px`:`calc(var(--rail-width, 320px) + 24px)`,onMinimize:()=>jr(e),onExpand:()=>jr(null),onLocate:dl,draft:n,onDraftChange:t=>Hc(e,t),onAnswer:(e,t)=>Vc(z.id,Z.messageId,Z.index,e,t)})})(),cc===`context`&&!Va&&z&&(0,m.jsx)(tt,{anchor:uc.current,title:`上下文`,onClose:()=>lc(void 0),children:(0,m.jsx)(et,{conversation:z,contextWindow:Jc?.contextWindow,connected:te&&I.statuses.get(L(z.id))?.state===`online`,onCompact:()=>kc({type:`conversation.compact`,conversationId:z.id}),onCancel:()=>kc({type:`conversation.compact.cancel`,conversationId:z.id})},z.id)}),cc===`session`&&!Va&&z&&(0,m.jsx)(tt,{anchor:uc.current,title:`会话操作`,searchable:!1,onClose:()=>lc(void 0),choices:[{id:`reload`,label:d.some(e=>e.key===`reload:${z.id}`)?`正在重新加载资源…`:`重新加载资源`,detail:OA(z)?`请先结束或停止当前任务`:`重新读取 Agent、技能和扩展;保留历史与草稿,无需重启服务`,disabled:!te||OA(z)||d.some(e=>e.key===`reload:${z.id}`)},{id:`new`,label:`新建空白会话`,detail:`在同一目录开始新对话;保留当前会话历史与草稿`},{id:`fork`,label:`分叉当前会话`,detail:`从现有上下文继续另一条路线`,disabled:OA(z)||!!ku},{id:`context`,label:`查看与压缩上下文`,detail:z.compaction?.status===`running`?`正在压缩,可查看进度或停止`:`查看用量、压缩进度与最近结果`},{id:`split`,label:oo?`合并主区`:`拆分主区`,detail:`并排或上下阅读会话与文件`,disabled:!Ua},{id:`update`,label:`软件更新`,detail:`检查版本、选择更新目标与查看进度`}],onChoose:e=>{e===`split`?(tc(),lc(void 0)):e===`update`?(lc(void 0),bn.open()):e===`context`?(uc.current=document.querySelector(`[data-context-button]`),lc(`context`)):Mu(e)&&lc(void 0)}}),cc===`workspaces`&&(0,m.jsx)(tt,{anchor:uc.current,title:`进入工作区`,onClose:()=>lc(void 0),choices:O.workspaces.filter(e=>!e.closedAt&&!e.id.startsWith(`pending:`)).sort((e,t)=>be(e.id).localeCompare(be(t.id))||(e.worktreeOf??e.id).localeCompare(t.worktreeOf??t.id)||Number(!!e.worktreeOf)-Number(!!t.worktreeOf)).map(e=>({id:e.id,label:e.name+(e.id===Ua?` · 当前`:``),detail:e.path,group:be(e.id)+` · `+(O.workspaces.find(t=>t.id===e.worktreeOf)?.name??e.name)})),onChoose:e=>{ed(L(e)),$u(`workspace`,e),Ia(e),lc(void 0)},children:(0,m.jsx)(`button`,{type:`button`,onClick:()=>{lc(void 0),Le(!0)},children:`添加工作区`})}),cc===`worktrees`&&Ga&&(0,m.jsx)(Cn,{anchor:uc.current,workspaceId:Ga,summaries:O.workspaces.filter(e=>L(e.id)===L(Ga)).map(e=>({path:e.path,running:O.conversations.filter(t=>t.workspaceId===e.id&&[`running`,`waiting`,`awaiting_background`].includes(t.status)).length})),onClose:()=>lc(void 0),onEnter:e=>{ed(L(e)),$u(`workspace`,e),Ia(e),lc(void 0)},onBranches:()=>{lc(void 0),qo(`branches`)}}),cc===`line`&&ic&&(0,m.jsx)(tt,{anchor:uc.current,title:`跳转到行与列`,onClose:()=>lc(void 0),children:(0,m.jsxs)(`form`,{onSubmit:e=>{e.preventDefault();let t=/^(\d+)(?::(\d+))?$/.exec(dc.trim());!t||Number(t[1])<1||t[2]&&Number(t[2])<1||(ls({scope:Qo,path:ic.path,line:Number(t[1]),column:Number(t[2]??1),request:++de.current}),lc(void 0))},children:[(0,m.jsxs)(`label`,{children:[`行号或 行号:列号`,(0,m.jsx)(`input`,{autoFocus:!0,"aria-label":`跳转位置`,value:dc,onChange:e=>fc(e.target.value),pattern:`[1-9][0-9]*(:[1-9][0-9]*)?`,required:!0})]}),(0,m.jsx)(`button`,{type:`submit`,children:`跳转`})]})}),cc===`language`&&(0,m.jsx)(tt,{anchor:uc.current,title:`文件语言与语法高亮`,onClose:()=>lc(void 0),choices:[{id:`auto`,label:`自动识别`},{id:`plain`,label:`纯文本`},...[`cpp`,`c`,`js`,`ts`,`tsx`,`py`,`go`,`rs`,`java`,`json`,`md`,`sh`,`css`,`html`,`yaml`,`sql`].map(e=>({id:e,label:Pn(e)||e}))],onChoose:e=>{mc(t=>({...t,[ac]:e===`auto`?void 0:e})),lc(void 0)}}),cc===`diff`&&(0,m.jsxs)(tt,{anchor:uc.current,title:`当前文件差异`,onClose:()=>lc(void 0),children:[(0,m.jsxs)(`p`,{children:[ys?.target.comparison,` · `,xs]}),[-1,1].map(e=>(0,m.jsx)(`button`,{type:`button`,onClick:()=>{lc(void 0),window.dispatchEvent(new CustomEvent(`super-pi-status-diff-jump`,{detail:{url:ys?.target.url,direction:e}}))},children:e<0?`上一处改动`:`下一处改动`},e))]}),(0,m.jsxs)(`footer`,{className:`workbench-status`,"data-workbench-status":`1`,"aria-label":`工作台状态`,children:[(0,m.jsxs)(`div`,{className:`workbench-status-group`,children:[(0,m.jsx)(We,{connected:te,onSelectServer:e=>ed(e),onSettings:()=>{_e(),$l(`servers`),Zl(!0)}}),nd&&te&&(0,m.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-branch`,"data-workbench-branch":nd,title:`进入其他工作树或管理分支`,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`worktrees`?void 0:`worktrees`)},children:[(0,m.jsx)(vi,{name:`git`}),(0,m.jsx)(`code`,{children:nd}),id&&(0,m.jsx)(`code`,{children:id})]}),!!rd&&(0,m.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-changes`,"data-workbench-changes":rd,onClick:()=>{qo(`changes`)},children:[rd,` 个改动`]}),(0,m.jsxs)(`button`,{type:`button`,className:`workbench-status-scope workbench-status-button`,title:hc?.path??`选择工作区`,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`workspaces`?void 0:`workspaces`)},children:[(0,m.jsx)(vi,{name:`files`}),(0,m.jsxs)(`span`,{children:[hc?.name??`选择工作区`,Ka?` / `+Ka:``]})]})]}),(0,m.jsxs)(`div`,{className:`workbench-status-group workbench-status-context`,children:[!Va&&z&&(0,m.jsx)(Qe,{conversation:z,contextWindow:Jc?.contextWindow,expanded:cc===`context`,onOpen:e=>{uc.current=e.currentTarget,lc(e=>e===`context`?void 0:`context`)}}),R===`session`&&z&&(0,m.jsx)(vA,{kind:`model`,label:Jc?.label??Wc?.modelId??`选择模型`,value:Wc?`${Wc.provider}/${Wc.modelId}`:void 0,options:el,providerOptions:[...new Set($c.map(e=>e.provider))],disabled:!qc||Bc,onChoose:nl}),R===`session`&&z&&(0,m.jsx)(vA,{kind:`thinking`,label:Kc??`思考等级`,value:Gc,options:tl,disabled:!qc||Bc,onChoose:rl}),R===`group`&>&&(0,m.jsx)(`button`,{type:`button`,className:`workbench-status-button`,onClick:()=>window.dispatchEvent(new CustomEvent(`super-pi-status-group-models`,{detail:{roomId:gt}})),children:`群成员模型`}),R===`file`&&ic&&(sc?(0,m.jsxs)(m.Fragment,{children:[(0,m.jsxs)(`button`,{type:`button`,className:`workbench-status-button workbench-editor-cursor`,"data-workbench-editor-position":`1`,onClick:e=>{uc.current=e.currentTarget,fc(`${sc.line}:${sc.column}`),lc(`line`)},children:[`第 `,sc.line,` 行,第 `,sc.column,` 列`]}),(0,m.jsx)(`button`,{type:`button`,className:`workbench-status-button`,"data-file-highlight-status":sc.highlight,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`language`?void 0:`language`)},children:sc.language})]}):(0,m.jsx)(`span`,{title:ic.path,children:ic.name})),bs===`diff`&&xs&&(0,m.jsx)(`button`,{type:`button`,className:`workbench-status-button`,title:xs,onClick:e=>{uc.current=e.currentTarget,lc(e=>e===`diff`?void 0:`diff`)},children:xs}),bn.entry(`workbench-status-button software-update-desktop`),(0,m.jsxs)(`button`,{type:`button`,className:`workbench-version workbench-status-button`,"data-super-pi-version":(bn.status??mn)?.runningVersion??``,title:`查看版本与软件更新`,onClick:bn.open,children:[`v`,(bn.status??mn)?.runningVersion??`…`]})]})]}),(0,m.jsx)(YA,{...Lu,contentOwner:!0,activeTab:bo,collapsed:!1,onToggle:ad,onCloseView:e=>{xr?(kn(),wn(!0)):tr(t=>({...t,[er.sides[e]+`Closed`]:!0}))}})]})})}v_(__()),(0,f.createRoot)(document.getElementById(`root`)).render((0,m.jsx)(p.StrictMode,{children:(0,m.jsx)(Wj,{})}));export{kn as _,nm as a,$p as c,Zi as d,ea as f,Nn as g,Pn as h,eh as i,Vp as l,zr as m,lh as n,Qp as o,Br as p,Zm as r,em as s,sg as t,Hp as u,d as v,r as y};
|