@deepseekcode/cli 1.0.11 → 1.0.13
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/README.md +10 -0
- package/dist/cli.js +1062 -924
- package/package.json +2 -1
- package/web/dist/assets/AgentFlowView-D_eqHssN.js +1 -0
- package/web/dist/assets/AgentsView-DxXbT1TA.js +1 -0
- package/web/dist/assets/{AskQuestionModal-DGd7VFFR.js → AskQuestionModal-OOxUqiN1.js} +1 -1
- package/web/dist/assets/{AuditView-BVyD7ivS.js → AuditView-DLmHV1Xa.js} +1 -1
- package/web/dist/assets/AutomationView-Dnkht7AC.js +1 -0
- package/web/dist/assets/ChannelConfigView-gal4YqIE.js +8 -0
- package/web/dist/assets/{FileTreeView-HfjwdQz9.js → FileTreeView-xuW_AJmw.js} +3 -3
- package/web/dist/assets/{HookApprovalModal-dGHgJ_pM.js → HookApprovalModal-Dnrkw1Mh.js} +1 -1
- package/web/dist/assets/HookConfigView-BddeGF3E.js +3 -0
- package/web/dist/assets/{InboxView-DQ1i65AD.js → InboxView-DOIcm5GF.js} +1 -1
- package/web/dist/assets/ModelsView-YK7jq8J0.js +1 -0
- package/web/dist/assets/SessionGrid-OuKqyYjF.js +22 -0
- package/web/dist/assets/{SettingsPanel-D96vsDCf.js → SettingsPanel-BK2mvSsv.js} +3 -3
- package/web/dist/assets/{SkillsView-DsRZm-UY.js → SkillsView-CjR2b3-r.js} +1 -1
- package/web/dist/assets/TerminalView-Okh3EsS2.js +3 -0
- package/web/dist/assets/Toast-Bmm1ZZzF.js +1 -0
- package/web/dist/assets/ToolsView-BcTnj3DK.js +1 -0
- package/web/dist/assets/hookRisk-BXEfLOCo.js +1 -0
- package/web/dist/assets/{icons-uody4X-4.js → icons-CjRO1znb.js} +54 -49
- package/web/dist/assets/index-CektHuu_.js +20 -0
- package/web/dist/assets/index-Czlzypr3.css +1 -0
- package/web/dist/assets/{markdown-BUScHEtT.js → markdown-hmVtvQNZ.js} +1 -1
- package/web/dist/assets/panels-C0Mxu2Md.js +1 -0
- package/web/dist/assets/{react-vendor-C5NlWs7r.js → react-vendor-Dp4P972X.js} +6 -6
- package/web/dist/assets/{state-DKyBAq9j.js → state-C_jK7HTi.js} +3 -3
- package/web/dist/index.html +6 -6
- package/web/dist/assets/AgentFlowView-CZQeHyLi.js +0 -1
- package/web/dist/assets/AgentsView-CfQ-EXdY.js +0 -1
- package/web/dist/assets/AutomationView-3dP2f6BZ.js +0 -1
- package/web/dist/assets/ChannelConfigView-BXvSck5e.js +0 -8
- package/web/dist/assets/HookConfigView-F6uvScie.js +0 -3
- package/web/dist/assets/ModelsView-CsOKSn0l.js +0 -1
- package/web/dist/assets/SessionGrid-DPDDTcff.js +0 -20
- package/web/dist/assets/TerminalView-CMmJ55Zj.js +0 -3
- package/web/dist/assets/Toast-CcbSW0V2.js +0 -1
- package/web/dist/assets/ToolsView-CHJ8k68t.js +0 -1
- package/web/dist/assets/hookRisk-DsIEdNpD.js +0 -1
- package/web/dist/assets/index-DGWtPRgs.js +0 -21
- package/web/dist/assets/index-DuBeChMI.css +0 -1
- package/web/dist/assets/panels-C_0RapVg.js +0 -1
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ModelsView-YK7jq8J0.js","assets/markdown-hmVtvQNZ.js","assets/icons-CjRO1znb.js","assets/Toast-Bmm1ZZzF.js","assets/react-vendor-Dp4P972X.js","assets/state-C_jK7HTi.js","assets/ToolsView-BcTnj3DK.js","assets/AgentFlowView-D_eqHssN.js","assets/SkillsView-CjR2b3-r.js","assets/AgentsView-DxXbT1TA.js","assets/HookConfigView-BddeGF3E.js","assets/FileTreeView-xuW_AJmw.js","assets/TerminalView-Okh3EsS2.js","assets/terminal-Ck_l6svU.js","assets/TerminalView-C1Mzzh8g.css","assets/SessionGrid-OuKqyYjF.js","assets/hookRisk-BXEfLOCo.js","assets/SettingsPanel-BK2mvSsv.js","assets/HookApprovalModal-Dnrkw1Mh.js","assets/AskQuestionModal-OOxUqiN1.js","assets/ChannelConfigView-gal4YqIE.js","assets/InboxView-DOIcm5GF.js","assets/AutomationView-Dnkht7AC.js","assets/AuditView-DLmHV1Xa.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Kn=Object.defineProperty;var qn=(s,e,t)=>e in s?Kn(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var ee=(s,e,t)=>qn(s,typeof e!="symbol"?e+"":e,t);import{j as u}from"./markdown-hmVtvQNZ.js";import{r as g,S as Fe,F as Jt,C as Vn,D as Yt,L as wt,E as Jn,a as Bt,b as dn,d as Yn,P as Qt,G as At,e as as,f as Et,H as Ss,h as Qn,M as un,i as Xn,X as lt,j as Zn,A as is,R as pn,k as vs,l as eo,m as ws,n as to,o as so,p as no,q as hn,s as oo,I as fn,t as ro,u as ao,v as io,w as lo,x as co,y as uo,z as po,B as ho,J as fo,K as mo,N as go,O as yo,T as bo,Q as xo,U as ko,V as So,Y as vo,g as wo,W as Co}from"./icons-CjRO1znb.js";import{r as _o}from"./react-vendor-Dp4P972X.js";import{s as To,c as pe}from"./state-C_jK7HTi.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function t(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(r){if(r.ep)return;r.ep=!0;const o=t(r);fetch(r.href,o)}})();var Xt={},Cs=_o;Xt.createRoot=Cs.createRoot,Xt.hydrateRoot=Cs.hydrateRoot;const No="modulepreload",Bo=function(s){return"/"+s},_s={},re=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),i=(a==null?void 0:a.nonce)||(a==null?void 0:a.getAttribute("nonce"));r=Promise.allSettled(t.map(l=>{if(l=Bo(l),l in _s)return;_s[l]=!0;const c=l.endsWith(".css"),d=c?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${d}`))return;const p=document.createElement("link");if(p.rel=c?"stylesheet":No,c||(p.as="script"),p.crossOrigin="",p.href=l,i&&p.setAttribute("nonce",i),document.head.appendChild(p),c)return new Promise((h,f)=>{p.addEventListener("load",h),p.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(a){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=a,window.dispatchEvent(i),!i.defaultPrevented)throw a}return r.then(a=>{for(const i of a||[])i.status==="rejected"&&o(i.reason);return e().catch(o)})},L=s=>typeof s=="string",qe=()=>{let s,e;const t=new Promise((n,r)=>{s=n,e=r});return t.resolve=s,t.reject=e,t},Ts=s=>s==null?"":String(s),Ao=(s,e,t)=>{s.forEach(n=>{e[n]&&(t[n]=e[n])})},Eo=/###/g,Ns=s=>s&&s.includes("###")?s.replace(Eo,"."):s,Bs=s=>!s||L(s),ot=(s,e,t)=>{const n=L(e)?e.split("."):e;let r=0;for(;r<n.length-1;){if(Bs(s))return{};const o=Ns(n[r]);!s[o]&&t&&(s[o]=new t),Object.prototype.hasOwnProperty.call(s,o)?s=s[o]:s={},++r}return Bs(s)?{}:{obj:s,k:Ns(n[r])}},As=(s,e,t)=>{const{obj:n,k:r}=ot(s,e,Object);if(n!==void 0||e.length===1){n[r]=t;return}let o=e[e.length-1],a=e.slice(0,e.length-1),i=ot(s,a,Object);for(;i.obj===void 0&&a.length;)o=`${a[a.length-1]}.${o}`,a=a.slice(0,a.length-1),i=ot(s,a,Object),i!=null&&i.obj&&typeof i.obj[`${i.k}.${o}`]<"u"&&(i.obj=void 0);i.obj[`${i.k}.${o}`]=t},Po=(s,e,t,n)=>{const{obj:r,k:o}=ot(s,e,Object);r[o]=r[o]||[],r[o].push(t)},Ct=(s,e)=>{const{obj:t,k:n}=ot(s,e);if(t&&Object.prototype.hasOwnProperty.call(t,n))return t[n]},jo=(s,e,t)=>{const n=Ct(s,t);return n!==void 0?n:Ct(e,t)},mn=(s,e,t)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(Object.prototype.hasOwnProperty.call(s,n)?L(s[n])||s[n]instanceof String||L(e[n])||e[n]instanceof String?t&&(s[n]=e[n]):mn(s[n],e[n],t):s[n]=e[n]);return s},_e=s=>s.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),Ro={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},Lo=s=>L(s)?s.replace(/[&<>"'\/]/g,e=>Ro[e]):s;class Mo{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){const t=this.regExpMap.get(e);if(t!==void 0)return t;const n=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,n),this.regExpQueue.push(e),n}}const Io=[" ",",","?","!",";"],Oo=new Mo(20),$o=(s,e,t)=>{e=e||"",t=t||"";const n=Io.filter(a=>!e.includes(a)&&!t.includes(a));if(n.length===0)return!0;const r=Oo.getRegExp(`(${n.map(a=>a==="?"?"\\?":a).join("|")})`);let o=!r.test(s);if(!o){const a=s.indexOf(t);a>0&&!r.test(s.substring(0,a))&&(o=!0)}return o},Zt=(s,e,t=".")=>{if(!s)return;if(s[e])return Object.prototype.hasOwnProperty.call(s,e)?s[e]:void 0;const n=e.split(t);let r=s;for(let o=0;o<n.length;){if(!r||typeof r!="object")return;let a,i="";for(let l=o;l<n.length;++l)if(l!==o&&(i+=t),i+=n[l],a=r[i],a!==void 0){if(["string","number","boolean"].includes(typeof a)&&l<n.length-1)continue;o+=l-o+1;break}r=a}return r},ct=s=>s==null?void 0:s.replace(/_/g,"-"),Do={type:"logger",log(s){this.output("log",s)},warn(s){this.output("warn",s)},error(s){this.output("error",s)},output(s,e){var t,n;(n=(t=console==null?void 0:console[s])==null?void 0:t.apply)==null||n.call(t,console,e)}};class _t{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||Do,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,t,n,r){return r&&!this.debug?null:(e=e.map(o=>L(o)?o.replace(/[\r\n\x00-\x1F\x7F]/g," "):o),L(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new _t(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new _t(this.logger,e)}}var we=new _t;class Pt{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const r=this.observers[n].get(t)||0;this.observers[n].set(t,r+1)}),this}off(e,t){if(this.observers[e]){if(!t){delete this.observers[e];return}this.observers[e].delete(t)}}once(e,t){const n=(...r)=>{t(...r),this.off(e,n)};return this.on(e,n),this}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([r,o])=>{for(let a=0;a<o;a++)r(...t)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([r,o])=>{for(let a=0;a<o;a++)r(e,...t)})}}class Es extends Pt{constructor(e,t={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.options.ignoreJSONStructure===void 0&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){this.options.ns.includes(e)||this.options.ns.push(e)}removeNamespaces(e){const t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,n,r={}){var c,d;const o=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,a=r.ignoreJSONStructure!==void 0?r.ignoreJSONStructure:this.options.ignoreJSONStructure;let i;e.includes(".")?i=e.split("."):(i=[e,t],n&&(Array.isArray(n)?i.push(...n):L(n)&&o?i.push(...n.split(o)):i.push(n)));const l=Ct(this.data,i);return!l&&!t&&!n&&e.includes(".")&&(e=i[0],t=i[1],n=i.slice(2).join(".")),l||!a||!L(n)?l:Zt((d=(c=this.data)==null?void 0:c[e])==null?void 0:d[t],n,o)}addResource(e,t,n,r,o={silent:!1}){const a=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator;let i=[e,t];n&&(i=i.concat(a?n.split(a):n)),e.includes(".")&&(i=e.split("."),r=t,t=i[1]),this.addNamespaces(t),As(this.data,i,r),o.silent||this.emit("added",e,t,n,r)}addResources(e,t,n,r={silent:!1}){for(const o in n)(L(n[o])||Array.isArray(n[o]))&&this.addResource(e,t,o,n[o],{silent:!0});r.silent||this.emit("added",e,t,n)}addResourceBundle(e,t,n,r,o,a={silent:!1,skipCopy:!1}){let i=[e,t];e.includes(".")&&(i=e.split("."),r=n,n=t,t=i[1]),this.addNamespaces(t);let l=Ct(this.data,i)||{};a.skipCopy||(n=JSON.parse(JSON.stringify(n))),r?mn(l,n,o):l={...l,...n},As(this.data,i,l),a.silent||this.emit("added",e,t,n)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return this.getResource(e,t)!==void 0}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){const t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(r=>t[r]&&Object.keys(t[r]).length>0)}toJSON(){return this.data}}var gn={processors:{},addPostProcessor(s){this.processors[s.name]=s},handle(s,e,t,n,r){return s.forEach(o=>{var a;e=((a=this.processors[o])==null?void 0:a.process(e,t,n,r))??e}),e}};const yn=Symbol("i18next/PATH_KEY");function Fo(){const s=[],e=Object.create(null);let t;return e.get=(n,r)=>{var o;return(o=t==null?void 0:t.revoke)==null||o.call(t),r===yn?s:(s.push(r),t=Proxy.revocable(n,e),t.proxy)},Proxy.revocable(Object.create(null),e).proxy}function We(s,e){const{[yn]:t}=s(Fo()),n=(e==null?void 0:e.keySeparator)??".",r=(e==null?void 0:e.nsSeparator)??":",o=(e==null?void 0:e.enableSelector)==="strict";if(t.length>1&&r){const a=e==null?void 0:e.ns,i=o?Array.isArray(a)?a:a?[a]:null:Array.isArray(a)?a:null;if(i&&(o?i:i.length>1?i.slice(1):[]).includes(t[0]))return`${t[0]}${r}${t.slice(1).join(n)}`}return t.join(n)}const It=s=>!L(s)&&typeof s!="boolean"&&typeof s!="number";class Tt extends Pt{constructor(e,t={}){super(),Ao(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=we.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const n={...t};if(e==null)return!1;const r=this.resolve(e,n);if((r==null?void 0:r.res)===void 0)return!1;const o=It(r.res);return!(n.returnObjects===!1&&o)}extractFromKey(e,t){let n=t.nsSeparator!==void 0?t.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const r=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator;let o=t.ns||this.options.defaultNS||[];const a=n&&e.includes(n),i=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!$o(e,n,r);if(a&&!i){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:L(o)?[o]:o};const c=e.split(n);(n!==r||n===r&&this.options.ns.includes(c[0]))&&(o=c.shift()),e=c.join(r)}return{key:e,namespaces:L(o)?[o]:o}}translate(e,t,n){let r=typeof t=="object"?{...t}:t;if(typeof r!="object"&&this.options.overloadTranslationOptionHandler&&(r=this.options.overloadTranslationOptionHandler(arguments)),typeof r=="object"&&(r={...r}),r||(r={}),e==null)return"";typeof e=="function"&&(e=We(e,{...this.options,...r})),Array.isArray(e)||(e=[String(e)]),e=e.map(b=>typeof b=="function"?We(b,{...this.options,...r}):String(b));const o=r.returnDetails!==void 0?r.returnDetails:this.options.returnDetails,a=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator,{key:i,namespaces:l}=this.extractFromKey(e[e.length-1],r),c=l[l.length-1];let d=r.nsSeparator!==void 0?r.nsSeparator:this.options.nsSeparator;d===void 0&&(d=":");const p=r.lng||this.language,h=r.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((p==null?void 0:p.toLowerCase())==="cimode")return h?o?{res:`${c}${d}${i}`,usedKey:i,exactUsedKey:i,usedLng:p,usedNS:c,usedParams:this.getUsedParamsDetails(r)}:`${c}${d}${i}`:o?{res:i,usedKey:i,exactUsedKey:i,usedLng:p,usedNS:c,usedParams:this.getUsedParamsDetails(r)}:i;const f=this.resolve(e,r);let m=f==null?void 0:f.res;const y=(f==null?void 0:f.usedKey)||i,v=(f==null?void 0:f.exactUsedKey)||i,C=["[object Number]","[object Function]","[object RegExp]"],S=r.joinArrays!==void 0?r.joinArrays:this.options.joinArrays,T=!this.i18nFormat||this.i18nFormat.handleAsObject,_=r.count!==void 0&&!L(r.count),x=Tt.hasDefaultValue(r),R=_?this.pluralResolver.getSuffix(p,r.count,r):"",j=r.ordinal&&_?this.pluralResolver.getSuffix(p,r.count,{ordinal:!1}):"",D=_&&!r.ordinal&&r.count===0,O=D&&r[`defaultValue${this.options.pluralSeparator}zero`]||r[`defaultValue${R}`]||r[`defaultValue${j}`]||r.defaultValue;let W=m;T&&!m&&x&&(W=O);const ne=It(W),N=Object.prototype.toString.apply(W);if(T&&W&&ne&&!C.includes(N)&&!(L(S)&&Array.isArray(W))){if(!r.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const b=this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,W,{...r,ns:l}):`key '${i} (${this.language})' returned an object instead of string.`;return o?(f.res=b,f.usedParams=this.getUsedParamsDetails(r),f):b}if(a){const b=Array.isArray(W),A=b?[]:{},F=b?v:y;for(const U in W)if(Object.prototype.hasOwnProperty.call(W,U)){const se=`${F}${a}${U}`;x&&!m?A[U]=this.translate(se,{...r,defaultValue:It(O)?O[U]:void 0,joinArrays:!1,ns:l}):A[U]=this.translate(se,{...r,joinArrays:!1,ns:l}),A[U]===se&&(A[U]=W[U])}m=A}}else if(T&&L(S)&&Array.isArray(m))m=m.join(S),m&&(m=this.extendTranslation(m,e,r,n));else{let b=!1,A=!1;!this.isValidLookup(m)&&x&&(b=!0,m=O),this.isValidLookup(m)||(A=!0,m=i);const U=(r.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&A?void 0:m,se=x&&O!==m&&this.options.updateMissing;if(A||b||se){if(this.logger.log(se?"updateKey":"missingKey",p,c,_&&!se?`${i}${this.pluralResolver.getSuffix(p,r.count,r)}`:i,se?O:m),a){const P=this.resolve(i,{...r,keySeparator:!1});P&&P.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let B=[];const M=this.languageUtils.getFallbackCodes(this.options.fallbackLng,r.lng||this.language);if(this.options.saveMissingTo==="fallback"&&M&&M[0])for(let P=0;P<M.length;P++)B.push(M[P]);else this.options.saveMissingTo==="all"?B=this.languageUtils.toResolveHierarchy(r.lng||this.language):B.push(r.lng||this.language);const $=(P,le,ce)=>{var Pe;const H=x&&ce!==m?ce:U;this.options.missingKeyHandler?this.options.missingKeyHandler(P,c,le,H,se,r):(Pe=this.backendConnector)!=null&&Pe.saveMissing&&this.backendConnector.saveMissing(P,c,le,H,se,r),this.emit("missingKey",P,c,le,m)};this.options.saveMissing&&(this.options.saveMissingPlurals&&_?B.forEach(P=>{const le=this.pluralResolver.getSuffixes(P,r);D&&r[`defaultValue${this.options.pluralSeparator}zero`]&&!le.includes(`${this.options.pluralSeparator}zero`)&&le.push(`${this.options.pluralSeparator}zero`),le.forEach(ce=>{$([P],i+ce,r[`defaultValue${ce}`]||O)})}):$(B,i,O))}m=this.extendTranslation(m,e,r,f,n),A&&m===i&&this.options.appendNamespaceToMissingKey&&(m=`${c}${d}${i}`),(A||b)&&this.options.parseMissingKeyHandler&&(m=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${d}${i}`:i,b?m:void 0,r))}return o?(f.res=m,f.usedParams=this.getUsedParamsDetails(r),f):m}extendTranslation(e,t,n,r,o){var l,c;if((l=this.i18nFormat)!=null&&l.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||r.usedLng,r.usedNS,r.usedKey,{resolved:r});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const d=L(e)&&(((c=n==null?void 0:n.interpolation)==null?void 0:c.skipOnVariables)!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let p;if(d){const f=e.match(this.interpolator.nestingRegexp);p=f&&f.length}let h=n.replace&&!L(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(h={...this.options.interpolation.defaultVariables,...h}),e=this.interpolator.interpolate(e,h,n.lng||this.language||r.usedLng,n),d){const f=e.match(this.interpolator.nestingRegexp),m=f&&f.length;p<m&&(n.nest=!1)}!n.lng&&r&&r.res&&(n.lng=this.language||r.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...f)=>(o==null?void 0:o[0])===f[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${f[0]} in key: ${t[0]}`),null):this.translate(...f,t),n)),n.interpolation&&this.interpolator.reset()}const a=n.postProcess||this.options.postProcess,i=L(a)?[a]:a;return e!=null&&(i!=null&&i.length)&&n.applyPostProcessor!==!1&&(e=gn.handle(i,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...r,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,t={}){let n,r,o,a,i;return L(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?We(l,{...this.options,...t}):l)),e.forEach(l=>{if(this.isValidLookup(n))return;const c=this.extractFromKey(l,t),d=c.key;r=d;let p=c.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));const h=t.count!==void 0&&!L(t.count),f=h&&!t.ordinal&&t.count===0,m=t.context!==void 0&&(L(t.context)||typeof t.context=="number")&&t.context!=="",y=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);p.forEach(v=>{var C,S;this.isValidLookup(n)||(i=v,!this.checkedLoadedFor[`${y[0]}-${v}`]&&((C=this.utils)!=null&&C.hasLoadedNamespace)&&!((S=this.utils)!=null&&S.hasLoadedNamespace(i))&&(this.checkedLoadedFor[`${y[0]}-${v}`]=!0,this.logger.warn(`key "${r}" for languages "${y.join(", ")}" won't get resolved as namespace "${i}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),y.forEach(T=>{var R;if(this.isValidLookup(n))return;a=T;const _=[d];if((R=this.i18nFormat)!=null&&R.addLookupKeys)this.i18nFormat.addLookupKeys(_,d,T,v,t);else{let j;h&&(j=this.pluralResolver.getSuffix(T,t.count,t));const D=`${this.options.pluralSeparator}zero`,O=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(h&&(t.ordinal&&j.startsWith(O)&&_.push(d+j.replace(O,this.options.pluralSeparator)),_.push(d+j),f&&_.push(d+D)),m){const W=`${d}${this.options.contextSeparator||"_"}${t.context}`;_.push(W),h&&(t.ordinal&&j.startsWith(O)&&_.push(W+j.replace(O,this.options.pluralSeparator)),_.push(W+j),f&&_.push(W+D))}}let x;for(;x=_.pop();)this.isValidLookup(n)||(o=x,n=this.getResource(T,v,x,t))}))})}),{res:n,usedKey:r,exactUsedKey:o,usedLng:a,usedNS:i}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,t,n,r={}){var o;return(o=this.i18nFormat)!=null&&o.getResource?this.i18nFormat.getResource(e,t,n,r):this.resourceStore.getResource(e,t,n,r)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!L(e.replace);let r=n?e.replace:e;if(n&&typeof e.count<"u"&&(r={...r,count:e.count}),this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),!n){r={...r};for(const o of t)delete r[o]}return r}static hasDefaultValue(e){const t="defaultValue";for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)&&n.startsWith(t)&&e[n]!==void 0)return!0;return!1}}class Ps{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=we.create("languageUtils")}getScriptPartFromCode(e){if(e=ct(e),!e||!e.includes("-"))return null;const t=e.split("-");return t.length===2||(t.pop(),t[t.length-1].toLowerCase()==="x")?null:this.formatLanguageCode(t.join("-"))}getLanguagePartFromCode(e){if(e=ct(e),!e||!e.includes("-"))return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(L(e)&&e.includes("-")){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch{}return t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t||(this.options.lowerCaseLng?e.toLowerCase():e)}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.includes(e)}getBestMatchFromCodes(e){if(!e)return null;let t;return e.forEach(n=>{if(t)return;const r=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(r))&&(t=r)}),!t&&this.options.supportedLngs&&e.forEach(n=>{if(t)return;const r=this.getScriptPartFromCode(n);if(this.isSupportedCode(r))return t=r;const o=this.getLanguagePartFromCode(n);if(this.isSupportedCode(o))return t=o;t=this.options.supportedLngs.find(a=>a===o?!0:!a.includes("-")&&!o.includes("-")?!1:!!(a.includes("-")&&!o.includes("-")&&a.slice(0,a.indexOf("-"))===o||a.startsWith(o)&&o.length>1))}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if(typeof e=="function"&&(e=e(t)),L(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let n=e[t];return n||(n=e[this.getScriptPartFromCode(t)]),n||(n=e[this.formatLanguageCode(t)]),n||(n=e[this.getLanguagePartFromCode(t)]),n||(n=e.default),n||[]}toResolveHierarchy(e,t){const n=this.getFallbackCodes((t===!1?[]:t)||this.options.fallbackLng||[],e),r=[],o=a=>{a&&(this.isSupportedCode(a)?r.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return L(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&o(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&o(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&o(this.getLanguagePartFromCode(e))):L(e)&&o(this.formatLanguageCode(e)),n.forEach(a=>{r.includes(a)||o(this.formatLanguageCode(a))}),r}}const js={zero:0,one:1,two:2,few:3,many:4,other:5},Rs={select:s=>s===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Wo{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=we.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const n=ct(e==="dev"?"en":e),r=t.ordinal?"ordinal":"cardinal",o=JSON.stringify({cleanedCode:n,type:r});if(o in this.pluralRulesCache)return this.pluralRulesCache[o];let a;try{a=new Intl.PluralRules(n,{type:r})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),Rs;if(!e.match(/-|_/))return Rs;const l=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(l,t)}return this.pluralRulesCache[o]=a,a}needsPlural(e,t={}){let n=this.getRule(e,t);return n||(n=this.getRule("dev",t)),(n==null?void 0:n.resolvedOptions().pluralCategories.length)>1}getPluralFormsOfKey(e,t,n={}){return this.getSuffixes(e,n).map(r=>`${t}${r}`)}getSuffixes(e,t={}){let n=this.getRule(e,t);return n||(n=this.getRule("dev",t)),n?n.resolvedOptions().pluralCategories.sort((r,o)=>js[r]-js[o]).map(r=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${r}`):[]}getSuffix(e,t,n={}){const r=this.getRule(e,n);return r?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${r.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,n))}}const Ls=(s,e,t,n=".",r=!0)=>{let o=jo(s,e,t);return!o&&r&&L(t)&&(o=Zt(s,t,n),o===void 0&&(o=Zt(e,t,n))),o},Ho=s=>s.replace(/\$/g,"$$$$");class Ms{constructor(e={}){var t;this.logger=we.create("interpolator"),this.options=e,this.format=((t=e==null?void 0:e.interpolation)==null?void 0:t.format)||(n=>n),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});const{escape:t,escapeValue:n,useRawValueToEscape:r,prefix:o,prefixEscaped:a,suffix:i,suffixEscaped:l,formatSeparator:c,unescapeSuffix:d,unescapePrefix:p,nestingPrefix:h,nestingPrefixEscaped:f,nestingSuffix:m,nestingSuffixEscaped:y,nestingOptionsSeparator:v,maxReplaces:C,alwaysFormat:S}=e.interpolation;this.escape=t!==void 0?t:Lo,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=r!==void 0?r:!1,this.prefix=o?_e(o):a||"{{",this.suffix=i?_e(i):l||"}}",this.formatSeparator=c||",",this.unescapePrefix=d?"":p?_e(p):"-",this.unescapeSuffix=this.unescapePrefix?"":d?_e(d):"",this.nestingPrefix=h?_e(h):f||_e("$t("),this.nestingSuffix=m?_e(m):y||_e(")"),this.nestingOptionsSeparator=v||",",this.maxReplaces=C||1e3,this.alwaysFormat=S!==void 0?S:!1,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){const e=(t,n)=>(t==null?void 0:t.source)===n?(t.lastIndex=0,t):new RegExp(n,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,n,r){var f;let o,a,i;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=m=>{if(!m.includes(this.formatSeparator)){const S=Ls(t,l,m,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(S,void 0,n,{...r,...t,interpolationkey:m}):S}const y=m.split(this.formatSeparator),v=y.shift().trim(),C=y.join(this.formatSeparator).trim();return this.format(Ls(t,l,v,this.options.keySeparator,this.options.ignoreJSONStructure),C,n,{...r,...t,interpolationkey:v})};this.resetRegExp(),!this.escapeValue&&typeof e=="string"&&/\$t\([^)]*\{[^}]*\{\{/.test(e)&&this.logger.warn("nesting options string contains interpolated variables with escapeValue: false — if any of those values are attacker-controlled they can inject additional nesting options (e.g. redirect lng/ns). Sanitise untrusted input before passing it to t(), or keep escapeValue: true.");const d=(r==null?void 0:r.missingInterpolationHandler)||this.options.missingInterpolationHandler,p=((f=r==null?void 0:r.interpolation)==null?void 0:f.skipOnVariables)!==void 0?r.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:m=>m},{regex:this.regexp,safeValue:m=>this.escapeValue?this.escape(m):m}].forEach(m=>{for(i=0;o=m.regex.exec(e);){const y=o[1].trim();if(a=c(y),a===void 0)if(typeof d=="function"){const C=d(e,o,r);a=L(C)?C:""}else if(r&&Object.prototype.hasOwnProperty.call(r,y))a="";else if(p){a=o[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${e}`),a="";else!L(a)&&!this.useRawValueToEscape&&(a=Ts(a));const v=m.safeValue(a);if(e=e.replace(o[0],Ho(v)),p?(m.regex.lastIndex+=v.length,m.regex.lastIndex-=o[0].length):m.regex.lastIndex=0,i++,i>=this.maxReplaces)break}}),e}nest(e,t,n={}){let r,o,a;const i=(l,c)=>{const d=this.nestingOptionsSeparator;if(!l.includes(d))return l;const p=l.split(new RegExp(`${_e(d)}[ ]*{`));let h=`{${p[1]}`;l=p[0],h=this.interpolate(h,a);const f=h.match(/'/g),m=h.match(/"/g);(((f==null?void 0:f.length)??0)%2===0&&!m||((m==null?void 0:m.length)??0)%2!==0)&&(h=h.replace(/'/g,'"'));try{a=JSON.parse(h),c&&(a={...c,...a})}catch(y){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,y),`${l}${d}${h}`}return a.defaultValue&&a.defaultValue.includes(this.prefix)&&delete a.defaultValue,l};for(;r=this.nestingRegexp.exec(e);){let l=[];a={...n},a=a.replace&&!L(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const c=/{.*}/s.test(r[1])?r[1].lastIndexOf("}")+1:r[1].indexOf(this.formatSeparator);if(c!==-1&&(l=r[1].slice(c).split(this.formatSeparator).map(d=>d.trim()).filter(Boolean),r[1]=r[1].slice(0,c)),o=t(i.call(this,r[1].trim(),a),a),o&&r[0]===e&&!L(o))return o;L(o)||(o=Ts(o)),o||(this.logger.warn(`missed to resolve ${r[1]} for nesting ${e}`),o=""),l.length&&(o=l.reduce((d,p)=>this.format(d,p,n.lng,{...n,interpolationkey:r[1].trim()}),o.trim())),e=e.replace(r[0],o),this.regexp.lastIndex=0}return e}}const Uo=s=>{let e=s.toLowerCase().trim();const t={};if(s.includes("(")){const n=s.split("(");e=n[0].toLowerCase().trim();const r=n[1].slice(0,-1);e==="currency"&&!r.includes(":")?t.currency||(t.currency=r.trim()):e==="relativetime"&&!r.includes(":")?t.range||(t.range=r.trim()):r.split(";").forEach(a=>{if(a){const[i,...l]=a.split(":"),c=l.join(":").trim().replace(/^'+|'+$/g,""),d=i.trim();t[d]||(t[d]=c),c==="false"&&(t[d]=!1),c==="true"&&(t[d]=!0),isNaN(c)||(t[d]=parseInt(c,10))}})}return{formatName:e,formatOptions:t}},Is=s=>{const e={};return(t,n,r)=>{let o=r;r&&r.interpolationkey&&r.formatParams&&r.formatParams[r.interpolationkey]&&r[r.interpolationkey]&&(o={...o,[r.interpolationkey]:void 0});const a=n+JSON.stringify(o);let i=e[a];return i||(i=s(ct(n),r),e[a]=i),i(t)}},Go=s=>(e,t,n)=>s(ct(t),n)(e);class zo{constructor(e={}){this.logger=we.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const n=t.cacheInBuiltFormats?Is:Go;this.formats={number:n((r,o)=>{const a=new Intl.NumberFormat(r,{...o});return i=>a.format(i)}),currency:n((r,o)=>{const a=new Intl.NumberFormat(r,{...o,style:"currency"});return i=>a.format(i)}),datetime:n((r,o)=>{const a=new Intl.DateTimeFormat(r,{...o});return i=>a.format(i)}),relativetime:n((r,o)=>{const a=new Intl.RelativeTimeFormat(r,{...o});return i=>a.format(i,o.range||"day")}),list:n((r,o)=>{const a=new Intl.ListFormat(r,{...o});return i=>a.format(i)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=Is(t)}format(e,t,n,r={}){if(!t||e==null)return e;const o=t.split(this.formatSeparator),a=[];for(let l=0;l<o.length;l++){let c=o[l];for(;c.indexOf("(")>-1&&!c.includes(")")&&l+1<o.length;)c=`${c}${this.formatSeparator}${o[++l]}`;a.push(c)}return a.reduce((l,c)=>{var h;const{formatName:d,formatOptions:p}=Uo(c);if(this.formats[d]){let f=l;try{const m=((h=r==null?void 0:r.formatParams)==null?void 0:h[r.interpolationkey])||{},y=m.locale||m.lng||r.locale||r.lng||n;f=this.formats[d](l,y,{...p,...r,...m})}catch(m){this.logger.warn(m)}return f}else this.logger.warn(`there was no format function for ${d}`);return l},e)}}const Ko=(s,e)=>{s.pending[e]!==void 0&&(delete s.pending[e],s.pendingCount--)};class qo extends Pt{constructor(e,t,n,r={}){var o,a;super(),this.backend=e,this.store=t,this.services=n,this.languageUtils=n.languageUtils,this.options=r,this.logger=we.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=r.maxParallelReads||10,this.readingCalls=0,this.maxRetries=r.maxRetries>=0?r.maxRetries:5,this.retryTimeout=r.retryTimeout>=1?r.retryTimeout:350,this.state={},this.queue=[],(a=(o=this.backend)==null?void 0:o.init)==null||a.call(o,n,r.backend,r)}queueLoad(e,t,n,r){const o={},a={},i={},l={};return e.forEach(c=>{let d=!0;t.forEach(p=>{const h=`${c}|${p}`;!n.reload&&this.store.hasResourceBundle(c,p)?this.state[h]=2:this.state[h]<0||(this.state[h]===1?a[h]===void 0&&(a[h]=!0):(this.state[h]=1,d=!1,a[h]===void 0&&(a[h]=!0),o[h]===void 0&&(o[h]=!0),l[p]===void 0&&(l[p]=!0)))}),d||(i[c]=!0)}),(Object.keys(o).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:r}),{toLoad:Object.keys(o),pending:Object.keys(a),toLoadLanguages:Object.keys(i),toLoadNamespaces:Object.keys(l)}}loaded(e,t,n){const r=e.split("|"),o=r[0],a=r[1];t&&this.emit("failedLoading",o,a,t),!t&&n&&this.store.addResourceBundle(o,a,n,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&n&&(this.state[e]=0);const i={};this.queue.forEach(l=>{Po(l.loaded,[o],a),Ko(l,e),t&&l.errors.push(t),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(c=>{i[c]||(i[c]={});const d=l.loaded[c];d.length&&d.forEach(p=>{i[c][p]===void 0&&(i[c][p]=!0)})}),l.done=!0,l.errors.length?l.callback(l.errors):l.callback())}),this.emit("loaded",i),this.queue=this.queue.filter(l=>!l.done)}read(e,t,n,r=0,o=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:n,tried:r,wait:o,callback:a});return}this.readingCalls++;const i=(c,d)=>{if(this.readingCalls--,this.waitingReads.length>0){const p=this.waitingReads.shift();this.read(p.lng,p.ns,p.fcName,p.tried,p.wait,p.callback)}if(c&&d&&r<this.maxRetries){setTimeout(()=>{this.read(e,t,n,r+1,o*2,a)},o);return}a(c,d)},l=this.backend[n].bind(this.backend);if(l.length===2){try{const c=l(e,t);c&&typeof c.then=="function"?c.then(d=>i(null,d)).catch(i):i(null,c)}catch(c){i(c)}return}return l(e,t,i)}prepareLoading(e,t,n={},r){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),r&&r();L(e)&&(e=this.languageUtils.toResolveHierarchy(e)),L(t)&&(t=[t]);const o=this.queueLoad(e,t,n,r);if(!o.toLoad.length)return o.pending.length||r(),null;o.toLoad.forEach(a=>{this.loadOne(a)})}load(e,t,n){this.prepareLoading(e,t,{},n)}reload(e,t,n){this.prepareLoading(e,t,{reload:!0},n)}loadOne(e,t=""){const n=e.split("|"),r=n[0],o=n[1];this.read(r,o,"read",void 0,void 0,(a,i)=>{a&&this.logger.warn(`${t}loading namespace ${o} for language ${r} failed`,a),!a&&i&&this.logger.log(`${t}loaded namespace ${o} for language ${r}`,i),this.loaded(e,a,i)})}saveMissing(e,t,n,r,o,a={},i=()=>{}){var l,c,d,p,h;if((c=(l=this.services)==null?void 0:l.utils)!=null&&c.hasLoadedNamespace&&!((p=(d=this.services)==null?void 0:d.utils)!=null&&p.hasLoadedNamespace(t))){this.logger.warn(`did not save key "${n}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(!(n==null||n==="")){if((h=this.backend)!=null&&h.create){const f={...a,isUpdate:o},m=this.backend.create.bind(this.backend);if(m.length<6)try{let y;m.length===5?y=m(e,t,n,r,f):y=m(e,t,n,r),y&&typeof y.then=="function"?y.then(v=>i(null,v)).catch(i):i(null,y)}catch(y){i(y)}else m(e,t,n,r,i,f)}!e||!e[0]||this.store.addResource(e[0],t,n,r)}}}const Ot=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",enableSelector:!1,partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:s=>{let e={};if(typeof s[1]=="object"&&(e=s[1]),L(s[1])&&(e.defaultValue=s[1]),L(s[2])&&(e.tDescription=s[2]),typeof s[2]=="object"||typeof s[3]=="object"){const t=s[3]||s[2];Object.keys(t).forEach(n=>{e[n]=t[n]})}return e},interpolation:{escapeValue:!0,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),Os=s=>(L(s.ns)&&(s.ns=[s.ns]),L(s.fallbackLng)&&(s.fallbackLng=[s.fallbackLng]),L(s.fallbackNS)&&(s.fallbackNS=[s.fallbackNS]),s.supportedLngs&&!s.supportedLngs.includes("cimode")&&(s.supportedLngs=s.supportedLngs.concat(["cimode"])),s),mt=()=>{},Vo=s=>{Object.getOwnPropertyNames(Object.getPrototypeOf(s)).forEach(t=>{typeof s[t]=="function"&&(s[t]=s[t].bind(s))})};class rt extends Pt{constructor(e={},t){if(super(),this.options=Os(e),this.services={},this.logger=we,this.modules={external:[]},Vo(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,typeof e=="function"&&(t=e,e={}),e.defaultNS==null&&e.ns&&(L(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const n=Ot();this.options={...n,...this.options,...Os(e)},this.options.interpolation={...n.interpolation,...this.options.interpolation},e.keySeparator!==void 0&&(this.options.userDefinedKeySeparator=e.keySeparator),e.nsSeparator!==void 0&&(this.options.userDefinedNsSeparator=e.nsSeparator),typeof this.options.overloadTranslationOptionHandler!="function"&&(this.options.overloadTranslationOptionHandler=n.overloadTranslationOptionHandler);const r=c=>c?typeof c=="function"?new c:c:null;if(!this.options.isClone){this.modules.logger?we.init(r(this.modules.logger),this.options):we.init(null,this.options);let c;this.modules.formatter?c=this.modules.formatter:c=zo;const d=new Ps(this.options);this.store=new Es(this.options.resources,this.options);const p=this.services;p.logger=we,p.resourceStore=this.store,p.languageUtils=d,p.pluralResolver=new Wo(d,{prepend:this.options.pluralSeparator}),c&&(p.formatter=r(c),p.formatter.init&&p.formatter.init(p,this.options),this.options.interpolation.format=p.formatter.format.bind(p.formatter)),p.interpolator=new Ms(this.options),p.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},p.backendConnector=new qo(r(this.modules.backend),p.resourceStore,p,this.options),p.backendConnector.on("*",(h,...f)=>{this.emit(h,...f)}),this.modules.languageDetector&&(p.languageDetector=r(this.modules.languageDetector),p.languageDetector.init&&p.languageDetector.init(p,this.options.detection,this.options)),this.modules.i18nFormat&&(p.i18nFormat=r(this.modules.i18nFormat),p.i18nFormat.init&&p.i18nFormat.init(this)),this.translator=new Tt(this.services,this.options),this.translator.on("*",(h,...f)=>{this.emit(h,...f)}),this.modules.external.forEach(h=>{h.init&&h.init(this)})}if(this.format=this.options.interpolation.format,t||(t=mt),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const c=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);c.length>0&&c[0]!=="dev"&&(this.options.lng=c[0])}!this.services.languageDetector&&!this.options.lng&&this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(c=>{this[c]=(...d)=>this.store[c](...d)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(c=>{this[c]=(...d)=>(this.store[c](...d),this)});const i=qe(),l=()=>{const c=(d,p)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),i.resolve(p),t(d,p)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return c(null,this.t.bind(this));this.changeLanguage(this.options.lng,c)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),i}loadResources(e,t=mt){var o,a;let n=t;const r=L(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if((r==null?void 0:r.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const i=[],l=c=>{if(!c||c==="cimode")return;this.services.languageUtils.toResolveHierarchy(c).forEach(p=>{p!=="cimode"&&(i.includes(p)||i.push(p))})};r?l(r):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(d=>l(d)),(a=(o=this.options.preload)==null?void 0:o.forEach)==null||a.call(o,c=>l(c)),this.services.backendConnector.load(i,this.options.ns,c=>{!c&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(c)})}else n(null)}reloadResources(e,t,n){const r=qe();return typeof e=="function"&&(n=e,e=void 0),typeof t=="function"&&(n=t,t=void 0),e||(e=this.languages),t||(t=this.options.ns),n||(n=mt),this.services.backendConnector.reload(e,t,o=>{r.resolve(),n(o)}),r}use(e){if(!e)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return e.type==="backend"&&(this.modules.backend=e),(e.type==="logger"||e.log&&e.warn&&e.error)&&(this.modules.logger=e),e.type==="languageDetector"&&(this.modules.languageDetector=e),e.type==="i18nFormat"&&(this.modules.i18nFormat=e),e.type==="postProcessor"&&gn.addPostProcessor(e),e.type==="formatter"&&(this.modules.formatter=e),e.type==="3rdParty"&&this.modules.external.push(e),this}setResolvedLanguage(e){if(!(!e||!this.languages)&&!["cimode","dev"].includes(e)){for(let t=0;t<this.languages.length;t++){const n=this.languages[t];if(!["cimode","dev"].includes(n)&&this.store.hasLanguageSomeTranslations(n)){this.resolvedLanguage=n;break}}!this.resolvedLanguage&&!this.languages.includes(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;const n=qe();this.emit("languageChanging",e);const r=i=>{this.language=i,this.languages=this.services.languageUtils.toResolveHierarchy(i),this.resolvedLanguage=void 0,this.setResolvedLanguage(i)},o=(i,l)=>{l?this.isLanguageChangingTo===e&&(r(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,n.resolve((...c)=>this.t(...c)),t&&t(i,(...c)=>this.t(...c))},a=i=>{var d,p;!e&&!i&&this.services.languageDetector&&(i=[]);const l=L(i)?i:i&&i[0],c=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(L(i)?[i]:i);c&&(this.language||r(c),this.translator.language||this.translator.changeLanguage(c),(p=(d=this.services.languageDetector)==null?void 0:d.cacheUserLanguage)==null||p.call(d,c)),this.loadResources(c,h=>{o(h,c)})};return!e&&this.services.languageDetector&&!this.services.languageDetector.async?a(this.services.languageDetector.detect()):!e&&this.services.languageDetector&&this.services.languageDetector.async?this.services.languageDetector.detect.length===0?this.services.languageDetector.detect().then(a):this.services.languageDetector.detect(a):a(e),n}getFixedT(e,t,n,r){const o=r==null?void 0:r.scopeNs,a=(i,l,...c)=>{let d;typeof l!="object"?d=this.options.overloadTranslationOptionHandler([i,l].concat(c)):d={...l},d.lng=d.lng||a.lng,d.lngs=d.lngs||a.lngs;const p=d.ns!==void 0&&d.ns!==null;d.ns=d.ns||a.ns,d.keyPrefix!==""&&(d.keyPrefix=d.keyPrefix||n||a.keyPrefix);const h={...this.options,...d};Array.isArray(o)&&!p&&(h.ns=o),typeof d.keyPrefix=="function"&&(d.keyPrefix=We(d.keyPrefix,h));const f=this.options.keySeparator||".";let m;return d.keyPrefix&&Array.isArray(i)?m=i.map(y=>(typeof y=="function"&&(y=We(y,h)),`${d.keyPrefix}${f}${y}`)):(typeof i=="function"&&(i=We(i,h)),m=d.keyPrefix?`${d.keyPrefix}${f}${i}`:i),this.t(m,d)};return L(e)?a.lng=e:a.lngs=e,a.ns=t,a.keyPrefix=n,a}t(...e){var t;return(t=this.translator)==null?void 0:t.translate(...e)}exists(...e){var t;return(t=this.translator)==null?void 0:t.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;const n=t.lng||this.resolvedLanguage||this.languages[0],r=this.options?this.options.fallbackLng:!1,o=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const a=(i,l)=>{const c=this.services.backendConnector.state[`${i}|${l}`];return c===-1||c===0||c===2};if(t.precheck){const i=t.precheck(this,a);if(i!==void 0)return i}return!!(this.hasResourceBundle(n,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||a(n,e)&&(!r||a(o,e)))}loadNamespaces(e,t){const n=qe();return this.options.ns?(L(e)&&(e=[e]),e.forEach(r=>{this.options.ns.includes(r)||this.options.ns.push(r)}),this.loadResources(r=>{n.resolve(),t&&t(r)}),n):(t&&t(),Promise.resolve())}loadLanguages(e,t){const n=qe();L(e)&&(e=[e]);const r=this.options.preload||[],o=e.filter(a=>!r.includes(a)&&this.services.languageUtils.isSupportedCode(a));return o.length?(this.options.preload=r.concat(o),this.loadResources(a=>{n.resolve(),t&&t(a)}),n):(t&&t(),Promise.resolve())}dir(e){var r,o;if(e||(e=this.resolvedLanguage||(((r=this.languages)==null?void 0:r.length)>0?this.languages[0]:this.language)),!e)return"rtl";try{const a=new Intl.Locale(e);if(a&&a.getTextInfo){const i=a.getTextInfo();if(i&&i.direction)return i.direction}}catch{}const t=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"],n=((o=this.services)==null?void 0:o.languageUtils)||new Ps(Ot());return e.toLowerCase().indexOf("-latn")>1?"ltr":t.includes(n.getLanguagePartFromCode(e))||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},t){const n=new rt(e,t);return n.createInstance=rt.createInstance,n}cloneInstance(e={},t=mt){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const r={...this.options,...e,isClone:!0},o=new rt(r);if((e.debug!==void 0||e.prefix!==void 0)&&(o.logger=o.logger.clone(e)),["store","services","language"].forEach(i=>{o[i]=this[i]}),o.services={...this.services},o.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},n){const i=Object.keys(this.store.data).reduce((l,c)=>(l[c]={...this.store.data[c]},l[c]=Object.keys(l[c]).reduce((d,p)=>(d[p]={...l[c][p]},d),l[c]),l),{});o.store=new Es(i,r),o.services.resourceStore=o.store}if(e.interpolation){const l={...Ot().interpolation,...this.options.interpolation,...e.interpolation},c={...r,interpolation:l};o.services.interpolator=new Ms(c)}return o.translator=new Tt(o.services,r),o.translator.on("*",(i,...l)=>{o.emit(i,...l)}),o.init(r,t),o.translator.options=r,o.translator.backendConnector.services.utils={hasLoadedNamespace:o.hasLoadedNamespace.bind(o)},o}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const de=rt.createInstance();de.createInstance;de.dir;de.init;de.loadResources;de.reloadResources;de.use;de.changeLanguage;de.getFixedT;de.t;de.exists;de.setDefaultNamespace;de.hasLoadedNamespace;de.loadNamespaces;de.loadLanguages;const Jo=(s,e,t,n)=>{var o,a,i,l;const r=[t,{code:e,...n||{}}];if((a=(o=s==null?void 0:s.services)==null?void 0:o.logger)!=null&&a.forward)return s.services.logger.forward(r,"warn","react-i18next::",!0);Me(r[0])&&(r[0]=`react-i18next:: ${r[0]}`),(l=(i=s==null?void 0:s.services)==null?void 0:i.logger)!=null&&l.warn?s.services.logger.warn(...r):console!=null&&console.warn&&console.warn(...r)},$s={},es=(s,e,t,n)=>{Me(t)&&$s[t]||(Me(t)&&($s[t]=new Date),Jo(s,e,t,n))},bn=(s,e)=>()=>{if(s.isInitialized)e();else{const t=()=>{setTimeout(()=>{s.off("initialized",t)},0),e()};s.on("initialized",t)}},ts=(s,e,t)=>{s.loadNamespaces(e,bn(s,t))},Ds=(s,e,t,n)=>{if(Me(t)&&(t=[t]),s.options.preload&&s.options.preload.indexOf(e)>-1)return ts(s,t,n);t.forEach(r=>{s.options.ns.indexOf(r)<0&&s.options.ns.push(r)}),s.loadLanguages(e,bn(s,n))},Yo=(s,e,t={})=>!e.languages||!e.languages.length?(es(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(s,{lng:t.lng,precheck:(n,r)=>{if(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!r(n.isLanguageChangingTo,s))return!1}}),Me=s=>typeof s=="string",Qo=s=>typeof s=="object"&&s!==null,Xo=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,Zo={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},er=s=>Zo[s],tr=s=>s.replace(Xo,er);let ss={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:tr,transDefaultProps:void 0};const sr=(s={})=>{ss={...ss,...s}},nr=()=>ss;let xn;const or=s=>{xn=s},rr=()=>xn,ar={type:"3rdParty",init(s){sr(s.options.react),or(s)}},ir=g.createContext();class lr{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(t=>{this.usedNamespaces[t]||(this.usedNamespaces[t]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const cr=(s,e)=>{if(Me(e))return e;if(Qo(e)&&Me(e.defaultValue))return e.defaultValue;if(typeof s=="function")return"";if(Array.isArray(s)){const t=s[s.length-1];return typeof t=="function"?"":t}return s},dr={t:cr,ready:!1},ur=()=>()=>{},Ee=(s,e={})=>{var O,W,ne;const{i18n:t}=e,{i18n:n,defaultNS:r}=g.useContext(ir)||{},o=t||n||rr();o&&!o.reportNamespaces&&(o.reportNamespaces=new lr),o||es(o,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const a=g.useMemo(()=>{var N;return{...nr(),...(N=o==null?void 0:o.options)==null?void 0:N.react,...e}},[o,e]),{useSuspense:i,keyPrefix:l}=a,c=s||r||((O=o==null?void 0:o.options)==null?void 0:O.defaultNS),d=Me(c)?[c]:c||["translation"],p=g.useMemo(()=>d,d);(ne=(W=o==null?void 0:o.reportNamespaces)==null?void 0:W.addUsedNamespaces)==null||ne.call(W,p);const h=g.useRef(0),f=g.useCallback(N=>{if(!o)return ur;const{bindI18n:b,bindI18nStore:A}=a,F=()=>{h.current+=1,N()};return b&&o.on(b,F),A&&o.store.on(A,F),()=>{b&&b.split(" ").forEach(U=>o.off(U,F)),A&&A.split(" ").forEach(U=>o.store.off(U,F))}},[o,a]),m=g.useRef(),y=g.useCallback(()=>{if(!o)return dr;const N=!!(o.isInitialized||o.initializedStoreOnce)&&p.every(B=>Yo(B,o,a)),b=e.lng||o.language,A=h.current,F=m.current;if(F&&F.ready===N&&F.lng===b&&F.keyPrefix===l&&F.revision===A)return F;const se={t:o.getFixedT(b,a.nsMode==="fallback"?p:p[0],l,{scopeNs:p}),ready:N,lng:b,keyPrefix:l,revision:A};return m.current=se,se},[o,p,l,a,e.lng]),[v,C]=g.useState(0),{t:S,ready:T}=To.useSyncExternalStore(f,y,y);g.useEffect(()=>{if(o&&!T&&!i){const N=()=>C(b=>b+1);e.lng?Ds(o,e.lng,p,N):ts(o,p,N)}},[o,e.lng,p,T,i,v]);const _=o||{},x=g.useRef(null),R=g.useRef(),j=N=>{const b=Object.getOwnPropertyDescriptors(N);b.__original&&delete b.__original;const A=Object.create(Object.getPrototypeOf(N),b);if(!Object.prototype.hasOwnProperty.call(A,"__original"))try{Object.defineProperty(A,"__original",{value:N,writable:!1,enumerable:!1,configurable:!1})}catch{}return A},D=g.useMemo(()=>{const N=_,b=N==null?void 0:N.language;let A=N;N&&(x.current&&x.current.__original===N?R.current!==b?(A=j(N),x.current=A,R.current=b):A=x.current:(A=j(N),x.current=A,R.current=b));const F=!T&&!i?(...se)=>(es(o,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),S(...se)):S,U=[F,A,T];return U.t=F,U.i18n=A,U.ready=T,U},[S,_,T,_.resolvedLanguage,_.language,_.languages]);if(o&&i&&!T)throw new Promise(N=>{const b=()=>N();e.lng?Ds(o,e.lng,p,b):ts(o,p,b)});return D},pr={};function hr(s,e){let t;try{t=s()}catch{return}return{getItem:r=>{var o;const a=l=>l===null?null:JSON.parse(l,void 0),i=(o=t.getItem(r))!=null?o:null;return i instanceof Promise?i.then(a):a(i)},setItem:(r,o)=>t.setItem(r,JSON.stringify(o,void 0)),removeItem:r=>t.removeItem(r)}}const dt=s=>e=>{try{const t=s(e);return t instanceof Promise?t:{then(n){return dt(n)(t)},catch(n){return this}}}catch(t){return{then(n){return this},catch(n){return dt(n)(t)}}}},fr=(s,e)=>(t,n,r)=>{let o={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:v=>v,version:0,merge:(v,C)=>({...C,...v}),...e},a=!1;const i=new Set,l=new Set;let c;try{c=o.getStorage()}catch{}if(!c)return s((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...v)},n,r);const d=dt(o.serialize),p=()=>{const v=o.partialize({...n()});let C;const S=d({state:v,version:o.version}).then(T=>c.setItem(o.name,T)).catch(T=>{C=T});if(C)throw C;return S},h=r.setState;r.setState=(v,C)=>{h(v,C),p()};const f=s((...v)=>{t(...v),p()},n,r);let m;const y=()=>{var v;if(!c)return;a=!1,i.forEach(S=>S(n()));const C=((v=o.onRehydrateStorage)==null?void 0:v.call(o,n()))||void 0;return dt(c.getItem.bind(c))(o.name).then(S=>{if(S)return o.deserialize(S)}).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==o.version){if(o.migrate)return o.migrate(S.state,S.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return S.state}).then(S=>{var T;return m=o.merge(S,(T=n())!=null?T:f),t(m,!0),p()}).then(()=>{C==null||C(m,void 0),a=!0,l.forEach(S=>S(m))}).catch(S=>{C==null||C(void 0,S)})};return r.persist={setOptions:v=>{o={...o,...v},v.getStorage&&(c=v.getStorage())},clearStorage:()=>{c==null||c.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:v=>(i.add(v),()=>{i.delete(v)}),onFinishHydration:v=>(l.add(v),()=>{l.delete(v)})},y(),m||f},mr=(s,e)=>(t,n,r)=>{let o={storage:hr(()=>localStorage),partialize:y=>y,version:0,merge:(y,v)=>({...v,...y}),...e},a=!1;const i=new Set,l=new Set;let c=o.storage;if(!c)return s((...y)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...y)},n,r);const d=()=>{const y=o.partialize({...n()});return c.setItem(o.name,{state:y,version:o.version})},p=r.setState;r.setState=(y,v)=>{p(y,v),d()};const h=s((...y)=>{t(...y),d()},n,r);r.getInitialState=()=>h;let f;const m=()=>{var y,v;if(!c)return;a=!1,i.forEach(S=>{var T;return S((T=n())!=null?T:h)});const C=((v=o.onRehydrateStorage)==null?void 0:v.call(o,(y=n())!=null?y:h))||void 0;return dt(c.getItem.bind(c))(o.name).then(S=>{if(S)if(typeof S.version=="number"&&S.version!==o.version){if(o.migrate)return[!0,o.migrate(S.state,S.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,S.state];return[!1,void 0]}).then(S=>{var T;const[_,x]=S;if(f=o.merge(x,(T=n())!=null?T:h),t(f,!0),_)return d()}).then(()=>{C==null||C(f,void 0),f=n(),a=!0,l.forEach(S=>S(f))}).catch(S=>{C==null||C(void 0,S)})};return r.persist={setOptions:y=>{o={...o,...y},y.storage&&(c=y.storage)},clearStorage:()=>{c==null||c.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>m(),hasHydrated:()=>a,onHydrate:y=>(i.add(y),()=>{i.delete(y)}),onFinishHydration:y=>(l.add(y),()=>{l.delete(y)})},o.skipHydration||m(),f||h},gr=(s,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((pr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),fr(s,e)):mr(s,e),Ue=gr;let Fs=!1;function Ae(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(Fs||(Fs=!0,console.warn("[uuid] crypto.randomUUID unavailable (non-secure context) — using Math.random fallback")),"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)}))}const yr="deepseekcode-chat-store",br=500;let gt=null;const xr={getItem:s=>{const e=localStorage.getItem(s);if(!e)return null;try{const t=JSON.parse(e);return t&&typeof t=="object"&&"state"in t?t:{state:t,version:0}}catch{return null}},setItem:(s,e)=>{gt&&clearTimeout(gt),gt=setTimeout(()=>{gt=null;try{localStorage.setItem(s,JSON.stringify(e))}catch{}},br)},removeItem:s=>{localStorage.removeItem(s)}},G=pe()(Ue((s,e)=>({messagesBySession:{},generatingSessions:[],pausedSessions:[],sessionInputs:{},getMessages:t=>e().messagesBySession[t]||[],replaceMessages:(t,n)=>s(r=>({messagesBySession:{...r.messagesBySession,[t]:n.slice(-200)}})),addMessage:(t,n)=>s(r=>{const a=[...r.messagesBySession[t]||[],n].slice(-200);return{messagesBySession:{...r.messagesBySession,[t]:a}}}),updateLastMessage:(t,n)=>s(r=>{const o=(r.messagesBySession[t]||[]).map((a,i,l)=>i===l.length-1&&a.type==="assistant"?{...a,content:n}:a);return{messagesBySession:{...r.messagesBySession,[t]:o}}}),appendToLastMessage:(t,n)=>s(r=>{const o=r.messagesBySession[t];if(!o||o.length===0)return r;const a=o.length-1,i=o[a];if(i&&i.type==="assistant"){const l=o.slice();return l[a]={...i,content:i.content+n},{messagesBySession:{...r.messagesBySession,[t]:l}}}return{messagesBySession:{...r.messagesBySession,[t]:[...o,{id:Ae(),type:"assistant",content:n,timestamp:Date.now()}].slice(-200)}}}),setThinking:(t,n)=>s(r=>{const o=(r.messagesBySession[t]||[]).map((a,i,l)=>{var d;if(i!==l.length-1||a.type!=="assistant")return a;const c=(d=a.steps)==null?void 0:d.findIndex(p=>p.status==="running");if(c!==void 0&&c!==-1&&a.steps&&a.steps[c]){const p=a.steps.map((h,f)=>f===c?{...h,thought:n}:h);return{...a,steps:p}}return{...a,thinking:n}});return{messagesBySession:{...r.messagesBySession,[t]:o}}}),appendToLastMessageThinking:(t,n)=>s(r=>{var p,h;const o=r.messagesBySession[t];if(!o||o.length===0)return r;const a=o.length-1,i=o[a];if(!i||i.type!=="assistant")return{messagesBySession:{...r.messagesBySession,[t]:[...o,{id:Ae(),type:"assistant",content:"",timestamp:Date.now(),thinking:n}].slice(-200)}};let l;const c=(p=i.steps)==null?void 0:p.findIndex(f=>f.status==="running");if(c!==void 0&&c!==-1&&((h=i.steps)!=null&&h[c])){const f=i.steps.slice(),m=f[c];f[c]={...m,thought:(m.thought||"")+n},l={...i,steps:f}}else if(i.steps&&i.steps.length>0){const f=i.steps.length-1,m=i.steps.slice(),y=m[f];m[f]={...y,thought:(y.thought||"")+n},l={...i,steps:m}}else l={...i,thinking:(i.thinking||"")+n};const d=o.slice();return d[a]=l,{messagesBySession:{...r.messagesBySession,[t]:d}}}),addStep:(t,n)=>s(r=>{const o=(r.messagesBySession[t]||[]).map((a,i,l)=>{var h,f;if(i!==l.length-1||a.type!=="assistant")return a;const c=(h=a.toolCalls)==null?void 0:h.filter(m=>{var y;return!((y=a.steps)!=null&&y.some(v=>{var C;return(C=v.toolCalls)==null?void 0:C.some(S=>S.id===m.id)}))}),d={...n};c!=null&&c.length&&(d.toolCalls=[...d.toolCalls||[],...c]);let p=a.thinking||"";return p.trim().length>0&&(d.thought=(d.thought||"")+p,p=""),{...a,thinking:p,toolCalls:c!=null&&c.length?(f=a.toolCalls)==null?void 0:f.filter(m=>!c.some(y=>y.id===m.id)):a.toolCalls,steps:[...a.steps||[],d]}});return{messagesBySession:{...r.messagesBySession,[t]:o}}}),updateStep:(t,n,r)=>s(o=>{const a=(o.messagesBySession[t]||[]).map((i,l,c)=>{if(l!==c.length-1||!i.steps)return i;const d=i.steps.findIndex(h=>h.id===n);if(d===-1)return i;const p=i.steps.map((h,f)=>f===d?{...h,...r}:h);return{...i,steps:p}});return{messagesBySession:{...o.messagesBySession,[t]:a}}}),addToolCall:(t,n)=>s(r=>{const o=(r.messagesBySession[t]||[]).map((a,i,l)=>{var d;if(i!==l.length-1||a.type!=="assistant")return a;const c=(d=a.steps)==null?void 0:d.findIndex(p=>p.status==="running");if(c!==void 0&&c!==-1&&a.steps&&a.steps[c]){const p=a.steps.map((h,f)=>f===c?{...h,toolCalls:[...h.toolCalls||[],n]}:h);return{...a,steps:p}}if(a.steps&&a.steps.length>0){const p=a.steps.length-1,h=a.steps.map((f,m)=>m===p?{...f,toolCalls:[...f.toolCalls||[],n]}:f);return{...a,steps:h}}return{...a,toolCalls:[...a.toolCalls||[],n]}});return{messagesBySession:{...r.messagesBySession,[t]:o}}}),updateToolCall:(t,n,r)=>s(o=>{const a=l=>{if(!l)return null;const c=l.findIndex(d=>d.id===n);return c===-1?null:l.map((d,p)=>p===c?{...d,...r}:d)},i=(o.messagesBySession[t]||[]).map((l,c,d)=>{var f,m;if(c!==d.length-1||l.type!=="assistant")return l;const p=(f=l.steps)==null?void 0:f.findIndex(y=>y.status==="running");if(p!==void 0&&p!==-1&&l.steps&&l.steps[p]){const y=a((m=l.steps[p])==null?void 0:m.toolCalls);if(y){const v=l.steps.map((C,S)=>S===p?{...C,toolCalls:y}:C);return{...l,steps:v}}}if(l.steps){let y=!1;const v=l.steps.map(C=>{if(y)return C;const S=a(C.toolCalls);return S?(y=!0,{...C,toolCalls:S}):C});if(y)return{...l,steps:v}}const h=a(l.toolCalls);return h?{...l,toolCalls:h}:l});return{messagesBySession:{...o.messagesBySession,[t]:i}}}),appendToLastToolCallArgs:(t,n,r,o)=>s(a=>{const i=d=>{let p=d.args;if(typeof p=="string")p=p+r;else if(typeof p=="object"&&p!==null){const h=r.trim();if(h.startsWith("{")&&h.endsWith("}"))try{const f=JSON.parse(h);typeof p=="string"?p={...f}:p={...p,...f}}catch{p=JSON.stringify(p).slice(0,-1)+","+h.slice(1)}else typeof p=="string"?p=p+h:p=JSON.stringify(p)+h}else p=r;return{...d,args:p}},l=d=>{if(!d)return null;const p=d.findIndex(h=>o!==void 0&&h.index===o||h.id===n);return p===-1?null:d.map((h,f)=>f===p?i(h):h)},c=(a.messagesBySession[t]||[]).map((d,p,h)=>{var y,v;if(p!==h.length-1||d.type!=="assistant")return d;const f=(y=d.steps)==null?void 0:y.findIndex(C=>C.status==="running");if(f!==void 0&&f!==-1&&d.steps&&d.steps[f]){const C=l((v=d.steps[f])==null?void 0:v.toolCalls);if(C){const S=d.steps.map((T,_)=>_===f?{...T,toolCalls:C}:T);return{...d,steps:S}}}if(d.steps){let C=!1;const S=d.steps.map(T=>{if(C)return T;const _=l(T.toolCalls);return _?(C=!0,{...T,toolCalls:_}):T});if(C)return{...d,steps:S}}const m=l(d.toolCalls);return m?{...d,toolCalls:m}:d});return{messagesBySession:{...a.messagesBySession,[t]:c}}}),startGeneration:t=>s(n=>({generatingSessions:n.generatingSessions.includes(t)?n.generatingSessions:[...n.generatingSessions,t]})),endGeneration:(t,n)=>s(r=>{var c,d;const o=r.messagesBySession[t]||[],a=Date.now(),i=o.map(p=>{var y,v;let h=!1;const f=(y=p.steps)==null?void 0:y.map(C=>{if(!C.toolCalls)return C;const S=C.toolCalls.map(T=>T.status!=="running"?T:(h=!0,{...T,status:"error",result:"生成已结束(工具执行超时或连接中断)",duration:Math.floor((a-(T.timestamp||a))/1e3)}));return S!==C.toolCalls?{...C,toolCalls:S}:C}),m=(v=p.toolCalls)==null?void 0:v.map(C=>C.status!=="running"?C:(h=!0,{...C,status:"error",result:"生成已结束(工具执行超时或连接中断)",duration:Math.floor((a-(C.timestamp||a))/1e3)}));return h?{...p,steps:f,toolCalls:m}:p}),l=i[i.length-1];if(l&&l.type==="assistant"&&!l.content&&!l.thinking&&!((c=l.steps)!=null&&c.length)&&!((d=l.toolCalls)!=null&&d.length)&&!l.hookApproval){const{[t]:p,...h}=r.messagesBySession;return{generatingSessions:r.generatingSessions.filter(f=>f!==t),pausedSessions:r.pausedSessions.filter(f=>f!==t),messagesBySession:{...h,[t]:i.slice(0,-1)}}}return{generatingSessions:r.generatingSessions.filter(p=>p!==t),pausedSessions:r.pausedSessions.filter(p=>p!==t),messagesBySession:{...r.messagesBySession,[t]:i}}}),pauseGeneration:t=>s(n=>({pausedSessions:n.pausedSessions.includes(t)?n.pausedSessions:[...n.pausedSessions,t]})),resumeGeneration:t=>s(n=>({pausedSessions:n.pausedSessions.filter(r=>r!==t)})),clearMessages:t=>s(n=>{const{[t]:r,...o}=n.messagesBySession;return{messagesBySession:o}}),removeSession:t=>s(n=>{const{[t]:r,...o}=n.messagesBySession,{[t]:a,...i}=n.sessionInputs;return{messagesBySession:o,sessionInputs:i,generatingSessions:n.generatingSessions.filter(l=>l!==t)}}),setSessionInput:(t,n)=>s(r=>({sessionInputs:{...r.sessionInputs,[t]:n}})),getSessionInput:t=>e().sessionInputs[t]||"",attachHookApproval:(t,n)=>s(r=>{const o=r.messagesBySession[t]||[];if(o.length===0){const c={id:`hook-approval-${n.approvalId||Date.now()}`,type:"assistant",content:"",timestamp:Date.now(),hookApproval:n};return{messagesBySession:{...r.messagesBySession,[t]:[c]}}}const a=o.length-1,i=o[a];if(i&&i.type==="assistant"){const c=o.slice();return c[a]={...i,hookApproval:n},{messagesBySession:{...r.messagesBySession,[t]:c}}}const l={id:`hook-approval-${n.approvalId||Date.now()}`,type:"assistant",content:"",timestamp:Date.now(),hookApproval:n};return{messagesBySession:{...r.messagesBySession,[t]:[...o,l].slice(-200)}}}),updateHookApprovalStatus:(t,n,r)=>s(o=>{const a=o.messagesBySession[t];if(!a)return o;const i=a.map(l=>{var c;return((c=l.hookApproval)==null?void 0:c.approvalId)===n?{...l,hookApproval:{...l.hookApproval,status:r}}:l});return{messagesBySession:{...o.messagesBySession,[t]:i}}}),setMessageFileJob:(t,n)=>s(r=>{const o=r.messagesBySession[t]||[];if(o.length===0){const c={id:`filejob-${n.jobId}`,type:"assistant",content:"",timestamp:Date.now(),fileJob:n};return{messagesBySession:{...r.messagesBySession,[t]:[c]}}}const a=o.length-1,i=o[a];if(i&&i.type==="assistant"){const c=o.slice();return c[a]={...i,fileJob:i.fileJob?{...i.fileJob,...n,attachments:n.attachments??i.fileJob.attachments,jobId:i.fileJob.jobId,updatedAt:Date.now()}:{...n,updatedAt:Date.now()}},{messagesBySession:{...r.messagesBySession,[t]:c}}}const l={id:`filejob-${n.jobId}`,type:"assistant",content:"",timestamp:Date.now(),fileJob:n};return{messagesBySession:{...r.messagesBySession,[t]:[...o,l].slice(-200)}}}),attachErrorCard:(t,n)=>s(r=>{const o=r.messagesBySession[t];if(!o||o.length===0)return r;const a=o.length-1,i=o[a];if(i&&i.type==="assistant"){const l=o.slice();return l[a]={...i,errorCard:n},{messagesBySession:{...r.messagesBySession,[t]:l}}}return r}),setTurnSummary:(t,n)=>s(r=>{const o=r.messagesBySession[t];if(!o||o.length===0)return r;const a=o.length-1,i=o[a];if(!i||i.type!=="assistant")return r;const l=o.slice();return l[a]={...i,summary:n},{messagesBySession:{...r.messagesBySession,[t]:l}}}),applyTombstone:(t,n)=>s(r=>{const o=r.messagesBySession[t];if(!o||o.length===0)return r;const a=new Set(n),i=o.map(l=>a.has(l.id)?{...l,deleted:!0}:l);return{messagesBySession:{...r.messagesBySession,[t]:i}}}),isGenerating:t=>e().generatingSessions.includes(t),isPaused:t=>e().pausedSessions.includes(t)}),{name:yr,storage:xr,partialize:s=>({messagesBySession:s.messagesBySession,sessionInputs:s.sessionInputs})})),Ws=6,$t=50,V=pe()(Ue((s,e)=>({sessions:[],activeSessionId:null,sessionTabs:[],layout:"single",sessionWorkspaceDirs:{},tasksBySession:{},historySessions:[],addSession:t=>s(n=>({sessions:[t,...n.sessions],activeSessionId:t.id})),removeSession:t=>s(n=>{var r;return{sessions:n.sessions.filter(o=>o.id!==t),activeSessionId:n.activeSessionId===t?((r=n.sessions[0])==null?void 0:r.id)||null:n.activeSessionId}}),updateSession:(t,n)=>s(r=>({sessions:r.sessions.map(o=>o.id===t?{...o,...n}:o)})),setActiveSession:t=>s({activeSessionId:t}),setSessionWorkspaceDir:(t,n)=>s(r=>({sessionWorkspaceDirs:{...r.sessionWorkspaceDirs,[t]:n}})),getSessionWorkspaceDir:t=>e().sessionWorkspaceDirs[t]||"",addSessionTab:(t,n)=>{const r=e();if(r.sessionTabs.length>=Ws){const h=r.sessionTabs.reduce((f,m)=>f.createdAt<m.createdAt?f:m);e().closeSessionTab(h.id)}const o=`session-${Date.now()}`,a=n&&n.split(/[\\/]/).filter(Boolean).pop()||void 0,i={id:o,title:t||`对话 ${r.sessionTabs.length+1}`,createdAt:Date.now(),project:a,status:"done"},l={id:o,title:t||`对话 ${r.sessionTabs.length+1}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0},c={...r.sessionWorkspaceDirs};n&&(c[o]=n);const d={...r.tasksBySession};d[o]||(d[o]=[]);const p=[i,...r.historySessions.filter(h=>h.id!==o)].slice(0,$t);return s({sessionTabs:[...r.sessionTabs,i],sessions:[...r.sessions,l],sessionWorkspaceDirs:c,tasksBySession:d,activeSessionId:o,historySessions:p}),o},closeSessionTab:t=>{var l;const n=e(),r=n.sessionTabs.find(c=>c.id===t),o=n.sessionTabs.filter(c=>c.id!==t);if(o.length===0)return;let a=n.historySessions;r&&(a=[r,...a.filter(c=>c.id!==t)].slice(0,$t));const i=o[o.length-1];s({sessionTabs:o,historySessions:a,activeSessionId:n.activeSessionId===t?i?i.id:((l=o[0])==null?void 0:l.id)||null:n.activeSessionId})},renameSessionTab:(t,n)=>s(r=>({sessionTabs:r.sessionTabs.map(o=>o.id===t?{...o,title:n}:o),sessions:r.sessions.map(o=>o.id===t?{...o,title:n,updatedAt:new Date().toISOString()}:o),historySessions:r.historySessions.map(o=>o.id===t?{...o,title:n}:o)})),getActiveSessionTab:()=>{const t=e();return t.sessionTabs.find(n=>n.id===t.activeSessionId)||null},getVisibleSessionTabs:()=>{const t=e(),n=t.sessionTabs.find(r=>r.id===t.activeSessionId);return n?[n]:t.sessionTabs.slice(0,1)},addSessionTask:(t,n,r,o)=>s(a=>{const i=a.tasksBySession[t]||[],l={id:`session-task-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,title:n.trim(),completed:!1,createdAt:Date.now(),backendId:r,description:o};return{tasksBySession:{...a.tasksBySession,[t]:[...i,l]}}}),toggleSessionTask:(t,n)=>s(r=>{const o=r.tasksBySession[t]||[];return{tasksBySession:{...r.tasksBySession,[t]:o.map(a=>a.id===n?{...a,completed:!a.completed}:a)}}}),removeSessionTask:(t,n)=>s(r=>({tasksBySession:{...r.tasksBySession,[t]:(r.tasksBySession[t]||[]).filter(o=>o.id!==n)}})),updateSessionTask:(t,n,r)=>s(o=>{const a=o.tasksBySession[t]||[];return{tasksBySession:{...o.tasksBySession,[t]:a.map(i=>i.id===n?{...i,title:r.trim()}:i)}}}),getSessionTasks:t=>e().tasksBySession[t]||[],setSessionTasks:(t,n)=>s(r=>({tasksBySession:{...r.tasksBySession,[t]:n}})),updateTaskPlanStatus:(t,n,r)=>s(o=>{const a=o.tasksBySession[t]||[];return{tasksBySession:{...o.tasksBySession,[t]:a.map(i=>i.id===n?{...i,...r}:i)}}}),autoNameSession:(t,n)=>{const o=e().sessionTabs.find(i=>i.id===t);if(!o||!/^对话 \d+$/.test(o.title))return;const a=n.trim().slice(0,20)+(n.trim().length>20?"...":"");a&&e().renameSessionTab(t,a)},updateSessionStatus:(t,n)=>s(r=>({sessionTabs:r.sessionTabs.map(o=>o.id===t?{...o,status:n}:o)})),getHistorySessions:()=>e().historySessions,restoreHistorySession:t=>{const n=e(),r=n.historySessions.find(i=>i.id===t);if(!r)return;const o=n.historySessions.filter(i=>i.id!==t);if(n.sessionTabs.some(i=>i.id===t)){s({historySessions:o,activeSessionId:t});return}let a=n.sessionTabs;if(a.length>=Ws){const i=a.reduce((l,c)=>l.createdAt<c.createdAt?l:c);a=a.filter(l=>l.id!==i.id),o.unshift(i)}s({sessionTabs:[...a,r],historySessions:o.slice(0,$t),activeSessionId:t})},clearHistorySessions:()=>s({historySessions:[]}),removeHistorySession:t=>s(n=>({historySessions:n.historySessions.filter(r=>r.id!==t)}))}),{name:"deepseekcode-session-storage",partialize:s=>({sessions:s.sessions,sessionTabs:s.sessionTabs,activeSessionId:s.activeSessionId,layout:s.layout,sessionWorkspaceDirs:s.sessionWorkspaceDirs,tasksBySession:s.tasksBySession,historySessions:s.historySessions})})),kr=pe(s=>({isOpen:!1,status:"idle",port:null,wsUrl:null,errorMessage:null,openTerminal:()=>s({isOpen:!0}),closeTerminal:()=>s({isOpen:!1}),toggleTerminal:()=>s(e=>({isOpen:!e.isOpen})),setStarting:()=>s({status:"starting",errorMessage:null}),setRunning:(e,t)=>s({status:"running",port:e,wsUrl:t}),setStopping:()=>s({status:"stopping"}),setIdle:()=>s({status:"idle",port:null,wsUrl:null,errorMessage:null}),setError:e=>s({status:"error",errorMessage:e})})),Hs={bg:"#0d1117",surface:"#161b22",border:"#30363d",text:"#c9d1d9",muted:"#8b949e",accentBlue:"#58a6ff",accentGreen:"#238636",accentRed:"#f85149",accentYellow:"#d29922",accentPurple:"#a855f7"},He=pe()(Ue(s=>({theme:"light",themePresetId:"linear",language:"zh-CN",fontSize:14,streamingEnabled:!0,yolo:{enabled:!1},autoSwarm:{enabled:!1},workspaceDir:"",workspaceGuardBypass:!0,customTheme:Hs,customThemeEnabled:!1,setTheme:e=>s({theme:e}),setThemePreset:e=>s({themePresetId:e,customThemeEnabled:!1}),setLanguage:e=>s({language:e}),setFontSize:e=>s({fontSize:e}),setStreamingEnabled:e=>s({streamingEnabled:e}),setYoloEnabled:e=>s({yolo:{enabled:e}}),setAutoSwarmEnabled:e=>s({autoSwarm:{enabled:e}}),setCustomTheme:e=>s(t=>({customTheme:{...t.customTheme,...e}})),setCustomThemeEnabled:e=>s({customThemeEnabled:e}),setWorkspaceGuardBypass:e=>s({workspaceGuardBypass:e}),resetCustomTheme:()=>s({customTheme:Hs}),setWorkspaceDir:e=>s({workspaceDir:e})}),{name:"deepseekcode-settings-storage",version:2,migrate:(s,e)=>{const t=s;return e<2&&t&&typeof t=="object"&&((t.themePresetId==="github"||t.themePresetId==="mimo")&&(t.themePresetId="linear"),t.theme==="dark"&&(t.theme="light")),t}})),Sr=[{eventType:"connected",description:"WebSocket 已连接",category:"session",emittedBy:["server"],handledByCli:!0,handledByWeb:!0},{eventType:"session_created",description:"新会话已创建",category:"session",emittedBy:["server","core"],handledByCli:!0,handledByWeb:!1,note:"CLI 已处理; Web 未处理"},{eventType:"session_resumed",description:"会话从存储中恢复",category:"session",emittedBy:["core","server"],handledByCli:!0,handledByWeb:!1,note:"CLI 已处理; Web 未处理"},{eventType:"auth_required",description:"需要认证",category:"session",emittedBy:["server"],handledByCli:!0,handledByWeb:!0,note:"CLI 已处理(2026-07-18)"},{eventType:"auth_success",description:"认证成功",category:"session",emittedBy:["server"],handledByCli:!0,handledByWeb:!0,note:"CLI 已处理(2026-07-18)"},{eventType:"auth_failed",description:"认证失败",category:"session",emittedBy:["server"],handledByCli:!0,handledByWeb:!0,note:"CLI 已处理(2026-07-18)"},{eventType:"message_ack",description:"消息确认",category:"session",emittedBy:["client"],handledByCli:!1,handledByWeb:!1,note:"CLI 发送给服务器的入站事件,无需 handler"},{eventType:"workspace_changed",description:"工作空间已切换",category:"session",emittedBy:["server"],handledByCli:!0,handledByWeb:!0},{eventType:"session_switched",description:"会话已切换",category:"session",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"CLI 已处理(2026-07-18)"},{eventType:"start",description:"AI 开始生成",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"content",description:"生成内容增量",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"thinking",description:"思考过程增量",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"tool_call",description:"工具调用流式增量",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"tool_result",description:"工具执行结果",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"step_start",description:"步骤开始",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"step_thinking",description:"步骤思考",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"step_action",description:"步骤动作",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"step_complete",description:"步骤完成",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"turn_summary",description:"回合结束摘要(思考时长+工具计数+头条)",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI/Web 渲染为折叠摘要行(Thought for Ns, ran N …)"},{eventType:"progress",description:"通用进度(当前未使用)",category:"stream",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,note:"已定义但从未发送"},{eventType:"complete",description:"生成完成",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"error",description:"生成错误",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"generation_paused",description:"生成已暂停",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"generation_resumed",description:"生成已恢复",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"stall_detected",description:"流级卡死检测(自动重试/通知)",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"由 StreamHeartbeat 或 StallDetector 触发;CLI 显示重试进度"},{eventType:"task_interrupted",description:"任务中断(服务重启/异常退出)",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"服务启动扫描时将 running activeRun 标记为 interrupted 后触发;提示用户使用 /resume 恢复"},{eventType:"plan_start",description:"计划开始",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"由 EnterPlanMode 工具 emit"},{eventType:"plan_thinking",description:"计划思考",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"plan_tasks",description:"计划任务列表生成",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"由 ExitPlanMode 工具 emit(解析计划内容为任务列表);CLI handler 解析 data.tasks"},{eventType:"plan_task_start",description:"计划任务开始",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"plan_task_update",description:"计划任务更新",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"plan_task_result",description:"计划任务结果",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"plan_complete",description:"计划完成",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"由 ExitPlanMode 工具 emit(携带 currentPlan/proposedPlan)"},{eventType:"plan_error",description:"计划错误",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"plan_mode_change",description:"计划模式切换",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"CLI 已添加 handler(2026-07-01);Web 仍需添加"},{eventType:"plan_mode_enter",description:"进入计划模式(CLI 遗留)",category:"plan",emittedBy:["none"],handledByCli:!0,handledByWeb:!0,deprecated:!0,note:"兼容遗留代码,应改用 plan_mode_change"},{eventType:"plan_mode_exit",description:"退出计划模式(CLI 遗留)",category:"plan",emittedBy:["none"],handledByCli:!0,handledByWeb:!0,deprecated:!0,note:"兼容遗留代码,应改用 plan_mode_change"},{eventType:"plan_confirm",description:"计划等待确认",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"CLI 已处理(2026-07-18); Web 未处理"},{eventType:"plan_refine",description:"计划优化",category:"plan",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,note:"已定义但从未发送"},{eventType:"token_update",description:"Token 用量更新",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"context_compressed",description:"上下文已压缩",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"compaction_progress",description:"压缩进度更新",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"context_analysis",description:"上下文分布分析",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已处理(2026-07-18); Web 有 handler 但路由不可达"},{eventType:"threshold_warning",description:"Token 阈值警告",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已处理(2026-07-18); Web 有 handler 但路由不可达"},{eventType:"threshold_error",description:"Token 阈值错误",category:"context",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,note:"已定义但从未发送"},{eventType:"context_blocked",description:"上下文已满,生成被阻止",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已处理(2026-07-18); Web 有 handler 但路由不可达"},{eventType:"blocking_limit",description:"已达到阻止极限",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已处理(2026-07-18); Web 有 handler 但路由不可达"},{eventType:"microcompact_progress",description:"微压缩进度",category:"context",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,note:"已定义但从未发送"},{eventType:"session_memory_update",description:"会话记忆更新",category:"context",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,note:"已定义但从未发送"},{eventType:"tool_retry",description:"工具重试",category:"context",emittedBy:["none"],handledByCli:!1,handledByWeb:!0,note:"Web 有 handler 但路由不可达"},{eventType:"model_fallback",description:"模型回退",category:"context",emittedBy:["none"],handledByCli:!1,handledByWeb:!0,note:"Web 有 handler 但路由不可达"},{eventType:"workflow_started",description:"工作流已启动",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_event",description:"工作流事件",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_progress",description:"工作流进度",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_finished",description:"工作流完成",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_error",description:"工作流错误",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_checkpoint",description:"工作流检查点",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_node_start",description:"工作流节点开始",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_node_complete",description:"工作流节点完成",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_paused",description:"工作流已暂停",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_resumed",description:"工作流已恢复",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_cancelled",description:"工作流已取消",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"workflow_recovered",description:"工作流已恢复(从故障)",category:"workflow",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,note:"已定义但从未发送"},{eventType:"workflow_handoff",description:"ReAct 转交 workflow(范式切换)",category:"workflow",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"task_update",description:"任务更新",category:"task",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已添加 handler(2026-07-01)"},{eventType:"task_output",description:"任务输出",category:"task",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已添加 handler(2026-07-01)"},{eventType:"task_finished",description:"任务完成",category:"task",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已添加 handler(2026-07-01)"},{eventType:"task_error",description:"任务错误",category:"task",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已添加 handler(2026-07-01)"},{eventType:"goal_created",description:"目标已创建",category:"goal",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"2026-07-21: Web handled via goal_tasks/goal_task_update"},{eventType:"goal_tasks",description:"目标任务列表(批量初始化看板)",category:"goal",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"2026-07-21: 统一看板数据源"},{eventType:"goal_task_update",description:"目标任务更新",category:"goal",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"2026-07-21: Web 已添加 handler"},{eventType:"hook_ask",description:"Hook 审批请求",category:"hook",emittedBy:["server"],handledByCli:!0,handledByWeb:!0},{eventType:"hook_allow",description:"Hook 允许响应",category:"hook",emittedBy:["client"],handledByCli:!1,handledByWeb:!1,note:"入站事件(CLI→服务器),无需 handler"},{eventType:"hook_deny",description:"Hook 拒绝响应",category:"hook",emittedBy:["client"],handledByCli:!1,handledByWeb:!1,note:"入站事件(CLI→服务器),无需 handler"},{eventType:"hook_response_ack",description:"Hook 响应确认",category:"hook",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"CLI 已添加 handler(2026-07-01)"},{eventType:"mcp_update",description:"MCP 状态更新",category:"mcp",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已添加 handler(2026-07-01)"},{eventType:"doctor_result",description:"诊断完成",category:"diagnostic",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"degradation",description:"降级状态更新(遗留)",category:"diagnostic",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"degradation_update",description:"降级状态更新",category:"diagnostic",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"commands_list",description:"命令列表(服务器→客户端)",category:"system",emittedBy:["core","server"],handledByCli:!0,handledByWeb:!1,note:"CLI 已处理(setDynamicCommands); Web 未处理"},{eventType:"ping",description:"心跳 Ping",category:"system",emittedBy:["client"],handledByCli:!1,handledByWeb:!1,note:"由 Server 的 WS 层自动处理"},{eventType:"pong",description:"心跳 Pong",category:"system",emittedBy:["server"],handledByCli:!1,handledByWeb:!1,note:"由 Client 的 WS 层自动处理"},{eventType:"log",description:"服务端日志",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"notification",description:"通知消息",category:"system",emittedBy:["server"],handledByCli:!0,handledByWeb:!0},{eventType:"channel_message",description:"频道入站消息(转发到 Web UI)",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"CLI 已处理(2026-07-18); Web 未处理"},{eventType:"channel_status",description:"频道连接状态变更",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"CLI 已处理(2026-07-18); Web 未处理"},{eventType:"channel_error",description:"频道运行时错误",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"CLI 已处理(2026-07-18); Web 未处理"},{eventType:"filejob_start",description:"文件处理任务开始(解析/渲染)",category:"task",emittedBy:["core"],handledByCli:!1,handledByWeb:!0,note:"对话内嵌文件处理面板;Web 已处理,CLI 忽略(parseTurnEvent default→null)"},{eventType:"filejob_progress",description:"文件处理进度更新",category:"task",emittedBy:["core"],handledByCli:!1,handledByWeb:!0,note:"解析/渲染进度百分比"},{eventType:"filejob_result",description:"文件处理完成(结果文件列表)",category:"task",emittedBy:["core"],handledByCli:!1,handledByWeb:!0,note:"携带 RenderedFileResult[]"},{eventType:"filejob_error",description:"文件处理失败",category:"task",emittedBy:["core"],handledByCli:!1,handledByWeb:!0,note:"脱敏错误详情"},{eventType:"todo_update",description:"待办事项更新",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"todo_item_done",description:"待办项完成",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"运行时可能发送"},{eventType:"todo_progress",description:"待办进度",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"运行时可能发送"},{eventType:"tombstone",description:"消息已删除/墓碑",category:"system",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,note:"已定义但从未发送"},{eventType:"disconnected",description:"连接断开",category:"session",emittedBy:["server"],handledByCli:!0,handledByWeb:!0},{eventType:"status",description:"状态更新(modelName/connected/statusText)",category:"system",emittedBy:["core","server"],handledByCli:!0,handledByWeb:!0},{eventType:"usage",description:"Token 用量",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"model_name",description:"当前模型名称",category:"system",emittedBy:["core","server"],handledByCli:!0,handledByWeb:!0},{eventType:"throttle",description:"速率限制状态",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!1},{eventType:"ask_user_question",description:"向用户提问",category:"hook",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"question_answer_ack",description:"提问回答确认",category:"hook",emittedBy:["core"],handledByCli:!0,handledByWeb:!1},{eventType:"hook_auto_ack",description:"Hook 自动模式确认",category:"hook",emittedBy:["core"],handledByCli:!0,handledByWeb:!1},{eventType:"tool.approval_required",description:"工具调用需要审批(停放入口)",category:"inbox",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"无人值守/定时运行时写操作先停放;CLI 状态提示,Web Inbox 视图已建"},{eventType:"inbox.pending",description:"Inbox 新待办(审批/提问/通知)",category:"inbox",emittedBy:["core","server"],handledByCli:!0,handledByWeb:!0,note:"CLI 状态提示;Web Inbox 视图消费"},{eventType:"inbox.resolved",description:"Inbox 待办已解决(approve/reject)",category:"inbox",emittedBy:["core","server"],handledByCli:!0,handledByWeb:!0,note:"CLI 状态提示;Web Inbox 视图消费"},{eventType:"audit.record",description:"审计记录新增(工具批准/拒绝历史)",category:"inbox",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 忽略(避免刷屏);tools 页审计视图数据源"},{eventType:"automation.update",description:"自动化任务新增/更新/删除/状态变更",category:"automation",emittedBy:["server"],handledByCli:!0,handledByWeb:!0,note:"REST /api/automations 已可用;Web 自动化视图消费"},{eventType:"automation.run",description:"自动化触发运行(started/finished/error)",category:"automation",emittedBy:["core","server"],handledByCli:!0,handledByWeb:!0,note:"CLI 状态提示;Web RunDetail 消费"},{eventType:"code_review_ready",description:"代码审查结果就绪",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!1},{eventType:"pdca_phase",description:"PDCA 循环阶段",category:"system",emittedBy:["none"],handledByCli:!0,handledByWeb:!1,note:"已退役:5-phase light pipeline 被 WorkflowRuntime 取代"},{eventType:"plan_waiting",description:"计划等待用户输入",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!1},{eventType:"plan_continue",description:"计划继续执行",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!1},{eventType:"plan_settled",description:"计划已定稿",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!1},{eventType:"plan_cleared",description:"计划已清除",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!1},{eventType:"user_exit_plan_mode",description:"用户手动退出计划模式",category:"plan",emittedBy:["client"],handledByCli:!1,handledByWeb:!1,note:"入站事件(CLI→服务器),客户端无需 handler"},{eventType:"plan_task_complete",description:"计划任务完成(单个)",category:"plan",emittedBy:["core"],handledByCli:!0,handledByWeb:!1,note:"CLI 处理 plan_task_complete 和 plan_task_result 两个独立事件"},{eventType:"step_prompt",description:"步骤提示(Web 路由用)",category:"stream",emittedBy:["none"],handledByCli:!1,handledByWeb:!0,note:"Web 路由的内部事件,不通过 WS 发送"},{eventType:"command_start",description:"命令开始(Web 路由用)",category:"system",emittedBy:["none"],handledByCli:!1,handledByWeb:!0,note:"Web systemHandler 处理"},{eventType:"command_complete",description:"命令完成(Web 路由用)",category:"system",emittedBy:["none"],handledByCli:!1,handledByWeb:!0,note:"Web systemHandler 处理"},{eventType:"command_error",description:"命令错误(Web 路由用)",category:"system",emittedBy:["none"],handledByCli:!1,handledByWeb:!0,note:"Web systemHandler 处理"}];function ve(s){return s==="auto-plan"?"plan":s==="auto-act"?"act":s==="auto-goal"?"goal":s}function $e(s){return s==="auto-plan"||s==="auto-act"||s==="auto-goal"}function vr(s){switch(s){case"plan":return"auto-plan";case"auto-plan":return"plan";case"act":return"auto-act";case"auto-act":return"act";case"goal":return"auto-goal";case"auto-goal":return"goal"}}const Nl=["plan","act","goal"];function ns(s,e){return e?s==="plan"?"auto-plan":s==="act"?"auto-act":"auto-goal":s}function wr(s){const e=["plan","act","goal"],t=e.indexOf(ve(s)),n=e[(t+1)%e.length]??"act";return ns(n,$e(s))}const Cr={plan:{label:"Plan",accent:"blue"},"auto-plan":{label:"Auto-Plan",accent:"cyan"},act:{label:"Act",accent:"green"},"auto-act":{label:"Auto-Act",accent:"yellow"},goal:{label:"Goal",accent:"magenta"},"auto-goal":{label:"Auto-Goal",accent:"red"}},Bl={low:{label:"Low",accent:"green"},medium:{label:"Medium",accent:"cyan"},high:{label:"High",accent:"yellow"},critical:{label:"Critical",accent:"red"}},Al={allow:{label:"Allow",key:"y"},deny:{label:"Deny",key:"n"},allow_session:{label:"Allow session",key:"s"},auto:{label:"Auto mode",key:"a"}};function _r(s){return s==="plan"||s==="auto-plan"||s==="act"||s==="auto-act"||s==="goal"||s==="auto-goal"?s:"act"}function Ve(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${Math.round(s/1e3)}K`:String(s)}function Tr(s){return s<=0?"":s>=100?`${Math.round(s)}t/s`:`${s.toFixed(1)}t/s`}function kn(s){if(s<=0)return"";if(s>=60){const e=Math.floor(s/60),t=s%60;return`${e}m${t}s`}return`${s}s`}function Nr(s,e){switch(s){case"bash":case"shell":case"PowerShell":return`ran ${e} shell command${e>1?"s":""}`;case"read_file":return`read ${e} file${e>1?"s":""}`;case"write_file":return`wrote ${e} file${e>1?"s":""}`;case"edit_file":return`edited ${e} file${e>1?"s":""}`;default:return`ran ${e} ${s}${e>1?"s":""}`}}function El(s){const e=Object.entries(s.toolCounts).filter(([,r])=>r>0).sort((r,o)=>o[1]-r[1]),t=s.headline||`Thought for ${kn(Math.max(1,Math.round(s.durationMs/1e3)))}`,n=e.map(([r,o])=>Nr(r,o));return n.length>0?`${t}, ${n.join(", ")}`:t}function Pl(s,e){const t=s.toLowerCase();return/\b(rm|del|delete|drop|truncate|format|mkfs)\b/.test(t)?"critical":/\b(bash|shell|exec|cmd|powershell|terminal)\b/.test(t)?/\b(rm\s+-rf|sudo|chmod\s+777|curl.*\|\s*(ba)?sh|wget.*-O|>\/dev\/|mkfs)\b/i.test(e)?"critical":"high":/\b(write|edit|save|upload|deploy|publish)\b/i.test(t)||/\b(install|uninstall|npm|pip|cargo|gem|apt|brew|choco|yum|dnf)\b/i.test(t)?"high":/\b(git|commit|push|merge|rebase)\b/i.test(t)?/\b(push|force|hard\s*reset|rebase)\b/i.test(e)?"high":"medium":/\b(http|fetch|curl|wget|api|request|download)\b/i.test(t)?"medium":/\b(read|open|list|ls|dir|cat|view|search|find|grep|glob)\b/i.test(t)?"low":"medium"}function jl(s,e){if(e==null)return null;if(/\b(bash|shell|exec|cmd|powershell|terminal)\b/i.test(s))return e||null;if(/\b(write|edit|save|create)\b/i.test(s)){const t=e.match(/(?:file_path|path|file)["\s:=]+([^\s",}]+)/i);return t?`${t[1]}
|
|
3
|
+
${e.slice(0,200)}`:e.slice(0,200)||null}return e&&e.length>0?e.length>200?`${e.slice(0,200)}...`:e:null}Sr.map(s=>s.eventType);function Br(){return`err-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}const De=pe(s=>({errors:[],push:(e,t,n,r)=>{const o=Br(),a={id:o,level:e,title:t,detail:n,action:r,timestamp:Date.now(),dismissed:!1};return s(i=>({errors:[...i.errors.slice(-49),a]})),o},dismiss:e=>s(t=>({errors:t.errors.map(n=>n.id===e?{...n,dismissed:!0}:n)})),clearAll:()=>s({errors:[]})})),te={info:(s,e)=>De.getState().push("info",s,e),warn:(s,e)=>De.getState().push("warning",s,e),error:(s,e)=>De.getState().push("error",s,e),critical:(s,e)=>De.getState().push("critical",s,e)},Je=20,Ar=()=>{const s=window.location.protocol==="https:"?"wss:":"ws:",e=window.location.hostname,t=window.location.port,n=t?String(Number(t)+1):"",r=n?`${e}:${n}`:e;return`${s}//${r}/ws`},Er=Ar();class Pr{constructor(e){ee(this,"ws",null);ee(this,"url");ee(this,"messageHandlers",new Set);ee(this,"openHandlers",new Set);ee(this,"closeHandlers",new Set);ee(this,"errorHandlers",new Set);ee(this,"reconnectAttempts",0);ee(this,"reconnectHandlers",new Set);ee(this,"reconnectSuccessHandlers",new Set);ee(this,"reconnectGiveUpHandlers",new Set);ee(this,"isManualClose",!1);ee(this,"authenticated",!1);ee(this,"sessionId",null);ee(this,"heartbeatInterval",null);ee(this,"reconnectTimer",null);ee(this,"lastPongTime",0);ee(this,"HEARTBEAT_INTERVAL",15e3);ee(this,"HEARTBEAT_TIMEOUT",45e3);this.url=e||Er}setSessionId(e){this.sessionId=e}getSessionId(){return this.sessionId}getReconnectState(){var e;return{attempts:this.reconnectAttempts,maxAttempts:Je,reconnecting:this.reconnectAttempts>0&&((e=this.ws)==null?void 0:e.readyState)!==WebSocket.OPEN}}onReconnectAttempt(e){return this.reconnectHandlers.add(e),()=>this.reconnectHandlers.delete(e)}onReconnectSuccess(e){return this.reconnectSuccessHandlers.add(e),()=>this.reconnectSuccessHandlers.delete(e)}onReconnectGiveUp(e){return this.reconnectGiveUpHandlers.add(e),()=>this.reconnectGiveUpHandlers.delete(e)}connect(){var t,n;if(((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN||((n=this.ws)==null?void 0:n.readyState)===WebSocket.CONNECTING)return;this.isManualClose=!1;const e=this.sessionId?`${this.url}?sessionId=${encodeURIComponent(this.sessionId)}`:this.url;this.ws=new WebSocket(e),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{var o;console.log("WebSocket connected");const r=this.reconnectAttempts>0;this.reconnectAttempts=0,this.lastPongTime=Date.now(),r&&this.reconnectSuccessHandlers.forEach(a=>a()),((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"})),this.startHeartbeat(),this.openHandlers.forEach(a=>a())},this.ws.onclose=()=>{console.log("WebSocket closed"),this.stopHeartbeat(),this.closeHandlers.forEach(r=>r()),this.isManualClose||this.scheduleReconnect()},this.ws.onerror=r=>{te.error("WebSocket connection error",r.message||"Connection failed"),this.errorHandlers.forEach(o=>o())},this.ws.onmessage=r=>{this._onMessage(r)}}async _onMessage(e){var t,n;try{let r;if(e.data instanceof Blob?r=await e.data.text():e.data instanceof ArrayBuffer?r=new TextDecoder().decode(e.data):typeof e.data=="string"?r=e.data:r=String(e.data),r=r.trim(),!r)return;const o=JSON.parse(r);if(console.log("[WS←]",o.type,o.sessionId,JSON.stringify(o.data||o.message||"").slice(0,200)),(o.type==="pong"||o.type==="ping")&&(this.lastPongTime=Date.now(),o.type==="pong"))return;o.seq!==void 0&&o.seq>=0&&this.send({type:"message_ack",data:JSON.stringify({seq:o.seq})}),this.messageHandlers.forEach(a=>a(o))}catch(r){const o=((n=(t=e.data)==null?void 0:t.constructor)==null?void 0:n.name)||typeof e.data;let a;if(e.data instanceof Blob?a=`[Blob ${e.data.size} bytes]`:e.data instanceof ArrayBuffer?a=`[ArrayBuffer ${e.data.byteLength} bytes]`:a=String(e.data).slice(0,500),typeof e.data=="string"&&e.data.trim()){const i=e.data.trim();try{this.messageHandlers.forEach(l=>l({type:"log",data:JSON.stringify({level:"info",message:i})}));return}catch{}}te.error("Failed to parse WebSocket message",`type=${o} data=${a} error=${r}`)}}startHeartbeat(){this.stopHeartbeat(),this.lastPongTime=Date.now(),this.heartbeatInterval=setInterval(()=>{var e,t;if(Date.now()-this.lastPongTime>this.HEARTBEAT_TIMEOUT){console.warn("[WS] Heartbeat timeout, reconnecting..."),this.stopHeartbeat(),this.isManualClose=!0,(e=this.ws)==null||e.close(),this.ws=null,this.scheduleReconnect();return}((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.send({type:"ping"})},this.HEARTBEAT_INTERVAL)}stopHeartbeat(){this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null)}scheduleReconnect(){if(this.reconnectAttempts++,this.reconnectAttempts>Je){console.error(`[WS] Max reconnect attempts (${Je}) reached — giving up.`),te.error("WebSocket",`Connection lost — max reconnect attempts (${Je}) reached. Refresh the page to try again.`),this.reconnectGiveUpHandlers.forEach(r=>r());return}const e=Math.min(3e3*Math.pow(2,this.reconnectAttempts),3e4),t=Math.random()*1e3-500,n=Math.max(100,Math.round(e+t));console.log(`[WS] Reconnecting... Attempt ${this.reconnectAttempts}, delay=${n}ms`),this.reconnectHandlers.forEach(r=>r(this.reconnectAttempts,Je)),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.connect()},n)}disconnect(){var e;this.isManualClose=!0,this.reconnectAttempts=0,this.stopHeartbeat(),this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),(e=this.ws)==null||e.close(),this.ws=null}send(e){var t,n;if(((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN){const r=JSON.stringify(e);console.log("[WS→]",e.type,e.sessionId,r.slice(0,200)),this.ws.send(r)}else console.warn("[WS] NOT CONNECTED — dropping:",e.type,e.sessionId,"readyState=",(n=this.ws)==null?void 0:n.readyState)}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onOpen(e){return this.openHandlers.add(e),()=>this.openHandlers.delete(e)}onClose(e){return this.closeHandlers.add(e),()=>this.closeHandlers.delete(e)}onError(e){return this.errorHandlers.add(e),()=>this.errorHandlers.delete(e)}get isConnected(){var e;return((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN}setToken(e){try{sessionStorage.setItem("auth_token",e)}catch{}}get isAuthenticated(){return this.authenticated}setAuthenticated(e){this.authenticated=e}}const I=new Pr,Be=pe()(Ue((s,e)=>({pendingApprovals:[],autoMode:!1,sessionAllowList:[],showConfigHint:!0,addApproval:t=>s(n=>({pendingApprovals:[...n.pendingApprovals,t]})),removeApproval:t=>s(n=>({pendingApprovals:n.pendingApprovals.filter(r=>r.approvalId!==t)})),clearApprovals:()=>s({pendingApprovals:[]}),setAutoMode:t=>s({autoMode:t}),addToSessionAllowList:t=>s(n=>n.sessionAllowList.includes(t)?n:{sessionAllowList:[...n.sessionAllowList,t]}),isSessionAllowed:t=>e().sessionAllowList.includes(t),setShowConfigHint:t=>s({showConfigHint:t})}),{name:"deepseekcode-hook-approval",partialize:s=>({autoMode:s.autoMode,showConfigHint:s.showConfigHint})}));function jr(s){if(!s)return 0;const e=(s.match(/[\u4e00-\u9fff]/g)||[]).length,t=s.length-e;return Math.ceil(e*1.5+t*.25)}const J=pe((s,e)=>({currentUsage:{promptTokens:0,completionTokens:0,totalTokens:0,estimatedCost:0},maxContextTokens:1e6,degradation:null,compactingUntil:0,lastCompactInfo:null,compactionProgress:null,showTokenInfo:!1,model:"",history:[],_hasBackendData:!1,tokenRate:0,sessionBaseTotal:0,workflowTokens:0,_lastTotal:0,_lastTotalTs:0,contextDistribution:null,thresholdWarning:null,retryState:null,setContextDistribution:t=>s({contextDistribution:t}),setThresholdWarning:t=>s({thresholdWarning:t}),setRetryState:t=>s({retryState:t}),updateUsage:t=>s(n=>{const r=t.totalTokens??n.currentUsage.totalTokens,o=Date.now(),a=n._lastTotal,i=n._lastTotalTs;let l=n.tokenRate;if(i>0&&a>0&&o>i&&r>a){const c=r-a,d=(o-i)/1e3,p=c/d;l=l>0?l*.6+p*.4:p}return{currentUsage:{...n.currentUsage,...t},_hasBackendData:!0,tokenRate:l,_lastTotal:r,_lastTotalTs:o}}),setModel:t=>s({model:t}),addWorkflowTokens:t=>s(n=>({workflowTokens:n.workflowTokens+(Number(t)||0)})),setMaxContextTokens:t=>s({maxContextTokens:t}),setDegradation:t=>s({degradation:t}),setCompacting:t=>s({compactingUntil:Date.now()+3e3,lastCompactInfo:t}),setCompactionProgress:t=>s({compactionProgress:t}),setShowTokenInfo:t=>s({showTokenInfo:t}),addToHistory:t=>s(n=>({history:[...n.history.slice(-100),{timestamp:Date.now(),usage:t}]})),estimateTokens:t=>jr(t),recalculateFromMessages:t=>{if(!t||t.length===0){s({currentUsage:{promptTokens:0,completionTokens:0,totalTokens:0,estimatedCost:0},_hasBackendData:!1});return}const n=e().estimateTokens;let r=0,o=0;for(const l of t){let c=l.content||"";if(l.thinking&&(c+=" "+l.thinking),l.steps)for(const p of l.steps)p.thought&&(c+=" "+p.thought),p.action&&(c+=" "+p.action),p.result&&(c+=" "+p.result);if(l.toolCalls)for(const p of l.toolCalls)p.args&&(c+=" "+(typeof p.args=="string"?p.args:JSON.stringify(p.args)));const d=n(c);l.type==="user"?r+=d:o+=d}const a=r+o,i=r/1e6*.15+o/1e6*.6;s({currentUsage:{promptTokens:r,completionTokens:o,totalTokens:a,estimatedCost:i}})},resetUsage:()=>s(t=>({currentUsage:{promptTokens:0,completionTokens:0,totalTokens:0,estimatedCost:0},_hasBackendData:!1,sessionBaseTotal:t.currentUsage.totalTokens,workflowTokens:0,tokenRate:0,_lastTotal:0,_lastTotalTs:0,contextDistribution:null,thresholdWarning:null}))})),Sn="";function Rr(s){return`${Sn}${s}`}class Lr{constructor(e){ee(this,"baseUrl");this.baseUrl=e}async request(e,t={}){try{const n=localStorage.getItem("auth_token"),r={"Content-Type":"application/json",...t.headers};n&&(r.Authorization=`Bearer ${n}`);const o=await fetch(`${this.baseUrl}${e}`,{headers:r,...t}),a=await o.json();return o.ok?a&&typeof a.success=="boolean"?{success:a.success,data:a.data,error:a.error}:{success:!0,data:a}:{success:!1,error:a.error||`HTTP ${o.status}`}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Network error"}}}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:t?JSON.stringify(t):void 0})}put(e,t){return this.request(e,{method:"PUT",body:t?JSON.stringify(t):void 0})}delete(e,t){return this.request(e,{method:"DELETE",body:t?JSON.stringify(t):void 0})}patch(e,t){return this.request(e,{method:"PATCH",body:t?JSON.stringify(t):void 0})}}const k=new Lr(Sn),q={providers:{presets:()=>k.get("/api/providers/presets"),refresh:()=>k.post("/api/providers/refresh")},models:{list:async()=>{var e;const s=await k.get("/api/models");return s.success&&((e=s.data)!=null&&e.models)&&(s.data.models=s.data.models.map(t=>({...t,isGlobalDefault:t.isDefault===!0,isPlanDefault:t.defaultFor==="plan",isActDefault:t.defaultFor==="act",isGoalDefault:t.defaultFor==="goal"}))),s},get:s=>k.get(`/api/models/${s}`),create:s=>k.post("/api/models",s),update:(s,e,t)=>k.post("/api/models/update",{provider:s,modelId:e,...t}),delete:(s,e)=>k.post("/api/models/delete",{provider:s,modelId:e}),test:s=>k.post(`/api/models/${s}/test`),fetch:(s,e)=>k.post("/api/models/fetch",{baseUrl:s,apiKey:e}),toggle:(s,e)=>k.post("/api/models/toggle",{provider:s,modelId:e}),setDefaults:s=>k.post("/api/models/defaults",s)},tools:{list:()=>k.get("/api/tools"),get:s=>k.get(`/api/tools/${s}`),update:(s,e)=>k.put(`/api/tools/${s}`,e),toggle:(s,e)=>k.post(`/api/tools/${s}/toggle`,{enabled:e})},skills:{list:()=>k.get("/api/skills"),get:s=>k.get(`/api/skills/${s}`),create:s=>k.post("/api/skills",s),update:(s,e)=>k.put(`/api/skills/${s}`,e),toggle:(s,e)=>k.post(`/api/skills/${s}/toggle`,{enabled:e}),import:s=>k.post("/api/skills/import",s)},agents:{list:()=>k.get("/api/agents"),get:s=>k.get(`/api/agents/${s}`),create:s=>k.post("/api/agents",s),update:(s,e)=>k.put(`/api/agents/${s}`,e),delete:s=>k.delete(`/api/agents/${s}`),setActive:s=>k.post(`/api/agents/${s}/activate`),toggle:(s,e)=>k.post(`/api/agents/${s}/toggle`,{enabled:e}),setModelBinding:(s,e)=>k.post(`/api/agents/${s}/model`,e)},files:{list:s=>k.get(`/api/files${s?`?path=${encodeURIComponent(s)}`:""}`),read:s=>k.get(`/api/files/read?path=${encodeURIComponent(s)}`),create:(s,e)=>k.post("/api/files",{path:s,content:e}),update:(s,e)=>k.put("/api/files/write",{path:s,content:e}),delete:s=>k.delete(`/api/files?path=${encodeURIComponent(s)}`),download:async s=>{try{const e={},t=localStorage.getItem("auth_token");t&&(e.Authorization=`Bearer ${t}`);const n=await fetch(Rr(`/api/files/download?path=${encodeURIComponent(s)}`),{headers:e});if(!n.ok){let i=`HTTP ${n.status}`;try{const l=await n.json();l!=null&&l.error&&(i=l.error)}catch{}return{success:!1,error:i}}const r=await n.blob(),o=URL.createObjectURL(r),a=document.createElement("a");return a.href=o,a.download=s.split(/[\\/]/).pop()||"download",a.click(),URL.revokeObjectURL(o),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Download failed"}}},upload:async(s,e)=>{try{const t=await Mr(s);return k.post("/api/files/upload",{path:e,content:t,base64:!0})}catch(t){return{success:!1,error:t instanceof Error?t.message:"Upload failed"}}}},sessions:{list:()=>k.get("/api/sessions"),get:s=>k.get(`/api/sessions/${s}`),create:s=>k.post("/api/sessions",{title:s}),delete:s=>k.delete(`/api/sessions/${s}`)},tasks:{list:()=>k.get("/api/tasks"),get:s=>k.get(`/api/tasks/${s}`),create:s=>k.post("/api/tasks",s),update:(s,e)=>k.put(`/api/tasks/${s}`,e),updateStatus:(s,e)=>k.patch(`/api/tasks/${s}/status`,{status:e}),delete:s=>k.delete(`/api/tasks/${s}`),clearCompleted:()=>k.delete("/api/tasks")},config:{provider:{get:()=>k.get("/api/config/provider"),save:s=>k.post("/api/config/provider",s),delete:s=>k.post("/api/config/provider/remove",{provider:s}),setDefault:s=>k.post("/api/config/provider",{provider:s,setDefault:!0})},files:{list:()=>k.get("/api/config/files"),read:s=>k.get(`/api/config/files/read?file=${encodeURIComponent(s)}`),write:(s,e)=>k.put("/api/config/files/write",{file:s,content:e})}},git:{status:()=>k.get("/api/git/status"),branches:()=>k.get("/api/git/branches"),commit:s=>k.post("/api/git/commit",s),push:()=>k.post("/api/git/push"),checkout:s=>k.post("/api/git/checkout",{branch:s}),prStatus:()=>k.get("/api/repos/pr")},fileJob:{parse:s=>k.post("/api/filejob/parse",{files:s}),parsePaths:s=>k.post("/api/filejob/parse",{paths:s}),importPaths:s=>k.post("/api/filejob/import",{paths:s}),render:s=>k.post("/api/filejob/render",s)},system:{status:()=>k.get("/api/system/status"),restart:()=>k.post("/api/system/restart"),shutdown:()=>k.post("/api/system/shutdown")},observability:{summary:()=>k.get("/api/observability/summary"),costs:()=>k.get("/api/observability/costs"),listRuns:()=>k.get("/api/observability/runs"),getRun:s=>k.get(`/api/observability/runs/${encodeURIComponent(s)}`),getRunEvents:(s,e=0,t=50)=>k.get(`/api/observability/runs/${encodeURIComponent(s)}/events?page=${e}&size=${t}`)},plans:{list:()=>k.get("/api/plans"),read:s=>k.get(`/api/plans/${encodeURIComponent(s)}`),delete:s=>k.delete(`/api/plans/${encodeURIComponent(s)}`)},logs:{list:()=>k.get("/api/logs"),read:(s,e)=>k.get(`/api/logs/read?file=${encodeURIComponent(s)}${e?`&maxLines=${e}`:""}`),downloadUrl:s=>`/api/logs/download?file=${encodeURIComponent(s)}`},hooks:{list:()=>k.get("/api/hooks/rules"),get:s=>k.get(`/api/hooks/rules/${encodeURIComponent(s)}`),create:s=>k.post("/api/hooks/rules",s),update:(s,e)=>k.put(`/api/hooks/rules/${encodeURIComponent(s)}`,e),delete:s=>k.delete(`/api/hooks/rules/${encodeURIComponent(s)}`),batchDelete:s=>k.post("/api/hooks/rules/batch-delete",{names:s}),toggle:(s,e)=>k.patch(`/api/hooks/rules/${encodeURIComponent(s)}/toggle`,{enabled:e}),batchToggle:(s,e)=>k.post("/api/hooks/rules/batch-toggle",{names:s,enabled:e}),dryRun:s=>k.post("/api/hooks/dry-run",s),stats:()=>k.get("/api/hooks/stats"),events:()=>k.get("/api/hooks/events"),agents:()=>k.get("/api/hooks/agents"),export:()=>k.get("/api/hooks/export"),import:s=>k.post("/api/hooks/import",s)},channels:{list:()=>k.get("/api/channels"),create:s=>k.post("/api/channels",s),update:(s,e)=>k.put(`/api/channels/${encodeURIComponent(s)}`,e),delete:s=>k.delete(`/api/channels/${encodeURIComponent(s)}`),toggle:(s,e)=>k.patch(`/api/channels/${encodeURIComponent(s)}/toggle`,{enabled:e}),test:s=>k.post(`/api/channels/${encodeURIComponent(s)}/test`),wechat:{qrcode:(s,e)=>k.get(`/api/channels/${encodeURIComponent(s)}/wechat/qrcode?token=${encodeURIComponent(e)}`),qrcodeStatus:(s,e,t)=>k.get(`/api/channels/${encodeURIComponent(s)}/wechat/qrcode/status?token=${encodeURIComponent(e)}&qrcode=${encodeURIComponent(t)}`)},weixin:{bind:()=>k.get("/api/weixin/bind"),bindStatus:s=>k.get(`/api/weixin/bind/status?qrcode=${encodeURIComponent(s)}`)}},inbox:{list:s=>k.get(`/api/inbox?${new URLSearchParams(s).toString()}`),stats:()=>k.get("/api/inbox/stats"),resolve:(s,e)=>k.post(`/api/inbox/${encodeURIComponent(s)}/resolve`,{resolution:e})},audit:{query:s=>k.get(`/api/audit?${new URLSearchParams(Object.fromEntries(Object.entries(s||{}).map(([e,t])=>[e,String(t)]))).toString()}`),stats:()=>k.get("/api/audit/stats")},automations:{list:()=>k.get("/api/automations"),create:s=>k.post("/api/automations",s),update:(s,e)=>k.put(`/api/automations/${encodeURIComponent(s)}`,e),remove:s=>k.delete(`/api/automations/${encodeURIComponent(s)}`),toggle:(s,e)=>k.post(`/api/automations/${encodeURIComponent(s)}/toggle`,{enabled:e}),run:s=>k.post(`/api/automations/${encodeURIComponent(s)}/run`),runs:s=>k.get(`/api/automations/${encodeURIComponent(s)}/runs`),addPermission:(s,e,t)=>k.post(`/api/automations/${encodeURIComponent(s)}/permissions`,{tool:e,target:t}),revokePermission:(s,e)=>k.delete(`/api/automations/${encodeURIComponent(s)}/permissions`,{entry:e})}};function Mr(s){return new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const r=n.result,o=r.indexOf(",");e(o>=0?r.slice(o+1):r)},n.onerror=()=>t(n.error||new Error("Failed to read file")),n.readAsDataURL(s)})}const Ir=Object.freeze(Object.defineProperty({__proto__:null,api:q,apiClient:k,default:q},Symbol.toStringTag,{value:"Module"})),Dt=s=>s==="normal"?"act":s;let yt=0;const Or=s=>s==="normal"?"normal":s==="auto"?"auto-act":_r(typeof s=="string"?s:void 0),Ye=s=>s==="normal"?"act":$e(s)?"auto":ve(s),Nt=pe()(Ue((s,e)=>({mode:"act",currentPlanContent:null,modeHistory:[],thinkingStatusBySession:{},prePlanMode:null,setMode:t=>{const n=e().mode;if(n===t)return;s(i=>({mode:t,modeHistory:[...i.modeHistory,{previousMode:n,newMode:t,description:`Mode changed: ${n} -> ${t}`,timestamp:Date.now()}]})),Be.getState().setAutoMode(t!=="normal"&&$e(t));const r=Ye(n),o=Ye(t);if(r===o)return;try{const i=V.getState().activeSessionId||I.getSessionId();i&&I.send({type:"plan_mode_change",sessionId:i,data:JSON.stringify({previousMode:Ye(n),newMode:Ye(t),frontendMode:t,timestamp:Date.now()})})}catch(i){console.warn("[ExecutionModeStore] Failed to notify mode change via WS:",i)}const a=++yt;q.models.list().then(i=>{var f;if(a!==yt||!i.success||!((f=i.data)!=null&&f.models))return;const l=i.data.models.filter(m=>m.enabled!==!1),c=ve(Dt(t)),d=l.find(m=>m.defaultFor===c),p=l.find(m=>m.isDefault||m.defaultFor==="global"),h=(d==null?void 0:d.id)||(p==null?void 0:p.id)||"";h&&J.getState().setModel(h)}).catch(i=>{console.warn("[ExecutionModeStore] Failed to refresh models:",i)})},applyBackendMode:t=>{const n=e().mode;if(n===t)return;s(o=>({mode:t,prePlanMode:t!=="plan"?null:o.prePlanMode,modeHistory:[...o.modeHistory,{previousMode:n,newMode:t,description:`Backend mode changed: ${n} -> ${t}`,timestamp:Date.now()}]})),Be.getState().setAutoMode(t!=="normal"&&$e(t));const r=++yt;q.models.list().then(o=>{var p;if(r!==yt||!o.success||!((p=o.data)!=null&&p.models))return;const a=o.data.models.filter(h=>h.enabled!==!1),i=ve(Dt(t)),l=a.find(h=>h.defaultFor===i),c=a.find(h=>h.isDefault||h.defaultFor==="global"),d=(l==null?void 0:l.id)||(c==null?void 0:c.id)||"";d&&J.getState().setModel(d)}).catch(o=>{console.warn("[ExecutionModeStore] Failed to refresh models after backend mode change:",o)})},toggleMode:()=>{const t=e().mode,n=t==="normal"?"act":wr(t);e().setMode(n)},setBaseMode:t=>{const n=e().mode,r=n!=="normal"&&$e(n);e().setMode(ns(t,r))},setAuto:t=>{e().setMode(ns(ve(Dt(e().mode)),t))},toggleAuto:()=>{const t=e().mode;e().setMode(t==="normal"?"auto-act":vr(t))},enterPlanMode:(t,n)=>{const r=e().mode,o=r!=="normal"&&ve(r)!=="plan"?r:e().prePlanMode,a=r!=="normal"&&ve(r)==="goal"?"goal":"plan";s(i=>({mode:a,prePlanMode:o,modeHistory:[...i.modeHistory,{previousMode:r,newMode:a,description:`Enter ${a} mode: ${n}`,timestamp:Date.now()}]})),Be.getState().setAutoMode(!1)},exitPlanMode:(t,n)=>{const r=e().mode,o=e().prePlanMode,a=o&&(o==="normal"||ve(o)!=="plan")?o:"act";s(i=>({mode:a,prePlanMode:null,modeHistory:[...i.modeHistory,{previousMode:r,newMode:a,description:`Exit to ${a} mode: ${n}`,timestamp:Date.now()}]})),Be.getState().setAutoMode(a!=="normal"&&$e(a))},enterGoalMode:(t,n)=>{const r=e().mode;s(o=>({mode:"goal",modeHistory:[...o.modeHistory,{previousMode:r,newMode:"goal",description:`Enter Goal mode: ${n}`,timestamp:Date.now()}]})),Be.getState().setAutoMode(!1);try{const o=V.getState().activeSessionId||I.getSessionId()||void 0;I.send({type:"plan_mode_change",sessionId:o,data:JSON.stringify({previousMode:Ye(r),newMode:"goal",frontendMode:"goal",goalDescription:n,timestamp:Date.now()})})}catch(o){console.warn("[ExecutionModeStore] Failed to notify goal mode change via WS:",o)}},exitGoalMode:()=>{const t=e().mode;s(n=>({mode:"act",modeHistory:[...n.modeHistory,{previousMode:t,newMode:"act",description:"Exit Goal mode",timestamp:Date.now()}]})),Be.getState().setAutoMode(!1)},setPlanContent:t=>s({currentPlanContent:t}),setThinkingStatus:(t,n)=>s(r=>({thinkingStatusBySession:{...r.thinkingStatusBySession,[t]:n}})),getThinkingStatus:t=>e().thinkingStatusBySession[t]||"",reset:()=>s({mode:"act",currentPlanContent:null,modeHistory:[],thinkingStatusBySession:{},prePlanMode:null})}),{name:"deepseekcode-plan-storage",version:1,migrate:s=>s,merge:(s,e)=>{const t=s??{};return{...e,...t,mode:Or(t.mode)}},partialize:s=>({mode:s.mode,currentPlanContent:s.currentPlanContent,modeHistory:s.modeHistory})})),$r={info:"bg-accent-blue",warn:"bg-accent-yellow",error:"bg-accent-red",success:"bg-accent-green",tool:"bg-accent-purple"};function Dr(s){return s==null||s===""?"-":new Date(s).toLocaleString()}function Fr(){const[s,e]=g.useState([]),[t,n]=g.useState(!0),[r,o]=g.useState(null),[a,i]=g.useState(null),[l,c]=g.useState(!1),d=g.useCallback(async()=>{n(!0);try{const m=await q.logs.list();m.success&&Array.isArray(m.data)&&e(m.data)}catch(m){console.error("Failed to load log files:",m)}n(!1)},[]);g.useEffect(()=>{d()},[d]);const p=g.useCallback(async m=>{if(!m.previewable)return;o(m),c(!0);const y=await q.logs.read(m.name,500);y.success&&y.data&&i(y.data),c(!1)},[]),h=g.useCallback(()=>{o(null),i(null)},[]),f=m=>m<1024?`${m} B`:m<1024*1024?`${(m/1024).toFixed(1)} KB`:`${(m/(1024*1024)).toFixed(1)} MB`;return r&&a?u.jsxs("div",{className:"flex flex-col min-h-0 h-full",children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 shrink-0",children:[u.jsx("button",{onClick:h,className:"p-1 rounded hover:bg-dark-hover transition-colors",title:"返回文件列表",children:u.jsx(Vn,{size:16})}),u.jsx("span",{className:"text-sm font-medium text-dark-text truncate flex-1",children:r.name}),u.jsxs("a",{href:q.logs.downloadUrl(r.name),download:r.name,className:"flex items-center gap-1 px-2 py-1 text-xs bg-accent-blue text-white rounded hover:opacity-90 transition-opacity",children:[u.jsx(Yt,{size:12}),"下载"]})]}),l?u.jsx("div",{className:"flex-1 flex items-center justify-center",children:u.jsx(wt,{size:20,className:"animate-spin text-accent-blue"})}):u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"text-[10px] text-dark-muted mb-1 shrink-0",children:[f(a.size)," · ",a.totalLines," 行",a.startLine>1&&` (显示最新 ${a.totalLines-a.startLine+1} 行)`]}),u.jsx("div",{className:`flex-1 overflow-y-auto min-h-0 font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-all
|
|
4
|
+
bg-dark-bg border border-dark-border rounded p-3 custom-scrollbar`,style:{scrollbarWidth:"thin",scrollbarColor:"#30363d transparent"},children:a.content||u.jsx("span",{className:"text-dark-muted italic",children:"(空文件)"})})]})]}):u.jsxs("div",{className:"flex flex-col min-h-0 h-full",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2 shrink-0",children:[u.jsx("span",{className:"text-xs font-medium text-dark-text",children:"日志文件"}),u.jsx("button",{onClick:d,className:"px-2 py-1 text-[10px] bg-dark-hover rounded hover:bg-dark-border transition-colors",disabled:t,children:t?"刷新中...":"刷新"})]}),t?u.jsx("div",{className:"flex items-center justify-center py-8",children:u.jsx(wt,{size:16,className:"animate-spin text-accent-blue"})}):s.length===0?u.jsxs("div",{className:"text-center py-8 text-dark-muted",children:[u.jsx(Jt,{size:32,className:"mx-auto mb-1 opacity-50"}),u.jsx("p",{className:"text-xs",children:"暂无日志文件"})]}):u.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 space-y-1 custom-scrollbar",children:s.map(m=>u.jsxs("div",{className:"flex items-center gap-2 p-2 rounded hover:bg-dark-hover transition-colors group",children:[u.jsx(Jt,{size:14,className:"text-accent-blue shrink-0"}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("div",{className:"text-xs text-dark-text truncate",children:m.name}),u.jsxs("div",{className:"text-[10px] text-dark-muted",children:[f(m.size)," · ",Dr(m.modified)]})]}),u.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[m.previewable&&u.jsx("button",{onClick:()=>p(m),className:"p-1.5 rounded hover:bg-dark-border transition-colors",title:"预览",children:u.jsx(Jn,{size:14})}),u.jsx("a",{href:q.logs.downloadUrl(m.name),download:m.name,className:"p-1.5 rounded hover:bg-dark-border transition-colors block",title:"下载",children:u.jsx(Yt,{size:14})})]})]},m.name))})]})}const Us=g.memo(g.forwardRef(function({logs:e},t){return u.jsx("div",{ref:t,className:"flex-1 overflow-y-auto min-h-0 font-mono text-xs space-y-0.5 custom-scrollbar",children:e.length===0?u.jsxs("div",{className:"text-center text-dark-muted py-12",children:[u.jsx(Fe,{size:48,className:"mx-auto mb-2 opacity-50"}),u.jsx("p",{children:"暂无实时日志"})]}):e.map(n=>u.jsxs("div",{className:`p-2 rounded hover:bg-dark-surface transition-colors ${n.level==="error"?"bg-accent-red/10":n.level==="warn"?"bg-accent-yellow/10":n.level==="success"?"bg-accent-green/10":""}`,children:[u.jsx("span",{className:"text-dark-muted text-xs",children:new Date(n.timestamp).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",second:"2-digit"})})," ",u.jsx("span",{className:`px-1.5 py-0.5 rounded text-white text-xs ${$r[n.level]}`,children:n.level.toUpperCase()})," ",u.jsxs("span",{className:"text-dark-muted text-xs",children:["[",n.source,"]"]})," ",u.jsx("span",{className:"text-dark-text whitespace-pre-wrap break-all",children:n.message})]},n.id))})})),vn=g.memo(function({logs:e,onClear:t,compact:n}){const[r,o]=g.useState("stream"),a=g.useRef(null),i=g.useRef(!0),l=g.useCallback(()=>{const d=a.current;return d?d.scrollHeight-d.scrollTop-d.clientHeight<50:!0},[]),c=g.useCallback(()=>{const d=a.current;d&&(d.scrollTop=d.scrollHeight)},[]);return g.useEffect(()=>{const d=a.current;if(!d)return;const p=()=>{i.current=l()};return d.addEventListener("scroll",p,{passive:!0}),()=>d.removeEventListener("scroll",p)},[l]),g.useEffect(()=>{i.current&&c()},[e,c]),n?u.jsxs("div",{className:"flex flex-col min-h-0 flex-1 p-2",children:[u.jsxs("div",{className:"flex items-center justify-between mb-2 shrink-0",children:[u.jsxs("h2",{className:"flex items-center gap-2 text-xs font-semibold",children:[u.jsx(Fe,{size:14,className:"text-accent-blue"}),"日志",u.jsxs("span",{className:"text-sm font-normal text-dark-muted",children:["(",e.length,")"]})]}),u.jsx("button",{onClick:t,className:"bg-dark-surface border border-dark-border rounded hover:bg-dark-hover transition-colors px-2 py-1 text-[10px]",children:"清空"})]}),u.jsx(Us,{ref:a,logs:e})]}):u.jsxs("div",{className:"flex flex-col min-h-0 flex-1 overflow-hidden p-4",children:[u.jsx("div",{className:"flex items-center justify-between mb-3 shrink-0",children:u.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[u.jsx(Fe,{size:18,className:"text-accent-blue"}),"后台日志"]})}),u.jsx("div",{className:"flex gap-1 mb-3 shrink-0 border-b border-dark-border",children:[["stream","实时日志流",Fe],["files","日志文件",Jt]].map(([d,p,h])=>u.jsxs("button",{onClick:()=>o(d),className:`flex items-center gap-1.5 px-4 py-2 text-sm rounded-t transition-colors border-b-2 ${r===d?"border-accent-blue text-accent-blue bg-accent-blue/5":"border-transparent text-dark-muted hover:text-dark-text hover:bg-dark-hover"}`,children:[u.jsx(h,{size:14}),p,d==="stream"&&e.length>0&&u.jsxs("span",{className:"ml-1 text-[10px] text-dark-muted",children:["(",e.length,")"]})]},d))}),r==="stream"&&u.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[u.jsx("div",{className:"flex items-center justify-end mb-2 shrink-0",children:u.jsx("button",{onClick:t,className:"bg-dark-surface border border-dark-border rounded hover:bg-dark-hover transition-colors px-3 py-1.5 text-sm",children:"清空"})}),u.jsx(Us,{ref:a,logs:e})]}),r==="files"&&u.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:u.jsx("div",{className:"border border-dark-border rounded-lg p-3 bg-dark-surface h-full",children:u.jsx(Fr,{})})})]})}),Wr=Object.freeze(Object.defineProperty({__proto__:null,LogsPanel:vn},Symbol.toStringTag,{value:"Module"})),Gs=({id:s,label:e,badge:t,isOpen:n,onToggle:r,children:o})=>u.jsxs("div",{className:"border-b border-dark-border/40 last:border-b-0",children:[u.jsxs("button",{onClick:()=>r(s),className:`w-full flex items-center gap-2 px-3 py-2.5 text-xs text-dark-text
|
|
5
|
+
hover:bg-dark-hover/50 transition-colors text-left`,children:[n?u.jsx(Bt,{size:14,className:"shrink-0 text-dark-muted"}):u.jsx(dn,{size:14,className:"shrink-0 text-dark-muted"}),u.jsx("span",{className:"font-medium truncate",children:e}),t!==void 0&&t>0&&u.jsx("span",{className:"ml-auto flex items-center justify-center min-w-[18px] h-[18px] rounded-full bg-accent-red/15 text-accent-red text-[10px] font-medium px-1",children:t>99?"99+":t})]}),u.jsx("div",{className:`grid transition-[grid-template-rows] duration-200 ease-in-out ${n?"grid-rows-[1fr]":"grid-rows-[0fr]"}`,children:u.jsx("div",{className:"overflow-hidden min-h-0",children:u.jsx("div",{className:"px-3 pb-3 pt-1",children:o})})})]});function Hr({workspaceDir:s,onWorkspaceChange:e,logs:t,onClearLogs:n}){const{t:r}=Ee(),[o,a]=g.useState(new Set(["workspace"])),i=g.useCallback(l=>{a(c=>{const d=new Set(c);return d.has(l)?d.delete(l):d.add(l),d})},[]);return u.jsxs("div",{className:"w-72 2xl:w-80 shrink-0 border-l border-dark-border bg-dark-surface flex flex-col overflow-hidden",children:[u.jsx("div",{className:"shrink-0 px-3 py-2.5 border-b border-dark-border bg-dark-surface",children:u.jsx("span",{className:"text-xs font-semibold text-dark-text",children:r("chat.panelTitle")})}),u.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar divide-y divide-dark-border/20",children:[u.jsx(Gs,{id:"workspace",label:r("chat.workingDir"),isOpen:o.has("workspace"),onToggle:i,children:u.jsxs("div",{className:"space-y-2",children:[u.jsx("div",{className:"truncate font-mono text-[11px] text-dark-muted bg-dark-bg rounded border border-dark-border px-2.5 py-2 break-all",children:s}),u.jsx("button",{onClick:e,className:"w-full text-left text-[11px] text-accent-blue px-2 py-1.5 rounded hover:bg-dark-hover transition-colors",children:r("chat.switchDir")})]})}),u.jsx(Gs,{id:"logs",label:r("chat.backgroundLogs"),badge:t.length,isOpen:o.has("logs"),onToggle:i,children:u.jsx("div",{className:"max-h-[40vh] overflow-y-auto custom-scrollbar -mx-1",children:u.jsx(vn,{logs:t,onClear:n,compact:!0})})})]})]})}const Ur=[{labelKey:"nav.groupWorkspace",ids:["chat","terminal","files"]},{labelKey:"nav.groupConfig",ids:["models","tools","skills","agents","hooks","channels"]},{labelKey:"nav.groupSystem",ids:["logs","settings"]}],Gr=[{id:"pull-requests",icon:At,labelKey:"nav.pullRequests"},{id:"scheduled",icon:as,labelKey:"nav.scheduled"},{id:"plugins",icon:Et,labelKey:"nav.plugins"}],zr=(...s)=>s.filter(Boolean).join(" "),zs=g.memo(function({collapsed:e,onToggleCollapse:t,tabs:n,activeTab:r,onTabChange:o,isConnected:a,onNewSession:i,onSwitchSession:l,onCloseSession:c,onRenameSession:d,getTabTitle:p}){const{t:h}=Ee(),f=V(B=>B.sessionTabs),m=V(B=>B.activeSessionId),y=V(B=>B.historySessions),v=V(B=>B.restoreHistorySession),C=V(B=>B.removeHistorySession),[S,T]=g.useState(!1),[_,x]=g.useState(null),[R,j]=g.useState(""),D=g.useRef(null),O=g.useMemo(()=>Ur.map(B=>({...B,tabs:B.ids.map(M=>n.find($=>$.id===M)).filter(M=>!!M)})).filter(B=>B.tabs.length>0),[n]),W=g.useCallback((B,M)=>{x(B),j(M),setTimeout(()=>{var $;return($=D.current)==null?void 0:$.select()},50)},[]),ne=g.useCallback(()=>{_&&R.trim()&&d(_,R.trim()),x(null)},[_,R,d]),N=g.useCallback((B,M)=>{var Pe;const $=G.getState().getMessages(B),P=[];P.push(`# ${M||h("nav.chat")}`),P.push(""),P.push(`> ${h("chat.exportMd")} · ${new Date().toLocaleString()}`),P.push(""),P.push("---"),P.push(""),(!$||$.length===0)&&(P.push(h("chat.noSessions")),P.push(""));for(const Z of $){if(Z.deleted)continue;const ht=Z.type==="user"?h("chat.you"):h("chat.assistantLabel");if(P.push(`## ${ht} · ${new Date(Z.timestamp).toLocaleString()}`),P.push(""),Z.thinking&&Z.thinking.trim()&&(P.push("<details>"),P.push(`<summary>💭 ${h("chat.thoughtProcess")}</summary>`),P.push(""),P.push(Z.thinking.trim()),P.push(""),P.push("</details>"),P.push("")),Z.content&&Z.content.trim()&&(P.push(Z.content.trim()),P.push("")),Z.steps&&Z.steps.length>0){P.push(`**${h("chat.runningSteps")}:**`),P.push("");for(const he of Z.steps){if(P.push(`- **${he.title}**${he.status?` (\`${he.status}\`)`:""}`),he.thought&&P.push(` - 💭 ${he.thought}`),(Pe=he.toolCalls)!=null&&Pe.length)for(const ft of he.toolCalls)P.push(` - 🛠 \`${ft.name}\``);he.result&&P.push(` - ${he.result}`)}P.push("")}P.push("---"),P.push("")}const le=new Blob([P.join(`
|
|
6
|
+
`)],{type:"text/markdown;charset=utf-8"}),ce=URL.createObjectURL(le),H=document.createElement("a");H.href=ce,H.download=`${(M||"session").replace(/[\\/:*?"<>|]/g,"_").slice(0,80)}.md`,H.click(),URL.revokeObjectURL(ce)},[h]),b=g.useCallback(B=>{v(B),I.setSessionId(B)},[v]),A=g.useCallback(B=>{l(B),r!=="chat"&&o("chat")},[l,o,r]),F=G(B=>B.generatingSessions),U=g.useCallback(B=>F.includes(B.id)?"running":B.status||"done",[F]),se=g.useMemo(()=>{const B=new Map;for(const M of f){const $=M.project||"default",P=B.get($)||[];P.push(M),B.set($,P)}return Array.from(B.entries())},[f]);return u.jsxs("div",{className:"flex h-full flex-col",children:[u.jsxs("div",{className:`flex h-14 shrink-0 items-center gap-2.5 border-b border-dark-border/70 ${e?"justify-center px-2":"px-4"}`,children:[u.jsx("img",{src:"/logo.svg",alt:"deepseekcode",className:"h-7 w-7 rounded-lg shadow-sm"}),!e&&u.jsx("span",{className:"flex-1 truncate text-[15px] font-semibold tracking-tight text-dark-text",children:"deepseekcode"}),u.jsx("button",{onClick:t,className:`rounded-md p-1.5 text-dark-muted transition-colors hover:bg-dark-hover hover:text-dark-text ${e?"hidden":""}`,title:h("nav.collapseSidebar"),"aria-label":h("nav.collapseSidebar"),children:u.jsx(Yn,{size:16,"aria-hidden":"true"})})]}),u.jsx("div",{className:e?"p-2":"px-3 pt-3",children:e?u.jsx("button",{onClick:i,className:"btn btn-primary w-full !px-0 aspect-square",title:h("chat.newSession"),"aria-label":h("chat.newSession"),children:u.jsx(Qt,{size:16,"aria-hidden":"true"})}):u.jsxs("button",{onClick:i,className:"btn btn-primary w-full",children:[u.jsx(Qt,{size:15,"aria-hidden":"true"}),h("chat.newSession")]})}),!e&&u.jsx("div",{className:"px-3 pt-2",children:u.jsx("div",{className:"flex items-center gap-1",children:Gr.map(B=>{const M=B.icon,$=r===B.id;return u.jsxs("button",{onClick:()=>o(B.id),className:zr("flex flex-1 flex-col items-center gap-1 rounded-lg border px-1 py-1.5 text-[10px] transition-colors",$?"border-accent-blue/30 text-accent-blue bg-accent-blue/10":"border-dark-border text-dark-muted hover:bg-dark-hover hover:text-dark-text"),title:h(B.labelKey),children:[u.jsx(M,{size:14,"aria-hidden":"true"}),u.jsx("span",{className:"truncate",children:h(B.labelKey)})]},B.id)})})}),u.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar px-3 pb-2 min-h-0",children:[!e&&u.jsxs("div",{className:"pt-2",children:[u.jsxs("div",{className:"side-group-label flex items-center justify-between",children:[u.jsx("span",{children:h("nav.sessions")}),y.length>0&&u.jsxs("button",{onClick:()=>T(B=>!B),className:"flex items-center gap-0.5 rounded px-1 py-0.5 text-dark-muted/70 transition-colors hover:text-dark-text",title:h("chat.sessionHistory"),"aria-expanded":S,children:[u.jsx(Ss,{size:11,"aria-hidden":"true"}),u.jsx(Bt,{size:11,"aria-hidden":"true",className:`transition-transform ${S?"":"-rotate-90"}`})]})]}),u.jsxs("div",{className:"space-y-1.5",children:[se.map(([B,M])=>u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 text-[10px] text-dark-muted/70",children:[u.jsx(Qn,{size:10,"aria-hidden":"true",className:"shrink-0 opacity-60"}),u.jsx("span",{className:"truncate",children:B==="default"?h("nav.mySessions"):B}),u.jsx("span",{className:"ml-auto text-[9px] text-dark-muted/40",children:M.length})]}),u.jsx("div",{className:"space-y-0.5",children:M.map($=>{const P=$.id===m,le=_===$.id,ce=U($);return u.jsxs("div",{onClick:()=>!le&&A($.id),onDoubleClick:()=>W($.id,$.title),className:`group flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-[7px] text-[13px] transition-colors ${P?"bg-dark-hover font-medium text-dark-text":"text-dark-muted hover:bg-dark-hover/60 hover:text-dark-text"}`,children:[u.jsx(un,{size:13,"aria-hidden":"true",className:"shrink-0 opacity-60"}),le?u.jsx("input",{ref:D,value:R,onChange:H=>j(H.target.value),onBlur:ne,onKeyDown:H=>{H.key==="Enter"?ne():H.key==="Escape"&&x(null)},onClick:H=>H.stopPropagation(),className:"min-w-0 flex-1 rounded border border-accent-blue bg-dark-bg px-1 py-0.5 text-xs text-dark-text outline-none",autoFocus:!0}):u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"flex-1 truncate",children:$.title}),ce==="running"&&u.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-red animate-pulse",title:h("nav.sessionRunning")}),ce==="waiting"&&u.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-yellow",title:h("nav.sessionWaiting")}),ce==="failed"&&u.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-red",title:h("nav.sessionFailed")}),u.jsx("button",{onClick:H=>{H.stopPropagation(),W($.id,$.title)},className:"shrink-0 rounded p-0.5 opacity-0 transition-all hover:bg-dark-bg group-hover:opacity-100",title:h("chat.renameSession"),"aria-label":h("chat.renameSession"),children:u.jsx(Xn,{size:11,"aria-hidden":"true"})}),u.jsx("button",{onClick:H=>{H.stopPropagation(),N($.id,$.title)},className:"shrink-0 rounded p-0.5 opacity-0 transition-all hover:bg-dark-bg group-hover:opacity-100",title:h("chat.exportMd"),"aria-label":h("chat.exportMd"),children:u.jsx(Yt,{size:11,"aria-hidden":"true"})}),f.length>1&&u.jsx("button",{onClick:H=>{H.stopPropagation(),c($.id)},className:"shrink-0 rounded p-0.5 opacity-0 transition-all hover:bg-dark-bg group-hover:opacity-100","aria-label":h("a11y.close"),children:u.jsx(lt,{size:12,"aria-hidden":"true"})})]})]},$.id)})})]},B)),f.length===0&&u.jsx("div",{className:"px-2.5 py-2 text-xs text-dark-muted/60",children:h("chat.noSessions")})]}),S&&y.length>0&&u.jsx("div",{className:"mt-1 space-y-0.5 border-t border-dark-border/50 pt-1",children:y.slice(0,10).map(B=>u.jsxs("div",{onClick:()=>b(B.id),className:"group flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-1.5 text-xs text-dark-muted transition-colors hover:bg-dark-hover/60 hover:text-dark-text",children:[u.jsx(Ss,{size:11,"aria-hidden":"true",className:"shrink-0 opacity-50"}),u.jsx("span",{className:"flex-1 truncate",children:B.title}),u.jsx("button",{onClick:M=>{M.stopPropagation(),C(B.id)},className:"shrink-0 rounded p-0.5 opacity-0 transition-all hover:bg-dark-bg group-hover:opacity-100","aria-label":h("chat.removeFromHistory"),children:u.jsx(lt,{size:11,"aria-hidden":"true"})})]},B.id))})]}),u.jsx("nav",{className:e?"pt-2":"",children:O.map(B=>u.jsxs("div",{children:[!e&&u.jsx("div",{className:"side-group-label",children:h(B.labelKey)}),e&&u.jsx("div",{className:"mx-2 my-2 border-t border-dark-border/60"}),u.jsx("div",{className:`space-y-0.5 ${e?"flex flex-col items-center":""}`,children:B.tabs.map(M=>{const $=r===M.id,P=M.iconComponent;return e?u.jsx("button",{onClick:()=>o(M.id),className:`flex h-9 w-9 items-center justify-center rounded-lg transition-colors ${$?"bg-accent-blue/10 text-accent-blue":"text-dark-muted hover:bg-dark-hover hover:text-dark-text"}`,title:p(M.id,M.title),"aria-label":p(M.id,M.title),"aria-current":$?"page":void 0,children:P&&u.jsx(P,{size:17,"aria-hidden":"true"})},M.id):u.jsxs("button",{onClick:()=>o(M.id),className:"side-nav-item","data-active":$,"aria-current":$?"page":void 0,children:[P&&u.jsx(P,{size:15,"aria-hidden":"true",className:"shrink-0"}),u.jsx("span",{className:"truncate",children:p(M.id,M.title)})]},M.id)})})]},B.labelKey))})]}),u.jsxs("div",{className:`shrink-0 border-t border-dark-border/70 ${e?"p-2":"p-3"}`,children:[e&&u.jsx("button",{onClick:t,className:"mb-2 flex w-full items-center justify-center rounded-md p-1.5 text-dark-muted transition-colors hover:bg-dark-hover hover:text-dark-text",title:h("nav.expandSidebar"),"aria-label":h("nav.expandSidebar"),children:u.jsx(Zn,{size:16,"aria-hidden":"true"})}),u.jsxs("div",{className:`flex items-center gap-2 text-xs text-dark-muted ${e?"justify-center":"px-1.5"}`,role:"status","aria-label":h("a11y.connectionStatus"),children:[u.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${a?"bg-accent-green":"bg-accent-red"}`,"aria-hidden":"true"}),!e&&u.jsx("span",{className:"truncate",children:h(a?"chat.connected":"chat.disconnected")})]})]})]})}),Ks=200,Kr=(s,e)=>({runId:e,sessionId:s,status:"RUNNING",completedPhases:0,totalPhases:0,completedEffects:0,totalEffects:0,tokensUsed:0,tokensRemaining:0,updatedAt:Date.now()}),Re=()=>Date.now(),Ce=(s,e)=>{const t=String(s||"").toLowerCase();return e||t==="done"||t==="success"||t==="completed"||t==="complete"?"completed":t==="running"||t==="in_progress"||t==="started"?"running":t==="failed"||t==="error"?"failed":t==="skipped"||t==="cancelled"||t==="canceled"?"skipped":"pending"},qs=s=>s.id||`${s.type||"event"}-${s.timestamp||Re()}-${Math.random().toString(36).slice(2,8)}`,ue=pe()(Ue((s,e)=>({bySession:{},byRun:{},agentsBySession:{},tasksBySession:{},eventsBySession:{},upsert:(t,n)=>s(r=>{const o=n.runId,a=r.byRun[o]||r.bySession[t]||Kr(t,o),i={...a.agentNodes||{}};n.agentNode&&(i[n.agentNode.nodeId]=n.agentNode);const{agentNode:l,...c}=n,d={...a,...c,agentNodes:i,sessionId:t,runId:o,updatedAt:Re()},p={...r.agentsBySession[t]||{}};l&&(p[l.nodeId]={...p[l.nodeId]||{},id:l.nodeId,sessionId:t,name:l.role,role:l.role,source:"workflow",runId:o,phase:l.phase,status:l.status,tokens:l.tokens,error:l.error,updatedAt:l.updatedAt||Re()});const h=n.lastEventType||n.status||"workflow_update",m=[{id:qs({type:h}),sessionId:t,type:h,source:"workflow",timestamp:Re(),status:d.status,runId:o,agentId:l==null?void 0:l.nodeId,message:d.error,data:c},...r.eventsBySession[t]||[]].slice(0,Ks);return{bySession:{...r.bySession,[t]:d},byRun:{...r.byRun,[o]:d},agentsBySession:{...r.agentsBySession,[t]:p},eventsBySession:{...r.eventsBySession,[t]:m}}}),fail:(t,n,r)=>e().upsert(t,{runId:n,status:"ERROR",error:r,lastEventType:"workflow_error"}),getForSession:t=>e().bySession[t],upsertAgent:(t,n)=>s(r=>{var i;const o=(i=r.agentsBySession[t])==null?void 0:i[n.id],a={id:n.id,sessionId:t,name:n.name||n.role||(o==null?void 0:o.name)||n.id,role:n.role||(o==null?void 0:o.role)||n.name||n.id,source:n.source||(o==null?void 0:o.source)||"agent",status:n.status||(o==null?void 0:o.status)||"idle",runId:n.runId??(o==null?void 0:o.runId),phase:n.phase??(o==null?void 0:o.phase),taskId:n.taskId??(o==null?void 0:o.taskId),currentTask:n.currentTask??(o==null?void 0:o.currentTask),tokens:n.tokens??(o==null?void 0:o.tokens),error:n.error??(o==null?void 0:o.error),updatedAt:n.updatedAt||Re()};return{agentsBySession:{...r.agentsBySession,[t]:{...r.agentsBySession[t]||{},[n.id]:a}}}}),upsertTask:(t,n)=>s(r=>{var c;const o=(c=r.tasksBySession[t])==null?void 0:c[n.id],a=Re(),i=n.status||(o==null?void 0:o.status)||"pending",l={id:n.id,sessionId:t,title:n.title||(o==null?void 0:o.title)||n.description||n.id,status:i,source:n.source||(o==null?void 0:o.source)||"task",description:n.description??(o==null?void 0:o.description),agentType:n.agentType??(o==null?void 0:o.agentType),progress:n.progress??(o==null?void 0:o.progress),result:n.result??(o==null?void 0:o.result),error:n.error??(o==null?void 0:o.error),runId:n.runId??(o==null?void 0:o.runId),dependencies:n.dependencies??(o==null?void 0:o.dependencies),startedAt:n.startedAt??(o==null?void 0:o.startedAt)??(i==="running"?a:void 0),completedAt:n.completedAt??(o==null?void 0:o.completedAt)??(i==="completed"||i==="failed"?a:void 0),createdAt:n.createdAt||(o==null?void 0:o.createdAt)||a,updatedAt:n.updatedAt||a,raw:n.raw??(o==null?void 0:o.raw)};return{tasksBySession:{...r.tasksBySession,[t]:{...r.tasksBySession[t]||{},[n.id]:l}}}}),setTasks:(t,n,r="plan")=>s(o=>{const a=o.tasksBySession[t]||{},i=Object.fromEntries(Object.entries(a).filter(([,d])=>d.source!==r)),l=Re(),c=Object.fromEntries(n.map((d,p)=>{const h=a[d.id],f=d.status||(h==null?void 0:h.status)||"pending",m={id:d.id,sessionId:t,title:d.title||(h==null?void 0:h.title)||d.description||`Task ${p+1}`,status:f,source:d.source||r,description:d.description??(h==null?void 0:h.description),agentType:d.agentType??(h==null?void 0:h.agentType),progress:d.progress??(h==null?void 0:h.progress),result:d.result??(h==null?void 0:h.result),error:d.error??(h==null?void 0:h.error),runId:d.runId??(h==null?void 0:h.runId),dependencies:d.dependencies??(h==null?void 0:h.dependencies),startedAt:d.startedAt??(h==null?void 0:h.startedAt),completedAt:d.completedAt??(h==null?void 0:h.completedAt),createdAt:d.createdAt||(h==null?void 0:h.createdAt)||l+p,updatedAt:d.updatedAt||l,raw:d.raw??(h==null?void 0:h.raw)};return[m.id,m]}));return{tasksBySession:{...o.tasksBySession,[t]:{...i,...c}}}}),recordEvent:(t,n)=>s(r=>{const o={id:qs(n),sessionId:t,type:n.type,source:n.source||"system",timestamp:n.timestamp||Re(),title:n.title,message:n.message,status:n.status,runId:n.runId,agentId:n.agentId,taskId:n.taskId,data:n.data};return{eventsBySession:{...r.eventsBySession,[t]:[o,...r.eventsBySession[t]||[]].slice(0,Ks)}}}),getAgentsForSession:t=>Object.values(e().agentsBySession[t]||{}).sort((n,r)=>r.updatedAt-n.updatedAt),getTasksForSession:t=>Object.values(e().tasksBySession[t]||{}).sort((n,r)=>{const o={running:0,pending:1,failed:2,completed:3,skipped:4};return o[n.status]-o[r.status]||n.createdAt-r.createdAt}),getEventsForSession:t=>e().eventsBySession[t]||[],getAgentTree:t=>{const n=Object.values(e().agentsBySession[t]||{}),r=new Map(n.map(l=>[l.id,l])),o=n.filter(l=>!l.parentId||!r.has(l.parentId)),a=l=>n.filter(c=>c.parentId===l),i=l=>({agent:l,children:a(l.id).map(i),isRunning:l.status==="running",tokensUsed:l.tokens||0});return o.map(i)},getRunningAgentCount:t=>Object.values(e().agentsBySession[t]||{}).filter(r=>r.status==="running").length}),{name:"deepseekcode-workflow-store",partialize:s=>({bySession:s.bySession,byRun:s.byRun,agentsBySession:s.agentsBySession,tasksBySession:s.tasksBySession,eventsBySession:s.eventsBySession})})),qr=s=>{if(s==null||s==="")return{};if(typeof s!="string")return s;try{return JSON.parse(s)}catch{return s}},Qe=(s,e="")=>typeof s=="string"?s:String((s==null?void 0:s.content)||(s==null?void 0:s.message)||(s==null?void 0:s.text)||(s==null?void 0:s.error)||e||""),Vr=s=>Array.isArray(s)?s:Array.isArray(s==null?void 0:s.tasks)?s.tasks:Array.isArray(s==null?void 0:s.items)?s.items:Array.isArray(s==null?void 0:s.planTasks)?s.planTasks:[],Vs=(s,e,t=0)=>{const n=String(s.id||s.taskId||s.backendId||`plan-task-${t+1}`),r=Ce(s.status||s.planStatus,s.completed),o=Date.now()+t;return{id:n,sessionId:e,title:String(s.title||s.name||s.content||s.description||`Task ${t+1}`),description:s.description||s.details||s.content,status:r,source:"plan",agentType:s.agentType||s.agent||s.role,progress:s.progress!=null?Number(s.progress):void 0,result:s.result,error:s.error,dependencies:Array.isArray(s.dependencies)?s.dependencies.map(String):void 0,startedAt:s.startedAt?Number(s.startedAt):r==="running"?o:void 0,completedAt:s.completedAt?Number(s.completedAt):r==="completed"||r==="failed"?o:void 0,createdAt:s.createdAt&&Number(s.createdAt)||o,updatedAt:o,raw:s}},Js=(s,e,t=0)=>{const n=String(s.id||s.taskId||s.backendId||`goal-task-${t+1}`),r=Ce(s.status),o=Date.now()+t;return{id:n,sessionId:e,title:String(s.title||s.name||s.content||s.description||`Task ${t+1}`),description:s.description||s.details||s.content,status:r,source:"goal",agentType:s.agentType||s.agent||s.role,progress:s.progress!=null?Number(s.progress):void 0,result:s.result,error:s.error,dependencies:Array.isArray(s.parentIds)?s.parentIds.map(String):void 0,startedAt:s.startedAt?Number(s.startedAt):r==="running"?o:void 0,completedAt:s.completedAt?Number(s.completedAt):r==="completed"||r==="failed"?o:void 0,createdAt:s.createdAt&&Number(s.createdAt)||o,updatedAt:s.updatedAt?Number(s.updatedAt):o,raw:s}},Jr=(s,e)=>{const t=String((e==null?void 0:e.taskId)||(e==null?void 0:e.id)||"");if(!t)return;const n=ue.getState().getTasksForSession(s).find(i=>i.id===t),r=V.getState().getSessionTasks(s).find(i=>i.id===t||i.backendId===t),o=e!=null&&e.status?Ce(e.status):(n==null?void 0:n.status)||"pending",a={id:t,sessionId:s,title:(e==null?void 0:e.title)||(n==null?void 0:n.title)||(r==null?void 0:r.title)||t,description:(e==null?void 0:e.description)??(n==null?void 0:n.description)??(r==null?void 0:r.description),status:o,source:"goal",agentType:(e==null?void 0:e.agentType)||(n==null?void 0:n.agentType),progress:(e==null?void 0:e.progress)!=null?Number(e.progress):n==null?void 0:n.progress,result:(e==null?void 0:e.result)??(n==null?void 0:n.result),error:(e==null?void 0:e.error)??(n==null?void 0:n.error),startedAt:o==="running"?Date.now():n==null?void 0:n.startedAt,completedAt:o==="completed"||o==="failed"?Date.now():n==null?void 0:n.completedAt,createdAt:(n==null?void 0:n.createdAt)||Date.now(),updatedAt:Date.now(),raw:e};return ue.getState().upsertTask(s,a),wn(s,a),a},vt=s=>({id:s.id,title:s.title,completed:s.status==="completed",createdAt:s.createdAt,description:s.description,planStatus:s.status,agentType:s.agentType,dependencies:s.dependencies,result:s.result,error:s.error,startedAt:s.startedAt,completedAt:s.completedAt,progress:s.progress}),wn=(s,e)=>{const t=V.getState(),n=t.getSessionTasks(s),r=vt(e);if(n.some(o=>o.id===e.id||o.backendId===e.id)){t.updateTaskPlanStatus(s,e.id,r);return}t.setSessionTasks(s,[...n,r])},bt=s=>{const e=G.getState(),t=e.getMessages(s),n=t[t.length-1];(!n||n.type!=="assistant")&&e.addMessage(s,{id:`plan-${Date.now()}`,type:"assistant",content:"",timestamp:Date.now()})};function Ft(s,e,t){const n=Nt.getState(),r=G.getState(),o=ue.getState(),a=qr(e);switch(s){case"plan_start":{r.startGeneration(t),bt(t);const i=Qe(a,"Plan started");i&&n.setThinkingStatus(t,i),o.recordEvent(t,{type:s,source:"plan",title:"Plan started",message:i,status:"running",data:a});break}case"plan_thinking":{const i=Qe(a,"Analyzing request...");n.setThinkingStatus(t,i),bt(t),r.setThinking(t,i),o.recordEvent(t,{type:s,source:"plan",title:"Plan thinking",message:i,status:"running",data:a});break}case"plan_complete":{const i=(a==null?void 0:a.plan)||(a==null?void 0:a.content)||(a==null?void 0:a.result)||(a==null?void 0:a.markdown);if(i){n.setPlanContent(String(i)),bt(t);const l=r.getMessages(t),c=l[l.length-1];(c==null?void 0:c.type)==="assistant"&&!c.content.trim()&&r.updateLastMessage(t,String(i))}else{const l=[...r.getMessages(t)].reverse().find(c=>c.type==="assistant");l!=null&&l.content&&n.setPlanContent(l.content)}r.endGeneration(t),o.recordEvent(t,{type:s,source:"plan",title:"Plan complete",message:Qe(a,"Plan complete"),status:"completed",data:a});break}case"plan_error":{const i=Qe(a,"Plan failed");bt(t),r.updateLastMessage(t,`Plan failed: ${i}`),r.endGeneration(t,i),o.recordEvent(t,{type:s,source:"plan",title:"Plan failed",message:i,status:"failed",data:a});break}case"plan_tasks":{const i=Vr(a).map((l,c)=>Vs(l,t,c));o.setTasks(t,i,"plan"),V.getState().setSessionTasks(t,i.map(vt)),o.recordEvent(t,{type:s,source:"plan",title:"Plan tasks updated",message:`${i.length} tasks`,status:"pending",data:a});break}case"plan_task_start":case"plan_task_update":case"plan_task_result":{const i=Vs(a,t),l=s==="plan_task_start"?"running":Ce(s==="plan_task_result"?a.status||(a.error?"failed":"completed"):a.status||a.planStatus),c={...i,status:l,startedAt:i.startedAt||(l==="running"?Date.now():void 0),completedAt:i.completedAt||(l==="completed"||l==="failed"?Date.now():void 0)};o.upsertTask(t,c),wn(t,c),o.recordEvent(t,{type:s,source:"plan",title:c.title,message:c.result||c.error||c.description,status:c.status,taskId:c.id,data:a});break}case"step_prompt":{const i=Qe(a),l=(a==null?void 0:a.taskId)||(a==null?void 0:a.id);l&&o.upsertTask(t,{id:String(l),title:a.title||a.step||String(l),status:"running",source:"plan",description:i}),o.recordEvent(t,{type:s,source:"plan",title:(a==null?void 0:a.step)||"Step prompt",message:i,status:"running",taskId:l?String(l):void 0,data:a});break}case"plan_mode_change":{const i=(a==null?void 0:a.frontendMode)||(a==null?void 0:a.newMode),l=a==null?void 0:a.planPath;i==="normal"?n.applyBackendMode("normal"):i==="auto"?n.setAuto(!0):(i==="plan"||i==="act"||i==="goal"||i==="auto-plan"||i==="auto-act"||i==="auto-goal")&&n.applyBackendMode(i);const c=l?` [plan: ${l}]`:"";o.recordEvent(t,{type:s,source:"system",title:"Mode changed",message:`${(a==null?void 0:a.previousMode)||"unknown"} -> ${i||"unknown"}${c}`,status:(a==null?void 0:a.success)===!1?"failed":"completed",data:a});break}case"goal_created":{o.recordEvent(t,{type:s,source:"goal",title:(a==null?void 0:a.goalTitle)||(a==null?void 0:a.title)||"Goal created",message:a!=null&&a.goalId?`Goal ${a.goalId}`:"Goal created",status:"pending",data:a});break}case"goal_tasks":{const i=Array.isArray(a==null?void 0:a.tasks)?a.tasks.map((l,c)=>Js(l,t,c)):[];i.length>0&&(o.setTasks(t,i,"goal"),V.getState().setSessionTasks(t,i.map(vt))),o.recordEvent(t,{type:s,source:"goal",title:(a==null?void 0:a.goalTitle)||"Goal tasks",message:`${i.length} tasks`,status:"pending",data:a});break}case"goal_task_update":{const i=String((a==null?void 0:a.taskId)||(a==null?void 0:a.id)||""),l=Jr(t,a);o.recordEvent(t,{type:s,source:"goal",title:(l==null?void 0:l.title)||i||"Goal task update",message:(a==null?void 0:a.result)||(a==null?void 0:a.error)||(a!=null&&a.status?`status: ${a.status}`:"updated"),status:l==null?void 0:l.status,taskId:i||void 0,data:a});break}case"goal_update":{const i=Array.isArray(a==null?void 0:a.tasks)?a.tasks.map((l,c)=>Js(l,t,c)):[];i.length>0&&(o.setTasks(t,i,"goal"),V.getState().setSessionTasks(t,i.map(vt))),o.recordEvent(t,{type:s,source:"goal",title:(a==null?void 0:a.goalTitle)||(a==null?void 0:a.title)||"Goal update",message:(a==null?void 0:a.status)||(a!=null&&a.id?`Goal ${a.id}`:"Goal updated"),status:a!=null&&a.status?Ce(a.status):void 0,data:a});break}}}const Yr=4e3,st=pe(s=>({toasts:[],addToast:(e,t,n)=>{const r=`toast-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,o={id:r,type:e,message:t,duration:n??Yr,createdAt:Date.now()};s(a=>({toasts:[...a.toasts.slice(-9),o]})),o.duration>0&&setTimeout(()=>{s(a=>({toasts:a.toasts.filter(i=>i.id!==r)}))},o.duration)},dismissToast:e=>s(t=>({toasts:t.toasts.filter(n=>n.id!==e)})),clearAll:()=>s({toasts:[]})})),X={info:(s,e)=>st.getState().addToast("info",s,e),success:(s,e)=>st.getState().addToast("success",s,e),warning:(s,e)=>st.getState().addToast("warning",s,e),error:(s,e)=>st.getState().addToast("error",s,e??6e3)};function Qr(s){const e=s.toLowerCase();let t="unknown";return e.includes("401")||e.includes("unauthorized")||e.includes("invalid api key")||/api ?key.*invalid/.test(e)?t="auth":e.includes("429")||e.includes("rate limit")||e.includes("quota")||e.includes("insufficient_quota")?t="rate_limit":e.includes("timeout")||e.includes("timed out")||e.includes("timedout")?t="timeout":e.includes("network")||e.includes("econnrefused")||e.includes("fetch failed")||e.includes("socket")||e.includes("websocket")?t="network":e.includes("tool")||e.includes("bash")||e.includes("command failed")?t="tool":(e.includes("model")||e.includes("api")||e.includes("provider")||e.includes("response"))&&(t="model"),{id:`error-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,category:t,summary:Xr(s,t),detail:s,retryable:t!=="auth",timestamp:Date.now()}}function Xr(s,e){const t={auth:"API Key 无效或已失效(401 Unauthorized)",rate_limit:"请求频率超限或配额不足(429)",timeout:"请求超时",network:"网络连接异常",tool:"工具执行失败",model:"模型调用失败",unknown:"发生未知错误"},n=(s.split(`
|
|
7
|
+
`)[0]||"").trim().slice(0,120);return n?`${t[e]}: ${n}`:t[e]}function Zr(s,e,t){var r;const n=G.getState();switch(s){case"start":n.startGeneration(t),n.addMessage(t,{id:Ae(),type:"assistant",content:"",timestamp:Date.now()});break;case"content":{let o=String(e||"");try{const i=JSON.parse(e);o=i.text||i.content||o}catch{}const a=o.replace(/\[FINISH\]/g,"");a&&n.appendToLastMessage(t,a)}break;case"thinking":{let o=String(e||"");try{const a=JSON.parse(e);o=a.text||a.content||o}catch{}n.appendToLastMessageThinking(t,o)}break;case"tool_call":try{const o=JSON.parse(e||"{}"),a=o.id||Ae(),i=typeof o.index=="number"?o.index:void 0,l=o.args||o.arguments||"",c=n.messagesBySession[t]||[],d=c[c.length-1];[...((r=d==null?void 0:d.steps)==null?void 0:r.flatMap(f=>f.toolCalls||[]))||[],...(d==null?void 0:d.toolCalls)||[]].find(f=>i!==void 0&&f.index===i||f.id===a)?n.updateToolCall(t,a,{args:l}):n.addToolCall(t,{id:a,index:i,name:o.name||"Unknown",args:l,status:"running",timestamp:Date.now()})}catch(o){te.warn("Failed to parse tool call",String(o))}break;case"tool_result":try{const o=JSON.parse(e||"{}"),i=G.getState().messagesBySession[t]||[],l=[];for(const f of i){const m=f.steps||[];for(const y of m)y.toolCalls&&l.push(...y.toolCalls);f.toolCalls&&l.push(...f.toolCalls)}const c=o.toolName,d=o.id,p=typeof o.index=="number"?o.index:void 0;let h;if(d&&(h=l.find(f=>f.id===d)),!h&&p!==void 0&&(h=l.find(f=>f.index===p&&f.name===c)),!h){const f=l.filter(m=>m.name===c&&m.status==="running");f.sort((m,y)=>(m.timestamp||0)-(y.timestamp||0)),h=f[0]}if(!h){const f=l.filter(m=>m.name===c&&m.status==="error"&&m.result==="生成已结束(工具执行超时或连接中断)");f.sort((m,y)=>(y.timestamp||0)-(m.timestamp||0)),h=f[0]}if(h){const f=Math.floor((Date.now()-(h.timestamp||Date.now()))/1e3),m=typeof o.result=="string"&&o.result.startsWith("Error:");n.updateToolCall(t,h.id,{status:m?"error":"completed",result:o.result,duration:f})}}catch(o){te.warn("Failed to parse tool result",String(o))}break;case"turn_summary":{try{const o=JSON.parse(e||"{}"),a={};if(o.toolCounts&&typeof o.toolCounts=="object"&&!Array.isArray(o.toolCounts))for(const[i,l]of Object.entries(o.toolCounts)){const c=Number(l);Number.isFinite(c)&&c>0&&(a[i]=c)}n.setTurnSummary(t,{thoughtMs:Number(o.thoughtMs??o.durationMs??0)||0,durationMs:Number(o.durationMs??o.thoughtMs??0)||0,toolCounts:a,...typeof o.headline=="string"&&o.headline?{headline:o.headline}:{}})}catch(o){te.warn("Failed to parse turn_summary",String(o))}break}case"complete":n.endGeneration(t);{const o=G.getState().messagesBySession[t]||[];o.length>0&&J.getState().recalculateFromMessages(o)}break;case"generation_paused":n.pauseGeneration(t);break;case"generation_resumed":n.resumeGeneration(t);break;case"compaction_progress":try{const o=JSON.parse(e||"{}");J.getState().setCompactionProgress({stage:o.stage||"",percent:o.percent||0,message:o.message||""})}catch(o){console.error("Failed to parse compaction_progress:",o)}break;case"context_compressed":try{const o=JSON.parse(e||"{}"),a=`Context compressed: ${o.originalCount} -> ${o.compressedCount} msgs, freed ${o.tokensSaved} tokens`;n.appendToLastMessage(t,`
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
${a}
|
|
11
|
+
|
|
12
|
+
`),X.info(a,5e3),J.getState().setCompacting({originalCount:o.originalCount||0,compressedCount:o.compressedCount||0,tokensSaved:o.tokensSaved||0}),J.getState().setCompactionProgress(null)}catch(o){console.error("Failed to parse context_compressed:",o)}break;case"error":{n.endGeneration(t);const o=typeof e=="string"?e:String(e||"Error occurred"),a=Qr(o),i=n.messagesBySession[t]||[],l=i[i.length-1];l&&l.type==="assistant"&&!l.errorCard?n.attachErrorCard(t,a):n.addMessage(t,{id:Ae(),type:"assistant",content:"",timestamp:Date.now(),errorCard:a});break}case"context_analysis":try{const o=JSON.parse(e||"{}");o&&o.total!==void 0&&J.getState().setContextDistribution(o)}catch(o){console.error("Failed to parse context_analysis:",o)}break;case"threshold_warning":try{const o=JSON.parse(e||"{}");J.getState().setThresholdWarning(o);const a=o.percentLeft!==void 0?o.percentLeft:0;a<=5?console.warn(`Context nearly full (${a}% remaining)`):a<=15&&console.info(`Context running low (${a}% remaining)`)}catch(o){console.error("Failed to parse threshold_warning:",o)}break;case"blocking_limit":try{const o=JSON.parse(e||"{}");J.getState().setThresholdWarning(o),console.error(o.message||"Context blocked")}catch(o){console.error("Failed to parse blocking_limit:",o)}break;case"context_blocked":try{const o=JSON.parse(e||"{}");J.getState().setThresholdWarning(o),console.error(o.message||"Context is full — generation blocked")}catch(o){console.error("Failed to parse context_blocked:",o)}break;case"tool_retry":try{const o=JSON.parse(e||"{}");J.getState().setRetryState({active:o.attempt<(o.maxRetries||3),attempt:o.attempt||0,maxRetries:o.maxRetries||3,errorCategory:o.errorCategory||"unknown",toolName:o.toolName})}catch(o){console.error("Failed to parse tool_retry:",o)}break;case"model_fallback":try{const o=JSON.parse(e||"{}");console.warn(`Model fallback: ${o.fromModel||"?"} → ${o.toModel||"?"}`)}catch(o){console.error("Failed to parse model_fallback:",o)}break;case"tombstone":try{const a=JSON.parse(e||"{}").messageIds||[];a.length>0&&n.applyTombstone(t,a)}catch(o){te.warn("Failed to parse tombstone",String(o))}break}}const ls=pe()((s,e)=>({backendCommands:[],loaded:!1,setBackendCommands:t=>{s({backendCommands:t,loaded:!0})},getAllCommands:()=>e().backendCommands}));async function ea(s="",e){try{let t=`${s}/api/commands`;e&&(t+=`?lang=${encodeURIComponent(e)}`);const n=await fetch(t);if(!n.ok)return[];const r=await n.json(),o=Array.isArray(r==null?void 0:r.data)?r.data:[];return ls.getState().setBackendCommands(o),o}catch{return[]}}function Wt(s,e,t,n,r){var o,a,i;switch(s){case"token_update":try{const c=typeof e=="string"?JSON.parse(e):e||{};if(c.source==="workflow"){J.getState().addWorkflowTokens(Number(c.workflowNodeTokens)||0);break}c.totalTokens>0&&J.getState().updateUsage({promptTokens:c.promptTokens||0,completionTokens:c.completionTokens||0,totalTokens:c.totalTokens||0}),c.model&&J.getState().setModel(c.model)}catch{}break;case"model_name":try{const c=r&&typeof r.model=="string"&&r.model||(typeof e=="string"?e:(e==null?void 0:e.model)||"");c&&J.getState().setModel(c)}catch{}break;case"auth_required":let l=localStorage.getItem("auth_token");l||(l="default-token",localStorage.setItem("auth_token",l)),I.setToken(l),I.setAuthenticated(!1),I.send({type:"auth",token:l});break;case"auth_success":I.setAuthenticated(!0),I.send({type:"subscribe_logs"});{const c=He.getState();ea("",(o=c.language)!=null&&o.startsWith("zh")?"zh":"en");const d=c.workspaceDir;d&&I.send({type:"workspace",message:d})}break;case"auth_failed":te.error("Auth failed",String(e));break;case"log":try{const c=typeof e=="string"?JSON.parse(e):e,d={id:`log-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,level:c.level||"info",source:c.source||"System",message:c.message||"",timestamp:c.timestamp||Date.now()};n.setLogs(p=>[...p,d].slice(-500)),n.activeTab!=="logs"&&n.setUnreadLogs(p=>p+1)}catch(c){te.warn("Failed to parse log entry",String(c))}break;case"commands_list":try{const c=JSON.parse(e||"[]");ls.getState().setBackendCommands(Array.isArray(c)?c:[])}catch(c){te.warn("Failed to parse commands list",String(c))}break;case"command_start":break;case"command_complete":try{const d=((typeof e=="string"?JSON.parse(e):e||{}).result||"").toString();X.success(d.length>120?d.slice(0,120)+"...":d||"Command completed",4e3)}catch{}break;case"command_error":try{const c=typeof e=="string"?JSON.parse(e):e||{};X.error((c.error||"Command failed").toString(),6e3)}catch{}break;case"ping":I.send({type:"pong",data:Date.now().toString()});break;case"workspace_changed":try{const c=JSON.parse(e||"{}");c.newDir&&He.getState().setWorkspaceDir(c.newDir)}catch{}break;case"degradation_update":try{const c=typeof e=="string"?JSON.parse(e):e||{},d=c.active,p=c.mode||"normal",h=Number(c.retryCount)||0,f=Number(c.maxRetries)||0,m=c.message||"",v={normal:"normal",retrying:"retrying",alternative:"alternative model",degraded:"degraded",verifying:"verifying",verified_fail:"verify failed"}[p]||p;if(J.getState().setDegradation({active:d,retryCount:h,maxRetries:f,mode:p,message:m,label:v}),d){const C=h>0?` (${h}/${f})`:"";X.warning(m||`API Degraded: ${v}${C}`,8e3),n.setLogs(S=>[...S,{id:`deg-${Date.now()}`,level:"warn",source:"Infrastructure",message:`Degradation: ${v} | ${m||"no details"}`,timestamp:Date.now()}].slice(-500))}else X.success("API Normal")}catch(c){te.warn("Degradation update parse error",String(c))}break;case"doctor_result":try{const c=typeof e=="string"?JSON.parse(e):e||{},d=c.overallStatus||c.status||"unknown",p=c.healthRate,h=c.issues||[],m={healthy:"healthy",degraded:"degraded",unhealthy:"unhealthy",unknown:"unknown"}[d]||d,y=typeof p=="number"?` (${Math.round(p*100)}%)`:"";if(d==="healthy")X.success(`Doctor: ${m}${y}`);else if(X.warning(`Doctor: ${m}${y}`,1e4),h&&h.length>0)for(const v of h)n.setLogs(C=>[...C,{id:`doctor-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,level:"warn",source:"Doctor",message:typeof v=="string"?v:v.message||JSON.stringify(v),timestamp:Date.now()}].slice(-500))}catch(c){te.warn("Doctor result parse error",String(c))}break;case"session_created":{try{const c=typeof e=="string"?JSON.parse(e):e||{};c.id&&(I.setSessionId(c.id),V.getState().updateSession(c.id,c))}catch{}typeof e=="string"&&e&&te.info(`Session event: ${s}`);break}case"session_resumed":{try{const c=typeof e=="string"?JSON.parse(e):e||{};if((a=c.session)!=null&&a.id&&(I.setSessionId(c.session.id),V.getState().updateSession(c.session.id,c.session)),c.messages&&Array.isArray(c.messages)){const d=((i=c.session)==null?void 0:i.id)||t;G.getState().replaceMessages(d,c.messages.map(p=>({id:p.id||`msg-${p.timestamp||Date.now()}`,type:p.type==="user"?"user":"assistant",content:p.content||"",timestamp:p.timestamp||Date.now(),thinking:p.thinking||void 0})))}}catch(c){te.warn("Failed to process session_resumed",String(c))}typeof e=="string"&&e&&te.info(`Session event: ${s}`);break}case"mcp_update":try{const c=typeof e=="string"?JSON.parse(e):e||{},d=c.server||c.name||"MCP",p=c.action||c.status||"updated";te.info(`MCP ${d}: ${p}`)}catch{}break}}function ta(s,e){var t;try{const n=typeof s=="string"?JSON.parse(s):s||{},r=Be.getState(),{approvalId:o,toolName:a,askPayload:i,timeoutMs:l,timeoutAction:c}=n,d=He.getState();if(r.isSessionAllowed(a)||r.autoMode||(t=d==null?void 0:d.yolo)!=null&&t.enabled){I.send({type:"hook_allow",data:JSON.stringify({approvalId:o})});return}G.getState().addMessage(e,{id:`hook-approval-${o||Date.now()}`,type:"assistant",content:"",timestamp:Date.now(),hookApproval:{approvalId:o||"",toolName:a||"unknown",askPayload:i||"",status:"pending",timestamp:Date.now(),timeoutMs:typeof l=="number"?l:void 0,timeoutAction:c==="allow"||c==="deny"?c:void 0}}),r.addApproval({approvalId:o||"",toolName:a||"unknown",askPayload:i||"",timestamp:Date.now(),timeoutMs:typeof l=="number"?l:void 0,timeoutAction:c==="allow"||c==="deny"?c:void 0}),window.dispatchEvent(new CustomEvent("hook-approval-required"))}catch{}}function Ys(s,e){try{const t=typeof s=="string"?JSON.parse(s):s||{},n=V.getState(),r=ue.getState(),{action:o,taskId:a,data:i}=t;if(o==="created"&&i){const l={id:a||`task-${Date.now()}`,title:i.title||"",completed:i.status==="COMPLETED",createdAt:Date.parse(i.createdAt)||Date.now(),backendId:a,backendStatus:i.status,description:i.description},c=n.tasksBySession[e]||[];n.setSessionTasks(e,[...c,l]),r.upsertTask(e,{id:l.id,title:l.title,description:l.description,status:Ce(i.status),source:"task",progress:i.progress!=null?Number(i.progress):void 0,raw:t})}else if((o==="updated"||o==="status_changed")&&i)n.updateTaskPlanStatus(e,a,{backendStatus:i.status,progress:i.progress}),r.upsertTask(e,{id:a,title:i.title||a,description:i.description,status:Ce(i.status),source:"task",progress:i.progress!=null?Number(i.progress):void 0,raw:t});else if(o==="deleted"){const l=n.tasksBySession[e]||[];n.setSessionTasks(e,l.filter(c=>c.id!==a&&c.backendId!==a))}else if(t&&!o&&(t.id||t.taskId)){const l=String(t.id||t.taskId),c=t,d=String(c.status||"").toUpperCase()==="COMPLETED",p={id:l,title:String(c.title||c.name||l),completed:d,createdAt:Date.parse(c.createdAt)||Date.now(),backendId:l,backendStatus:c.status,description:c.description,progress:c.progress!=null?Number(c.progress):void 0},h=n.getSessionTasks(e);h.some(f=>f.id===l||f.backendId===l)?n.updateTaskPlanStatus(e,l,{backendStatus:c.status,progress:p.progress,completed:d}):n.setSessionTasks(e,[...h,p]),r.upsertTask(e,{id:l,title:p.title,description:p.description,status:Ce(c.status),source:"task",progress:p.progress,raw:t})}r.recordEvent(e,{type:"task_update",source:"task",title:(i==null?void 0:i.title)||t&&(t.title||t.id||t.taskId)||a||"Task update",message:o||"updated",status:(i==null?void 0:i.status)||(t==null?void 0:t.status),taskId:a||(t==null?void 0:t.id)||(t==null?void 0:t.taskId),data:t})}catch{}}function sa(s,e,t,n){try{const r=JSON.parse(e||"{}"),o=n(t,s,r);if(o){const a=G.getState();switch(s){case"step_start":a.updateStep(t,o.id,{title:r.step||o.title,description:r.description||o.description,status:r.status==="start"?"running":r.status||"running"});break;case"step_thinking":a.updateStep(t,o.id,{thought:r.thought});break;case"step_action":a.updateStep(t,o.id,{action:r.action});break;case"step_complete":a.updateStep(t,o.id,{status:r.status??"success",result:r.result});break}}}catch(r){te.warn("Failed to parse "+s,String(r))}}function na(s,e){var t,n;try{const r=typeof s=="string"?JSON.parse(s):s||{};let o=[];if(Array.isArray(r)?o=r:(t=r.tasks)!=null&&t.length?o=r.tasks:(n=r.items)!=null&&n.length&&(o=r.items),o.length>0&&e){const a=V.getState(),i=ue.getState();o.forEach(l=>{const c=l.content||l.title||l.name||"";if(c.trim()){if(!a.getSessionTasks(e).find(m=>m.title===c.trim())&&(a.addSessionTask(e,c.trim()),l.completed||l.status==="completed"||l.status==="COMPLETED"||l.status==="done"||l.activeForm==="completed")){const v=a.getSessionTasks(e).find(C=>C.title===c.trim());v&&a.toggleSessionTask(e,v.id)}const h=String(l.id||l.taskId||c.trim()),f=l.completed||l.status==="completed"||l.status==="COMPLETED"||l.status==="done"||l.activeForm==="completed";i.upsertTask(e,{id:h,title:c.trim(),description:l.description,status:Ce(l.status,f),source:"todo",raw:l})}}),i.recordEvent(e,{type:"todo_update",source:"todo",title:"Todo list updated",message:`${o.length} items`,status:"updated",data:r})}}catch{}}function oa(s,e){try{const t=typeof s=="string"?JSON.parse(s):s||{},n=t.questionId||"",r=t.question||"";if(!n||!r)return;window.__pendingQuestion={questionId:n,question:r,header:t.header||void 0,options:Array.isArray(t.options)?t.options:void 0,multiSelect:t.multiSelect===!0},window.dispatchEvent(new CustomEvent("ask-question-required"))}catch{}}function ra(s,e){try{const t=typeof s=="string"?JSON.parse(s):s||{},n=t.title||t.name||"";if(n&&e){const o=V.getState().getSessionTasks(e).find(a=>a.title===n&&!a.completed);o&&V.getState().toggleSessionTask(e,o.id),ue.getState().upsertTask(e,{id:(o==null?void 0:o.id)||n,title:n,status:"completed",source:"todo"}),ue.getState().recordEvent(e,{type:"todo_item_done",source:"todo",title:n,status:"completed",taskId:(o==null?void 0:o.id)||n,data:t})}}catch{}}function Xe(s){if(!s)return null;try{return JSON.parse(s)}catch{return null}}const Ze=pe((s,e)=>({items:[],pendingCount:0,audit:[],auditTotal:0,automations:[],runsByAutomation:{},loading:!1,error:null,fetchInbox:async()=>{const t=await q.inbox.list({state:"all"});if(t.success&&t.data){const n=t.data.items;s({items:n,pendingCount:n.filter(r=>r.state==="pending").length})}else s({error:t.error||"加载 Inbox 失败"})},resolveInbox:async(t,n)=>{const r=await q.inbox.resolve(t,n);return r.success?(await e().fetchInbox(),!0):(s({error:r.error||"解决失败"}),!1)},fetchAudit:async t=>{const n=await q.audit.query(t||{pageSize:100});n.success&&n.data?s({audit:n.data.records,auditTotal:n.data.total}):s({error:n.error||"加载审计失败"})},fetchAutomations:async()=>{const t=await q.automations.list();t.success&&t.data?s({automations:t.data}):s({error:t.error||"加载自动化失败"})},createAutomation:async t=>{const n=await q.automations.create(t);return n.success&&n.data?(await e().fetchAutomations(),n.data):(s({error:n.error||"创建自动化失败"}),null)},deleteAutomation:async t=>{const n=await q.automations.remove(t);return n.success?(await e().fetchAutomations(),!0):(s({error:n.error||"删除失败"}),!1)},toggleAutomation:async(t,n)=>{const r=await q.automations.toggle(t,n);r.success?await e().fetchAutomations():s({error:r.error||"切换失败"})},runAutomation:async t=>{const n=await q.automations.run(t);n.success?(await e().fetchRuns(t),await e().fetchAutomations()):s({error:n.error||"触发失败"})},fetchRuns:async t=>{const n=await q.automations.runs(t);n.success&&n.data&&s(r=>({runsByAutomation:{...r.runsByAutomation,[t]:n.data}}))},onInboxPending:t=>{s(n=>({items:[t,...n.items.filter(r=>r.id!==t.id)],pendingCount:n.pendingCount+1}))},onInboxResolved:t=>{s(n=>{var r;return{items:n.items.map(o=>o.id===t.id?t:o),pendingCount:Math.max(0,n.pendingCount-(t.state==="resolved"&&((r=n.items.find(o=>o.id===t.id))==null?void 0:r.state)==="pending"?1:0))}})},onAuditRecord:t=>{s(n=>({audit:[t,...n.audit].slice(0,200)}))},onAutomationUpdate:t=>{s(n=>({automations:n.automations.some(o=>o.id===t.id)?n.automations.map(o=>o.id===t.id?t:o):[...n.automations,t]}))},onAutomationRun:t=>{s(n=>({runsByAutomation:{...n.runsByAutomation,[t.automationId]:[t,...n.runsByAutomation[t.automationId]||[]].slice(0,50)}}))}})),et={pending:s=>{const e=Xe(s);e&&Ze.getState().onInboxPending(e)},resolved:s=>{const e=Xe(s);e&&Ze.getState().onInboxResolved(e)},auditRecord:s=>{const e=Xe(s);e&&Ze.getState().onAuditRecord(e)},automationUpdate:s=>{const e=Xe(s);e!=null&&e.automation&&Ze.getState().onAutomationUpdate(e.automation)},automationRun:s=>{const e=Xe(s);e!=null&&e.run&&Ze.getState().onAutomationRun(e.run)}};function aa(s,e,t){let n={};if(e&&typeof e=="object")n=e;else try{n=JSON.parse(String(e||"{}"))}catch{}const r=String(n.jobId||`fjob-${Date.now()}`),o=n.stage||(s==="filejob_result"?"complete":s==="filejob_error"?"error":"uploaded"),a={jobId:r,stage:o,parseProgress:n.parseProgress,parsedFiles:n.parsedFiles,mapping:n.mapping,renderProgress:n.renderProgress,currentRow:n.currentRow,totalRows:n.totalRows,result:n.result,error:n.error,errorDetail:n.errorDetail};n.attachments&&(a.attachments=n.attachments),G.getState().setMessageFileJob(t,a)}const ia=pe((s,e)=>({channels:[],loading:!1,error:null,formOpen:!1,editing:null,qrOpen:!1,qrChannel:null,selectedType:null,load:async()=>{s({loading:!0,error:null});const t=await q.channels.list(),n=t.success&&Array.isArray(t.data)?t.data:[];if(s({loading:!1,channels:n,...t.success&&!Array.isArray(t.data)?{error:"服务端返回的频道数据格式异常"}:t.success?{}:{error:t.error??"Failed to load"}}),!e().selectedType&&n.length>0){const o=n[0].type;s({selectedType:o})}},create:async t=>{const n=await q.channels.create(t);return n.success?(await e().load(),s({formOpen:!1,editing:null}),!0):(s({error:n.error??"Create failed"}),!1)},update:async(t,n)=>{const r=await q.channels.update(t,n);return r.success?(await e().load(),s({formOpen:!1,editing:null}),!0):(s({error:r.error??"Update failed"}),!1)},remove:async t=>{const n=await q.channels.delete(t);return n.success?(s(r=>({channels:r.channels.filter(o=>o.id!==t)})),!0):(s({error:n.error??"Delete failed"}),!1)},toggle:async(t,n)=>(await q.channels.toggle(t,n)).success?(s(o=>({channels:o.channels.map(a=>a.id===t?{...a,enabled:n}:a)})),!0):(await e().load(),!1),openForm:t=>s({formOpen:!0,editing:t??null,error:null}),closeForm:()=>s({formOpen:!1,editing:null,error:null}),openQr:t=>s({qrOpen:!0,qrChannel:t??null}),closeQr:()=>{s({qrOpen:!1,qrChannel:null}),e().load()},clearError:()=>s({error:null}),selectType:t=>s({selectedType:t,error:null}),updateChannelStatus:t=>{s(n=>({channels:n.channels.map(r=>r.id===t.channelId?{...r,connected:t.connected,_state:t.state}:r)}))}})),la=["start","content","thinking","tool_call","tool_result","turn_summary","complete","generation_paused","generation_resumed","error","context_compressed","compaction_progress","tombstone","context_analysis","threshold_warning","blocking_limit","tool_retry","model_fallback","context_blocked"],os=(s,e=[])=>{if(!s)return e;if(Array.isArray(s))return s.forEach(r=>os(r,e)),e;if(typeof s!="object")return e;const t=s,n=t.content;return typeof n=="string"&&n.trim()&&e.push(n.trim()),Object.entries(t).forEach(([r,o])=>{r!=="content"&&r!=="structuredOutput"&&os(o,e)}),e},ca=s=>{const e=os(s);return e[e.length-1]||""};function da({activeTab:s,setLogs:e,setUnreadLogs:t}){const n=G,r=g.useCallback(c=>{if(!c)return{};if(typeof c=="object")return c;if(typeof c!="string")return{};try{return JSON.parse(c)}catch{return{}}},[]),o=g.useCallback((c,d,p)=>{const h=r(d),f=h.runId||"";if(!f)return;const m=ue.getState(),y=G.getState();if(c==="workflow_error"){m.fail(p,f,h.error||"Workflow failed"),(y.isGenerating(p)||y.isPaused(p))&&y.endGeneration(p,h.error||"Workflow failed");return}const v=c==="workflow_finished"?h.status||"COMPLETED":c==="workflow_started"?h.status||"RUNNING":c==="workflow_paused"?h.status||"PAUSED":c==="workflow_resumed"?h.status||"RESUMING":c==="workflow_cancelled"?h.status||"CANCELLED":c==="workflow_recovered"?h.status||"RUNNING":h.status||void 0,C=h.type||c,S=h.data&&typeof h.data=="object"?h.data:{},T=String(h.kind||S.kind||""),_=h.nodeId||h.node_id||S.nodeId||S.node_id,x=h.role||h.agentRole||h.agent_role||S.role||S.agentRole||S.agent_role,R=h.phase||h.phaseId||S.phase||S.phaseId,j=h.effectId||S.effectId||_,D=h.toolName||h.tool_name||S.toolName||S.tool_name,O=h.error||S.error,W=["effect.scheduled","effect.completed","effect.failed"].includes(C)&&_&&T!=="tool",ne=["effect.scheduled","effect.completed","effect.failed"].includes(C)&&T==="tool"&&(D||_),N=_?m.getAgentsForSession(p).find(b=>b.id===String(_)):void 0;if(m.upsert(p,{runId:f,status:v,completedPhases:Number(h.completedPhases||0),totalPhases:Number(h.totalPhases||0),completedEffects:Number(h.completedEffects||0),totalEffects:Number(h.totalEffects||0),tokensUsed:Number(h.tokensUsed||0),tokensRemaining:Number(h.tokensRemaining||0),lastEventType:C,agentNode:W?{nodeId:String(_),role:String(x||(N==null?void 0:N.role)||(N==null?void 0:N.name)||"agent"),phase:R?String(R):N==null?void 0:N.phase,status:C==="effect.failed"?"failed":C==="effect.completed"?"completed":"scheduled",tokens:h.tokensUsed!=null?Number(h.tokensUsed):S.tokens!=null&&typeof S.tokens=="number"?Number(S.tokens):void 0,error:O?String(O):void 0,updatedAt:Date.now()}:void 0}),ne){const b=C==="effect.failed"?"failed":C==="effect.completed"?"completed":"running",A=String(j||`${f}-${D||_}`);m.upsertTask(p,{id:A,title:String(D||_),description:_?String(_):void 0,status:b,source:"workflow",runId:f,result:S.artifactRef?String(S.artifactRef):void 0,error:O?String(O):void 0,raw:h}),m.recordEvent(p,{type:C,source:"workflow",title:String(D||_),status:b,runId:f,taskId:A,message:O?String(O):void 0,data:h})}if(c==="workflow_started")y.startGeneration(p);else if(c==="workflow_finished"){const b=ca(h.output);if(b){const A=y.getMessages(p),F=A[A.length-1];(F==null?void 0:F.type)==="assistant"?y.appendToLastMessage(p,b):y.addMessage(p,{id:Ae(),type:"assistant",content:b,timestamp:Date.now()})}y.endGeneration(p)}else v==="PAUSED"?y.pauseGeneration(p):(v==="RUNNING"||v==="RESUMING")&&y.resumeGeneration(p)},[r]),a=g.useCallback(c=>{var f;const p=n.getState().messagesBySession[c]||[],h=p[p.length-1];return(f=h==null?void 0:h.steps)==null?void 0:f[h.steps.length-1]},[n]),i=g.useCallback((c,d,p)=>{const h=a(c),f=d==="step_complete",m=h&&(h.status==="success"||h.status==="error");if(!h||m&&!f){const y=(p==null?void 0:p.step)||d.replace("step_","").replace("_"," ");return n.getState().addStep(c,{id:`step-${Date.now()}`,title:y,description:(p==null?void 0:p.description)||"Executing...",status:"running",timestamp:Date.now()}),a(c)}return h},[a,n]),l=g.useCallback(c=>{const d=c.type,p=c.data;if(d==="model_name"){Wt(d,p,c.sessionId||"",{activeTab:s,setLogs:e,setUnreadLogs:t},c);return}if(d==="models_updated"||d==="models.updated"){window.dispatchEvent(new CustomEvent("models-updated"));return}if(d==="workspace_changed"){Wt(d,p,c.sessionId||"",{activeTab:s,setLogs:e,setUnreadLogs:t});return}const h=V.getState().activeSessionId,f=c.sessionId||h;if(f){if(d==="hook_ask"){ta(p,f);return}if(d==="ask_user_question"){oa(p);return}if(d==="question_answer_ack"){window.dispatchEvent(new CustomEvent("ask-question-dismiss"));return}if(d==="task_update"){Ys(p,f);return}if(d==="task_output"){try{n.getState().appendToLastMessage(f,String(p||""))}catch{}return}if(d==="task_finished"||d==="task_error"){d==="task_error"?te.error("Task error",String(p)):Ys(p,f);return}if(d==="filejob_start"||d==="filejob_progress"||d==="filejob_result"||d==="filejob_error"){aa(d,p,f);return}if(d.startsWith("step_")){sa(d,p,f,i);return}if(d.startsWith("plan_")){try{Ft(d,p,f)}catch(m){te.error(`Failed to handle ${d}`,String(m))}return}if(d.startsWith("goal_")){try{Ft(d,p,f)}catch(m){te.error(`Failed to handle ${d}`,String(m))}return}if(d==="step_prompt"){try{Ft(d,p,f)}catch(m){te.error(`Failed to handle ${d}`,String(m))}return}if(d==="todo_update"){na(p,f);return}if(d==="todo_item_done"){ra(p,f);return}if(d!=="todo_progress"){if(d==="inbox.pending"){et.pending(p);return}if(d==="inbox.resolved"){et.resolved(p);return}if(d==="audit.record"){et.auditRecord(p);return}if(d==="automation.update"){et.automationUpdate(p);return}if(d==="automation.run"){et.automationRun(p);return}if(d!=="tool.approval_required"){if(["workflow_started","workflow_event","workflow_progress","workflow_finished","workflow_error","workflow_checkpoint","workflow_node_start","workflow_node_complete","workflow_paused","workflow_resumed","workflow_cancelled","workflow_handoff"].includes(d)){o(d,p,f);return}if(la.includes(d)){Zr(d,p,f);return}if(d==="channel_status"){try{const m=JSON.parse(p||"{}");ia.getState().updateChannelStatus(m)}catch{}return}if(!(d==="channel_message"||d==="channel_error")&&["token_update","auth_required","auth_success","auth_failed","log","commands_list","ping","degradation_update","doctor_result","session_created","session_resumed","mcp_update","hook_response_ack"].includes(d)){Wt(d,p,f,{activeTab:s,setLogs:e,setUnreadLogs:t});return}}}}},[s,i,o,e,t]);g.useEffect(()=>{I.connect();const c=I.onMessage(l),d=I.onClose(()=>{const p=G.getState();for(const h of p.generatingSessions)p.endGeneration(h,"WebSocket disconnected")});return()=>{c(),d()}},[l])}const at={linear:{id:"linear",nameKey:"settings.themePresetLinear",descriptionKey:"settings.themePresetLinearDesc",dark:{bg:"#0a0a0c",surface:"#121215",border:"#26262b",text:"#e4e4e7",muted:"#8e8e96",accentBlue:"#7c83f8",accentGreen:"#4ade80",accentRed:"#f87171",accentYellow:"#fbbf24",accentPurple:"#c084fc"},light:{bg:"#ffffff",surface:"#f6f6f7",border:"#e4e4e8",text:"#18181b",muted:"#71717a",accentBlue:"#5e6ad2",accentGreen:"#16a34a",accentRed:"#dc2626",accentYellow:"#b45309",accentPurple:"#7c3aed"}},mimo:{id:"mimo",nameKey:"settings.themePresetMimo",descriptionKey:"settings.themePresetMimoDesc",dark:{bg:"#fcfaf8",surface:"#f6f1ea",border:"#e7dfd5",text:"#26251e",muted:"#5a574f",accentBlue:"#26251e",accentGreen:"#1f7a4d",accentRed:"#b84f42",accentYellow:"#a16b2d",accentPurple:"#7a5c8f"},light:{bg:"#ffffff",surface:"#f8f4ef",border:"#e2d8cd",text:"#24221c",muted:"#605b52",accentBlue:"#26251e",accentGreen:"#1f7a4d",accentRed:"#b84f42",accentYellow:"#a16b2d",accentPurple:"#7a5c8f"}},github:{id:"github",nameKey:"settings.themePresetGithub",descriptionKey:"settings.themePresetGithubDesc",dark:{bg:"#0d1117",surface:"#161b22",border:"#30363d",text:"#c9d1d9",muted:"#8b949e",accentBlue:"#58a6ff",accentGreen:"#238636",accentRed:"#f85149",accentYellow:"#d29922",accentPurple:"#a855f7"},light:{bg:"#ffffff",surface:"#f6f8fa",border:"#d0d7de",text:"#24292f",muted:"#57606a",accentBlue:"#0969da",accentGreen:"#1a7f37",accentRed:"#cf222e",accentYellow:"#9a6700",accentPurple:"#8250df"}},cherry:{id:"cherry",nameKey:"settings.themePresetCherry",descriptionKey:"settings.themePresetCherryDesc",dark:{bg:"#0f1419",surface:"#1a2332",border:"#2d3f50",text:"#e1e8ed",muted:"#8899aa",accentBlue:"#01a9ff",accentGreen:"#00c853",accentRed:"#ff5252",accentYellow:"#ffab00",accentPurple:"#7c4dff"},light:{bg:"#f5f9ff",surface:"#ffffff",border:"#cce0ff",text:"#1a2332",muted:"#5c6f87",accentBlue:"#0160ff",accentGreen:"#00a844",accentRed:"#e53935",accentYellow:"#f9a825",accentPurple:"#651fff"}},ocean:{id:"ocean",nameKey:"settings.themePresetOcean",descriptionKey:"settings.themePresetOceanDesc",dark:{bg:"#0b1e2e",surface:"#122b3d",border:"#1e4057",text:"#d4e6f5",muted:"#7a9bb5",accentBlue:"#00bcd4",accentGreen:"#26a69a",accentRed:"#ef5350",accentYellow:"#ffca28",accentPurple:"#ab47bc"},light:{bg:"#edf7fc",surface:"#ffffff",border:"#b3d9e8",text:"#0b1e2e",muted:"#4f7a94",accentBlue:"#00838f",accentGreen:"#00897b",accentRed:"#d32f2f",accentYellow:"#f57f17",accentPurple:"#8e24aa"}},mint:{id:"mint",nameKey:"settings.themePresetMint",descriptionKey:"settings.themePresetMintDesc",dark:{bg:"#0d1f1c",surface:"#162d28",border:"#264b41",text:"#d1f0e8",muted:"#7dafa3",accentBlue:"#26c6da",accentGreen:"#66bb6a",accentRed:"#ef5350",accentYellow:"#ffd54f",accentPurple:"#ad8aff"},light:{bg:"#edf7f4",surface:"#ffffff",border:"#b8d9cf",text:"#0d1f1c",muted:"#4a7f72",accentBlue:"#0097a7",accentGreen:"#388e3c",accentRed:"#d32f2f",accentYellow:"#f9a825",accentPurple:"#7c4dff"}},lavender:{id:"lavender",nameKey:"settings.themePresetLavender",descriptionKey:"settings.themePresetLavenderDesc",dark:{bg:"#1a1428",surface:"#261f38",border:"#3c3354",text:"#e2daf2",muted:"#9387b5",accentBlue:"#86bef5",accentGreen:"#81c784",accentRed:"#ef9a9a",accentYellow:"#ffe082",accentPurple:"#ce93d8"},light:{bg:"#f5f0ff",surface:"#ffffff",border:"#d4c8e8",text:"#1a1428",muted:"#6c5b8a",accentBlue:"#1565c0",accentGreen:"#2e7d32",accentRed:"#c62828",accentYellow:"#f57f17",accentPurple:"#7b1fa2"}},midnight:{id:"midnight",nameKey:"settings.themePresetMidnight",descriptionKey:"settings.themePresetMidnightDesc",dark:{bg:"#0a0e1a",surface:"#111726",border:"#1e2740",text:"#c8d2e8",muted:"#6a7596",accentBlue:"#4fc3f7",accentGreen:"#4caf50",accentRed:"#e57373",accentYellow:"#ffd54f",accentPurple:"#b39ddb"},light:{bg:"#eef1f7",surface:"#ffffff",border:"#c0c9dc",text:"#0a0e1a",muted:"#4f5a78",accentBlue:"#0288d1",accentGreen:"#2e7d32",accentRed:"#d32f2f",accentYellow:"#f57f17",accentPurple:"#5e35b1"}},sunset:{id:"sunset",nameKey:"settings.themePresetSunset",descriptionKey:"settings.themePresetSunsetDesc",dark:{bg:"#1e1410",surface:"#2a1d16",border:"#443124",text:"#f0dfcf",muted:"#b8957a",accentBlue:"#5fa5e8",accentGreen:"#81c784",accentRed:"#ff7043",accentYellow:"#ffb74d",accentPurple:"#e0a0e0"},light:{bg:"#fff6f0",surface:"#ffffff",border:"#f0d5c0",text:"#2a1d16",muted:"#8a6e5a",accentBlue:"#1976d2",accentGreen:"#388e3c",accentRed:"#e64a19",accentYellow:"#ef6c00",accentPurple:"#8e24aa"}},forest:{id:"forest",nameKey:"settings.themePresetForest",descriptionKey:"settings.themePresetForestDesc",dark:{bg:"#0e1a12",surface:"#172a1d",border:"#2a4733",text:"#d1e8d6",muted:"#7da684",accentBlue:"#5bb8e8",accentGreen:"#66bb6a",accentRed:"#ef9a9a",accentYellow:"#e6c35c",accentPurple:"#ae8ad9"},light:{bg:"#f0f7f0",surface:"#ffffff",border:"#b8d9be",text:"#0e1a12",muted:"#477a50",accentBlue:"#1565c0",accentGreen:"#2e7d32",accentRed:"#c62828",accentYellow:"#827717",accentPurple:"#6a1b9a"}},candy:{id:"candy",nameKey:"settings.themePresetCandy",descriptionKey:"settings.themePresetCandyDesc",dark:{bg:"#16101a",surface:"#22182a",border:"#3d284a",text:"#f0def5",muted:"#b28dc2",accentBlue:"#5fc3f5",accentGreen:"#81e080",accentRed:"#ff6b6b",accentYellow:"#ffd93d",accentPurple:"#e066ff"},light:{bg:"#faf0ff",surface:"#ffffff",border:"#e0cce8",text:"#1a0a24",muted:"#7a5c8a",accentBlue:"#1976d2",accentGreen:"#388e3c",accentRed:"#d32f2f",accentYellow:"#f9a825",accentPurple:"#8e24aa"}},nord:{id:"nord",nameKey:"settings.themePresetNord",descriptionKey:"settings.themePresetNordDesc",dark:{bg:"#2e3440",surface:"#3b4252",border:"#4c566a",text:"#eceff4",muted:"#81a1c1",accentBlue:"#88c0d0",accentGreen:"#a3be8c",accentRed:"#bf616a",accentYellow:"#ebcb8b",accentPurple:"#b48ead"},light:{bg:"#f5f7fa",surface:"#ffffff",border:"#d8dee9",text:"#2e3440",muted:"#5e6d85",accentBlue:"#5e81ac",accentGreen:"#6f9e6f",accentRed:"#bf616a",accentYellow:"#b48d56",accentPurple:"#8f6f9e"}}},rs="linear";function Qs(s,e,t){const n=at[s]||at[rs];if(!n)return{bg:"#fcfaf8",surface:"#f6f1ea",border:"#e7dfd5",text:"#26251e",muted:"#5a574f",accentBlue:"#26251e",accentGreen:"#1f7a4d",accentRed:"#b84f42",accentYellow:"#a16b2d",accentPurple:"#7a5c8f"};const r={...e==="dark"?n.dark:n.light};return t&&Object.assign(r,t),r}const Se=s=>{const e=parseInt(s.slice(1,3),16),t=parseInt(s.slice(3,5),16),n=parseInt(s.slice(5,7),16);return`${e} ${t} ${n}`},ua=(s,e,t)=>{const n=[parseInt(s.slice(1,3),16),parseInt(s.slice(3,5),16),parseInt(s.slice(5,7),16)],r=[parseInt(e.slice(1,3),16),parseInt(e.slice(3,5),16),parseInt(e.slice(5,7),16)];return n.map((o,a)=>Math.round(o+((r[a]??o)-o)*t)).join(" ")};function Xs(s,e,t,n,r){t.classList.toggle("dark",s==="dark"),t.classList.toggle("light",s==="light"),t.style.setProperty("--color-bg",Se(e.bg)),t.style.setProperty("--color-surface",Se(e.surface)),t.style.setProperty("--color-border",Se(e.border)),t.style.setProperty("--color-text",Se(e.text)),t.style.setProperty("--color-muted",Se(e.muted)),t.style.setProperty("--color-accent-blue",Se(e.accentBlue)),t.style.setProperty("--color-accent-green",Se(e.accentGreen)),t.style.setProperty("--color-accent-red",Se(e.accentRed)),t.style.setProperty("--color-accent-yellow",Se(e.accentYellow)),t.style.setProperty("--color-accent-purple",Se(e.accentPurple)),t.style.setProperty("--color-hover",ua(e.surface,e.text,.06)),n&&n.setAttribute("content",e.bg),r&&r.setAttribute("content",s)}function pa({theme:s,themePresetId:e,customTheme:t,customThemeEnabled:n}){g.useEffect(()=>{const r=document.documentElement,o=document.querySelector('meta[name="theme-color"]'),a=document.querySelector('meta[name="color-scheme"]'),i=s==="dark"?"dark":s==="light"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",l=n?t:void 0,c=Qs(e||rs,i,l);if(Xs(i,c,r,o,a),s==="auto"){const d=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const h=d.matches?"dark":"light",f=Qs(e||rs,h,l);Xs(h,f,r,o,a)};return d.addEventListener("change",p),()=>d.removeEventListener("change",p)}},[s,e,t,n])}class Zs extends g.Component{constructor(t){super(t);ee(this,"handleRetry",()=>{this.setState({hasError:!1,error:null})});this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary] Caught error:",t,n)}render(){var t;return this.state.hasError?this.props.fallback?this.props.fallback:u.jsx("div",{className:"flex items-center justify-center h-full w-full bg-dark-bg",children:u.jsxs("div",{className:"max-w-md p-8 text-center",children:[u.jsx("div",{className:"flex justify-center mb-4",children:u.jsx("div",{className:"w-16 h-16 rounded-full bg-accent-red/10 flex items-center justify-center",children:u.jsx(is,{size:32,className:"text-accent-red"})})}),u.jsx("h2",{className:"text-xl font-semibold text-dark-text mb-2",children:"页面出现错误"}),u.jsx("p",{className:"text-sm text-dark-muted mb-6",children:((t=this.state.error)==null?void 0:t.message)||"发生了未知错误,请尝试刷新页面"}),u.jsxs("div",{className:"flex items-center justify-center gap-3",children:[u.jsxs("button",{onClick:this.handleRetry,className:"flex items-center gap-2 px-4 py-2 bg-accent-blue text-white rounded-lg hover:opacity-90 transition-opacity",children:[u.jsx(pn,{size:16}),"重试"]}),u.jsx("button",{onClick:()=>window.location.reload(),className:"px-4 py-2 bg-dark-hover text-dark-text rounded-lg hover:bg-dark-border transition-colors",children:"刷新页面"})]})]})}):this.props.children}}const ha=g.memo(function(e){const{t}=Ee(),n=J(b=>b.currentUsage),r=J(b=>b.maxContextTokens),o=J(b=>b.model),a=J(b=>b.tokenRate),i=J(b=>b.compactingUntil),l=J(b=>b.lastCompactInfo),c=J(b=>b.degradation),d=J(b=>b.compactionProgress),p=V(b=>b.activeSessionId),h=G(b=>p?b.isGenerating(p):!1),f=ue(b=>p?b.bySession[p]:void 0),m=ue(b=>p?b.getRunningAgentCount(p):0),y=Nt(b=>b.mode),v=Be(b=>b.autoMode),[C,S]=g.useState(0),T=g.useRef(0);g.useEffect(()=>{if(h&&!T.current&&(T.current=Date.now()),!h){T.current=0,S(0);return}const b=setInterval(()=>S(Math.floor((Date.now()-T.current)/1e3)),1e3);return()=>clearInterval(b)},[h]);const _=n.totalTokens,x=n.promptTokens,R=n.completionTokens,j=r>0?Math.min(100,Math.round(n.totalTokens/r*100)):0,D=Tr(a),O=y==="normal"?"act":y,W=Cr[O],ne=ve(O),N=ne==="plan"?"border-accent-blue/30 text-accent-blue":ne==="goal"?"border-accent-purple/30 text-accent-purple":"border-accent-green/30 text-accent-green";return u.jsxs("div",{className:"h-9 border-t border-dark-border bg-dark-bg flex items-center px-3 gap-2 shrink-0 select-none text-xs overflow-hidden",children:[u.jsx("span",{className:"font-semibold text-dark-text whitespace-nowrap",children:"DeepSeekCode"}),u.jsx("span",{className:`px-2 py-0.5 rounded-full border whitespace-nowrap ${N}`,children:W.label}),v&&u.jsx("span",{className:"px-2 py-0.5 rounded-full border border-accent-yellow/30 text-accent-yellow whitespace-nowrap",children:"Auto"}),u.jsx("span",{className:"text-dark-muted truncate max-w-[14rem]",children:o||t("common.connecting")}),u.jsxs("span",{className:"hidden md:inline-flex items-center gap-1 text-dark-muted whitespace-nowrap",children:[u.jsx("span",{className:"text-dark-text",children:Ve(x)}),u.jsx("span",{className:"text-dark-muted/60",children:"+"}),u.jsx("span",{className:"text-accent-green",children:Ve(R)}),u.jsx("span",{className:"text-dark-muted/60",children:"="}),u.jsx("span",{className:"text-dark-text",children:Ve(_)}),u.jsx("span",{className:"text-dark-muted/60",children:"/"}),u.jsx("span",{children:Ve(r)})]}),u.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[u.jsx("span",{className:"w-16 lg:w-20 h-1.5 bg-dark-border/70 rounded-full overflow-hidden inline-flex",children:u.jsx("span",{className:`h-full transition-all rounded-full ${j>=90?"bg-accent-red":j>=70?"bg-accent-yellow":"bg-dark-text/70"}`,style:{width:`${j}%`}})}),u.jsxs("span",{className:j>=90?"text-accent-red font-bold":j>=70?"text-accent-yellow":"",children:[j,"%"]})]}),h&&u.jsxs(u.Fragment,{children:[u.jsxs("span",{className:"text-dark-text flex items-center gap-1 whitespace-nowrap",children:[u.jsx(wt,{size:12,className:"animate-spin"}),kn(C)]}),D&&u.jsx("span",{className:"text-accent-purple whitespace-nowrap",children:D})]}),m>0&&u.jsxs("span",{className:"text-dark-text whitespace-nowrap",children:[m," agent",m>1?"s":""]}),u.jsx("div",{className:"flex-1"}),f&&u.jsxs("span",{className:"hidden xl:flex items-center gap-2 text-[11px] text-dark-text whitespace-nowrap",children:[u.jsx("span",{className:"text-dark-muted",children:"wf"}),u.jsx("span",{className:"font-mono",children:f.status}),u.jsxs("span",{children:[f.completedPhases,"/",f.totalPhases||0]}),u.jsx("span",{className:"text-dark-muted",children:Ve(f.tokensUsed)})]}),d&&u.jsxs("span",{className:"hidden lg:flex items-center gap-2 text-[11px] text-dark-text whitespace-nowrap",children:[u.jsx("span",{children:"compact"}),u.jsxs("span",{children:[d.percent,"%"]}),u.jsx("span",{className:"w-20 h-1.5 bg-dark-border/70 rounded-full overflow-hidden",children:u.jsx("span",{className:"h-full bg-dark-text/70 rounded-full block",style:{width:`${d.percent}%`}})})]}),!d&&Date.now()<i&&l&&u.jsxs("span",{className:"hidden lg:inline text-dark-muted text-[11px] whitespace-nowrap",children:[l.originalCount," ","->"," ",l.compressedCount]}),(c==null?void 0:c.active)&&u.jsxs("span",{className:"text-accent-yellow text-[11px] whitespace-nowrap",children:[c.label," ",c.retryCount>0?`${c.retryCount}/${c.maxRetries}`:""]})]})}),be=pe()((s,e)=>({status:null,branches:null,loading:!1,refreshing:!1,lastAction:null,busy:!1,refreshStatus:async()=>{const t=await q.git.status();return t.success&&t.data?(s({status:t.data}),t.data):(s({status:{available:!1,error:t.error||"Failed to load git status"}}),null)},refreshBranches:async()=>{const t=await q.git.branches();t.success&&t.data?s({branches:t.data}):s({branches:null})},refreshAll:async()=>{if(!e().refreshing){s({refreshing:!0,loading:e().status===null});try{await e().refreshStatus(),await e().refreshBranches()}finally{s({refreshing:!1,loading:!1})}}},commit:async t=>{s({busy:!0});const n=await q.git.commit({message:t});return s({busy:!1,lastAction:n.success&&n.data?n.data:{ok:!1,error:n.error||"Commit failed"}}),e().refreshStatus(),e().lastAction},push:async()=>{s({busy:!0});const t=await q.git.push();return s({busy:!1,lastAction:t.success&&t.data?t.data:{ok:!1,error:t.error||"Push failed"}}),e().refreshStatus(),e().lastAction},checkout:async t=>{s({busy:!0});const n=await q.git.checkout(t);return s({busy:!1,lastAction:n.success&&n.data?n.data:{ok:!1,error:n.error||"Checkout failed"}}),e().refreshAll(),e().lastAction}}));function Cn(s){var e,t,n="";if(typeof s=="string"||typeof s=="number")n+=s;else if(typeof s=="object")if(Array.isArray(s)){var r=s.length;for(e=0;e<r;e++)s[e]&&(t=Cn(s[e]))&&(n&&(n+=" "),n+=t)}else for(t in s)s[t]&&(n&&(n+=" "),n+=t);return n}function fa(){for(var s,e,t=0,n="",r=arguments.length;t<r;t++)(s=arguments[t])&&(e=Cn(s))&&(n&&(n+=" "),n+=e);return n}function Le(...s){return fa(s)}const Ht="dsc-git-commit-draft",ma=g.memo(function(){const{t:e}=Ee(),t=be(x=>x.status),n=be(x=>x.branches),r=be(x=>x.busy),o=be(x=>x.lastAction),a=He(x=>x.workspaceDir),[i,l]=g.useState(!1),[c,d]=g.useState(""),[p,h]=g.useState(!1),[f,m]=g.useState(null),y=g.useRef(null);g.useEffect(()=>{be.getState().refreshAll();const x=setInterval(()=>{document.visibilityState==="visible"&&be.getState().refreshStatus()},3e4);return()=>clearInterval(x)},[]),g.useEffect(()=>{const x=localStorage.getItem(Ht);x&&d(x)},[]);const v=g.useCallback(async()=>{try{const{api:x}=await re(async()=>{const{api:j}=await Promise.resolve().then(()=>Ir);return{api:j}},void 0),R=await x.git.prStatus();R.success&&m(R.data||{available:!1,message:""})}catch{}},[]);g.useEffect(()=>{v()},[v]),g.useEffect(()=>{if(!i)return;const x=R=>{y.current&&!y.current.contains(R.target)&&l(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[i]);const C=g.useCallback(async()=>{const x=c.trim();if(!x){X.warning(e("git.emptyCommitMsg"));return}const j=await be.getState().commit(x);j.ok?(X.success(e("git.commitSuccess")),h(!1),localStorage.removeItem(Ht),d("")):X.error(j.error||e("git.commitFailed"))},[c,e]),S=g.useCallback(async()=>{const R=await be.getState().push();R.ok?X.success(e("git.pushSuccess")):X.error(R.error||e("git.pushFailed"))},[e]),T=g.useCallback(async x=>{const j=await be.getState().checkout(x);j.ok?X.success(e("git.checkoutSuccess",{branch:x})):X.error(j.error||e("git.checkoutFailed"))},[e]),_=t&&t.available===!1;return u.jsxs("div",{ref:y,className:"relative",children:[u.jsxs("button",{onClick:()=>l(x=>!x),className:Le("flex items-center gap-1.5 rounded-lg px-2 py-1.5 text-xs transition-colors",i?"bg-dark-hover text-dark-text":"text-dark-muted hover:bg-dark-hover hover:text-dark-text"),title:e("git.panelTitle"),"aria-expanded":i,children:[u.jsx(vs,{size:13,className:Le(_?"text-dark-muted/50":"text-accent-blue")}),u.jsx("span",{className:"max-w-[120px] truncate font-mono",children:_?e("git.noRepo"):(t==null?void 0:t.branch)||"—"}),(t==null?void 0:t.dirty)&&u.jsxs("span",{className:"hidden sm:flex items-center gap-1 text-[10px] font-mono tabular-nums",children:[u.jsxs("span",{className:"text-accent-green",children:["+",t.totalAdded??0]}),u.jsxs("span",{className:"text-accent-red",children:["−",t.totalRemoved??0]})]}),u.jsx(Bt,{size:11,className:Le("transition-transform",i&&"rotate-180")})]}),i&&u.jsxs("div",{className:"absolute right-0 top-full z-40 mt-1.5 w-[380px] max-w-[90vw] rounded-xl border border-dark-border bg-dark-surface shadow-2xl overflow-hidden",children:[u.jsxs("div",{className:"flex items-center gap-2 px-3.5 py-2.5 border-b border-dark-border bg-dark-surface",children:[u.jsx(vs,{size:14,className:"text-accent-blue"}),u.jsx("span",{className:"text-xs font-medium text-dark-text",children:e("git.panelTitle")}),u.jsx("div",{className:"flex-1"}),u.jsx("button",{onClick:()=>void be.getState().refreshAll(),className:"rounded p-1 text-dark-muted hover:text-dark-text hover:bg-dark-hover transition-colors",title:e("git.refresh"),children:u.jsx(pn,{size:12,className:Le(be.getState().refreshing&&"animate-spin")})})]}),_?u.jsxs("div",{className:"px-3.5 py-4 text-center",children:[u.jsx(eo,{size:20,className:"mx-auto mb-2 text-dark-muted/50"}),u.jsx("div",{className:"text-xs text-dark-muted",children:e("git.notGitDesc")}),u.jsx("div",{className:"mt-1 text-[10px] font-mono text-dark-muted/60 break-all",children:a})]}):t?u.jsxs("div",{className:"p-3.5 space-y-3 max-h-[60vh] overflow-y-auto custom-scrollbar",children:[u.jsxs("div",{children:[u.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[u.jsx("span",{className:"text-[11px] text-dark-muted",children:e("git.changes")}),u.jsxs("span",{className:"text-[11px] font-mono tabular-nums",children:[u.jsxs("span",{className:"text-accent-green",children:["+",t.totalAdded??0]}),u.jsx("span",{className:"text-dark-muted/40",children:" / "}),u.jsxs("span",{className:"text-accent-red",children:["−",t.totalRemoved??0]})]})]}),u.jsxs("div",{className:"space-y-0.5 max-h-40 overflow-y-auto custom-scrollbar",children:[(t.changes||[]).slice(0,30).map(x=>u.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-mono",children:[u.jsx("span",{className:Le("w-6 shrink-0 rounded px-1 text-center text-[9px]",x.status.includes("?")?"bg-accent-purple/15 text-accent-purple":x.status===x.status.toUpperCase()&&x.status.trim()?"bg-accent-green/15 text-accent-green":"bg-accent-yellow/15 text-accent-yellow"),children:x.status}),u.jsx("span",{className:"flex-1 truncate text-dark-text",children:x.path}),u.jsxs("span",{className:"shrink-0 text-[10px] tabular-nums text-dark-muted/60",children:[x.added>0&&u.jsxs("span",{className:"text-accent-green",children:["+",x.added]}),x.removed>0&&u.jsxs("span",{className:"text-accent-red",children:["−",x.removed]})]})]},x.path)),(t.changes||[]).length===0&&u.jsx("div",{className:"py-2 text-center text-[11px] text-dark-muted/60",children:e("git.clean")})]})]}),u.jsxs("div",{children:[u.jsx("div",{className:"text-[11px] text-dark-muted mb-1",children:e("git.branch")}),u.jsx("div",{className:"flex flex-wrap gap-1",children:((n==null?void 0:n.branches)||[t.branch||""]).slice(0,8).map(x=>u.jsx("button",{onClick:()=>x!==t.branch&&T(x),disabled:x===t.branch,className:Le("rounded-md px-2 py-1 text-[11px] font-mono transition-colors",x===t.branch?"bg-accent-blue/10 text-accent-blue cursor-default":"bg-dark-bg border border-dark-border text-dark-muted hover:border-accent-blue/40 hover:text-dark-text"),children:x},x))}),(t.ahead??0)>0||(t.behind??0)>0?u.jsxs("div",{className:"mt-1 text-[10px] text-dark-muted/70",children:[(t.ahead??0)>0&&u.jsxs("span",{className:"text-accent-green",children:["↑ ",t.ahead," "]}),(t.behind??0)>0&&u.jsxs("span",{className:"text-accent-yellow",children:["↓ ",t.behind]}),e("git.upstream")]}):null]}),u.jsx("div",{children:p?u.jsxs("div",{className:"space-y-1.5",children:[u.jsx("textarea",{value:c,onChange:x=>{d(x.target.value),localStorage.setItem(Ht,x.target.value)},placeholder:e("git.commitPlaceholder"),rows:2,className:"w-full rounded-md border border-dark-border bg-dark-bg px-2.5 py-1.5 text-xs text-dark-text placeholder-dark-muted/50 resize-none focus:outline-none focus:border-accent-blue/50"}),u.jsxs("div",{className:"flex gap-1.5",children:[u.jsxs("button",{onClick:C,disabled:r||!c.trim(),className:"flex flex-1 items-center justify-center gap-1 rounded-md bg-accent-green/15 text-accent-green px-2.5 py-1.5 text-xs hover:bg-accent-green/25 transition-colors disabled:opacity-40",children:[r?u.jsx(wt,{size:12,className:"animate-spin"}):u.jsx(ws,{size:12}),e("git.commitConfirm")]}),u.jsx("button",{onClick:()=>h(!1),className:"rounded-md px-2.5 py-1.5 text-xs text-dark-muted hover:bg-dark-hover transition-colors",children:e("common.cancel")})]})]}):u.jsxs("div",{className:"flex gap-1.5",children:[u.jsxs("button",{onClick:()=>h(!0),disabled:r,className:"flex flex-1 items-center justify-center gap-1.5 rounded-md bg-accent-blue/10 text-accent-blue px-2.5 py-1.5 text-xs hover:bg-accent-blue/20 transition-colors disabled:opacity-50",children:[u.jsx(ws,{size:13}),e("git.commit")]}),u.jsxs("button",{onClick:S,disabled:r||!t.dirty,className:"flex items-center justify-center gap-1.5 rounded-md bg-dark-bg border border-dark-border text-dark-muted px-2.5 py-1.5 text-xs hover:border-accent-green/40 hover:text-accent-green transition-colors disabled:opacity-40",children:[u.jsx(to,{size:13}),e("git.push")]})]})}),u.jsxs("div",{className:"flex items-center gap-1.5 rounded-md bg-dark-bg border border-dark-border px-2.5 py-2",children:[u.jsx(At,{size:13,className:"text-accent-purple shrink-0"}),u.jsx("span",{className:"text-[11px] text-dark-muted truncate",children:f?f.available?e("git.prReady"):f.message||e("git.prUnavailable"):e("git.prLoading")})]}),u.jsxs("div",{className:"rounded-md bg-dark-bg border border-dark-border px-2.5 py-2 space-y-0.5",children:[u.jsx("div",{className:"text-[10px] text-dark-muted",children:e("git.environment")}),u.jsx("div",{className:"text-[11px] font-mono text-dark-text/80 break-all",children:a||"—"}),t.lastCommit&&u.jsxs("div",{className:"text-[10px] font-mono text-dark-muted/60 truncate",children:[t.lastCommit.hash.slice(0,7)," ",t.lastCommit.subject]})]}),o&&u.jsxs("div",{className:Le("flex items-center gap-1.5 text-[11px]",o.ok?"text-accent-green":"text-accent-red"),children:[o.ok?u.jsx(so,{size:12}):u.jsx(no,{size:12}),u.jsx("span",{className:"truncate",children:o.ok?e("git.ok"):o.error||""})]})]}):u.jsx("div",{className:"px-3.5 py-4 text-center text-xs text-dark-muted",children:e("git.loading")})]})]})}),ga={info:fn,success:oo,warning:is,error:hn},ya={info:"border-accent-blue/30 bg-accent-blue/10 text-accent-blue",success:"border-accent-green/30 bg-accent-green/10 text-accent-green",warning:"border-accent-yellow/30 bg-accent-yellow/10 text-accent-yellow",error:"border-accent-red/30 bg-accent-red/10 text-accent-red"},ba=g.memo(function(){const{toasts:e,dismissToast:t}=st();return e.length===0?null:u.jsx("div",{className:"fixed bottom-20 right-4 z-[100] flex flex-col gap-2 max-w-sm",children:e.map(n=>{const r=ga[n.type];return u.jsxs("div",{className:`flex items-start gap-2 px-3 py-2.5 rounded-lg border shadow-lg animate-fade-in-up ${ya[n.type]}`,children:[u.jsx(r,{size:16,className:"shrink-0 mt-0.5"}),u.jsx("span",{className:"text-xs flex-1",children:n.message}),u.jsx("button",{onClick:()=>t(n.id),className:"shrink-0 p-0.5 rounded hover:bg-dark-hover/50 transition-colors",children:u.jsx(lt,{size:12})})]},n.id)})})}),xa={critical:{icon:ro,border:"border-accent-red",bg:"bg-accent-red/10",text:"text-accent-red"},error:{icon:hn,border:"border-accent-red/60",bg:"bg-accent-red/5",text:"text-accent-red"},warning:{icon:is,border:"border-accent-yellow/60",bg:"bg-accent-yellow/5",text:"text-accent-yellow"},info:{icon:fn,border:"border-accent-blue/60",bg:"bg-accent-blue/5",text:"text-accent-blue"}},ka=g.memo(function(){const e=De(n=>n.errors.filter(r=>!r.dismissed)),t=De(n=>n.dismiss);return e.length===0?null:u.jsx("div",{className:"fixed bottom-4 right-4 z-[110] flex flex-col gap-2 max-w-sm",children:e.map(n=>{const r=xa[n.level],o=r.icon;return u.jsx(Sa,{entry:n,icon:o,config:r,onDismiss:()=>t(n.id)},n.id)})})});function Sa({entry:s,icon:e,config:t,onDismiss:n}){const[r,o]=g.useState(!1);return u.jsxs("div",{className:`flex flex-col px-3 py-2.5 rounded-lg border shadow-lg animate-fade-in-up ${t.bg} ${t.border}`,children:[u.jsxs("div",{className:"flex items-start gap-2",children:[u.jsx(e,{size:16,className:`shrink-0 mt-0.5 ${t.text}`}),u.jsx("span",{className:`text-xs flex-1 ${t.text}`,children:s.title}),u.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[s.detail&&u.jsx("button",{onClick:()=>o(!r),className:"p-0.5 rounded hover:bg-dark-hover/50 transition-colors",children:r?u.jsx(Bt,{size:12}):u.jsx(dn,{size:12})}),u.jsx("button",{onClick:n,className:"p-0.5 rounded hover:bg-dark-hover/50 transition-colors",children:u.jsx(lt,{size:12})})]})]}),r&&s.detail&&u.jsx("div",{className:"mt-1.5 ml-6 text-[11px] text-dark-muted whitespace-pre-wrap break-words leading-relaxed border-t border-dark-border/50 pt-1.5",children:s.detail}),s.action&&u.jsx("button",{onClick:s.action.onClick,className:"mt-1.5 ml-6 self-start text-[11px] px-2 py-0.5 rounded bg-dark-hover hover:bg-dark-border transition-colors",children:s.action.label})]})}function va(s){const{t:e}=Ee(),{setActiveTab:t,createNewSession:n,clearMessages:r,setTheme:o,setThemePreset:a,toggleTerminal:i,setLogs:l,setUnreadLogs:c}=s,d=ls(b=>b.backendCommands),p=Array.isArray(d)?d:[],[h,f]=g.useState(!1),[m,y]=g.useState(""),[v,C]=g.useState(0),S=g.useRef(null),T=g.useCallback((b,A)=>{const F=V.getState().activeSessionId;return F?(I.setSessionId(F),I.send({type:"command_execute",sessionId:F,data:JSON.stringify({command:`/${b}`,args:A||""})}),{success:!0,message:e("slashCommands.sent_command")+`/${b}`}):{success:!1,message:e("slashCommands.noActiveSession")}},[e]),_=g.useMemo(()=>[{id:"chat",name:"chat",description:e("slashCommands.chat_desc"),icon:"💬",local:!0,action:()=>(t("chat"),{success:!0,message:e("slashCommands.chat_result")})},{id:"terminal",name:"terminal",description:e("slashCommands.terminal_desc"),icon:"💻",local:!0,action:()=>(t("terminal"),{success:!0,message:e("slashCommands.terminal_result")})},{id:"files",name:"files",description:e("slashCommands.files_desc"),icon:"📁",local:!0,action:()=>(t("files"),{success:!0,message:e("slashCommands.files_result")})},{id:"models",name:"models",description:e("slashCommands.models_desc"),icon:"🧠",local:!0,action:()=>(t("models"),{success:!0,message:e("slashCommands.models_result")})},{id:"tools",name:"tools",description:e("slashCommands.tools_desc"),icon:"🔧",local:!0,action:()=>(t("tools"),{success:!0,message:e("slashCommands.tools_result")})},{id:"skills",name:"skills",description:e("slashCommands.skills_desc"),icon:"🎯",local:!0,action:()=>(t("skills"),{success:!0,message:e("slashCommands.skills_result")})},{id:"agents",name:"agents",description:e("slashCommands.agents_desc"),icon:"👥",local:!0,action:()=>(t("agents"),{success:!0,message:e("slashCommands.agents_result")})},{id:"settings",name:"settings",description:e("slashCommands.settings_desc"),icon:"⚙️",local:!0,action:()=>(t("settings"),{success:!0,message:e("slashCommands.settings_result")})},{id:"logs",name:"logs",description:e("slashCommands.logs_desc"),icon:"📜",local:!0,action:()=>(t("logs"),c(0),{success:!0,message:e("slashCommands.logs_result")})},{id:"new",name:"new",description:e("slashCommands.new_desc"),icon:"✨",local:!0,action:()=>(n(),{success:!0,message:e("slashCommands.new_result")})},{id:"clear",name:"clear",description:e("slashCommands.clear_desc"),icon:"🗑️",local:!0,action:()=>(r(),{success:!0,message:e("slashCommands.clear_result")})},{id:"theme",name:"theme",description:e("slashCommands.theme_desc"),args:"<dark|light|auto|preset-name>",icon:"🎨",local:!0,action:b=>{const A=b.trim().toLowerCase();if(["dark","light","auto"].includes(A))return o(A),{success:!0,message:e("slashCommands.theme_result")+A};if(at[A])return a?(a(A),{success:!0,message:e("slashCommands.theme_preset_result")+at[A].nameKey}):{success:!1,message:e("slashCommands.theme_preset_unavailable")};const F=Object.keys(at).join("|");return{success:!1,message:e("slashCommands.theme_error",{presets:F})}}},{id:"terminal-toggle",name:"terminal-toggle",description:e("slashCommands.toggle_terminal_desc"),icon:"🔲",local:!0,action:()=>(i(),{success:!0,message:e("slashCommands.toggle_terminal_result")})},{id:"clear-logs",name:"clear-logs",description:e("slashCommands.logs_clear_desc"),icon:"📭",local:!0,action:()=>(l([]),c(0),{success:!0,message:e("slashCommands.logs_clear_result")})},{id:"doctor",name:"doctor",description:e("slashCommands.doctor_desc"),icon:"🩺",local:!1,action:()=>T("doctor")},{id:"compact",name:"compact",description:e("slashCommands.compact_desc"),args:"[aggressive|summary]",icon:"🗜️",local:!1,action:b=>T("compact",b)},{id:"help",name:"help",description:e("slashCommands.help_desc"),icon:"❓",local:!1,action:()=>T("help")},{id:"cost",name:"cost",description:e("slashCommands.token_desc"),args:"[detail|reset]",icon:"💰",local:!1,action:b=>T("cost",b)},{id:"model",name:"model",description:e("slashCommands.model_desc"),args:"[model-name]",icon:"🤖",local:!1,action:b=>T("model",b)},{id:"status",name:"status",description:e("slashCommands.status_desc"),icon:"📊",local:!1,action:()=>T("status")},{id:"config",name:"config",description:e("slashCommands.config_desc"),args:"<get|set|list|delete> [key] [value]",icon:"🔧",local:!1,action:b=>T("config",b)},{id:"exit",name:"exit",description:e("slashCommands.exit_desc"),icon:"🚪",local:!1,action:()=>{const b=V.getState().activeSessionId;return b&&(I.setSessionId(b),I.send({type:"exit",sessionId:b})),{success:!0,message:e("slashCommands.exit_result")}}},{id:"test",name:"test",description:e("slashCommands.benchmark_desc"),args:"[simple|medium|complex|full|list]",icon:"🧪",local:!1,action:b=>T("test",b)}],[t,n,r,o,a,i,l,c,T,e]),x=g.useMemo(()=>p.map(b=>{const A=e(`slashCommands.${b.name}_desc`,b.description||b.usage||"");return{id:`backend-${b.name}`,name:b.name,description:A,icon:"🔌",local:!1,action:F=>{const U=V.getState().activeSessionId;return U?(I.setSessionId(U),I.send({type:"command_execute",sessionId:U,data:JSON.stringify({command:`/${b.name}`,args:F||""})}),{success:!0,message:e("slashCommands.sent_command")+`/${b.name}`}):{success:!1,message:e("slashCommands.noActiveSession")}}}}),[p,e]),R=g.useMemo(()=>{const b=new Set;return[..._,...x].filter(A=>b.has(A.name)?!1:(b.add(A.name),!0))},[_,x]),j=g.useMemo(()=>{if(!m)return R;const b=m.toLowerCase();return R.filter(A=>A.name.toLowerCase().includes(b)||A.description.toLowerCase().includes(b))},[R,m]),D=g.useCallback(()=>{f(!0),y(""),C(0)},[]),O=g.useCallback(()=>{f(!1),y(""),C(0)},[]),W=g.useCallback(()=>{C(b=>b>=j.length-1?0:b+1)},[j.length]),ne=g.useCallback(()=>{C(b=>b<=0?j.length-1:b-1)},[j.length]),N=g.useCallback((b,A)=>{const F=b.action(A);return O(),F},[O]);return g.useEffect(()=>{if(h&&S.current){const b=S.current.querySelector(`[data-index="${v}"]`);b&&b.scrollIntoView({block:"nearest"})}},[v,h]),{isOpen:h,filter:m,setFilter:y,selectedIndex:v,setSelectedIndex:C,filteredCommands:j,openMenu:D,closeMenu:O,selectNext:W,selectPrev:ne,executeCommand:N,containerRef:S,commands:_}}function wa({open:s,onClose:e,options:t}){const{t:n}=Ee(),{filter:r,setFilter:o,filteredCommands:a,selectedIndex:i,setSelectedIndex:l,selectNext:c,selectPrev:d,executeCommand:p,openMenu:h,closeMenu:f}=va(t),m=g.useRef(null),y=g.useRef(null),[v,C]=g.useState(!1);if(g.useEffect(()=>{s?(h(),C(!1),setTimeout(()=>{var _;return(_=m.current)==null?void 0:_.focus()},0)):f()},[s,h,f]),g.useEffect(()=>{if(!s||!y.current)return;const _=y.current.querySelector(`[data-cmd-index="${i}"]`);_&&_.scrollIntoView({block:"nearest"})},[i,s]),!s)return null;const S=_=>{_.local||(C(!0),X.info(n("palette.running")));const x=p(_,"");_.local&&(x!=null&&x.message)&&X.success(x.message),e()},T=_=>{if(_.key==="ArrowDown")_.preventDefault(),c();else if(_.key==="ArrowUp")_.preventDefault(),d();else if(_.key==="Enter"){_.preventDefault();const x=a[i];x&&S(x)}else _.key==="Escape"&&(_.preventDefault(),e())};return u.jsx("div",{className:"fixed inset-0 z-[100] flex items-start justify-center bg-black/50 backdrop-blur-sm pt-[12vh] px-4 animate-fade-in",onClick:e,role:"dialog","aria-modal":"true","aria-label":n("a11y.commandPalette"),children:u.jsxs("div",{className:"w-full max-w-xl bg-dark-surface border border-dark-border rounded-xl shadow-2xl overflow-hidden",onClick:_=>_.stopPropagation(),children:[u.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-dark-border",children:[u.jsx(ao,{size:16,className:"text-dark-muted shrink-0","aria-hidden":"true"}),u.jsx("input",{ref:m,value:r,onChange:_=>{o(_.target.value),l(0)},onKeyDown:T,placeholder:n("palette.placeholder"),"aria-label":n("palette.placeholder"),className:"flex-1 bg-transparent text-sm text-dark-text placeholder-dark-muted outline-none"}),v&&u.jsx("span",{className:"text-[10px] text-accent-blue animate-pulse-soft shrink-0",children:n("palette.running")})]}),u.jsx("div",{ref:y,className:"max-h-[50vh] overflow-y-auto custom-scrollbar py-1",children:a.length===0?u.jsx("div",{className:"px-4 py-8 text-center text-sm text-dark-muted",children:n("palette.empty")}):a.map((_,x)=>u.jsxs("button",{"data-cmd-index":x,onClick:()=>S(_),onMouseEnter:()=>l(x),className:`w-full px-4 py-2.5 flex items-center gap-3 text-left transition-colors ${x===i?"bg-accent-blue/10 border-l-2 border-accent-blue":"border-l-2 border-transparent hover:bg-dark-hover"}`,children:[u.jsx("span",{className:"text-lg shrink-0","aria-hidden":"true",children:_.icon}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsxs("span",{className:"text-sm font-medium text-dark-text",children:["/",_.name]}),_.args&&u.jsx("span",{className:"text-xs text-dark-muted",children:_.args}),!_.local&&u.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-accent-blue/20 text-accent-blue shrink-0",children:n("slashCommands.backend")})]}),u.jsx("div",{className:"text-xs text-dark-muted truncate",children:_.description})]}),x===i&&u.jsx(io,{size:14,className:"text-dark-muted shrink-0","aria-hidden":"true"})]},_.id))}),u.jsx("div",{className:"px-4 py-2 border-t border-dark-border text-[10px] text-dark-muted bg-dark-bg",children:n("palette.hint")})]})})}function Ca({isOpen:s,onClose:e,title:t,children:n,size:r="md",className:o}){if(g.useEffect(()=>{const i=l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),e())};return s&&(document.addEventListener("keydown",i),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",i),document.body.style.overflow=""}},[s,e]),!s)return null;const a={sm:"max-w-sm",md:"max-w-md",lg:"max-w-lg",xl:"max-w-xl"};return u.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center overflow-hidden p-4",children:[u.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),u.jsxs("div",{className:Le("relative w-full mx-4 bg-dark-surface border border-dark-border rounded-xl shadow-2xl animate-fade-in","max-h-[calc(100vh-2rem)] flex flex-col overflow-hidden",a[r],o),children:[t&&u.jsxs("div",{className:"flex shrink-0 items-center justify-between px-6 py-4 border-b border-dark-border",children:[u.jsx("h2",{className:"text-lg font-semibold text-dark-text",children:t}),u.jsx("button",{onClick:e,"aria-label":"Close",className:"p-1 rounded-lg text-dark-muted hover:text-dark-text hover:bg-dark-hover transition-colors",children:u.jsx(lt,{className:"w-5 h-5","aria-hidden":"true"})})]}),u.jsx("div",{className:"min-h-0 overflow-y-auto custom-scrollbar p-6",children:n})]})]})}function Te({keys:s,label:e}){return u.jsxs("div",{className:"flex items-center justify-between py-2 border-b border-dark-border/50 last:border-0",children:[u.jsx("span",{className:"text-sm text-dark-text",children:e}),u.jsx("span",{className:"flex items-center gap-1",children:s.map(t=>u.jsx("kbd",{className:"px-2 py-0.5 text-xs font-mono bg-dark-bg rounded border border-dark-border text-dark-muted",children:t},t))})]})}function _a({open:s,onClose:e}){const{t}=Ee(),n=navigator.platform.toLowerCase().includes("mac")?"⌘":"Ctrl";return u.jsx(Ca,{isOpen:s,onClose:e,title:t("shortcuts.title"),size:"md",children:u.jsxs("div",{className:"space-y-0.5",children:[u.jsx(Te,{keys:[n,"K"],label:t("shortcuts.commandPalette")}),u.jsx(Te,{keys:[n,"L"],label:t("shortcuts.clearLogs")}),u.jsx(Te,{keys:[n,"/"],label:t("shortcuts.help")}),u.jsx(Te,{keys:[n,"Enter"],label:t("shortcuts.submit")}),u.jsx(Te,{keys:["Shift","Enter"],label:t("shortcuts.newline")}),u.jsx(Te,{keys:["/"],label:t("shortcuts.slashCommand")}),u.jsx(Te,{keys:["@"],label:t("shortcuts.fileRef")}),u.jsx(Te,{keys:["Esc"],label:t("shortcuts.closeDialog")}),u.jsx(Te,{keys:["Esc","Esc"],label:t("shortcuts.stopGen")})]})})}const Ta={"pull-requests":At,scheduled:as,plugins:Et},Na={"pull-requests":"Agent 发起的 PR 列表将在这里展示。配置 git 远端与 PR 提供方(如 GitHub CLI)后可用。",scheduled:"定时任务(如每晚跑测试数据)将在这里管理。",plugins:"插件管理入口。可启停文件处理技能等扩展能力。"};function Ba({tabId:s}){const{t:e}=Ee(),t=Ta[s]||Et;return u.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center",children:[u.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-2xl border border-dark-border bg-dark-surface",children:u.jsx(t,{size:24,className:"text-accent-blue"})}),u.jsx("h2",{className:"text-sm font-medium text-dark-text",children:e(`nav.${s}`)}),u.jsx("p",{className:"max-w-sm text-xs leading-relaxed text-dark-muted",children:Na[s]||"功能开发中…"}),u.jsx("span",{className:"mt-1 rounded-full border border-accent-blue/30 bg-accent-blue/10 px-2.5 py-0.5 text-[10px] text-accent-blue",children:e("placeholder.comingSoon")})]})}const Aa=g.lazy(()=>re(()=>import("./ModelsView-YK7jq8J0.js"),__vite__mapDeps([0,1,2,3,4,5])).then(s=>({default:s.ModelsView}))),Ea=g.lazy(()=>re(()=>import("./ToolsView-BcTnj3DK.js"),__vite__mapDeps([6,1,2,4,5])).then(s=>({default:s.ToolsView}))),Pa=g.lazy(()=>re(()=>import("./AgentFlowView-D_eqHssN.js"),__vite__mapDeps([7,1,2,4,5])).then(s=>({default:s.AgentFlowView}))),ja=g.lazy(()=>re(()=>import("./SkillsView-CjR2b3-r.js"),__vite__mapDeps([8,1,2,3,4,5])).then(s=>({default:s.SkillsView}))),Ra=g.lazy(()=>re(()=>import("./AgentsView-DxXbT1TA.js"),__vite__mapDeps([9,1,2,4,5])).then(s=>({default:s.AgentsView}))),La=g.lazy(()=>re(()=>import("./HookConfigView-BddeGF3E.js"),__vite__mapDeps([10,1,2,5,4])).then(s=>({default:s.HookConfigView}))),Ma=g.lazy(()=>re(()=>import("./FileTreeView-xuW_AJmw.js"),__vite__mapDeps([11,1,2,4,5])).then(s=>({default:s.FileTreeView}))),Ia=g.lazy(()=>re(()=>import("./TerminalView-Okh3EsS2.js"),__vite__mapDeps([12,1,2,13,4,5,14])).then(s=>({default:s.TerminalView}))),Oa=g.lazy(()=>re(()=>import("./SessionGrid-OuKqyYjF.js"),__vite__mapDeps([15,1,2,16,4,5])).then(s=>({default:s.SessionGrid}))),$a=g.lazy(()=>re(()=>import("./SettingsPanel-BK2mvSsv.js"),__vite__mapDeps([17,1,2,4,5])).then(s=>({default:s.SettingsPanel}))),Da=g.lazy(()=>re(()=>Promise.resolve().then(()=>Wr),void 0).then(s=>({default:s.LogsPanel}))),Fa=g.lazy(()=>re(()=>import("./HookApprovalModal-Dnrkw1Mh.js"),__vite__mapDeps([18,1,2,16,4,5])).then(s=>({default:s.HookApprovalModal}))),Wa=g.lazy(()=>re(()=>import("./AskQuestionModal-OOxUqiN1.js"),__vite__mapDeps([19,1,2,4,5])).then(s=>({default:s.AskQuestionModal}))),Ha=g.lazy(()=>re(()=>import("./ChannelConfigView-gal4YqIE.js"),__vite__mapDeps([20,1,2,4,5])).then(s=>({default:s.ChannelConfigView}))),Ua=g.lazy(()=>re(()=>import("./InboxView-DOIcm5GF.js"),__vite__mapDeps([21,1,2,4,5])).then(s=>({default:s.InboxView}))),Ga=g.lazy(()=>re(()=>import("./AutomationView-Dnkht7AC.js"),__vite__mapDeps([22,1,2,4,5])).then(s=>({default:s.AutomationView}))),za=g.lazy(()=>re(()=>import("./AuditView-DLmHV1Xa.js"),__vite__mapDeps([23,1,2,4,5])).then(s=>({default:s.AuditView}))),en=()=>u.jsx("div",{className:"flex-1 flex items-center justify-center bg-dark-bg",children:u.jsx("div",{className:"w-5 h-5 border-2 border-accent-blue border-t-transparent rounded-full animate-spin"})}),Ut={chat:"nav.chat",terminal:"nav.terminal",files:"nav.files",models:"nav.models",tools:"nav.tools",skills:"nav.skills",agents:"nav.agents",hooks:"nav.hooks",channels:"nav.channels",inbox:"nav.inbox",audit:"nav.audit",settings:"nav.settings",logs:"nav.logs","pull-requests":"nav.pullRequests",scheduled:"nav.scheduled",plugins:"nav.plugins"},Ka=[{id:"chat",title:"对话"},{id:"terminal",title:"终端"},{id:"files",title:"文件"},{id:"models",title:"模型"},{id:"tools",title:"工具"},{id:"skills",title:"技能"},{id:"agents",title:"Agents"},{id:"hooks",title:"Hooks"},{id:"channels",title:"频道"},{id:"inbox",title:"Inbox"},{id:"audit",title:"审计"},{id:"scheduled",title:"自动化"},{id:"logs",title:"日志"},{id:"settings",title:"设置"},{id:"pull-requests",title:"Pull requests"},{id:"plugins",title:"Plugins"}],qa={chat:un,terminal:bo,files:yo,models:go,tools:mo,skills:fo,agents:ho,hooks:po,channels:uo,inbox:co,audit:Fe,logs:Fe,settings:lo,"pull-requests":At,scheduled:as,plugins:Et};function Va(){const[s,e]=g.useState("chat"),[t,n]=g.useState(!1),[r,o]=g.useState([]),[,a]=g.useState(0),[i,l]=g.useState(!1),[c,d]=g.useState(!1),[p,h]=g.useState(!1),[f,m]=g.useState(!1),[y,v]=g.useState(null),[C,S]=g.useState(!1),[T,_]=g.useState(!1),[x,R]=g.useState(!0),[j,D]=g.useState(()=>window.innerWidth>=1400),[O,W]=g.useState(()=>localStorage.getItem("dsc-sidebar-collapsed")==="1"),ne=g.useCallback(()=>{W(w=>(localStorage.setItem("dsc-sidebar-collapsed",w?"0":"1"),!w))},[]);g.useEffect(()=>{const w=window.matchMedia("(min-width: 1400px)"),E=K=>D(K.matches);return w.addEventListener("change",E),()=>w.removeEventListener("change",E)},[]);const{t:N,i18n:b}=Ee(),{toggleTerminal:A}=kr(),{theme:F,setTheme:U,setThemePreset:se,language:B,workspaceDir:M,setWorkspaceDir:$}=He(),P=Be();g.useEffect(()=>{B&&b.language!==B&&b.changeLanguage(B)},[B,b]);const le=g.useMemo(()=>Ka.filter(w=>!(w.id==="terminal"&&y===!1)),[y]),ce=g.useMemo(()=>le.map(w=>({...w,iconComponent:qa[w.id]})),[le]),H=g.useCallback(w=>{g.startTransition(()=>{e(w)})},[]);g.useEffect(()=>{const w=K=>{const z=K.message||N("common.unknownError"),fe=K.filename||"global";fe.includes("chrome-extension://")||fe.includes("moz-extension://")||o(oe=>[...oe,{id:`error-${Date.now()}-${Ae()}`,level:"error",source:"Browser",message:`${N("toast.uncaughtError")}${z}`,timestamp:Date.now()}].slice(-500))},E=K=>{var fe;const z=((fe=K.reason)==null?void 0:fe.message)||K.reason||N("toast.unknownReason");o(oe=>[...oe,{id:`rejection-${Date.now()}-${Ae()}`,level:"error",source:"Promise",message:`${N("toast.uncaughtRejection")}${z}`,timestamp:Date.now()}].slice(-500))};return window.addEventListener("error",w),window.addEventListener("unhandledrejection",E),()=>{window.removeEventListener("error",w),window.removeEventListener("unhandledrejection",E)}},[N]);const{sessionTabs:Pe,activeSessionId:Z,setActiveSession:ht,addSessionTab:he,closeSessionTab:ft,renameSessionTab:ps,getVisibleSessionTabs:Rn,autoNameSession:hs}=V(),{clearMessages:fs}=G(),{customTheme:Ln,customThemeEnabled:Mn,themePresetId:In}=He();pa({theme:F,themePresetId:In,customTheme:Ln,customThemeEnabled:Mn}),da({activeTab:s,setLogs:o,setUnreadLogs:a}),g.useEffect(()=>{k.get("/api/terminal/status").then(w=>v(w.success&&w.data?w.data.ttydAvailable!==!1:!1)).catch(()=>v(!1))},[]),g.useEffect(()=>{const w=E=>{const K=E.detail;K&&K!==s&&H(K)};return window.addEventListener("switch-tab",w),()=>window.removeEventListener("switch-tab",w)},[s,H]),g.useEffect(()=>{const w=window.location.hash.replace(/^#\/?/,"");!w||!(w in Ut)||H(w)},[]),g.useEffect(()=>{const w=I.onOpen(()=>{n(!0),X.success(N("toast.backendConnected"))}),E=I.onClose(()=>{t&&X.warning(N("toast.backendDisconnected")),n(!1)});return()=>{w(),E()}},[t,N]),g.useEffect(()=>{Pe.length===0&&he(N("chat.defaultSessionTitle",{n:1}))},[]),g.useEffect(()=>{const w=()=>d(!0);return window.addEventListener("hook-approval-required",w),()=>window.removeEventListener("hook-approval-required",w)},[]),g.useEffect(()=>{const w=()=>h(!0);return window.addEventListener("ask-question-required",w),()=>window.removeEventListener("ask-question-required",w)},[]),g.useEffect(()=>{P.autoMode&&P.pendingApprovals.length>0&&d(!1),P.pendingApprovals.length>0&&!P.autoMode&&d(!0)},[P.autoMode,P.pendingApprovals.length]);const ms=g.useRef(0);g.useEffect(()=>{const w=E=>{var ie,me;if(E.key!=="Escape"||E.defaultPrevented)return;const K=(ie=E.target)==null?void 0:ie.tagName;if(K==="INPUT"||K==="TEXTAREA"||(me=E.target)!=null&&me.isContentEditable)return;const z=G.getState(),oe=V.getState().activeSessionId;if(!oe||!z.isGenerating(oe))return;E.preventDefault();const ye=Date.now(),ke=ms.current;ms.current=ye,ke>0&&ye-ke<500?(I.send({type:"stop",sessionId:oe}),X.info(N("toast.terminated"))):(I.send({type:"pause",sessionId:oe}),X.info(N("toast.paused")))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[N]);const Ie=g.useCallback(()=>{g.startTransition(()=>{const w=he(void 0,M);I.setSessionId(w),Nt.getState().setMode("act"),H("chat")})},[he,M,H]),gs=g.useCallback(w=>{ht(w),I.setSessionId(w)},[ht]),ys=g.useCallback(w=>{ft(w)},[ft]),bs=g.useCallback((w,E)=>{ps(w,E)},[ps]),jt=g.useCallback(()=>{Z&&fs(Z)},[Z,fs]);g.useEffect(()=>{if(!Z)return;const w=G.getState().messagesBySession[Z];w&&w.length>0&&J.getState().recalculateFromMessages(w)},[Z]);const Rt=g.useCallback(async(w,E,K,z)=>{if(!E.trim())return;G.getState().isGenerating(w)&&(console.warn(`[sendMessage] Session ${w} stuck in generating state — force-ending`),G.getState().endGeneration(w,"Force-ended: new message"));const oe=Nt.getState();G.getState().resumeGeneration(w),I.setSessionId(w),G.getState().getMessages(w).some(je=>je.type==="user")||hs(w,E.trim());let ie=E.trim();if(K&&K.length>0){const je=[];for(const ze of K)try{const Ke=await q.files.read(ze),ks=Ke.success&&Ke.data?Ke.data:null;if(ks){ie=ie.replace(ze,"");const zn=ze.split(".").pop()||"";je.push(`<context ref="${ze}">
|
|
13
|
+
\`\`\`${zn}
|
|
14
|
+
${ks}
|
|
15
|
+
\`\`\`
|
|
16
|
+
</context>`)}}catch(Ke){console.warn(`Failed to read @-referenced file: ${ze}`,Ke)}je.length>0&&(ie=je.join(`
|
|
17
|
+
|
|
18
|
+
`)+`
|
|
19
|
+
|
|
20
|
+
`+ie.trim(),ie=ie.trim())}z!=null&&z.skipAddUserMessage||G.getState().addMessage(w,{id:`msg-${Date.now()}`,type:"user",content:ie,timestamp:Date.now()});const me=oe.mode,xs=ve(me==="normal"?"act":me);if(xs==="plan")I.send({type:"plan",sessionId:w,message:ie});else if(xs==="goal"){const je=`wf-${Date.now()}-${Ae()}`;G.getState().startGeneration(w),ue.getState().upsert(w,{runId:je,status:"RUNNING",completedPhases:0,totalPhases:0,completedEffects:0,totalEffects:0,tokensUsed:0,tokensRemaining:0,lastEventType:"workflow_start"}),I.send({type:"workflow_start",sessionId:w,runId:je,message:ie,projectId:M,memoryEnabled:!0,checkpointPolicy:"phase-and-token"})}else I.send({type:"chat",sessionId:w,message:ie})},[hs,M]),On=g.useCallback((w,E)=>{var ke,ie;const K=G.getState(),z=K.getMessages(w),fe=z.findIndex(me=>me.id===E);if(fe===-1)return;let oe=-1;for(let me=fe-1;me>=0;me--)if(((ke=z[me])==null?void 0:ke.type)==="user"){oe=me;break}if(oe===-1)return;const ye=z[oe];(ie=ye==null?void 0:ye.content)!=null&&ie.trim()&&(K.replaceMessages(w,z.slice(0,oe+1)),Rt(w,ye.content,void 0,{skipAddUserMessage:!0}))},[Rt]),$n=g.useCallback((w,E)=>{G.getState().applyTombstone(w,[E]),X.success(N("chat.messageDeleted"))},[N]),Dn=g.useCallback(w=>{const E=ue.getState().getForSession(w);E&&!["COMPLETED","CANCELLED","ERROR","FAILED"].includes(E.status)?I.send({type:"workflow_cancel",sessionId:w,runId:E.runId}):I.send({type:"stop",sessionId:w}),G.getState().endGeneration(w)},[]),Fn=g.useCallback(w=>{const E=ue.getState().getForSession(w);E&&["RUNNING","RESUMING"].includes(E.status)?I.send({type:"workflow_pause",sessionId:w,runId:E.runId}):I.send({type:"pause",sessionId:w}),G.getState().pauseGeneration(w)},[]),Wn=g.useCallback(w=>{const E=ue.getState().getForSession(w);E&&E.status==="PAUSED"?I.send({type:"workflow_resume",sessionId:w,runId:E.runId}):I.send({type:"resume",sessionId:w}),G.getState().resumeGeneration(w)},[]),Hn=g.useCallback(()=>{g.startTransition(()=>{const w=window.prompt(N("chat.switchDirPrompt"),M);if(w&&w.trim()&&w.trim()!==M){const E=w.trim();$(E),I.send({type:"workspace",message:E}),V.getState().sessionTabs.forEach(z=>{G.getState().clearMessages(z.id)}),V.setState({sessionTabs:[],sessions:[],sessionWorkspaceDirs:{},activeSessionId:null}),setTimeout(()=>{V.getState().addSessionTab(N("chat.defaultSessionTitle",{n:1}),E)},0)}})},[M,$,N]),Lt=()=>{o([]),a(0)},Un=g.useMemo(()=>({setActiveTab:H,createNewSession:Ie,clearMessages:jt,setTheme:U,setThemePreset:se,toggleTerminal:A,setLogs:o,setUnreadLogs:a}),[H,Ie,jt,U,se,A]);g.useEffect(()=>{const w=E=>{var oe,ye;const K=E.ctrlKey||E.metaKey,z=(oe=E.target)==null?void 0:oe.tagName,fe=z==="INPUT"||z==="TEXTAREA"||((ye=E.target)==null?void 0:ye.isContentEditable);if(E.key==="Escape"){if(C){E.preventDefault(),S(!1);return}if(T){E.preventDefault(),_(!1);return}if(i){E.preventDefault(),l(!1);return}return}if(K)if(E.key==="k"||E.key==="K")E.preventDefault(),_(!1),S(ke=>!ke);else if(E.key==="l"||E.key==="L"){if(fe)return;E.preventDefault(),Lt(),X.success(N("slashCommands.logs_clear_result"))}else E.key==="/"&&(E.preventDefault(),S(!1),_(ke=>!ke))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[C,T,i,N]);const Mt=(w,E)=>Ut[w]?N(Ut[w]):E,Gn=w=>{switch(w){case"chat":{const E=Rn(),K=Pe.find(z=>z.id===Z);return u.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[u.jsxs("div",{className:"h-11 flex items-center gap-1 px-3 border-b border-dark-border bg-dark-bg shrink-0 select-none",children:[u.jsx("button",{onClick:()=>m(z=>!z),className:`p-1.5 rounded-lg transition-colors ${f?"bg-accent-blue/10 text-accent-blue":"text-dark-muted hover:bg-dark-hover hover:text-dark-text"}`,title:N("a11y.toggleAgentFlow"),"aria-label":N("a11y.toggleAgentFlow"),"aria-expanded":f,children:u.jsx(ko,{size:16,"aria-hidden":"true"})}),u.jsx("span",{className:"ml-1 truncate text-[13px] font-medium text-dark-text",children:(K==null?void 0:K.title)||N("nav.chat")}),u.jsx("div",{className:"flex-1"}),u.jsx(ma,{}),u.jsx("button",{onClick:()=>R(z=>!z),className:`p-1.5 rounded-lg transition-colors ${x?"bg-accent-blue/10 text-accent-blue":"text-dark-muted hover:bg-dark-hover hover:text-dark-text"}`,title:"Task Board","aria-label":"Task Board","aria-expanded":x,children:u.jsx(So,{size:16,"aria-hidden":"true"})}),u.jsx("button",{onClick:()=>D(z=>!z),className:`p-1.5 rounded-lg transition-colors ${j?"bg-accent-blue/10 text-accent-blue":"text-dark-muted hover:bg-dark-hover hover:text-dark-text"}`,title:"右侧面板","aria-label":"切换右侧面板","aria-expanded":j,children:u.jsx(vo,{size:16,"aria-hidden":"true"})})]}),u.jsx(Oa,{tabs:E,activeSessionId:Z,onSend:Rt,onStop:Dn,onPause:Fn,onResume:Wn,activeTab:s,setActiveTab:H,createNewSession:Ie,clearMessages:jt,setTheme:U,toggleTerminal:A,setLogs:o,setUnreadLogs:a,showTaskBoard:x,onToggleTaskBoard:()=>R(z=>!z),onRegenerate:On,onDeleteMessage:$n})]})}case"terminal":return u.jsx(Ia,{});case"files":return u.jsx(Ma,{});case"models":return u.jsx(Aa,{});case"tools":return u.jsx(Ea,{});case"skills":return u.jsx(ja,{});case"agents":return u.jsx(Ra,{});case"hooks":return u.jsx(La,{});case"channels":return u.jsx(Ha,{});case"inbox":return u.jsx(Ua,{});case"audit":return u.jsx(za,{});case"scheduled":return u.jsx(Ga,{});case"logs":return u.jsx(Da,{logs:r,onClear:Lt});case"settings":return u.jsx($a,{onNavigate:H});case"pull-requests":case"plugins":return u.jsx(Ba,{tabId:w});default:return null}};return u.jsxs(Zs,{children:[u.jsxs("div",{className:"h-screen w-full flex bg-dark-bg text-dark-text overflow-hidden",children:[u.jsx("aside",{className:`hidden md:block shrink-0 border-r border-dark-border bg-dark-surface transition-[width] duration-200 ease-in-out overflow-hidden ${O?"w-14":"w-60"}`,children:u.jsx(zs,{collapsed:O,onToggleCollapse:ne,tabs:ce,activeTab:s,onTabChange:H,isConnected:t,onNewSession:Ie,onSwitchSession:gs,onCloseSession:ys,onRenameSession:bs,getTabTitle:Mt})}),i&&u.jsxs("div",{className:"md:hidden fixed inset-0 z-50",children:[u.jsx("div",{className:"absolute inset-0 bg-black/40 backdrop-blur-[2px]",onClick:()=>l(!1)}),u.jsx("aside",{className:"absolute left-0 top-0 h-full w-64 bg-dark-surface border-r border-dark-border shadow-2xl animate-slide-in",children:u.jsx(zs,{collapsed:!1,onToggleCollapse:()=>l(!1),tabs:ce,activeTab:s,onTabChange:w=>{H(w),l(!1)},isConnected:t,onNewSession:()=>{Ie(),l(!1)},onSwitchSession:w=>{gs(w),l(!1)},onCloseSession:ys,onRenameSession:bs,getTabTitle:Mt})})]}),u.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[u.jsxs("header",{className:"md:hidden h-12 bg-dark-surface border-b border-dark-border flex items-center gap-1 px-2 shrink-0",children:[u.jsx("button",{className:"p-2 rounded-lg text-dark-muted hover:bg-dark-hover hover:text-dark-text transition-colors",onClick:()=>l(!0),"aria-label":N("a11y.openMenu"),children:u.jsx(xo,{size:18,"aria-hidden":"true"})}),u.jsx("span",{className:"text-sm font-semibold truncate",children:Mt(s,"")}),u.jsx("div",{className:"flex-1"}),s==="chat"&&u.jsx("button",{onClick:Ie,className:"p-2 rounded-lg text-dark-muted hover:bg-dark-hover hover:text-dark-text transition-colors","aria-label":N("chat.newSession"),children:u.jsx(Qt,{size:18,"aria-hidden":"true"})})]}),u.jsxs("div",{className:"flex-1 flex overflow-hidden min-h-0",children:[s==="chat"&&u.jsx("div",{className:`shrink-0 border-r border-dark-border bg-dark-surface transition-all duration-200 ease-in-out overflow-hidden ${f?"w-80 xl:w-[420px]":"w-0 border-r-0"}`,children:f&&u.jsx(g.Suspense,{fallback:u.jsx(en,{}),children:u.jsx(Pa,{})})}),u.jsx("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:u.jsx(g.Suspense,{fallback:u.jsx(en,{}),children:u.jsx(Zs,{children:Gn(s)})})}),s==="chat"&&j&&u.jsx(Hr,{workspaceDir:M,onWorkspaceChange:Hn,logs:r,onClearLogs:Lt})]}),u.jsx(ha,{activeTab:s})]})]}),u.jsxs(g.Suspense,{fallback:null,children:[u.jsx(Fa,{isOpen:c,onCloseModal:()=>d(!1)}),u.jsx(Wa,{isOpen:p,onClose:()=>h(!1)})]}),u.jsx(wa,{open:C,onClose:()=>S(!1),options:Un}),u.jsx(_a,{open:T,onClose:()=>_(!1)}),u.jsx(ba,{}),u.jsx(ka,{})]})}const Ja={confirm:"确认",cancel:"取消",save:"保存",saving:"保存中...",delete:"删除",close:"关闭",refresh:"刷新",retry:"重试",loading:"加载中...",collapse:"折叠",expand:"展开",collapse_short:"收起",clear:"清空",noData:"暂无数据",noResults:"暂无结果",unknown:"未知",unknownError:"未知错误",connecting:"连接中…",back:"返回",send:"发送",copy:"复制",copied:"已复制",search:"搜索...",filter:"全部",pageInfo:"显示 {{start}}-{{end}} 条,共 {{total}} 条",prevPage:"上一页",nextPage:"下一页",enabled:"已启用",disabled:"已禁用",online:"在线",offline:"离线",busy:"忙碌",away:"离开",default:"默认"},Ya={chat:"对话",terminal:"终端",files:"文件",models:"模型",tools:"工具",skills:"技能",agents:"Agents",hooks:"Hooks",agentFlow:"Agent Flow",settings:"设置",logs:"日志",channels:"频道",sessions:"会话",groupWorkspace:"工作台",groupConfig:"配置",groupSystem:"系统",collapseSidebar:"收起侧栏",expandSidebar:"展开侧栏",moreOptions:"更多",pullRequests:"Pull requests",scheduled:"定时任务",inbox:"Inbox",audit:"审计",plugins:"插件",mySessions:"我的会话",sessionRunning:"运行中",sessionWaiting:"待确认",sessionFailed:"失败"},Qa={newSession:"新建会话",noSessions:"暂无会话",renameSession:"重命名会话",exportMd:"导出为 Markdown",you:"你",thinkingEllipsis:"思考中…",generatingPlaceholder:"AI 正在生成中…",defaultSessionTitle:"对话 {{n}}",welcome:"欢迎使用 deepseekcode",welcomeDesc:"我可以帮你编写代码、分析项目、自动化任务。试试发送一条消息吧!",suggestionCode:"代码编写",suggestionCodePrompt:"用 Python 实现快速排序,并解释它的时间复杂度",suggestionAnalyze:"代码分析",suggestionAnalyzePrompt:"分析当前项目的目录结构,告诉我它是如何组织的",suggestionAutomate:"自动化任务",suggestionAutomatePrompt:"帮我写一个脚本,自动整理当前目录下的文件",quickCommands:"查看快捷命令",refFiles:"引用文件",inputPlaceholder:"输入消息... Shift+Enter 换行,/ 命令,@ 引用文件,↑ 历史",charTokens:"{{chars}} 字符 · ~{{tokens}} tokens",nearLimit:"接近上限",shiftEnter:"Shift+Enter 换行",escHint:"Esc 暂停 · 双击 Esc 停止",resume:"恢复",resumeGen:"恢复生成",stop:"终止",stopGen:"终止生成",pause:"暂停",pauseGen:"暂停生成",sendBtn:"发送",voiceInput:"语音输入",voiceListening:"正在聆听...",voiceTranscribing:"识别中...",voiceUnsupported:"当前浏览器不支持语音输入",voiceError:"语音识别出错,请重试",connected:"已连接",disconnected:"未连接",sessionHistory:"会话历史",noHistory:"暂无历史会话",clearHistory:"清空历史",clearHistoryTitle:"清空历史",restoreSession:"点击恢复「{{title}}」",removeFromHistory:"从历史移除",workingDir:"工作目录",switchDir:"切换",clickToSwitchDir:"点击切换工作目录",switchDirPrompt:"请输入新的工作目录路径:",addTask:"添加",addTaskPlaceholder:"添加任务...",noTasks:"暂无任务,在上方输入添加",doubleClickEdit:"双击编辑",deleteTask:"删除任务",backgroundLogs:"后台日志",tokenPrompt:"提示词",tokenCompletion:"补全",tokenTotal:"总计",totalChars:"总字符数",avgTokens:"平均 token/条",estimatedCost:"预估成本: ${{cost}}",contextTrimming:"上下文裁剪",keepMore:"保留更多",trimMore:"裁剪更多",trimContext:"裁剪上下文 (保留 ~{{n}} 条消息)",currentMessages:"当前 {{n}} 条消息",totalCharsInfo:"· 共 {{n}} 字符",contextManager:"上下文管理",showContext:"显示上下文信息",taskBoard:"任务看板",morePending:"还有 {{n}} 个待处理任务...",moreCompleted:"还有 {{n}} 个已完成任务...",dependencyCount:"🔗 依赖 {{n}} 个任务",contextSuggestions:"展开 ({{n}}条建议)",collapseSuggestions:"收起",toolRequest:"工具请求: ",toolResult:"工具结果: ",memory:"记忆: ",filesCount:"({{n}}文件)",saveTokens:"可节省 ~{{n}}",ignoreSuggestion:"忽略此建议",fileMention:"@ 引用文件",fileMentionSearch:'@ 搜索: "{{query}}"',fileMentionHelp:"↑↓ 选择 · Enter 插入 · Esc 关闭",fileBrowser:"文件浏览器",fileSaved:"文件已保存",fileReadError:"读取文件失败",fileSaveError:"保存失败",fileModified:"● 已修改",selectFilePreview:"选择文件以预览或编辑",kbdHint:"命令面板",clickToSwitchMode:"点击切换模式 (Plan → Goal → Act)",selectModel:"选择模型",clickToSelectModel:"点击为当前模式选择模型",noEnabledModels:"暂无可用模型",globalDefault:"全局默认",planDefault:"Plan 默认",actDefault:"Act 默认",goalDefault:"Goal 默认",assistantLabel:"DeepSeekCode",thoughtProcess:"思维过程",runningSteps:"执行中",stepCount:"步",stepCountPlural:"步",copyMessage:"复制",regenerate:"重新生成",deleteMessage:"删除消息",historyCount:"{{n}} 条",startChatHint:"请先开始对话",panelTitle:"面板",messageDeleted:"消息已删除",thinking:"思考中"},Xa={title:"键盘快捷键",commandPalette:"打开命令面板",clearLogs:"清空日志",help:"显示快捷键帮助",submit:"提交输入",newline:"换行",closeDialog:"关闭弹窗 / 暂停生成",slashCommand:"快捷命令",fileRef:"引用文件",stopGen:"终止生成(连按两次 Esc)"},Za={placeholder:"搜索命令或跳转面板...",navGroup:"导航",commandGroup:"命令",empty:"没有匹配的命令",hint:"↑↓ 选择 · Enter 执行 · Esc 关闭",running:"执行中..."},ei={openMenu:"打开菜单",closeMenu:"关闭菜单",close:"关闭",expand:"展开",collapse:"折叠",delete:"删除",remove:"移除",send:"发送消息",newSession:"新建会话",messageInput:"消息输入框",connectionStatus:"连接状态",loading:"加载中",toggleAgentFlow:"切换 Agent 信息流",commandPalette:"命令面板",shortcutsHelp:"快捷键帮助"},ti={mode:"模式",planMode:"Plan 模式 — 只读分析",planModeDesc:"在 Plan 模式下,AI 将使用只读工具分析需求和代码,不会修改任何文件。",planModeHint:"分析完成后,请切换到 Act 模式执行具体实现。",switchToAct:"切换到 Act 模式执行",actMode:"Act 模式",actModeDesc:"在 Act 模式下,AI 可以读取、修改文件并执行命令。",actModeHint:"需要先分析需求?切换到 Plan 模式进行只读探索。",switchToPlan:"切换到 Plan 模式分析",readOnlyMode:"只读模式",planTitle:"Plan Mode:只读探索,不能修改代码",actTitle:"Act Mode:可以读写和执行",switchToPlanMode:"切换到规划模式",switchToActMode:"切换到执行模式",autoMode:"自动模式:自动批准工具调用",goalMode:"Goal 模式",planModeShort:"只读分析与规划,不修改文件",actModeShort:"读写文件并执行命令",goalModeShort:"围绕目标持续推进直到完成",autoApprove:"Auto 自动批准",autoApproveShort:"自动批准所有工具调用",planContent:"Plan 文件内容",analyzing:"正在分析需求..."},si={title:"设置",theme:"主题",themeDark:"🌙 深色",themeLight:"☀️ 浅色",themeAuto:"🔄 自动",themePresets:"主题预设",themePresetLinear:"极简 Linear",themePresetLinearDesc:"中性灰 + 单一强调色 — 极简专业",themePresetGithub:"GitHub 默认",themePresetGithubDesc:"中性暗/亮色 — 简洁专业",themePresetCherry:"Cherry Studio",themePresetCherryDesc:"蓝色渐变 — 清爽科技感",themePresetOcean:"海洋 Ocean",themePresetOceanDesc:"深蓝/青色 — 冷静专业",themePresetMint:"薄荷 Mint",themePresetMintDesc:"青绿/薄荷 — 清新爽朗",themePresetLavender:"薰衣草 Lavender",themePresetLavenderDesc:"柔紫 — 优雅精致",themePresetMidnight:"午夜 Midnight",themePresetMidnightDesc:"深海军蓝 — 极简高对比",themePresetSunset:"日落 Sunset",themePresetSunsetDesc:"暖橙/金色 — 活力充沛",themePresetForest:"森林 Forest",themePresetForestDesc:"自然绿 — 大地色系宁静",themePresetCandy:"糖果 Candy",themePresetCandyDesc:"明亮多彩 — 活泼生动",themePresetNord:"Nord",themePresetNordDesc:"北极蓝 — 流行精心设计",customOverrides:"自定义覆盖",customOverridesHint:"调整单个颜色以覆盖当前主题预设",customColors:"自定义配色",colorBg:"背景色",colorSurface:"面板色",colorBorder:"边框色",colorText:"文字色",colorMuted:"次要文字",colorAccentBlue:"强调蓝",colorAccentGreen:"强调绿",colorAccentRed:"强调红",colorAccentYellow:"强调黄",colorAccentPurple:"强调紫",resetColors:"重置为默认配色",advancedFeatures:"高级功能",yoloMode:"⚡ YOLO Mode",yoloDesc:"全自动模式 - 无需确认直接执行",autoSwarm:"🐝 Auto Swarm",autoSwarmDesc:"自动智能体集群 - 多 Agent 协同工作",workspaceGuard:"🔓 工作区守卫绕过",workspaceGuardDesc:"允许读取工作目录外的文件(临时取消路径限制)",about:"关于",aboutDesc:"基于 Web 的 AI 编码助手界面",language:"语言",languageZh:"中文",languageEn:"English"},ni={title:"模型配置",providerConfig:"Provider 配置",configured:"已配置",notConfigured:"未配置",modelsCount:"{{n}} 个模型 · {{apiType}}",clickToConfig:"点击配置 →",apiKeyHint:"已配置 API Key,输入新 Key 将覆盖旧配置。",apiKeyPlaceholder:"输入新 Key 以覆盖...",apiKeyDefaultPlaceholder:"sk-...",enterApiKey:"请输入 API Key",removeConfirm:'确定要移除 "{{providerKey}}" 的配置吗?这将删除其 API Key 和模型。',loadFailed:"加载模型失败",saveFailed:"保存失败",overallStatus:"总体状态",healthy:"健康",degraded:"降级",abnormal:"异常",healthRate:"健康率",onlineInstances:"在线实例",totalRequests:"总请求数",configuredModels:"已配置模型",addModel:"添加模型",provider_qwen:"通义千问 (Qwen)",provider_glm:"智谱 (GLM)",provider_baichuan:"百川 (Baichuan)",provider_minimax:"MiniMax / 海螺",provider_doubao:"豆包 (Doubao)",provider_hunyuan:"腾讯混元 (Hunyuan)",provider_spark:"讯飞星火 (Spark)",provider_custom:"Custom (自定义)"},oi={title:"工具列表",searchTools:"搜索工具...",disabled:"禁用",enabled:"启用",params:"参数",loadFailed:"加载工具失败",noTools:"暂无工具"},ri={title:"技能管理",list:"技能列表",noSkills:"暂无技能",loadFailed:"加载技能失败",loadFailedFallback:"加载失败",enable:"启用",disable:"禁用",enabled:"已启用",disabled:"已关闭",new:"新建技能",import:"导入",importTitle:"导入技能",edit:"编辑",save:"保存",cancel:"取消",retry:"重试",refresh:"刷新",tags:"标签",none:"无",source:"来源",localSkill:"本地技能",systemPrompt:"系统提示词",selectSkill:"选择一个技能",fieldId:"ID",fieldName:"名称",fieldCategory:"分类",fieldTrigger:"触发词",fieldTools:"所需工具",description:"描述",saving:"保存中",chooseFile:"选择技能文件",importHint:"支持 .skill.md 文件"},ai={title:"Agent 管理",idle:"空闲",busy:"工作中",error:"异常",active:"当前活跃",activate:"激活",noAgents:"暂无 Agent",noAgentsDesc:"Agent 将在运行时自动创建",deleteConfirm:"确定要删除这个 Agent 吗?",loadFailed:"加载 Agents 失败",infoFlow:"Agent 信息流",processing:"处理中",completed:"完成",failed:"失败",eventLog:"事件日志",waitingForActivity:"等待 Agent 活动...",dispatch:"分发",status:"状态",clearLog:"清空日志"},ii={permissionRequest:"权限申请",hookApproval:"Hook 拦截审批",hookConfirm:"Hook 请求确认",morePending:"还有 {{n}} 项待审批",tool:"工具:",reason:"原因:",needConfirm:"需要用户确认此操作",allow:"允许",deny:"拒绝",allowAlways:"本次会话始终允许",allowAlwaysDesc:"当前会话中不再询问此工具",autoMode:"自动模式",autoModeLabel:"自动模式(全部允许)",autoModeDesc:"自动批准所有 Hook 请求",moreOptions:"更多选项",highRiskWarning:"此操作可能造成不可逆的影响,请仔细确认",mediumRiskConfirm:"请确认此操作为预期行为",alreadyAllowed:"已允许:",alreadyDenied:"已拒绝:",risk_critical:"破坏性操作 - 可能删除数据",risk_critical_cmd:"高危命令 - 包含系统级操作",risk_high_shell:"Shell 命令执行",risk_high_file:"文件写入操作",risk_high_pkg:"包管理操作",risk_git_force:"Git 强制操作",risk_git:"Git 操作",risk_network:"网络请求",risk_low:"只读操作",risk_default:"工具调用",hookConfigTitle:"自定义 Hook 配置说明",hookConfigDesc:"你可以在项目根目录的 .agent/hooks.json 文件中添加或修改 Hook 拦截规则。",hookConfigDetail:"Hook 支持 SHELL(外部脚本)和 HTTP(REST 端点)两种类型,可以在工具执行前(PRE_TOOL_USE)或执行后(POST_TOOL_USE)触发。",hookConfigBuiltin:"内置了 BashSafetyHook(危险命令拦截)、FileWriteAuditHook(文件写入审计)、ToolUsageStatsHook(工具调用统计)三套 Hook。设置 enabled: false 可禁用任意 Hook。",optionAllow:"允许 — 执行此操作",optionAllowHint:"点击或按 Enter 确认",optionDeny:"拒绝 — 取消此操作",optionDenyHint:"点击或按 Esc 取消",optionAllowAlways:"本次会话始终允许",optionAllowAlwaysHint:"不再询问 {{tool}}",optionAutoMode:"自动模式 — 全部允许",optionAutoModeHint:"之后所有 Hook 将自动批准",shortcutHint:"快捷键: 1-4 选择 · Enter 允许 · Esc 拒绝",lastItem:"最后一项",modalHint:"请在弹窗中处理此审批请求",clickToSelect:"点击选择 · 1/2/3/4 键盘快捷键"},li={pending:"等待",thinking:"思考",action:"执行",result:"结果",running:"运行中",error:"错误",completed:"完成",params:"参数"},ci={quickCommands:"快捷命令",search:'搜索: "{{filter}}"',help:"↑↓ 选择 · Enter 执行 · Esc 关闭",backend:"后端",backendCommand:"后端命令",chat_desc:"切换到对话面板",chat_result:"已切换到对话面板",terminal_desc:"切换到终端面板",terminal_result:"已切换到终端面板",files_desc:"切换到文件面板",files_result:"已切换到文件面板",models_desc:"切换到模型面板",models_result:"已切换到模型面板",tools_desc:"列出可用工具",tools_result:"已切换到工具面板",skills_desc:"列出可用技能",skills_result:"已切换到技能面板",agents_desc:"切换到 Agents 面板",agents_result:"已切换到 Agents 面板",settings_desc:"切换到设置面板",settings_result:"已切换到设置面板",logs_desc:"切换到日志面板",logs_result:"已切换到日志面板",new_desc:"创建新会话",new_result:"新会话已创建",clear_desc:"清空当前会话消息",clear_result:"消息已清空",theme_desc:"切换主题 (dark/light/auto)",theme_error:"用法: /theme <dark|light|auto>",theme_result:"主题已切换为 ",theme_preset_result:"主题预设已切换为 ",theme_preset_unavailable:"主题预设切换不可用",toggle_terminal_desc:"切换底部终端面板显示",toggle_terminal_result:"终端面板已切换",logs_clear_desc:"清空日志",logs_clear_result:"日志已清空",doctor_desc:"系统自诊断 (Config/API Key/Network/Docker/Disk)",compact_desc:"压缩当前会话上下文",help_desc:"显示所有快捷命令",token_desc:"显示 token 使用量和 API 费用统计",review_desc:"代码审查 — 检查变更的正确性、安全性和代码质量",security_review_desc:"安全审查 — OWASP Top 10 + 命令注入/路径遍历/权限提升",memory_desc:"管理 AI 持久记忆 (list/add/delete/clear)",ps_desc:"查看和管理后台任务、子代理和 shell 进程",model_desc:"查看或切换 AI 模型",status_desc:"显示当前会话状态 (会话ID/消息数/模型/工作目录)",config_desc:"管理应用程序配置 (get/set/list/delete)",exit_desc:"退出应用",exit_result:"正在关闭服务...",benchmark_desc:"运行 DeepSeekCode 能力评测 (simple/medium/complex/full/list)",goal_desc:"设置多步工作目标",goal_list_desc:"列出活跃目标",goal_status_desc:"查看目标进度",workflow_list_desc:"列出工作流运行记录",workflow_status_desc:"查看工作流状态",workflow_checkpoints_desc:"列出工作流检查点",mcp_desc:"列出或重新加载 MCP 服务器",sessions_desc:"列出会话",resume_desc:"按 ID 恢复会话",permissions_desc:"显示权限规则和待审批项",init_desc:"生成 agent.md 项目指导文件",self_test_desc:"运行工具能力自测并生成报告",context_desc:"显示上下文分析报告",version_desc:"显示版本信息","check-update_desc":"检查可用更新",upgrade_desc:"升级到最新版本",acceptance_desc:"运行或检查验收工作流 (quick/full/list/report)",diff_desc:"查看未提交的 Git 变更",summary_desc:"总结当前会话内容",effort_desc:"显示或设置推理力度 (low|medium|high)",export_desc:"导出当前会话为 JSON",rename_desc:"重命名当前会话",hooks_desc:"显示活跃钩子配置",cost_desc:"显示预估会话成本",sent_command:"已发送命令 ",noActiveSession:"无活跃会话"},di={pageError:"页面出现错误",unknownError:"发生了未知错误,请尝试刷新页面",refreshPage:"刷新页面",genEnded:"生成已结束(工具执行超时或连接中断)"},ui={backendConnected:"后端已连接",backendDisconnected:"后端连接断开,正在重连...",paused:"已暂停,再按 ESC 终止",terminated:"已终止 (ESC×2)",contextCompressed:"上下文压缩: {{original}} → {{compressed}} 条消息, 释放 {{saved}} tokens",errorPrefix:"❌ 错误: {{error}}",uncaughtError:"未捕获错误:",uncaughtRejection:"未捕获的 Promise 拒绝: ",unknownReason:"未知原因",diagnosing:"⏳ 诊断中...",runDiagnostic:"🔍 运行诊断",inspectorOn:"开启检查模式 (Ctrl+Shift+Alt+C)",inspectorOff:"关闭检查模式"},pi={title:"频道管理",subtitle:"接入外部 IM 平台,通过微信、飞书、钉钉等与 AI 交互",newChannel:"新建频道",editChannel:"编辑频道",table:{name:"频道名称",type:"类型",appId:"App ID",status:"连接状态",enabled:"启用",actions:"操作"},status:{connected:"已连接",disconnected:"未连接",connecting:"连接中",error:"错误"},empty:"还没有配置任何频道",emptyHint:"点击「新建频道」添加一个 IM 平台机器人",form:{basicInfo:"基础信息",name:"频道名称",namePlaceholder:"例如:公司群机器人",type:"频道类型",credentials:"凭证信息",appId:"App ID / 企业ID",appIdPlaceholder:"填写应用 AppID",appSecret:"App Secret",appSecretPlaceholder:"填写应用密钥",token:"Token / Bot Token",tokenPlaceholder:"填写机器人 Token",encodingAESKey:"EncodingAESKey",encodingAESKeyPlaceholder:"仅微信需要,可选",enabled:"启用频道",wechatQrHint:"保存后可使用微信扫码登录",feishuWsHint:"飞书使用 WebSocket 连接,自动接收消息"},actions:{scanQr:"扫码",edit:"编辑",delete:"删除",deleteConfirm:"确定要删除此频道?",test:"测试连接",save:"保存频道",cancel:"取消"},errors:{loadFailed:"加载频道列表失败",createFailed:"创建频道失败",updateFailed:"更新频道失败",deleteFailed:"删除频道失败",notFound:"频道未找到",notImplemented:"尚未实现",nameRequired:"频道名称不能为空"},qr:{title:"微信扫码登录",generating:"二维码生成中...",waiting:"请使用微信扫描二维码",scanned:"已扫描,请在手机上确认",confirmed:"登录成功",expired:"二维码已失效",expiredHint:"点击重试重新生成二维码",error:"获取二维码失败",openInNewTab:"在新标签页打开"},typeLabels:{wechat:"微信",feishu:"飞书",dingtalk:"钉钉",telegram:"Telegram",discord:"Discord",slack:"Slack",signal:"Signal",whatsapp:"WhatsApp",line:"LINE",qqbot:"QQ Bot",matrix:"Matrix",mattermost:"Mattermost",msteams:"Teams",googlechat:"Google Chat",irc:"IRC"}},hi={stageUploaded:"等待处理",stageParsing:"正在解析数据文件",stageMapping:"模板映射",stageRendering:"正在生成文件",stageComplete:"文件处理完成",stageError:"文件处理失败",parsing:"正在解析 {{file}} …",parsedSummary:"{{rows}} 行 · {{fields}} 个字段",mappingTitle:"模板 ↔ 数据字段映射",templatePlaceholder:"模板占位符",dataField:"数据字段",mappingMore:"另有 {{n}} 个映射",rendering:"正在逐条生成 {{current}}/{{total}} …",download:"下载",downloadFailed:"下载失败",error:"处理失败",roleData:"数据文件",roleTemplate:"模板文件",attach:"添加附件(Excel/Word/CSV)",dropHint:"松开以添加附件",unsupportedType:"不支持的文件类型: {{name}}",fileTooLarge:"文件过大: {{name}}(≤50MB)",duplicateFile:"重复文件: {{name}}",maxAttachments:"单次最多 {{n}} 个文件",uploadFailed:"上传失败",stillUploading:"附件正在上传中,请稍候…",importFailed:"Import files failed"},fi={reconnecting:"重连中 {{attempt}}/{{max}}",hint:"正在重新连接后端…"},mi={title:"Full access(自动批准)已开启",desc:"Agent 可不经确认直接编辑文件和执行命令,存在数据丢失风险。",dismiss:"本次关闭",neverShow:"不再显示"},gi={panelTitle:"环境与变更",noRepo:"非 Git 仓库",notGitDesc:"当前工作目录不是 Git 仓库,无法展示变更统计。",refresh:"刷新",changes:"变更统计",clean:"工作区干净",branch:"分支",upstream:"相对上游",commit:"提交",push:"推送",commitConfirm:"提交",commitPlaceholder:"提交信息(Agent 生成草稿,可编辑)…",commitSuccess:"提交成功",commitFailed:"提交失败",pushSuccess:"推送成功",pushFailed:"推送失败",checkoutSuccess:"已切换到 {{branch}}",checkoutFailed:"切换失败",prReady:"PR 检查状态正常",prUnavailable:"Pull request status unavailable(未关联远端)",prLoading:"加载 PR 状态…",environment:"环境信息",ok:"操作成功",loading:"加载中…",emptyCommitMsg:"请输入提交信息"},yi={retry:"重试",details:"详情",modelSettings:"模型设置"},bi={comingSoon:"即将上线"},tn={common:Ja,nav:Ya,chat:Qa,shortcuts:Xa,palette:Za,a11y:ei,plan:ti,settings:si,models:ni,tools:oi,skills:ri,agents:ai,hook:ii,step:li,slashCommands:ci,error:di,toast:ui,channels:pi,fileJob:hi,reconnect:fi,autoAccess:mi,git:gi,errorCard:yi,placeholder:bi},xi={confirm:"Confirm",cancel:"Cancel",save:"Save",saving:"Saving...",delete:"Delete",close:"Close",refresh:"Refresh",retry:"Retry",loading:"Loading...",collapse:"Collapse",expand:"Expand",collapse_short:"Collapse",clear:"Clear",noData:"No data",noResults:"No results",unknown:"Unknown",unknownError:"Unknown error",connecting:"Connecting…",back:"Back",send:"Send",copy:"Copy",copied:"Copied",search:"Search...",filter:"All",pageInfo:"Showing {{start}}-{{end}} of {{total}}",prevPage:"Previous",nextPage:"Next",enabled:"Enabled",disabled:"Disabled",online:"Online",offline:"Offline",busy:"Busy",away:"Away",default:"Default"},ki={chat:"Chat",terminal:"Terminal",files:"Files",models:"Models",tools:"Tools",skills:"Skills",agents:"Agents",hooks:"Hooks",agentFlow:"Agent Flow",settings:"Settings",logs:"Logs",channels:"Channels",sessions:"Sessions",groupWorkspace:"Workspace",groupConfig:"Configuration",groupSystem:"System",collapseSidebar:"Collapse sidebar",expandSidebar:"Expand sidebar",moreOptions:"More",pullRequests:"Pull requests",scheduled:"Scheduled",inbox:"Inbox",audit:"Audit",plugins:"Plugins",mySessions:"My sessions",sessionRunning:"Running",sessionWaiting:"Awaiting confirmation",sessionFailed:"Failed"},Si={newSession:"New Session",noSessions:"No sessions yet",renameSession:"Rename session",exportMd:"Export as Markdown",you:"You",thinkingEllipsis:"Thinking…",generatingPlaceholder:"AI is generating…",defaultSessionTitle:"Chat {{n}}",welcome:"Welcome to deepseekcode",welcomeDesc:"I can help you write code, analyze projects, and automate tasks. Try sending a message!",suggestionCode:"Code Writing",suggestionCodePrompt:"Implement quicksort in Python and explain its time complexity",suggestionAnalyze:"Code Analysis",suggestionAnalyzePrompt:"Analyze the current project structure and explain how it is organized",suggestionAutomate:"Automation",suggestionAutomatePrompt:"Write a script to organize the files in the current directory",quickCommands:"View quick commands",refFiles:"Reference files",inputPlaceholder:"Type a message... Shift+Enter for newline, / commands, @ file refs, ↑ history",charTokens:"{{chars}} chars · ~{{tokens}} tokens",nearLimit:"Near limit",shiftEnter:"Shift+Enter newline",escHint:"Esc to pause · Double-Esc to stop",resume:"Resume",resumeGen:"Resume generation",stop:"Stop",stopGen:"Stop generation",pause:"Pause",pauseGen:"Pause generation",sendBtn:"Send",voiceInput:"Voice Input",voiceListening:"Listening...",voiceTranscribing:"Transcribing...",voiceUnsupported:"Voice input is not supported in this browser",voiceError:"Voice recognition error, please try again",connected:"Connected",disconnected:"Disconnected",sessionHistory:"Session History",noHistory:"No history sessions",clearHistory:"Clear history",clearHistoryTitle:"Clear history",restoreSession:'Click to restore "{{title}}"',removeFromHistory:"Remove from history",workingDir:"Working Directory",switchDir:"Switch",clickToSwitchDir:"Click to switch working directory",switchDirPrompt:"Enter new working directory path:",addTask:"Add",addTaskPlaceholder:"Add task...",noTasks:"No tasks, add one above",doubleClickEdit:"Double-click to edit",deleteTask:"Delete task",backgroundLogs:"Background Logs",tokenPrompt:"Prompt",tokenCompletion:"Completion",tokenTotal:"Total",totalChars:"Total chars",avgTokens:"Avg tokens/msg",estimatedCost:"Est. cost: ${{cost}}",contextTrimming:"Context Trimming",keepMore:"Keep more",trimMore:"Trim more",trimContext:"Trim context (keep ~{{n}} messages)",currentMessages:"{{n}} messages",totalCharsInfo:"· {{n}} chars total",contextManager:"Context Manager",showContext:"Show context info",taskBoard:"Task Board",morePending:"{{n}} more pending...",moreCompleted:"{{n}} more completed...",dependencyCount:"🔗 {{n}} dependencies",contextSuggestions:"Expand ({{n}} suggestions)",collapseSuggestions:"Collapse",toolRequest:"Tool request: ",toolResult:"Tool result: ",memory:"Memory: ",filesCount:"({{n}} files)",saveTokens:"Save ~{{n}}",ignoreSuggestion:"Ignore suggestion",fileMention:"@ Reference file",fileMentionSearch:'@ Search: "{{query}}"',fileMentionHelp:"↑↓ Select · Enter Insert · Esc Close",fileBrowser:"File Browser",fileSaved:"File saved",fileReadError:"Failed to read file",fileSaveError:"Save failed",fileModified:"● Modified",selectFilePreview:"Select a file to preview or edit",kbdHint:"command palette",clickToSwitchMode:"Click to toggle mode (Plan → Goal → Act)",selectModel:"Select model",clickToSelectModel:"Click to select a model for the current mode",noEnabledModels:"No enabled models",globalDefault:"Global default",planDefault:"Plan default",actDefault:"Act default",goalDefault:"Goal default",assistantLabel:"DeepSeekCode",thoughtProcess:"Thought process",runningSteps:"Running",stepCount:"step",stepCountPlural:"steps",copyMessage:"Copy",regenerate:"Regenerate",deleteMessage:"Delete message",historyCount:"{{n}} items",startChatHint:"Start a conversation first",panelTitle:"Panel",messageDeleted:"Message deleted",thinking:"Thinking"},vi={title:"Keyboard Shortcuts",commandPalette:"Open command palette",clearLogs:"Clear logs",help:"Show shortcuts help",submit:"Submit input",newline:"New line",closeDialog:"Close dialog / pause generation",slashCommand:"Quick commands",fileRef:"Reference files",stopGen:"Stop generation (double Esc)"},wi={placeholder:"Search commands or jump to panel...",navGroup:"Navigation",commandGroup:"Commands",empty:"No matching commands",hint:"↑↓ Select · Enter Run · Esc Close",running:"Running..."},Ci={openMenu:"Open menu",closeMenu:"Close menu",close:"Close",expand:"Expand",collapse:"Collapse",delete:"Delete",remove:"Remove",send:"Send message",newSession:"New session",messageInput:"Message input",connectionStatus:"Connection status",loading:"Loading",toggleAgentFlow:"Toggle agent flow",commandPalette:"Command palette",shortcutsHelp:"Shortcuts help"},_i={mode:"Mode",planMode:"Plan Mode — Read-only analysis",planModeDesc:"In Plan mode, AI uses read-only tools to analyze requirements and code without modifying any files.",planModeHint:"After analysis, switch to Act mode to implement changes.",switchToAct:"Switch to Act mode",actMode:"Act Mode",actModeDesc:"In Act mode, AI can read, modify files, and execute commands.",actModeHint:"Need to analyze first? Switch to Plan mode for read-only exploration.",switchToPlan:"Switch to Plan mode",readOnlyMode:"Read-only",planTitle:"Plan Mode: Read-only exploration, cannot modify code",actTitle:"Act Mode: Full read/write access",switchToPlanMode:"Switch to plan mode",switchToActMode:"Switch to act mode",autoMode:"Auto mode: auto-approve tool calls",goalMode:"Goal Mode",planModeShort:"Read-only analysis and planning",actModeShort:"Read/write files and run commands",goalModeShort:"Keep working toward the goal until done",autoApprove:"Auto Approve",autoApproveShort:"Auto-approve all tool calls",planContent:"Plan file content",analyzing:"Analyzing requirements..."},Ti={title:"Settings",theme:"Theme",themeDark:"🌙 Dark",themeLight:"☀️ Light",themeAuto:"🔄 Auto",themePresets:"Theme Presets",themePresetLinear:"Linear (minimal)",themePresetLinearDesc:"Neutral grays with a single accent — clean and focused",themePresetGithub:"GitHub",themePresetGithubDesc:"Neutral dark/light — clean and professional",themePresetCherry:"Cherry Studio",themePresetCherryDesc:"Blue gradient inspired — clean tech feel",themePresetOcean:"Ocean",themePresetOceanDesc:"Deep blue/cyan — calm and professional",themePresetMint:"Mint",themePresetMintDesc:"Teal/mint green — fresh and refreshing",themePresetLavender:"Lavender",themePresetLavenderDesc:"Soft purple — elegant and sophisticated",themePresetMidnight:"Midnight",themePresetMidnightDesc:"Deep navy — minimal and high contrast",themePresetSunset:"Sunset",themePresetSunsetDesc:"Warm orange/golden — energetic",themePresetForest:"Forest",themePresetForestDesc:"Natural green — earthy and calm",themePresetCandy:"Candy",themePresetCandyDesc:"Bright multi-color — vibrant and lively",themePresetNord:"Nord",themePresetNordDesc:"Arctic blue — popular well-designed palette",customOverrides:"Custom Overrides",customOverridesHint:"Tweak individual colors to override the active preset",customColors:"Custom Colors",colorBg:"Background",colorSurface:"Surface",colorBorder:"Border",colorText:"Text",colorMuted:"Muted Text",colorAccentBlue:"Accent Blue",colorAccentGreen:"Accent Green",colorAccentRed:"Accent Red",colorAccentYellow:"Accent Yellow",colorAccentPurple:"Accent Purple",resetColors:"Reset to default",advancedFeatures:"Advanced Features",yoloMode:"⚡ YOLO Mode",yoloDesc:"Full auto - execute without confirmation",autoSwarm:"🐝 Auto Swarm",autoSwarmDesc:"Agent swarm - multi-agent collaboration",workspaceGuard:"🔓 Workspace Guard Bypass",workspaceGuardDesc:"Allow reading files outside workspace dir (temporarily disable path restrictions)",about:"About",aboutDesc:"Web-based AI coding assistant interface",language:"Language",languageZh:"中文",languageEn:"English"},Ni={title:"Model Configuration",providerConfig:"Provider Config",configured:"Configured",notConfigured:"Not configured",modelsCount:"{{n}} models · {{apiType}}",clickToConfig:"Click to configure →",apiKeyHint:"API Key configured. Enter new key to overwrite.",apiKeyPlaceholder:"Enter new key to overwrite...",apiKeyDefaultPlaceholder:"sk-...",enterApiKey:"Please enter API Key",removeConfirm:'Are you sure you want to remove "{{providerKey}}" configuration? This will delete its API Key and models.',loadFailed:"Failed to load models",saveFailed:"Save failed",overallStatus:"Overall Status",healthy:"Healthy",degraded:"Degraded",abnormal:"Abnormal",healthRate:"Health Rate",onlineInstances:"Online Instances",totalRequests:"Total Requests",configuredModels:"Configured Models",addModel:"Add Model",provider_qwen:"Qwen (Tongyi Qianwen)",provider_glm:"GLM (Zhipu)",provider_baichuan:"Baichuan",provider_minimax:"MiniMax / Hailuo",provider_doubao:"Doubao",provider_hunyuan:"Tencent Hunyuan",provider_spark:"iFlytek Spark",provider_custom:"Custom"},Bi={title:"Tool List",searchTools:"Search tools...",disabled:"Disable",enabled:"Enable",params:"Parameters",loadFailed:"Failed to load tools",noTools:"No tools available"},Ai={title:"Skills Manager",list:"Skill List",noSkills:"No skills available",loadFailed:"Failed to load skills",loadFailedFallback:"Load failed",enable:"Enable",disable:"Disable",enabled:"Enabled",disabled:"Disabled",new:"New Skill",import:"Import",importTitle:"Import Skill",edit:"Edit",save:"Save",cancel:"Cancel",retry:"Retry",refresh:"Refresh",tags:"Tags",none:"None",source:"Source",localSkill:"Local skill",systemPrompt:"System Prompt",selectSkill:"Select a skill",fieldId:"ID",fieldName:"Name",fieldCategory:"Category",fieldTrigger:"Trigger",fieldTools:"Tools",description:"Description",saving:"Saving",chooseFile:"Choose skill file",importHint:"Supports `.skill.md` files."},Ei={title:"Agent Manager",idle:"Idle",busy:"Working",error:"Error",active:"Currently Active",activate:"Activate",noAgents:"No agents available",noAgentsDesc:"Agents are created automatically at runtime",deleteConfirm:"Are you sure you want to delete this agent?",loadFailed:"Failed to load agents",infoFlow:"Agent Info Flow",processing:"Processing",completed:"Completed",failed:"Failed",eventLog:"Event Log",waitingForActivity:"Waiting for agent activity...",dispatch:"Dispatch",status:"Status",clearLog:"Clear Log"},Pi={permissionRequest:"Permission Request",hookApproval:"Hook Interception Approval",hookConfirm:"Hook Request Confirmation",morePending:"{{n}} more pending",tool:"Tool: ",reason:"Reason: ",needConfirm:"Requires user confirmation",allow:"Allow",deny:"Deny",allowAlways:"Always allow this session",allowAlwaysDesc:"Don't ask again for this tool in current session",autoMode:"Auto Mode",autoModeLabel:"Auto mode (allow all)",autoModeDesc:"Auto-approve all hook requests",moreOptions:"More options",highRiskWarning:"This action may cause irreversible effects, please confirm carefully",mediumRiskConfirm:"Please confirm this is the intended action",alreadyAllowed:"Allowed: ",alreadyDenied:"Denied: ",risk_critical:"Destructive operation - may delete data",risk_critical_cmd:"High-risk command - system-level operations",risk_high_shell:"Shell command execution",risk_high_file:"File write operation",risk_high_pkg:"Package management operation",risk_git_force:"Git force operation",risk_git:"Git operation",risk_network:"Network request",risk_low:"Read-only operation",risk_default:"Tool call",hookConfigTitle:"Custom Hook Configuration",hookConfigDesc:"You can add or modify hook interception rules in the .agent/hooks.json file in the project root directory.",hookConfigDetail:"Hooks support SHELL (external scripts) and HTTP (REST endpoints) types, and can be triggered before (PRE_TOOL_USE) or after (POST_TOOL_USE) tool execution.",hookConfigBuiltin:"Built-in hooks: BashSafetyHook (dangerous command interception), FileWriteAuditHook (file write audit), ToolUsageStatsHook (tool usage statistics). Set enabled: false to disable any hook.",optionAllow:"Allow — execute this operation",optionAllowHint:"Click or press Enter to confirm",optionDeny:"Deny — cancel this operation",optionDenyHint:"Click or press Esc to cancel",optionAllowAlways:"Allow always this session",optionAllowAlwaysHint:"Don't ask again for {{tool}}",optionAutoMode:"Auto mode — allow all hooks",optionAutoModeHint:"All future hooks will be auto-approved",shortcutHint:"Shortcuts: 1-4 select · Enter allow · Esc deny",lastItem:"Last item",modalHint:"Please handle this approval request in the popup modal",clickToSelect:"Click to select · 1/2/3/4 keyboard shortcuts"},ji={pending:"Waiting",thinking:"Thinking",action:"Action",result:"Result",running:"Running",error:"Error",completed:"Completed",params:"Parameters"},Ri={quickCommands:"Quick Commands",search:'Search: "{{filter}}"',help:"↑↓ Select · Enter Execute · Esc Close",backend:"Backend",backendCommand:"Backend command",chat_desc:"Switch to chat panel",chat_result:"Switched to chat panel",terminal_desc:"Switch to terminal panel",terminal_result:"Switched to terminal panel",files_desc:"Switch to file panel",files_result:"Switched to file panel",models_desc:"Switch to model panel",models_result:"Switched to model panel",tools_desc:"List available tools",tools_result:"Switched to tool panel",skills_desc:"List available skills",skills_result:"Switched to skills panel",agents_desc:"Switch to agents panel",agents_result:"Switched to agents panel",settings_desc:"Switch to settings panel",settings_result:"Switched to settings panel",logs_desc:"Switch to logs panel",logs_result:"Switched to logs panel",new_desc:"Create new session",new_result:"New session created",clear_desc:"Clear current session messages",clear_result:"Messages cleared",theme_desc:"Toggle theme (dark/light/auto)",theme_error:"Usage: /theme <dark|light|auto|{{presets}}>",theme_result:"Theme switched to ",theme_preset_result:"Theme preset switched to ",theme_preset_unavailable:"Theme preset switching not available",toggle_terminal_desc:"Toggle terminal panel display",toggle_terminal_result:"Terminal panel toggled",logs_clear_desc:"Clear logs",logs_clear_result:"Logs cleared",doctor_desc:"System diagnostics (Config/API Key/Network/Docker/Disk)",compact_desc:"Compact current session context",help_desc:"Show all quick commands",token_desc:"Show token usage and API cost statistics",review_desc:"Code review — check correctness, security, and code quality",security_review_desc:"Security review — OWASP Top 10 + command injection/path traversal/privilege escalation",memory_desc:"Manage AI persistent memory (list/add/delete/clear)",ps_desc:"View and manage background tasks, sub-agents, and shell processes",model_desc:"View or switch AI models",status_desc:"Show current session status (session ID/message count/model/working directory)",config_desc:"Manage application configuration (get/set/list/delete)",exit_desc:"Exit application",exit_result:"Shutting down...",benchmark_desc:"Run DeepSeekCode capability benchmark (simple/medium/complex/full/list)",goal_desc:"Set a goal for multi-step work",goal_list_desc:"List active goals",goal_status_desc:"Show goal progress",workflow_list_desc:"List workflow runs",workflow_status_desc:"Show workflow status",workflow_checkpoints_desc:"List workflow checkpoints",mcp_desc:"List or reload MCP servers",sessions_desc:"List sessions",resume_desc:"Resume a session by id",permissions_desc:"Show permission rules and pending approvals",init_desc:"Generate agent.md project guidance file",self_test_desc:"Run tool capability self-test and generate a report",context_desc:"Show context analysis report",version_desc:"Show version information","check-update_desc":"Check for available updates",upgrade_desc:"Upgrade to the latest version",acceptance_desc:"Run or inspect acceptance workflows (quick/full/list/report)",diff_desc:"View uncommitted git changes in the workspace",summary_desc:"Summarize the current session conversation",effort_desc:"Show or set reasoning effort level (low|medium|high)",export_desc:"Export the current conversation as JSON",rename_desc:"Rename the current session",hooks_desc:"Show active hook configurations",cost_desc:"Show estimated session cost and duration",sent_command:"Command sent: ",noActiveSession:"No active session"},Li={pageError:"Page error",unknownError:"An unknown error occurred, please try refreshing the page",refreshPage:"Refresh page",genEnded:"Generation ended (tool execution timeout or connection lost)"},Mi={backendConnected:"Backend connected",backendDisconnected:"Backend disconnected, reconnecting...",paused:"Paused, press ESC again to stop",terminated:"Stopped (ESC×2)",contextCompressed:"Context compressed: {{original}} → {{compressed}} messages, saved {{saved}} tokens",errorPrefix:"❌ Error: {{error}}",uncaughtError:"Uncaught error: ",uncaughtRejection:"Uncaught Promise rejection: ",unknownReason:"Unknown reason",diagnosing:"⏳ Diagnosing...",runDiagnostic:"🔍 Run Diagnostic",inspectorOn:"Enable inspector (Ctrl+Shift+Alt+C)",inspectorOff:"Disable inspector"},Ii={title:"Channel Management",subtitle:"Connect external IM platforms to interact with AI via WeChat, Feishu, DingTalk, etc.",newChannel:"New Channel",editChannel:"Edit Channel",table:{name:"Channel Name",type:"Type",appId:"App ID",status:"Status",enabled:"Enabled",actions:"Actions"},status:{connected:"Connected",disconnected:"Disconnected",connecting:"Connecting",error:"Error"},empty:"No channels configured yet",emptyHint:'Click "New Channel" to add an IM platform bot',form:{basicInfo:"Basic Info",name:"Channel Name",namePlaceholder:"e.g. Office Group Bot",type:"Channel Type",credentials:"Credentials",appId:"App ID",appIdPlaceholder:"Enter App ID",appSecret:"App Secret",appSecretPlaceholder:"Enter App Secret",token:"Token",tokenPlaceholder:"Enter Bot Token",encodingAESKey:"EncodingAESKey",encodingAESKeyPlaceholder:"WeChat only, optional",enabled:"Enable Channel",wechatQrHint:"Save first, then scan QR code to login",feishuWsHint:"Feishu uses WebSocket to receive messages automatically"},actions:{scanQr:"Scan QR",edit:"Edit",delete:"Delete",deleteConfirm:"Are you sure you want to delete this channel?",test:"Test Connection",save:"Save Channel",cancel:"Cancel"},errors:{loadFailed:"Failed to load channels",createFailed:"Failed to create channel",updateFailed:"Failed to update channel",deleteFailed:"Failed to delete channel",notFound:"Channel not found",notImplemented:"Not implemented",nameRequired:"Channel name is required"},qr:{title:"WeChat QR Login",generating:"Generating QR code...",waiting:"Scan the QR code with WeChat",scanned:"Scanned, please confirm on your phone",confirmed:"Login successful",expired:"QR code expired",expiredHint:"Click retry to generate a new QR code",error:"Failed to get QR code",openInNewTab:"Open in new tab"},typeLabels:{wechat:"WeChat",feishu:"Feishu",dingtalk:"DingTalk",telegram:"Telegram",discord:"Discord",slack:"Slack",signal:"Signal",whatsapp:"WhatsApp",line:"LINE",qqbot:"QQ Bot",matrix:"Matrix",mattermost:"Mattermost",msteams:"Teams",googlechat:"Google Chat",irc:"IRC"}},Oi={stageUploaded:"等待处理",stageParsing:"正在解析数据文件",stageMapping:"模板映射",stageRendering:"正在生成文件",stageComplete:"文件处理完成",stageError:"文件处理失败",parsing:"正在解析 {{file}} …",parsedSummary:"{{rows}} 行 · {{fields}} 个字段",mappingTitle:"模板 ↔ 数据字段映射",templatePlaceholder:"模板占位符",dataField:"数据字段",mappingMore:"另有 {{n}} 个映射",rendering:"正在逐条生成 {{current}}/{{total}} …",download:"下载",downloadFailed:"下载失败",error:"处理失败",roleData:"数据文件",roleTemplate:"模板文件",attach:"添加附件(Excel/Word/CSV)",dropHint:"松开以添加附件",unsupportedType:"不支持的文件类型: {{name}}",fileTooLarge:"文件过大: {{name}}(≤50MB)",duplicateFile:"重复文件: {{name}}",maxAttachments:"单次最多 {{n}} 个文件",uploadFailed:"上传失败",stillUploading:"附件正在上传中,请稍候…",importFailed:"Import files failed"},$i={reconnecting:"Reconnecting {{attempt}}/{{max}}",hint:"正在重新连接后端…"},Di={title:"Full access(自动批准)已开启",desc:"Agent 可不经确认直接编辑文件和执行命令,存在数据丢失风险。",dismiss:"本次关闭",neverShow:"不再显示"},Fi={panelTitle:"环境与变更",noRepo:"非 Git 仓库",notGitDesc:"当前工作目录不是 Git 仓库,无法展示变更统计。",refresh:"刷新",changes:"Changes",clean:"工作区干净",branch:"分支",upstream:"提交领先上游",commit:"Commit",push:"Push",commitConfirm:"提交",commitPlaceholder:"提交信息(Agent 生成草稿,可编辑)…",commitSuccess:"提交成功",commitFailed:"提交失败",pushSuccess:"推送成功",pushFailed:"推送失败",checkoutSuccess:"已切换到 {{branch}}",checkoutFailed:"切换失败",prReady:"PR 检查状态正常",prUnavailable:"Pull request status unavailable(未关联远端)",prLoading:"加载 PR 状态…",environment:"环境信息",ok:"操作成功",loading:"加载中…",emptyCommitMsg:"请输入提交信息"},Wi={retry:"重试",details:"详情",modelSettings:"模型设置"},Hi={comingSoon:"即将上线"},sn={common:xi,nav:ki,chat:Si,shortcuts:vi,palette:wi,a11y:Ci,plan:_i,settings:Ti,models:Ni,tools:Bi,skills:Ai,agents:Ei,hook:Pi,step:ji,slashCommands:Ri,error:Li,toast:Mi,channels:Ii,fileJob:Oi,reconnect:$i,autoAccess:Di,git:Fi,errorCard:Wi,placeholder:Hi},Ui=(()=>{var s;try{const e=localStorage.getItem("deepseekcode-settings-storage");if(e){const t=JSON.parse(e);return((s=t==null?void 0:t.state)==null?void 0:s.language)||"zh-CN"}}catch{}return"zh-CN"})();de.use(ar).init({resources:{"zh-CN":{translation:tn,hook:tn.hook},en:{translation:sn,hook:sn.hook}},lng:Ui,fallbackLng:"zh-CN",interpolation:{escapeValue:!1}});let xt=new Set;function Gi(s){function e(){t(window)}function t(d){d&&typeof d.addEventListener=="function"&&(d.addEventListener("click",o,!0),d.addEventListener("mousedown",a,!0),d.addEventListener("mouseover",a,!0),d.addEventListener("mouseup",a,!0),d.addEventListener("pointerdown",i,!0),d.addEventListener("pointerover",l,!0),d.addEventListener("pointerup",c,!0))}function n(){r(window),xt.forEach(d=>{try{r(d.contentWindow)}catch{}}),xt=new Set}function r(d){d&&typeof d.removeEventListener=="function"&&(d.removeEventListener("click",o,!0),d.removeEventListener("mousedown",a,!0),d.removeEventListener("mouseover",a,!0),d.removeEventListener("mouseup",a,!0),d.removeEventListener("pointerdown",i,!0),d.removeEventListener("pointerover",l,!0),d.removeEventListener("pointerup",c,!0))}function o(d){var p;d.preventDefault(),d.stopPropagation(),n(),(p=s.onClick)===null||p===void 0||p.call(s,d.target)}function a(d){d.preventDefault(),d.stopPropagation()}function i(d){d.preventDefault(),d.stopPropagation()}function l(d){var p;d.preventDefault(),d.stopPropagation();const h=d.target;if(h.tagName==="IFRAME"){const f=h;try{if(!xt.has(f)){const m=f.contentWindow;t(m),xt.add(f)}}catch{}}(p=s.onPointerOver)===null||p===void 0||p.call(s,d.target)}function c(d){d.preventDefault(),d.stopPropagation()}return e(),n}const zi=s=>typeof(s==null?void 0:s.type)=="string",_n=s=>{var e;return typeof((e=s==null?void 0:s.type)===null||e===void 0?void 0:e.$$typeof)=="symbol"},Ki=s=>{var e;return((e=s==null?void 0:s.type)===null||e===void 0?void 0:e.$$typeof)===Symbol.for("react.forward_ref")},qi=s=>{const e=Object.keys(s).find(t=>t.startsWith("__reactInternalInstance$")||t.startsWith("__reactFiber$"));if(e)return s[e]},cs=s=>{if(!s)return;const e=qi(s);return e||cs(s.parentElement)},Vi=s=>{let e=s.return;for(;e;){if(!_n(e))return e;e=e.return}return null},Tn=s=>{const e=s==null?void 0:s.type;if(!e)return;const{displayName:t,name:n}=e;if(typeof t=="string")return t;if(typeof n=="string")return n},Ji=s=>{var e,t;if(!s)return;const n=(e=s._debugSource)!==null&&e!==void 0?e:(t=s._debugOwner)===null||t===void 0?void 0:t._debugSource;if(!n)return;const{fileName:r,lineNumber:o,columnNumber:a}=n;if(r&&o)return{lineNumber:String(o),columnNumber:String(a??1),absolutePath:r.match(/^<.*>$/)?r.replace(/^<|>$/g,""):r}},Yi=s=>{if(!(s!=null&&s.pendingProps))return;const{"data-inspector-line":e,"data-inspector-column":t,"data-inspector-relative-path":n}=s.pendingProps;if(e&&t&&n)return{lineNumber:e,columnNumber:t,relativePath:n}},ds=s=>{const e=[Ji(s),Yi(s)].filter(Boolean);if(e.length)return Object.assign({},...e)},Nn=s=>{if(!s)return;const e=Vi(s);if(!e)return;const t=zi(e),n=!e.child.sibling;let r=!t&&n?e:s;const o=r;for(;r;){if(ds(r))return r;r=r.return}return o},nn=s=>{const e=cs(s),t=Nn(e);return ds(t)},Qi=s=>{var e,t;let n=s,r;for(;n;){let o=(e=n.return)!==null&&e!==void 0?e:void 0,a;for(;_n(o);)Ki(o)&&(a=o),o=(t=o==null?void 0:o.return)!==null&&t!==void 0?t:void 0;if(a&&(n=a),Tn(n)&&(r||(r=n),ds(n)))return n;n=o}return r},on=s=>{const e=cs(s),t=Nn(e),n=Qi(t),r=Tn(n),o=s.nodeName.toLowerCase(),a=r?`${o} in <${r}>`:o;return{fiber:t,name:r,title:a}};function rn(s){return s.getBoundingClientRect()}function Xi(s){const e=window.getComputedStyle(s);return{borderLeft:Number.parseInt(e.borderLeftWidth,10),borderRight:Number.parseInt(e.borderRightWidth,10),borderTop:Number.parseInt(e.borderTopWidth,10),borderBottom:Number.parseInt(e.borderBottomWidth,10),marginLeft:Number.parseInt(e.marginLeft,10),marginRight:Number.parseInt(e.marginRight,10),marginTop:Number.parseInt(e.marginTop,10),marginBottom:Number.parseInt(e.marginBottom,10),paddingLeft:Number.parseInt(e.paddingLeft,10),paddingRight:Number.parseInt(e.paddingRight,10),paddingTop:Number.parseInt(e.paddingTop,10),paddingBottom:Number.parseInt(e.paddingBottom,10)}}var Zi="/__open-stack-frame-in-editor";const an=wo(Zi),el=s=>"codeInfo"in s?s.codeInfo:s,tl=s=>{if(!s)return;const e=el(s),{lineNumber:t,columnNumber:n,relativePath:r,absolutePath:o}=e,a=!!r,i=a?r:o;if(!i){console.error("[react-dev-inspector] Cannot open editor without source fileName",e);return}const l={fileName:i,lineNumber:t,colNumber:n},c=a?`${an}/relative`:an;fetch(`${c}?${new URLSearchParams(l)}`)},Gt=typeof navigator<"u"?navigator.userAgent.toLowerCase().indexOf("firefox")>0:!1;function zt(s,e,t,n){s.addEventListener?s.addEventListener(e,t,n):s.attachEvent&&s.attachEvent("on".concat(e),t)}function tt(s,e,t,n){s.removeEventListener?s.removeEventListener(e,t,n):s.detachEvent&&s.detachEvent("on".concat(e),t)}function Bn(s,e){const t=e.slice(0,e.length-1);for(let n=0;n<t.length;n++)t[n]=s[t[n].toLowerCase()];return t}function An(s){typeof s!="string"&&(s=""),s=s.replace(/\s/g,"");const e=s.split(",");let t=e.lastIndexOf("");for(;t>=0;)e[t-1]+=",",e.splice(t,1),t=e.lastIndexOf("");return e}function sl(s,e){const t=s.length>=e.length?s:e,n=s.length>=e.length?e:s;let r=!0;for(let o=0;o<t.length;o++)n.indexOf(t[o])===-1&&(r=!1);return r}const ut={backspace:8,"⌫":8,tab:9,clear:12,enter:13,"↩":13,return:13,esc:27,escape:27,space:32,left:37,up:38,right:39,down:40,arrowup:38,arrowdown:40,arrowleft:37,arrowright:39,del:46,delete:46,ins:45,insert:45,home:36,end:35,pageup:33,pagedown:34,capslock:20,num_0:96,num_1:97,num_2:98,num_3:99,num_4:100,num_5:101,num_6:102,num_7:103,num_8:104,num_9:105,num_multiply:106,num_add:107,num_enter:108,num_subtract:109,num_decimal:110,num_divide:111,"⇪":20,",":188,".":190,"/":191,"`":192,"-":Gt?173:189,"=":Gt?61:187,";":Gt?59:186,"'":222,"{":219,"}":221,"[":219,"]":221,"\\":220},xe={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,cmd:91,meta:91,command:91},nt={16:"shiftKey",18:"altKey",17:"ctrlKey",91:"metaKey",shiftKey:16,ctrlKey:17,altKey:18,metaKey:91},ae={16:!1,18:!1,17:!1,91:!1},Q={};for(let s=1;s<20;s++)ut["f".concat(s)]=111+s;let Y=[],it=null,En="all";const Ne=new Map,Ge=s=>ut[s.toLowerCase()]||xe[s.toLowerCase()]||s.toUpperCase().charCodeAt(0),nl=s=>Object.keys(ut).find(e=>ut[e]===s),ol=s=>Object.keys(xe).find(e=>xe[e]===s);function Pn(s){En=s||"all"}function pt(){return En||"all"}function rl(){return Y.slice(0)}function al(){return Y.map(s=>nl(s)||ol(s)||String.fromCharCode(s))}function il(){const s=[];return Object.keys(Q).forEach(e=>{Q[e].forEach(t=>{let{key:n,scope:r,mods:o,shortcut:a}=t;s.push({scope:r,shortcut:a,mods:o,keys:n.split("+").map(i=>Ge(i))})})}),s}function ll(s){const e=s.target||s.srcElement,{tagName:t}=e;let n=!0;const r=t==="INPUT"&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(e.type);return(e.isContentEditable||(r||t==="TEXTAREA"||t==="SELECT")&&!e.readOnly)&&(n=!1),n}function cl(s){return typeof s=="string"&&(s=Ge(s)),Y.indexOf(s)!==-1}function dl(s,e){let t,n;s||(s=pt());for(const r in Q)if(Object.prototype.hasOwnProperty.call(Q,r))for(t=Q[r],n=0;n<t.length;)t[n].scope===s?t.splice(n,1).forEach(a=>{let{element:i}=a;return us(i)}):n++;pt()===s&&Pn(e||"all")}function ul(s){let e=s.keyCode||s.which||s.charCode;s.key&&s.key.toLowerCase()==="capslock"&&(e=Ge(s.key));const t=Y.indexOf(e);if(t>=0&&Y.splice(t,1),s.key&&s.key.toLowerCase()==="meta"&&Y.splice(0,Y.length),(e===93||e===224)&&(e=91),e in ae){ae[e]=!1;for(const n in xe)xe[n]===e&&(ge[n]=!1)}}function jn(s){if(typeof s>"u")Object.keys(Q).forEach(r=>{Array.isArray(Q[r])&&Q[r].forEach(o=>kt(o)),delete Q[r]}),us(null);else if(Array.isArray(s))s.forEach(r=>{r.key&&kt(r)});else if(typeof s=="object")s.key&&kt(s);else if(typeof s=="string"){for(var e=arguments.length,t=new Array(e>1?e-1:0),n=1;n<e;n++)t[n-1]=arguments[n];let[r,o]=t;typeof r=="function"&&(o=r,r=""),kt({key:s,scope:r,method:o,splitKey:"+"})}}const kt=s=>{let{key:e,scope:t,method:n,splitKey:r="+"}=s;An(e).forEach(a=>{const i=a.split(r),l=i.length,c=i[l-1],d=c==="*"?"*":Ge(c);if(!Q[d])return;t||(t=pt());const p=l>1?Bn(xe,i):[],h=[];Q[d]=Q[d].filter(f=>{const y=(n?f.method===n:!0)&&f.scope===t&&sl(f.mods,p);return y&&h.push(f.element),!y}),h.forEach(f=>us(f))})};function ln(s,e,t,n){if(e.element!==n)return;let r;if(e.scope===t||e.scope==="all"){r=e.mods.length>0;for(const o in ae)Object.prototype.hasOwnProperty.call(ae,o)&&(!ae[o]&&e.mods.indexOf(+o)>-1||ae[o]&&e.mods.indexOf(+o)===-1)&&(r=!1);(e.mods.length===0&&!ae[16]&&!ae[18]&&!ae[17]&&!ae[91]||r||e.shortcut==="*")&&(e.keys=[],e.keys=e.keys.concat(Y),e.method(s,e)===!1&&(s.preventDefault?s.preventDefault():s.returnValue=!1,s.stopPropagation&&s.stopPropagation(),s.cancelBubble&&(s.cancelBubble=!0)))}}function cn(s,e){const t=Q["*"];let n=s.keyCode||s.which||s.charCode;if(s.key&&s.key.toLowerCase()==="capslock"||!ge.filter.call(this,s))return;if((n===93||n===224)&&(n=91),Y.indexOf(n)===-1&&n!==229&&Y.push(n),["metaKey","ctrlKey","altKey","shiftKey"].forEach(i=>{const l=nt[i];s[i]&&Y.indexOf(l)===-1?Y.push(l):!s[i]&&Y.indexOf(l)>-1?Y.splice(Y.indexOf(l),1):i==="metaKey"&&s[i]&&(Y=Y.filter(c=>c in nt||c===n))}),n in ae){ae[n]=!0;for(const i in xe)if(Object.prototype.hasOwnProperty.call(xe,i)){const l=nt[xe[i]];ge[i]=s[l]}if(!t)return}for(const i in ae)Object.prototype.hasOwnProperty.call(ae,i)&&(ae[i]=s[nt[i]]);s.getModifierState&&!(s.altKey&&!s.ctrlKey)&&s.getModifierState("AltGraph")&&(Y.indexOf(17)===-1&&Y.push(17),Y.indexOf(18)===-1&&Y.push(18),ae[17]=!0,ae[18]=!0);const r=pt();if(t)for(let i=0;i<t.length;i++)t[i].scope===r&&(s.type==="keydown"&&t[i].keydown||s.type==="keyup"&&t[i].keyup)&&ln(s,t[i],r,e);if(!(n in Q))return;const o=Q[n],a=o.length;for(let i=0;i<a;i++)if((s.type==="keydown"&&o[i].keydown||s.type==="keyup"&&o[i].keyup)&&o[i].key){const l=o[i],{splitKey:c}=l,d=l.key.split(c),p=[];for(let h=0;h<d.length;h++)p.push(Ge(d[h]));p.sort().join("")===Y.sort().join("")&&ln(s,l,r,e)}}function ge(s,e,t){Y=[];const n=An(s);let r=[],o="all",a=document,i=0,l=!1,c=!0,d="+",p=!1,h=!1;for(t===void 0&&typeof e=="function"&&(t=e),Object.prototype.toString.call(e)==="[object Object]"&&(e.scope&&(o=e.scope),e.element&&(a=e.element),e.keyup&&(l=e.keyup),e.keydown!==void 0&&(c=e.keydown),e.capture!==void 0&&(p=e.capture),typeof e.splitKey=="string"&&(d=e.splitKey),e.single===!0&&(h=!0)),typeof e=="string"&&(o=e),h&&jn(s,o);i<n.length;i++)s=n[i].split(d),r=[],s.length>1&&(r=Bn(xe,s)),s=s[s.length-1],s=s==="*"?"*":Ge(s),s in Q||(Q[s]=[]),Q[s].push({keyup:l,keydown:c,scope:o,mods:r,shortcut:n[i],method:t,key:n[i],splitKey:d,element:a});if(typeof a<"u"&&window){if(!Ne.has(a)){const f=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;return cn(y,a)},m=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;cn(y,a),ul(y)};Ne.set(a,{keydownListener:f,keyupListenr:m,capture:p}),zt(a,"keydown",f,p),zt(a,"keyup",m,p)}if(!it){const f=()=>{Y=[]};it={listener:f,capture:p},zt(window,"focus",f,p)}}}function pl(s){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"all";Object.keys(Q).forEach(t=>{Q[t].filter(r=>r.scope===e&&r.shortcut===s).forEach(r=>{r&&r.method&&r.method()})})}function us(s){const e=Object.values(Q).flat();if(e.findIndex(n=>{let{element:r}=n;return r===s})<0){const{keydownListener:n,keyupListenr:r,capture:o}=Ne.get(s)||{};n&&r&&(tt(s,"keyup",r,o),tt(s,"keydown",n,o),Ne.delete(s))}if((e.length<=0||Ne.size<=0)&&(Object.keys(Ne).forEach(r=>{const{keydownListener:o,keyupListenr:a,capture:i}=Ne.get(r)||{};o&&a&&(tt(r,"keyup",a,i),tt(r,"keydown",o,i),Ne.delete(r))}),Ne.clear(),Object.keys(Q).forEach(r=>delete Q[r]),it)){const{listener:r,capture:o}=it;tt(window,"focus",r,o),it=null}}const Kt={getPressedKeyString:al,setScope:Pn,getScope:pt,deleteScope:dl,getPressedKeyCodes:rl,getAllKeyCodes:il,isPressed:cl,filter:ll,trigger:pl,unbind:jn,keyMap:ut,modifier:xe,modifierMap:nt};for(const s in Kt)Object.prototype.hasOwnProperty.call(Kt,s)&&(ge[s]=Kt[s]);if(typeof window<"u"){const s=window.hotkeys;ge.noConflict=e=>(e&&window.hotkeys===ge&&(window.hotkeys=s),ge),window.hotkeys=ge}var qt;const hl=typeof window<"u"&&(!((qt=window==null?void 0:window.document)===null||qt===void 0)&&qt.createElement)?g.useLayoutEffect:g.useEffect,Oe=s=>{const e=g.useRef(s);e.current=g.useMemo(()=>s,[s]);const t=g.useRef();return t.current||(t.current=function(...n){var r;return(r=e.current)===null||r===void 0?void 0:r.apply(this,n)}),t.current},fl=({disable:s})=>{const e=g.useRef({x:0,y:0}),t=n=>{e.current.x=n.clientX,e.current.y=n.clientY};return g.useEffect(()=>(s||document.addEventListener("mousemove",t,!0),()=>{document.removeEventListener("mousemove",t,!0)}),[s]),e};class ml{constructor(e,t){Object.defineProperty(this,"node",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"border",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"padding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.node=e.createElement("div"),this.border=e.createElement("div"),this.padding=e.createElement("div"),this.content=e.createElement("div"),this.border.style.borderColor=St.border,this.padding.style.borderColor=St.padding,this.content.style.backgroundColor=St.background,Object.assign(this.node.style,{borderColor:St.margin,pointerEvents:"none",position:"fixed"}),this.node.style.zIndex="10000000",this.node.appendChild(this.border),this.border.appendChild(this.padding),this.padding.appendChild(this.content),t.prepend(this.node)}remove(){this.node.parentNode&&this.node.parentNode.removeChild(this.node)}update(e,t){Vt(t,"margin",this.node),Vt(t,"border",this.border),Vt(t,"padding",this.padding),Object.assign(this.content.style,{height:`${e.height-t.borderTop-t.borderBottom-t.paddingTop-t.paddingBottom}px`,width:`${e.width-t.borderLeft-t.borderRight-t.paddingLeft-t.paddingRight}px`}),Object.assign(this.node.style,{top:`${e.top-t.marginTop}px`,left:`${e.left-t.marginLeft}px`})}}class gl{constructor(e,t){Object.defineProperty(this,"tip",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"nameSpan",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"titleDiv",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"infoDiv",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dimSpan",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tip=e.createElement("div"),Object.assign(this.tip.style,{display:"flex",flexFlow:"row nowrap",alignItems:"center",backgroundColor:"#333740",borderRadius:"2px",fontFamily:'"SFMono-Regular", Consolas, "Liberation Mono", Menlo, Courier, monospace',fontWeight:"bold",padding:"6px 8px",pointerEvents:"none",position:"fixed",fontSize:"12px",whiteSpace:"nowrap"}),this.nameSpan=e.createElement("span"),this.tip.appendChild(this.nameSpan),Object.assign(this.nameSpan.style,{display:"flex",flexDirection:"column",borderRight:"1px solid #aaaaaa",paddingRight:"0.8rem",marginRight:"0.8rem"}),this.titleDiv=e.createElement("div"),this.nameSpan.appendChild(this.titleDiv),Object.assign(this.titleDiv.style,{color:"#ee78e6",fontSize:"16px"}),this.infoDiv=e.createElement("div"),this.nameSpan.appendChild(this.infoDiv),Object.assign(this.infoDiv.style,{color:"#ee78e6",fontSize:"14px"}),this.dimSpan=e.createElement("span"),this.tip.appendChild(this.dimSpan),Object.assign(this.dimSpan.style,{color:"#d7d7d7"}),this.tip.style.zIndex="10000000",t.appendChild(this.tip)}remove(){this.tip.parentNode&&this.tip.parentNode.removeChild(this.tip)}updateText(e,t,n,r){this.titleDiv.textContent=e,this.infoDiv.textContent=t??"",this.dimSpan.textContent=`${Math.round(n)}px × ${Math.round(r)}px`}updatePosition(e,t){const n=this.tip.getBoundingClientRect(),r=bl(e,t,{width:n.width,height:n.height});Object.assign(this.tip.style,r.style)}}class yl{constructor(){Object.defineProperty(this,"window",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tipBoundsWindow",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"container",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tip",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"rects",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"removeCallback",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const e=window.__REACT_DEVTOOLS_TARGET_WINDOW__||window;this.window=e;const t=window.__REACT_DEVTOOLS_TARGET_WINDOW__||window;this.tipBoundsWindow=t;const n=e.document;this.container=n.createElement("div"),this.container.style.zIndex="10000000",this.tip=new gl(n,this.container),this.rects=[],this.removeCallback=()=>{},n.body.appendChild(this.container)}remove(){this.tip.remove(),this.rects.forEach(e=>{e.remove()}),this.rects.length=0,this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.removeCallback()}setRemoveCallback(e){this.removeCallback=e.bind(this)}inspect(e,t,n){var r;const o=e.filter(l=>l.nodeType===Node.ELEMENT_NODE);for(;this.rects.length>o.length;){const l=this.rects.pop();l==null||l.remove()}if(o.length===0)return;for(;this.rects.length<o.length;)this.rects.push(new ml(this.window.document,this.container));const a={top:Number.POSITIVE_INFINITY,right:Number.NEGATIVE_INFINITY,bottom:Number.NEGATIVE_INFINITY,left:Number.POSITIVE_INFINITY};if(o.forEach((l,c)=>{const d=rn(l,this.window),p=Xi(l);a.top=Math.min(a.top,d.top-p.marginTop),a.right=Math.max(a.right,d.left+d.width+p.marginRight),a.bottom=Math.max(a.bottom,d.top+d.height+p.marginBottom),a.left=Math.min(a.left,d.left-p.marginLeft),this.rects[c].update(d,p)}),!t){t=o[0].nodeName.toLowerCase();const l=o[0],c=(r=l.ownerDocument.defaultView)===null||r===void 0?void 0:r.__REACT_DEVTOOLS_GLOBAL_HOOK__;if(c!=null&&c.rendererInterfaces){let d=null;for(const p of c.rendererInterfaces.values()){const h=p.getFiberIDForNative(l,!0);if(h!==null){d=p.getDisplayNameForFiberID(h,!0);break}}d&&(t+=` (in ${d})`)}}this.tip.updateText(t,n,a.right-a.left,a.bottom-a.top);const i=rn(this.tipBoundsWindow.document.documentElement,this.window);this.tip.updatePosition({top:a.top,left:a.left,height:a.bottom-a.top,width:a.right-a.left},{top:i.top+this.tipBoundsWindow.scrollY,left:i.left+this.tipBoundsWindow.scrollX,height:this.tipBoundsWindow.innerHeight,width:this.tipBoundsWindow.innerWidth})}}function bl(s,e,t){const n=Math.max(t.height,20),r=Math.max(t.width,60),o=5;let a;s.top+s.height+n<=e.top+e.height?s.top+s.height<e.top+0?a=e.top+o:a=s.top+s.height+o:s.top-n<=e.top+e.height?s.top-n-o<e.top+o?a=e.top+o:a=s.top-n-o:a=e.top+e.height-n-o;let i=s.left+o;return s.left<e.left&&(i=e.left+o),s.left+r>e.left+e.width&&(i=e.left+e.width-r-o),{style:{top:`${a}px`,left:`${i}px`}}}function Vt(s,e,t){Object.assign(t.style,{borderTopWidth:`${s[`${e}Top`]}px`,borderLeftWidth:`${s[`${e}Left`]}px`,borderRightWidth:`${s[`${e}Right`]}px`,borderBottomWidth:`${s[`${e}Bottom`]}px`,borderStyle:"solid"})}const St={background:"rgba(120, 170, 210, 0.7)",padding:"rgba(77, 200, 0, 0.3)",margin:"rgba(255, 155, 0, 0.3)",border:"rgba(255, 200, 50, 0.3)"},xl=()=>{var s;return!((s=navigator.platform)===null||s===void 0)&&s.startsWith("Mac")?["Ctrl","Shift","Command","C"]:["Ctrl","Shift","Alt","C"]},kl=s=>{const{keys:e,onHoverElement:t,onClickElement:n,onInspectElement:r,active:o,onActiveChange:a,disableLaunchEditor:i,disable:l=!0,children:c}=s,[d,p]=g.useState(o??!1);hl(()=>{o!==void 0&&p(o)},[o]),g.useEffect(()=>(d?C():S(),S),[d]);const h=e===null?null:(e??[]).join("+"),f=g.useRef(),m=fl({disable:l}),y=Oe(()=>{a==null||a(!0),o===void 0&&p(!0)}),v=Oe(()=>{a==null||a(!1),o===void 0&&p(!1)}),C=Oe(()=>{if(f.current||l)return;const x=new yl;f.current=x,ge("esc",v);const R=Gi({onPointerOver:T,onClick:_});x.setRemoveCallback(R);const j=m.current,D=document.elementFromPoint(j.x,j.y);D&&T(D)}),S=Oe(()=>{var x;(x=f.current)===null||x===void 0||x.remove(),f.current=void 0,ge.unbind("esc",v)}),T=Oe(x=>{var R;const j=f.current,D=nn(x),O=D==null?void 0:D.relativePath,W=D==null?void 0:D.absolutePath,{fiber:ne,name:N,title:b}=on(x);(R=j==null?void 0:j.inspect)===null||R===void 0||R.call(j,[x],b,O??W),t==null||t({element:x,fiber:ne,codeInfo:D,name:N})}),_=Oe(x=>{v();const R=nn(x),{fiber:j,name:D}=on(x);n==null||n({element:x,fiber:j,codeInfo:R,name:D}),j&&R&&(r==null||r({element:x,fiber:j,codeInfo:R,name:D}),!r&&!i&&tl(R))});return g.useEffect(()=>{const x=()=>{f.current?v():y()},R=h===null||l?null:h||xl().join("+");if(R)return ge(R,x),()=>{ge.unbind(R,x)}},[h,l]),u.jsx(u.Fragment,{children:c??null})};function Sl(){const[s,e]=g.useState(!1);return g.useEffect(()=>{const t=n=>{n.ctrlKey&&n.shiftKey&&n.altKey&&(n.key==="c"||n.key==="C")&&(n.preventDefault(),e(r=>!r))};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[]),u.jsxs(u.Fragment,{children:[u.jsx(kl,{active:s,onActiveChange:e}),u.jsx("button",{onClick:()=>e(t=>!t),title:s?"关闭检查模式":"开启检查模式 (Ctrl+Shift+Alt+C)",style:{position:"fixed",bottom:"20px",right:"20px",zIndex:99999,width:"44px",height:"44px",borderRadius:"50%",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"20px",boxShadow:"0 2px 12px rgba(0,0,0,0.25)",transition:"all 0.2s ease",background:s?"#22c55e":"#1e293b",color:"#fff"},children:u.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[u.jsx("circle",{cx:"12",cy:"12",r:"3"}),u.jsx("path",{d:"M22 12c0 5.52-4.48 10-10 10S2 17.52 2 12 6.48 2 12 2s10 4.48 10 10z"}),u.jsx("path",{d:"M12 2v20"}),u.jsx("path",{d:"M2 12h20"})]})})]})}Xt.createRoot(document.getElementById("root")).render(u.jsxs(Co.StrictMode,{children:[u.jsx(Sl,{}),u.jsx(Va,{})]}));export{Al as A,rs as D,Ca as M,at as T,Nl as W,re as _,q as a,ve as b,V as c,ue as d,Ee as e,kr as f,He as g,k as h,Le as i,Be as j,G as k,El as l,Cr as m,$e as n,J as o,Bl as p,kn as q,Pl as r,jl as s,X as t,Nt as u,ia as v,I as w,Ze as x,Ir as y};
|