@deepseekcode/cli 1.0.17 → 1.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +1014 -1004
- package/package.json +1 -1
- package/web/dist/assets/{AgentFlowView-D-nPVDb9.js → AgentFlowView-qR01S0jV.js} +1 -1
- package/web/dist/assets/{AgentsView-DHNgV13S.js → AgentsView-CLvG8aae.js} +1 -1
- package/web/dist/assets/{AuditView-ZCIV7Q0I.js → AuditView-CMYlGV9S.js} +1 -1
- package/web/dist/assets/{AutomationView-By6rBhla.js → AutomationView-wrcdqhJY.js} +1 -1
- package/web/dist/assets/{ChannelConfigView-_cIgiA-O.js → ChannelConfigView-DM70m5RE.js} +1 -1
- package/web/dist/assets/{ConnectorsView-BQQ_k_7I.js → ConnectorsView-B5ndd8pU.js} +1 -1
- package/web/dist/assets/{FileTreeView-DKUEkVqn.js → FileTreeView-DL66cxki.js} +1 -1
- package/web/dist/assets/{HookConfigView-DbkxVuAs.js → HookConfigView-BugHBHlO.js} +2 -2
- package/web/dist/assets/{InboxView-B3ddpq78.js → InboxView-DLPWNrqG.js} +1 -1
- package/web/dist/assets/ModelsView-CwhL9YPX.js +2 -0
- package/web/dist/assets/SessionGrid-CC1NAZ45.js +26 -0
- package/web/dist/assets/SettingsPanel-n1UbEjzX.js +4 -0
- package/web/dist/assets/{SkillsView-BwJowYXS.js → SkillsView-DznSS50I.js} +1 -1
- package/web/dist/assets/{TemplatesTab-BB-6z4z4.js → TemplatesTab-BPD0hvrG.js} +1 -1
- package/web/dist/assets/{TerminalView-D9e8fyOS.js → TerminalView-B4WUBGzA.js} +1 -1
- package/web/dist/assets/{ToolsView-CQ3hybgP.js → ToolsView-CQgPyD6U.js} +1 -1
- package/web/dist/assets/{icons-B5yCkBjC.js → icons-CrV0VGFQ.js} +107 -82
- package/web/dist/assets/index-DMxlsuNM.js +20 -0
- package/web/dist/assets/index-DjWfcgLQ.css +1 -0
- package/web/dist/assets/{markdown-D0iUI0Yw.js → markdown-CaPdHFK5.js} +1 -1
- package/web/dist/assets/panels-B3UcQJtY.js +1 -0
- package/web/dist/assets/{react-vendor-Bxu3r3ox.js → react-vendor-DnYXnA42.js} +1 -1
- package/web/dist/assets/{state-C80Yzgl0.js → state-BHmvnECu.js} +1 -1
- package/web/dist/index.html +6 -6
- package/web/dist/assets/AskQuestionModal-BKkh6JlF.js +0 -1
- package/web/dist/assets/HookApprovalModal-DC_q-If8.js +0 -1
- package/web/dist/assets/HookApprovalPreview-C8fU_Umi.js +0 -3
- package/web/dist/assets/ModelsView-B2N4jMxM.js +0 -1
- package/web/dist/assets/SessionGrid-CnK6naC_.js +0 -23
- package/web/dist/assets/SettingsPanel-czOfv9mx.js +0 -3
- package/web/dist/assets/index-DVZ3Ws5S.css +0 -1
- package/web/dist/assets/index-YAnKQ1Q6.js +0 -20
- package/web/dist/assets/panels-DOT_5rsR.js +0 -1
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ModelsView-CwhL9YPX.js","assets/markdown-CaPdHFK5.js","assets/icons-CrV0VGFQ.js","assets/react-vendor-DnYXnA42.js","assets/state-BHmvnECu.js","assets/ToolsView-CQgPyD6U.js","assets/AgentFlowView-qR01S0jV.js","assets/SkillsView-DznSS50I.js","assets/AgentsView-CLvG8aae.js","assets/TemplatesTab-BPD0hvrG.js","assets/HookConfigView-BugHBHlO.js","assets/FileTreeView-DL66cxki.js","assets/TerminalView-B4WUBGzA.js","assets/terminal-Ck_l6svU.js","assets/TerminalView-C1Mzzh8g.css","assets/SessionGrid-CC1NAZ45.js","assets/SettingsPanel-n1UbEjzX.js","assets/ChannelConfigView-DM70m5RE.js","assets/ConnectorsView-B5ndd8pU.js","assets/InboxView-DLPWNrqG.js","assets/AutomationView-wrcdqhJY.js","assets/AuditView-CMYlGV9S.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Eo=Object.defineProperty;var Bo=(s,e,t)=>e in s?Eo(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var se=(s,e,t)=>Bo(s,typeof e!="symbol"?e+"":e,t);import{j as c}from"./markdown-CaPdHFK5.js";import{r as g,S as Ye,F as bs,C as Wn,D as xs,L as bt,E as Po,a as Ct,b as Bs,X as xt,P as Lt,A as Ro,M as Wt,d as Ot,e as Hn,f as Io,G as Ht,h as Ps,i as Ut,H as Ys,j as Mo,k as Lo,l as Oo,m as Rs,R as Un,n as Qs,o as $o,p as Xs,q as Do,s as Fo,t as Wo,u as Kn,v as Ho,I as Gn,w as Uo,x as Ko,y as Go,T as zo,z as Vo,B as qo,J as Jo,K as Yo,N as Qo,O as Xo,Q as Zo,U as er,V as tr,Y as sr,Z as nr,_ as or,$ as rr,a0 as ar,a1 as ir,g as lr,W as cr}from"./icons-CrV0VGFQ.js";import{r as dr}from"./react-vendor-DnYXnA42.js";import{s as ur,c as be}from"./state-BHmvnECu.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))n(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const a of r.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function t(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function n(o){if(o.ep)return;o.ep=!0;const r=t(o);fetch(o.href,r)}})();var ks={},Zs=dr;ks.createRoot=Zs.createRoot,ks.hydrateRoot=Zs.hydrateRoot;const pr="modulepreload",mr=function(s){return"/"+s},en={},he=function(e,t,n){let o=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"));o=Promise.allSettled(t.map(l=>{if(l=mr(l),l in en)return;en[l]=!0;const d=l.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${l}"]${u}`))return;const p=document.createElement("link");if(p.rel=d?"stylesheet":pr,d||(p.as="script"),p.crossOrigin="",p.href=l,i&&p.setAttribute("nonce",i),document.head.appendChild(p),d)return new Promise((m,h)=>{p.addEventListener("load",m),p.addEventListener("error",()=>h(new Error(`Unable to preload CSS for ${l}`)))})}))}function r(a){const i=new Event("vite:preloadError",{cancelable:!0});if(i.payload=a,window.dispatchEvent(i),!i.defaultPrevented)throw a}return o.then(a=>{for(const i of a||[])i.status==="rejected"&&r(i.reason);return e().catch(r)})},O=s=>typeof s=="string",et=()=>{let s,e;const t=new Promise((n,o)=>{s=n,e=o});return t.resolve=s,t.reject=e,t},tn=s=>s==null?"":String(s),hr=(s,e,t)=>{s.forEach(n=>{e[n]&&(t[n]=e[n])})},fr=/###/g,sn=s=>s&&s.includes("###")?s.replace(fr,"."):s,nn=s=>!s||O(s),mt=(s,e,t)=>{const n=O(e)?e.split("."):e;let o=0;for(;o<n.length-1;){if(nn(s))return{};const r=sn(n[o]);!s[r]&&t&&(s[r]=new t),Object.prototype.hasOwnProperty.call(s,r)?s=s[r]:s={},++o}return nn(s)?{}:{obj:s,k:sn(n[o])}},on=(s,e,t)=>{const{obj:n,k:o}=mt(s,e,Object);if(n!==void 0||e.length===1){n[o]=t;return}let r=e[e.length-1],a=e.slice(0,e.length-1),i=mt(s,a,Object);for(;i.obj===void 0&&a.length;)r=`${a[a.length-1]}.${r}`,a=a.slice(0,a.length-1),i=mt(s,a,Object),i!=null&&i.obj&&typeof i.obj[`${i.k}.${r}`]<"u"&&(i.obj=void 0);i.obj[`${i.k}.${r}`]=t},gr=(s,e,t,n)=>{const{obj:o,k:r}=mt(s,e,Object);o[r]=o[r]||[],o[r].push(t)},$t=(s,e)=>{const{obj:t,k:n}=mt(s,e);if(t&&Object.prototype.hasOwnProperty.call(t,n))return t[n]},yr=(s,e,t)=>{const n=$t(s,t);return n!==void 0?n:$t(e,t)},zn=(s,e,t)=>{for(const n in e)n!=="__proto__"&&n!=="constructor"&&(Object.prototype.hasOwnProperty.call(s,n)?O(s[n])||s[n]instanceof String||O(e[n])||e[n]instanceof String?t&&(s[n]=e[n]):zn(s[n],e[n],t):s[n]=e[n]);return s},Pe=s=>s.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),br={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"},xr=s=>O(s)?s.replace(/[&<>"'\/]/g,e=>br[e]):s;class kr{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 Sr=[" ",",","?","!",";"],vr=new kr(20),wr=(s,e,t)=>{e=e||"",t=t||"";const n=Sr.filter(a=>!e.includes(a)&&!t.includes(a));if(n.length===0)return!0;const o=vr.getRegExp(`(${n.map(a=>a==="?"?"\\?":a).join("|")})`);let r=!o.test(s);if(!r){const a=s.indexOf(t);a>0&&!o.test(s.substring(0,a))&&(r=!0)}return r},Ss=(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 o=s;for(let r=0;r<n.length;){if(!o||typeof o!="object")return;let a,i="";for(let l=r;l<n.length;++l)if(l!==r&&(i+=t),i+=n[l],a=o[i],a!==void 0){if(["string","number","boolean"].includes(typeof a)&&l<n.length-1)continue;r+=l-r+1;break}o=a}return o},kt=s=>s==null?void 0:s.replace(/_/g,"-"),Cr={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 Dt{constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||Cr,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,o){return o&&!this.debug?null:(e=e.map(r=>O(r)?r.replace(/[\r\n\x00-\x1F\x7F]/g," "):r),O(e[0])&&(e[0]=`${n}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new Dt(this.logger,{prefix:`${this.prefix}:${e}:`,...this.options})}clone(e){return e=e||this.options,e.prefix=e.prefix||this.prefix,new Dt(this.logger,e)}}var je=new Dt;class Kt{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(n=>{this.observers[n]||(this.observers[n]=new Map);const o=this.observers[n].get(t)||0;this.observers[n].set(t,o+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=(...o)=>{t(...o),this.off(e,n)};return this.on(e,n),this}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([o,r])=>{for(let a=0;a<r;a++)o(...t)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([o,r])=>{for(let a=0;a<r;a++)o(e,...t)})}}class rn extends Kt{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,o={}){var d,u;const r=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,a=o.ignoreJSONStructure!==void 0?o.ignoreJSONStructure:this.options.ignoreJSONStructure;let i;e.includes(".")?i=e.split("."):(i=[e,t],n&&(Array.isArray(n)?i.push(...n):O(n)&&r?i.push(...n.split(r)):i.push(n)));const l=$t(this.data,i);return!l&&!t&&!n&&e.includes(".")&&(e=i[0],t=i[1],n=i.slice(2).join(".")),l||!a||!O(n)?l:Ss((u=(d=this.data)==null?void 0:d[e])==null?void 0:u[t],n,r)}addResource(e,t,n,o,r={silent:!1}){const a=r.keySeparator!==void 0?r.keySeparator:this.options.keySeparator;let i=[e,t];n&&(i=i.concat(a?n.split(a):n)),e.includes(".")&&(i=e.split("."),o=t,t=i[1]),this.addNamespaces(t),on(this.data,i,o),r.silent||this.emit("added",e,t,n,o)}addResources(e,t,n,o={silent:!1}){for(const r in n)(O(n[r])||Array.isArray(n[r]))&&this.addResource(e,t,r,n[r],{silent:!0});o.silent||this.emit("added",e,t,n)}addResourceBundle(e,t,n,o,r,a={silent:!1,skipCopy:!1}){let i=[e,t];e.includes(".")&&(i=e.split("."),o=n,n=t,t=i[1]),this.addNamespaces(t);let l=$t(this.data,i)||{};a.skipCopy||(n=JSON.parse(JSON.stringify(n))),o?zn(l,n,r):l={...l,...n},on(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(o=>t[o]&&Object.keys(t[o]).length>0)}toJSON(){return this.data}}var Vn={processors:{},addPostProcessor(s){this.processors[s.name]=s},handle(s,e,t,n,o){return s.forEach(r=>{var a;e=((a=this.processors[r])==null?void 0:a.process(e,t,n,o))??e}),e}};const qn=Symbol("i18next/PATH_KEY");function _r(){const s=[],e=Object.create(null);let t;return e.get=(n,o)=>{var r;return(r=t==null?void 0:t.revoke)==null||r.call(t),o===qn?s:(s.push(o),t=Proxy.revocable(n,e),t.proxy)},Proxy.revocable(Object.create(null),e).proxy}function Qe(s,e){const{[qn]:t}=s(_r()),n=(e==null?void 0:e.keySeparator)??".",o=(e==null?void 0:e.nsSeparator)??":",r=(e==null?void 0:e.enableSelector)==="strict";if(t.length>1&&o){const a=e==null?void 0:e.ns,i=r?Array.isArray(a)?a:a?[a]:null:Array.isArray(a)?a:null;if(i&&(r?i:i.length>1?i.slice(1):[]).includes(t[0]))return`${t[0]}${o}${t.slice(1).join(n)}`}return t.join(n)}const es=s=>!O(s)&&typeof s!="boolean"&&typeof s!="number";class Ft extends Kt{constructor(e,t={}){super(),hr(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,this.options.keySeparator===void 0&&(this.options.keySeparator="."),this.logger=je.create("translator"),this.checkedLoadedFor={}}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){const n={...t};if(e==null)return!1;const o=this.resolve(e,n);if((o==null?void 0:o.res)===void 0)return!1;const r=es(o.res);return!(n.returnObjects===!1&&r)}extractFromKey(e,t){let n=t.nsSeparator!==void 0?t.nsSeparator:this.options.nsSeparator;n===void 0&&(n=":");const o=t.keySeparator!==void 0?t.keySeparator:this.options.keySeparator;let r=t.ns||this.options.defaultNS||[];const a=n&&e.includes(n),i=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!wr(e,n,o);if(a&&!i){const l=e.match(this.interpolator.nestingRegexp);if(l&&l.length>0)return{key:e,namespaces:O(r)?[r]:r};const d=e.split(n);(n!==o||n===o&&this.options.ns.includes(d[0]))&&(r=d.shift()),e=d.join(o)}return{key:e,namespaces:O(r)?[r]:r}}translate(e,t,n){let o=typeof t=="object"?{...t}:t;if(typeof o!="object"&&this.options.overloadTranslationOptionHandler&&(o=this.options.overloadTranslationOptionHandler(arguments)),typeof o=="object"&&(o={...o}),o||(o={}),e==null)return"";typeof e=="function"&&(e=Qe(e,{...this.options,...o})),Array.isArray(e)||(e=[String(e)]),e=e.map(S=>typeof S=="function"?Qe(S,{...this.options,...o}):String(S));const r=o.returnDetails!==void 0?o.returnDetails:this.options.returnDetails,a=o.keySeparator!==void 0?o.keySeparator:this.options.keySeparator,{key:i,namespaces:l}=this.extractFromKey(e[e.length-1],o),d=l[l.length-1];let u=o.nsSeparator!==void 0?o.nsSeparator:this.options.nsSeparator;u===void 0&&(u=":");const p=o.lng||this.language,m=o.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if((p==null?void 0:p.toLowerCase())==="cimode")return m?r?{res:`${d}${u}${i}`,usedKey:i,exactUsedKey:i,usedLng:p,usedNS:d,usedParams:this.getUsedParamsDetails(o)}:`${d}${u}${i}`:r?{res:i,usedKey:i,exactUsedKey:i,usedLng:p,usedNS:d,usedParams:this.getUsedParamsDetails(o)}:i;const h=this.resolve(e,o);let f=h==null?void 0:h.res;const y=(h==null?void 0:h.usedKey)||i,b=(h==null?void 0:h.exactUsedKey)||i,C=["[object Number]","[object Function]","[object RegExp]"],k=o.joinArrays!==void 0?o.joinArrays:this.options.joinArrays,T=!this.i18nFormat||this.i18nFormat.handleAsObject,_=o.count!==void 0&&!O(o.count),w=Ft.hasDefaultValue(o),E=_?this.pluralResolver.getSuffix(p,o.count,o):"",N=o.ordinal&&_?this.pluralResolver.getSuffix(p,o.count,{ordinal:!1}):"",L=_&&!o.ordinal&&o.count===0,$=L&&o[`defaultValue${this.options.pluralSeparator}zero`]||o[`defaultValue${E}`]||o[`defaultValue${N}`]||o.defaultValue;let U=f;T&&!f&&w&&(U=$);const de=es(U),A=Object.prototype.toString.apply(U);if(T&&U&&de&&!C.includes(A)&&!(O(k)&&Array.isArray(U))){if(!o.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");const S=this.options.returnedObjectHandler?this.options.returnedObjectHandler(y,U,{...o,ns:l}):`key '${i} (${this.language})' returned an object instead of string.`;return r?(h.res=S,h.usedParams=this.getUsedParamsDetails(o),h):S}if(a){const S=Array.isArray(U),P=S?[]:{},H=S?b:y;for(const q in U)if(Object.prototype.hasOwnProperty.call(U,q)){const ne=`${H}${a}${q}`;w&&!f?P[q]=this.translate(ne,{...o,defaultValue:es($)?$[q]:void 0,joinArrays:!1,ns:l}):P[q]=this.translate(ne,{...o,joinArrays:!1,ns:l}),P[q]===ne&&(P[q]=U[q])}f=P}}else if(T&&O(k)&&Array.isArray(f))f=f.join(k),f&&(f=this.extendTranslation(f,e,o,n));else{let S=!1,P=!1;!this.isValidLookup(f)&&w&&(S=!0,f=$),this.isValidLookup(f)||(P=!0,f=i);const q=(o.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&P?void 0:f,ne=w&&$!==f&&this.options.updateMissing;if(P||S||ne){if(this.logger.log(ne?"updateKey":"missingKey",p,d,_&&!ne?`${i}${this.pluralResolver.getSuffix(p,o.count,o)}`:i,ne?$:f),a){const te=this.resolve(i,{...o,keySeparator:!1});te&&te.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 ge=[];const ae=this.languageUtils.getFallbackCodes(this.options.fallbackLng,o.lng||this.language);if(this.options.saveMissingTo==="fallback"&&ae&&ae[0])for(let te=0;te<ae.length;te++)ge.push(ae[te]);else this.options.saveMissingTo==="all"?ge=this.languageUtils.toResolveHierarchy(o.lng||this.language):ge.push(o.lng||this.language);const Fe=(te,B,D)=>{var M;const R=w&&D!==f?D:q;this.options.missingKeyHandler?this.options.missingKeyHandler(te,d,B,R,ne,o):(M=this.backendConnector)!=null&&M.saveMissing&&this.backendConnector.saveMissing(te,d,B,R,ne,o),this.emit("missingKey",te,d,B,f)};this.options.saveMissing&&(this.options.saveMissingPlurals&&_?ge.forEach(te=>{const B=this.pluralResolver.getSuffixes(te,o);L&&o[`defaultValue${this.options.pluralSeparator}zero`]&&!B.includes(`${this.options.pluralSeparator}zero`)&&B.push(`${this.options.pluralSeparator}zero`),B.forEach(D=>{Fe([te],i+D,o[`defaultValue${D}`]||$)})}):Fe(ge,i,$))}f=this.extendTranslation(f,e,o,h,n),P&&f===i&&this.options.appendNamespaceToMissingKey&&(f=`${d}${u}${i}`),(P||S)&&this.options.parseMissingKeyHandler&&(f=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${d}${u}${i}`:i,S?f:void 0,o))}return r?(h.res=f,h.usedParams=this.getUsedParamsDetails(o),h):f}extendTranslation(e,t,n,o,r){var l,d;if((l=this.i18nFormat)!=null&&l.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...n},n.lng||this.language||o.usedLng,o.usedNS,o.usedKey,{resolved:o});else if(!n.skipInterpolation){n.interpolation&&this.interpolator.init({...n,interpolation:{...this.options.interpolation,...n.interpolation}});const u=O(e)&&(((d=n==null?void 0:n.interpolation)==null?void 0:d.skipOnVariables)!==void 0?n.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);let p;if(u){const h=e.match(this.interpolator.nestingRegexp);p=h&&h.length}let m=n.replace&&!O(n.replace)?n.replace:n;if(this.options.interpolation.defaultVariables&&(m={...this.options.interpolation.defaultVariables,...m}),e=this.interpolator.interpolate(e,m,n.lng||this.language||o.usedLng,n),u){const h=e.match(this.interpolator.nestingRegexp),f=h&&h.length;p<f&&(n.nest=!1)}!n.lng&&o&&o.res&&(n.lng=this.language||o.usedLng),n.nest!==!1&&(e=this.interpolator.nest(e,(...h)=>(r==null?void 0:r[0])===h[0]&&!n.context?(this.logger.warn(`It seems you are nesting recursively key: ${h[0]} in key: ${t[0]}`),null):this.translate(...h,t),n)),n.interpolation&&this.interpolator.reset()}const a=n.postProcess||this.options.postProcess,i=O(a)?[a]:a;return e!=null&&(i!=null&&i.length)&&n.applyPostProcessor!==!1&&(e=Vn.handle(i,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...o,usedParams:this.getUsedParamsDetails(n)},...n}:n,this)),e}resolve(e,t={}){let n,o,r,a,i;return O(e)&&(e=[e]),Array.isArray(e)&&(e=e.map(l=>typeof l=="function"?Qe(l,{...this.options,...t}):l)),e.forEach(l=>{if(this.isValidLookup(n))return;const d=this.extractFromKey(l,t),u=d.key;o=u;let p=d.namespaces;this.options.fallbackNS&&(p=p.concat(this.options.fallbackNS));const m=t.count!==void 0&&!O(t.count),h=m&&!t.ordinal&&t.count===0,f=t.context!==void 0&&(O(t.context)||typeof t.context=="number")&&t.context!=="",y=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);p.forEach(b=>{var C,k;this.isValidLookup(n)||(i=b,!this.checkedLoadedFor[`${y[0]}-${b}`]&&((C=this.utils)!=null&&C.hasLoadedNamespace)&&!((k=this.utils)!=null&&k.hasLoadedNamespace(i))&&(this.checkedLoadedFor[`${y[0]}-${b}`]=!0,this.logger.warn(`key "${o}" 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 E;if(this.isValidLookup(n))return;a=T;const _=[u];if((E=this.i18nFormat)!=null&&E.addLookupKeys)this.i18nFormat.addLookupKeys(_,u,T,b,t);else{let N;m&&(N=this.pluralResolver.getSuffix(T,t.count,t));const L=`${this.options.pluralSeparator}zero`,$=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(m&&(t.ordinal&&N.startsWith($)&&_.push(u+N.replace($,this.options.pluralSeparator)),_.push(u+N),h&&_.push(u+L)),f){const U=`${u}${this.options.contextSeparator||"_"}${t.context}`;_.push(U),m&&(t.ordinal&&N.startsWith($)&&_.push(U+N.replace($,this.options.pluralSeparator)),_.push(U+N),h&&_.push(U+L))}}let w;for(;w=_.pop();)this.isValidLookup(n)||(r=w,n=this.getResource(T,b,w,t))}))})}),{res:n,usedKey:o,exactUsedKey:r,usedLng:a,usedNS:i}}isValidLookup(e){return e!==void 0&&!(!this.options.returnNull&&e===null)&&!(!this.options.returnEmptyString&&e==="")}getResource(e,t,n,o={}){var r;return(r=this.i18nFormat)!=null&&r.getResource?this.i18nFormat.getResource(e,t,n,o):this.resourceStore.getResource(e,t,n,o)}getUsedParamsDetails(e={}){const t=["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"],n=e.replace&&!O(e.replace);let o=n?e.replace:e;if(n&&typeof e.count<"u"&&(o={...o,count:e.count}),this.options.interpolation.defaultVariables&&(o={...this.options.interpolation.defaultVariables,...o}),!n){o={...o};for(const r of t)delete o[r]}return o}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 an{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=je.create("languageUtils")}getScriptPartFromCode(e){if(e=kt(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=kt(e),!e||!e.includes("-"))return e;const t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(O(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 o=this.formatLanguageCode(n);(!this.options.supportedLngs||this.isSupportedCode(o))&&(t=o)}),!t&&this.options.supportedLngs&&e.forEach(n=>{if(t)return;const o=this.getScriptPartFromCode(n);if(this.isSupportedCode(o))return t=o;const r=this.getLanguagePartFromCode(n);if(this.isSupportedCode(r))return t=r;t=this.options.supportedLngs.find(a=>a===r?!0:!a.includes("-")&&!r.includes("-")?!1:!!(a.includes("-")&&!r.includes("-")&&a.slice(0,a.indexOf("-"))===r||a.startsWith(r)&&r.length>1))}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t}getFallbackCodes(e,t){if(!e)return[];if(typeof e=="function"&&(e=e(t)),O(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),o=[],r=a=>{a&&(this.isSupportedCode(a)?o.push(a):this.logger.warn(`rejecting language code not found in supportedLngs: ${a}`))};return O(e)&&(e.includes("-")||e.includes("_"))?(this.options.load!=="languageOnly"&&r(this.formatLanguageCode(e)),this.options.load!=="languageOnly"&&this.options.load!=="currentOnly"&&r(this.getScriptPartFromCode(e)),this.options.load!=="currentOnly"&&r(this.getLanguagePartFromCode(e))):O(e)&&r(this.formatLanguageCode(e)),n.forEach(a=>{o.includes(a)||r(this.formatLanguageCode(a))}),o}}const ln={zero:0,one:1,two:2,few:3,many:4,other:5},cn={select:s=>s===1?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class Tr{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=je.create("pluralResolver"),this.pluralRulesCache={}}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){const n=kt(e==="dev"?"en":e),o=t.ordinal?"ordinal":"cardinal",r=JSON.stringify({cleanedCode:n,type:o});if(r in this.pluralRulesCache)return this.pluralRulesCache[r];let a;try{a=new Intl.PluralRules(n,{type:o})}catch{if(typeof Intl>"u")return this.logger.error("No Intl support, please use an Intl polyfill!"),cn;if(!e.match(/-|_/))return cn;const l=this.languageUtils.getLanguagePartFromCode(e);a=this.getRule(l,t)}return this.pluralRulesCache[r]=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(o=>`${t}${o}`)}getSuffixes(e,t={}){let n=this.getRule(e,t);return n||(n=this.getRule("dev",t)),n?n.resolvedOptions().pluralCategories.sort((o,r)=>ln[o]-ln[r]).map(o=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${o}`):[]}getSuffix(e,t,n={}){const o=this.getRule(e,n);return o?`${this.options.prepend}${n.ordinal?`ordinal${this.options.prepend}`:""}${o.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,n))}}const dn=(s,e,t,n=".",o=!0)=>{let r=yr(s,e,t);return!r&&o&&O(t)&&(r=Ss(s,t,n),r===void 0&&(r=Ss(e,t,n))),r},Nr=s=>s.replace(/\$/g,"$$$$");class un{constructor(e={}){var t;this.logger=je.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:o,prefix:r,prefixEscaped:a,suffix:i,suffixEscaped:l,formatSeparator:d,unescapeSuffix:u,unescapePrefix:p,nestingPrefix:m,nestingPrefixEscaped:h,nestingSuffix:f,nestingSuffixEscaped:y,nestingOptionsSeparator:b,maxReplaces:C,alwaysFormat:k}=e.interpolation;this.escape=t!==void 0?t:xr,this.escapeValue=n!==void 0?n:!0,this.useRawValueToEscape=o!==void 0?o:!1,this.prefix=r?Pe(r):a||"{{",this.suffix=i?Pe(i):l||"}}",this.formatSeparator=d||",",this.unescapePrefix=u?"":p?Pe(p):"-",this.unescapeSuffix=this.unescapePrefix?"":u?Pe(u):"",this.nestingPrefix=m?Pe(m):h||Pe("$t("),this.nestingSuffix=f?Pe(f):y||Pe(")"),this.nestingOptionsSeparator=b||",",this.maxReplaces=C||1e3,this.alwaysFormat=k!==void 0?k:!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,o){var h;let r,a,i;const l=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},d=f=>{if(!f.includes(this.formatSeparator)){const k=dn(t,l,f,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(k,void 0,n,{...o,...t,interpolationkey:f}):k}const y=f.split(this.formatSeparator),b=y.shift().trim(),C=y.join(this.formatSeparator).trim();return this.format(dn(t,l,b,this.options.keySeparator,this.options.ignoreJSONStructure),C,n,{...o,...t,interpolationkey:b})};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 u=(o==null?void 0:o.missingInterpolationHandler)||this.options.missingInterpolationHandler,p=((h=o==null?void 0:o.interpolation)==null?void 0:h.skipOnVariables)!==void 0?o.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:f=>f},{regex:this.regexp,safeValue:f=>this.escapeValue?this.escape(f):f}].forEach(f=>{for(i=0;r=f.regex.exec(e);){const y=r[1].trim();if(a=d(y),a===void 0)if(typeof u=="function"){const C=u(e,r,o);a=O(C)?C:""}else if(o&&Object.prototype.hasOwnProperty.call(o,y))a="";else if(p){a=r[0];continue}else this.logger.warn(`missed to pass in variable ${y} for interpolating ${e}`),a="";else!O(a)&&!this.useRawValueToEscape&&(a=tn(a));const b=f.safeValue(a);if(e=e.replace(r[0],Nr(b)),p?(f.regex.lastIndex+=b.length,f.regex.lastIndex-=r[0].length):f.regex.lastIndex=0,i++,i>=this.maxReplaces)break}}),e}nest(e,t,n={}){let o,r,a;const i=(l,d)=>{const u=this.nestingOptionsSeparator;if(!l.includes(u))return l;const p=l.split(new RegExp(`${Pe(u)}[ ]*{`));let m=`{${p[1]}`;l=p[0],m=this.interpolate(m,a);const h=m.match(/'/g),f=m.match(/"/g);(((h==null?void 0:h.length)??0)%2===0&&!f||((f==null?void 0:f.length)??0)%2!==0)&&(m=m.replace(/'/g,'"'));try{a=JSON.parse(m),d&&(a={...d,...a})}catch(y){return this.logger.warn(`failed parsing options string in nesting for key ${l}`,y),`${l}${u}${m}`}return a.defaultValue&&a.defaultValue.includes(this.prefix)&&delete a.defaultValue,l};for(;o=this.nestingRegexp.exec(e);){let l=[];a={...n},a=a.replace&&!O(a.replace)?a.replace:a,a.applyPostProcessor=!1,delete a.defaultValue;const d=/{.*}/s.test(o[1])?o[1].lastIndexOf("}")+1:o[1].indexOf(this.formatSeparator);if(d!==-1&&(l=o[1].slice(d).split(this.formatSeparator).map(u=>u.trim()).filter(Boolean),o[1]=o[1].slice(0,d)),r=t(i.call(this,o[1].trim(),a),a),r&&o[0]===e&&!O(r))return r;O(r)||(r=tn(r)),r||(this.logger.warn(`missed to resolve ${o[1]} for nesting ${e}`),r=""),l.length&&(r=l.reduce((u,p)=>this.format(u,p,n.lng,{...n,interpolationkey:o[1].trim()}),r.trim())),e=e.replace(o[0],r),this.regexp.lastIndex=0}return e}}const jr=s=>{let e=s.toLowerCase().trim();const t={};if(s.includes("(")){const n=s.split("(");e=n[0].toLowerCase().trim();const o=n[1].slice(0,-1);e==="currency"&&!o.includes(":")?t.currency||(t.currency=o.trim()):e==="relativetime"&&!o.includes(":")?t.range||(t.range=o.trim()):o.split(";").forEach(a=>{if(a){const[i,...l]=a.split(":"),d=l.join(":").trim().replace(/^'+|'+$/g,""),u=i.trim();t[u]||(t[u]=d),d==="false"&&(t[u]=!1),d==="true"&&(t[u]=!0),isNaN(d)||(t[u]=parseInt(d,10))}})}return{formatName:e,formatOptions:t}},pn=s=>{const e={};return(t,n,o)=>{let r=o;o&&o.interpolationkey&&o.formatParams&&o.formatParams[o.interpolationkey]&&o[o.interpolationkey]&&(r={...r,[o.interpolationkey]:void 0});const a=n+JSON.stringify(r);let i=e[a];return i||(i=s(kt(n),o),e[a]=i),i(t)}},Ar=s=>(e,t,n)=>s(kt(t),n)(e);class Er{constructor(e={}){this.logger=je.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";const n=t.cacheInBuiltFormats?pn:Ar;this.formats={number:n((o,r)=>{const a=new Intl.NumberFormat(o,{...r});return i=>a.format(i)}),currency:n((o,r)=>{const a=new Intl.NumberFormat(o,{...r,style:"currency"});return i=>a.format(i)}),datetime:n((o,r)=>{const a=new Intl.DateTimeFormat(o,{...r});return i=>a.format(i)}),relativetime:n((o,r)=>{const a=new Intl.RelativeTimeFormat(o,{...r});return i=>a.format(i,r.range||"day")}),list:n((o,r)=>{const a=new Intl.ListFormat(o,{...r});return i=>a.format(i)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=pn(t)}format(e,t,n,o={}){if(!t||e==null)return e;const r=t.split(this.formatSeparator),a=[];for(let l=0;l<r.length;l++){let d=r[l];for(;d.indexOf("(")>-1&&!d.includes(")")&&l+1<r.length;)d=`${d}${this.formatSeparator}${r[++l]}`;a.push(d)}return a.reduce((l,d)=>{var m;const{formatName:u,formatOptions:p}=jr(d);if(this.formats[u]){let h=l;try{const f=((m=o==null?void 0:o.formatParams)==null?void 0:m[o.interpolationkey])||{},y=f.locale||f.lng||o.locale||o.lng||n;h=this.formats[u](l,y,{...p,...o,...f})}catch(f){this.logger.warn(f)}return h}else this.logger.warn(`there was no format function for ${u}`);return l},e)}}const Br=(s,e)=>{s.pending[e]!==void 0&&(delete s.pending[e],s.pendingCount--)};class Pr extends Kt{constructor(e,t,n,o={}){var r,a;super(),this.backend=e,this.store=t,this.services=n,this.languageUtils=n.languageUtils,this.options=o,this.logger=je.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=o.maxParallelReads||10,this.readingCalls=0,this.maxRetries=o.maxRetries>=0?o.maxRetries:5,this.retryTimeout=o.retryTimeout>=1?o.retryTimeout:350,this.state={},this.queue=[],(a=(r=this.backend)==null?void 0:r.init)==null||a.call(r,n,o.backend,o)}queueLoad(e,t,n,o){const r={},a={},i={},l={};return e.forEach(d=>{let u=!0;t.forEach(p=>{const m=`${d}|${p}`;!n.reload&&this.store.hasResourceBundle(d,p)?this.state[m]=2:this.state[m]<0||(this.state[m]===1?a[m]===void 0&&(a[m]=!0):(this.state[m]=1,u=!1,a[m]===void 0&&(a[m]=!0),r[m]===void 0&&(r[m]=!0),l[p]===void 0&&(l[p]=!0)))}),u||(i[d]=!0)}),(Object.keys(r).length||Object.keys(a).length)&&this.queue.push({pending:a,pendingCount:Object.keys(a).length,loaded:{},errors:[],callback:o}),{toLoad:Object.keys(r),pending:Object.keys(a),toLoadLanguages:Object.keys(i),toLoadNamespaces:Object.keys(l)}}loaded(e,t,n){const o=e.split("|"),r=o[0],a=o[1];t&&this.emit("failedLoading",r,a,t),!t&&n&&this.store.addResourceBundle(r,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=>{gr(l.loaded,[r],a),Br(l,e),t&&l.errors.push(t),l.pendingCount===0&&!l.done&&(Object.keys(l.loaded).forEach(d=>{i[d]||(i[d]={});const u=l.loaded[d];u.length&&u.forEach(p=>{i[d][p]===void 0&&(i[d][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,o=0,r=this.retryTimeout,a){if(!e.length)return a(null,{});if(this.readingCalls>=this.maxParallelReads){this.waitingReads.push({lng:e,ns:t,fcName:n,tried:o,wait:r,callback:a});return}this.readingCalls++;const i=(d,u)=>{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(d&&u&&o<this.maxRetries){setTimeout(()=>{this.read(e,t,n,o+1,r*2,a)},r);return}a(d,u)},l=this.backend[n].bind(this.backend);if(l.length===2){try{const d=l(e,t);d&&typeof d.then=="function"?d.then(u=>i(null,u)).catch(i):i(null,d)}catch(d){i(d)}return}return l(e,t,i)}prepareLoading(e,t,n={},o){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),o&&o();O(e)&&(e=this.languageUtils.toResolveHierarchy(e)),O(t)&&(t=[t]);const r=this.queueLoad(e,t,n,o);if(!r.toLoad.length)return r.pending.length||o(),null;r.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("|"),o=n[0],r=n[1];this.read(o,r,"read",void 0,void 0,(a,i)=>{a&&this.logger.warn(`${t}loading namespace ${r} for language ${o} failed`,a),!a&&i&&this.logger.log(`${t}loaded namespace ${r} for language ${o}`,i),this.loaded(e,a,i)})}saveMissing(e,t,n,o,r,a={},i=()=>{}){var l,d,u,p,m;if((d=(l=this.services)==null?void 0:l.utils)!=null&&d.hasLoadedNamespace&&!((p=(u=this.services)==null?void 0:u.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((m=this.backend)!=null&&m.create){const h={...a,isUpdate:r},f=this.backend.create.bind(this.backend);if(f.length<6)try{let y;f.length===5?y=f(e,t,n,o,h):y=f(e,t,n,o),y&&typeof y.then=="function"?y.then(b=>i(null,b)).catch(i):i(null,y)}catch(y){i(y)}else f(e,t,n,o,i,h)}!e||!e[0]||this.store.addResource(e[0],t,n,o)}}}const ts=()=>({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]),O(s[1])&&(e.defaultValue=s[1]),O(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}),mn=s=>(O(s.ns)&&(s.ns=[s.ns]),O(s.fallbackLng)&&(s.fallbackLng=[s.fallbackLng]),O(s.fallbackNS)&&(s.fallbackNS=[s.fallbackNS]),s.supportedLngs&&!s.supportedLngs.includes("cimode")&&(s.supportedLngs=s.supportedLngs.concat(["cimode"])),s),Nt=()=>{},Rr=s=>{Object.getOwnPropertyNames(Object.getPrototypeOf(s)).forEach(t=>{typeof s[t]=="function"&&(s[t]=s[t].bind(s))})};class ht extends Kt{constructor(e={},t){if(super(),this.options=mn(e),this.services={},this.logger=je,this.modules={external:[]},Rr(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&&(O(e.ns)?e.defaultNS=e.ns:e.ns.includes("translation")||(e.defaultNS=e.ns[0]));const n=ts();this.options={...n,...this.options,...mn(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 o=d=>d?typeof d=="function"?new d:d:null;if(!this.options.isClone){this.modules.logger?je.init(o(this.modules.logger),this.options):je.init(null,this.options);let d;this.modules.formatter?d=this.modules.formatter:d=Er;const u=new an(this.options);this.store=new rn(this.options.resources,this.options);const p=this.services;p.logger=je,p.resourceStore=this.store,p.languageUtils=u,p.pluralResolver=new Tr(u,{prepend:this.options.pluralSeparator}),d&&(p.formatter=o(d),p.formatter.init&&p.formatter.init(p,this.options),this.options.interpolation.format=p.formatter.format.bind(p.formatter)),p.interpolator=new un(this.options),p.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},p.backendConnector=new Pr(o(this.modules.backend),p.resourceStore,p,this.options),p.backendConnector.on("*",(m,...h)=>{this.emit(m,...h)}),this.modules.languageDetector&&(p.languageDetector=o(this.modules.languageDetector),p.languageDetector.init&&p.languageDetector.init(p,this.options.detection,this.options)),this.modules.i18nFormat&&(p.i18nFormat=o(this.modules.i18nFormat),p.i18nFormat.init&&p.i18nFormat.init(this)),this.translator=new Ft(this.services,this.options),this.translator.on("*",(m,...h)=>{this.emit(m,...h)}),this.modules.external.forEach(m=>{m.init&&m.init(this)})}if(this.format=this.options.interpolation.format,t||(t=Nt),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){const d=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);d.length>0&&d[0]!=="dev"&&(this.options.lng=d[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(d=>{this[d]=(...u)=>this.store[d](...u)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(d=>{this[d]=(...u)=>(this.store[d](...u),this)});const i=et(),l=()=>{const d=(u,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(u,p)};if((this.languages||this.isLanguageChangingTo)&&!this.isInitialized)return d(null,this.t.bind(this));this.changeLanguage(this.options.lng,d)};return this.options.resources||!this.options.initAsync?l():setTimeout(l,0),i}loadResources(e,t=Nt){var r,a;let n=t;const o=O(e)?e:this.language;if(typeof e=="function"&&(n=e),!this.options.resources||this.options.partialBundledLanguages){if((o==null?void 0:o.toLowerCase())==="cimode"&&(!this.options.preload||this.options.preload.length===0))return n();const i=[],l=d=>{if(!d||d==="cimode")return;this.services.languageUtils.toResolveHierarchy(d).forEach(p=>{p!=="cimode"&&(i.includes(p)||i.push(p))})};o?l(o):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(u=>l(u)),(a=(r=this.options.preload)==null?void 0:r.forEach)==null||a.call(r,d=>l(d)),this.services.backendConnector.load(i,this.options.ns,d=>{!d&&!this.resolvedLanguage&&this.language&&this.setResolvedLanguage(this.language),n(d)})}else n(null)}reloadResources(e,t,n){const o=et();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=Nt),this.services.backendConnector.reload(e,t,r=>{o.resolve(),n(r)}),o}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"&&Vn.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=et();this.emit("languageChanging",e);const o=i=>{this.language=i,this.languages=this.services.languageUtils.toResolveHierarchy(i),this.resolvedLanguage=void 0,this.setResolvedLanguage(i)},r=(i,l)=>{l?this.isLanguageChangingTo===e&&(o(l),this.translator.changeLanguage(l),this.isLanguageChangingTo=void 0,this.emit("languageChanged",l),this.logger.log("languageChanged",l)):this.isLanguageChangingTo=void 0,n.resolve((...d)=>this.t(...d)),t&&t(i,(...d)=>this.t(...d))},a=i=>{var u,p;!e&&!i&&this.services.languageDetector&&(i=[]);const l=O(i)?i:i&&i[0],d=this.store.hasLanguageSomeTranslations(l)?l:this.services.languageUtils.getBestMatchFromCodes(O(i)?[i]:i);d&&(this.language||o(d),this.translator.language||this.translator.changeLanguage(d),(p=(u=this.services.languageDetector)==null?void 0:u.cacheUserLanguage)==null||p.call(u,d)),this.loadResources(d,m=>{r(m,d)})};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,o){const r=o==null?void 0:o.scopeNs,a=(i,l,...d)=>{let u;typeof l!="object"?u=this.options.overloadTranslationOptionHandler([i,l].concat(d)):u={...l},u.lng=u.lng||a.lng,u.lngs=u.lngs||a.lngs;const p=u.ns!==void 0&&u.ns!==null;u.ns=u.ns||a.ns,u.keyPrefix!==""&&(u.keyPrefix=u.keyPrefix||n||a.keyPrefix);const m={...this.options,...u};Array.isArray(r)&&!p&&(m.ns=r),typeof u.keyPrefix=="function"&&(u.keyPrefix=Qe(u.keyPrefix,m));const h=this.options.keySeparator||".";let f;return u.keyPrefix&&Array.isArray(i)?f=i.map(y=>(typeof y=="function"&&(y=Qe(y,m)),`${u.keyPrefix}${h}${y}`)):(typeof i=="function"&&(i=Qe(i,m)),f=u.keyPrefix?`${u.keyPrefix}${h}${i}`:i),this.t(f,u)};return O(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],o=this.options?this.options.fallbackLng:!1,r=this.languages[this.languages.length-1];if(n.toLowerCase()==="cimode")return!0;const a=(i,l)=>{const d=this.services.backendConnector.state[`${i}|${l}`];return d===-1||d===0||d===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)&&(!o||a(r,e)))}loadNamespaces(e,t){const n=et();return this.options.ns?(O(e)&&(e=[e]),e.forEach(o=>{this.options.ns.includes(o)||this.options.ns.push(o)}),this.loadResources(o=>{n.resolve(),t&&t(o)}),n):(t&&t(),Promise.resolve())}loadLanguages(e,t){const n=et();O(e)&&(e=[e]);const o=this.options.preload||[],r=e.filter(a=>!o.includes(a)&&this.services.languageUtils.isSupportedCode(a));return r.length?(this.options.preload=o.concat(r),this.loadResources(a=>{n.resolve(),t&&t(a)}),n):(t&&t(),Promise.resolve())}dir(e){var o,r;if(e||(e=this.resolvedLanguage||(((o=this.languages)==null?void 0:o.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=((r=this.services)==null?void 0:r.languageUtils)||new an(ts());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 ht(e,t);return n.createInstance=ht.createInstance,n}cloneInstance(e={},t=Nt){const n=e.forkResourceStore;n&&delete e.forkResourceStore;const o={...this.options,...e,isClone:!0},r=new ht(o);if((e.debug!==void 0||e.prefix!==void 0)&&(r.logger=r.logger.clone(e)),["store","services","language"].forEach(i=>{r[i]=this[i]}),r.services={...this.services},r.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},n){const i=Object.keys(this.store.data).reduce((l,d)=>(l[d]={...this.store.data[d]},l[d]=Object.keys(l[d]).reduce((u,p)=>(u[p]={...l[d][p]},u),l[d]),l),{});r.store=new rn(i,o),r.services.resourceStore=r.store}if(e.interpolation){const l={...ts().interpolation,...this.options.interpolation,...e.interpolation},d={...o,interpolation:l};r.services.interpolator=new un(d)}return r.translator=new Ft(r.services,o),r.translator.on("*",(i,...l)=>{r.emit(i,...l)}),r.init(o,t),r.translator.options=o,r.translator.backendConnector.services.utils={hasLoadedNamespace:r.hasLoadedNamespace.bind(r)},r}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}const ye=ht.createInstance();ye.createInstance;ye.dir;ye.init;ye.loadResources;ye.reloadResources;ye.use;ye.changeLanguage;ye.getFixedT;ye.t;ye.exists;ye.setDefaultNamespace;ye.hasLoadedNamespace;ye.loadNamespaces;ye.loadLanguages;const Ir=(s,e,t,n)=>{var r,a,i,l;const o=[t,{code:e,...n||{}}];if((a=(r=s==null?void 0:s.services)==null?void 0:r.logger)!=null&&a.forward)return s.services.logger.forward(o,"warn","react-i18next::",!0);Ue(o[0])&&(o[0]=`react-i18next:: ${o[0]}`),(l=(i=s==null?void 0:s.services)==null?void 0:i.logger)!=null&&l.warn?s.services.logger.warn(...o):console!=null&&console.warn&&console.warn(...o)},hn={},vs=(s,e,t,n)=>{Ue(t)&&hn[t]||(Ue(t)&&(hn[t]=new Date),Ir(s,e,t,n))},Jn=(s,e)=>()=>{if(s.isInitialized)e();else{const t=()=>{setTimeout(()=>{s.off("initialized",t)},0),e()};s.on("initialized",t)}},ws=(s,e,t)=>{s.loadNamespaces(e,Jn(s,t))},fn=(s,e,t,n)=>{if(Ue(t)&&(t=[t]),s.options.preload&&s.options.preload.indexOf(e)>-1)return ws(s,t,n);t.forEach(o=>{s.options.ns.indexOf(o)<0&&s.options.ns.push(o)}),s.loadLanguages(e,Jn(s,n))},Mr=(s,e,t={})=>!e.languages||!e.languages.length?(vs(e,"NO_LANGUAGES","i18n.languages were undefined or empty",{languages:e.languages}),!0):e.hasLoadedNamespace(s,{lng:t.lng,precheck:(n,o)=>{if(t.bindI18n&&t.bindI18n.indexOf("languageChanging")>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!o(n.isLanguageChangingTo,s))return!1}}),Ue=s=>typeof s=="string",Lr=s=>typeof s=="object"&&s!==null,Or=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,$r={"&":"&","&":"&","<":"<","<":"<",">":">",">":">","'":"'","'":"'",""":'"',""":'"'," ":" "," ":" ","©":"©","©":"©","®":"®","®":"®","…":"…","…":"…","/":"/","/":"/"},Dr=s=>$r[s],Fr=s=>s.replace(Or,Dr);let Cs={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:Fr,transDefaultProps:void 0};const Wr=(s={})=>{Cs={...Cs,...s}},Hr=()=>Cs;let Yn;const Ur=s=>{Yn=s},Kr=()=>Yn,Gr={type:"3rdParty",init(s){Wr(s.options.react),Ur(s)}},zr=g.createContext();class Vr{constructor(){this.usedNamespaces={}}addUsedNamespaces(e){e.forEach(t=>{this.usedNamespaces[t]||(this.usedNamespaces[t]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const qr=(s,e)=>{if(Ue(e))return e;if(Lr(e)&&Ue(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},Jr={t:qr,ready:!1},Yr=()=>()=>{},Be=(s,e={})=>{var $,U,de;const{i18n:t}=e,{i18n:n,defaultNS:o}=g.useContext(zr)||{},r=t||n||Kr();r&&!r.reportNamespaces&&(r.reportNamespaces=new Vr),r||vs(r,"NO_I18NEXT_INSTANCE","useTranslation: You will need to pass in an i18next instance by using initReactI18next");const a=g.useMemo(()=>{var A;return{...Hr(),...(A=r==null?void 0:r.options)==null?void 0:A.react,...e}},[r,e]),{useSuspense:i,keyPrefix:l}=a,d=s||o||(($=r==null?void 0:r.options)==null?void 0:$.defaultNS),u=Ue(d)?[d]:d||["translation"],p=g.useMemo(()=>u,u);(de=(U=r==null?void 0:r.reportNamespaces)==null?void 0:U.addUsedNamespaces)==null||de.call(U,p);const m=g.useRef(0),h=g.useCallback(A=>{if(!r)return Yr;const{bindI18n:S,bindI18nStore:P}=a,H=()=>{m.current+=1,A()};return S&&r.on(S,H),P&&r.store.on(P,H),()=>{S&&S.split(" ").forEach(q=>r.off(q,H)),P&&P.split(" ").forEach(q=>r.store.off(q,H))}},[r,a]),f=g.useRef(),y=g.useCallback(()=>{if(!r)return Jr;const A=!!(r.isInitialized||r.initializedStoreOnce)&&p.every(ge=>Mr(ge,r,a)),S=e.lng||r.language,P=m.current,H=f.current;if(H&&H.ready===A&&H.lng===S&&H.keyPrefix===l&&H.revision===P)return H;const ne={t:r.getFixedT(S,a.nsMode==="fallback"?p:p[0],l,{scopeNs:p}),ready:A,lng:S,keyPrefix:l,revision:P};return f.current=ne,ne},[r,p,l,a,e.lng]),[b,C]=g.useState(0),{t:k,ready:T}=ur.useSyncExternalStore(h,y,y);g.useEffect(()=>{if(r&&!T&&!i){const A=()=>C(S=>S+1);e.lng?fn(r,e.lng,p,A):ws(r,p,A)}},[r,e.lng,p,T,i,b]);const _=r||{},w=g.useRef(null),E=g.useRef(),N=A=>{const S=Object.getOwnPropertyDescriptors(A);S.__original&&delete S.__original;const P=Object.create(Object.getPrototypeOf(A),S);if(!Object.prototype.hasOwnProperty.call(P,"__original"))try{Object.defineProperty(P,"__original",{value:A,writable:!1,enumerable:!1,configurable:!1})}catch{}return P},L=g.useMemo(()=>{const A=_,S=A==null?void 0:A.language;let P=A;A&&(w.current&&w.current.__original===A?E.current!==S?(P=N(A),w.current=P,E.current=S):P=w.current:(P=N(A),w.current=P,E.current=S));const H=!T&&!i?(...ne)=>(vs(r,"USE_T_BEFORE_READY","useTranslation: t was called before ready. When using useSuspense: false, make sure to check the ready flag before using t."),k(...ne)):k,q=[H,P,T];return q.t=H,q.i18n=P,q.ready=T,q},[k,_,T,_.resolvedLanguage,_.language,_.languages]);if(r&&i&&!T)throw new Promise(A=>{const S=()=>A();e.lng?fn(r,e.lng,p,S):ws(r,p,S)});return L},Qr={};function Xr(s,e){let t;try{t=s()}catch{return}return{getItem:o=>{var r;const a=l=>l===null?null:JSON.parse(l,void 0),i=(r=t.getItem(o))!=null?r:null;return i instanceof Promise?i.then(a):a(i)},setItem:(o,r)=>t.setItem(o,JSON.stringify(r,void 0)),removeItem:o=>t.removeItem(o)}}const St=s=>e=>{try{const t=s(e);return t instanceof Promise?t:{then(n){return St(n)(t)},catch(n){return this}}}catch(t){return{then(n){return this},catch(n){return St(n)(t)}}}},Zr=(s,e)=>(t,n,o)=>{let r={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:b=>b,version:0,merge:(b,C)=>({...C,...b}),...e},a=!1;const i=new Set,l=new Set;let d;try{d=r.getStorage()}catch{}if(!d)return s((...b)=>{console.warn(`[zustand persist middleware] Unable to update item '${r.name}', the given storage is currently unavailable.`),t(...b)},n,o);const u=St(r.serialize),p=()=>{const b=r.partialize({...n()});let C;const k=u({state:b,version:r.version}).then(T=>d.setItem(r.name,T)).catch(T=>{C=T});if(C)throw C;return k},m=o.setState;o.setState=(b,C)=>{m(b,C),p()};const h=s((...b)=>{t(...b),p()},n,o);let f;const y=()=>{var b;if(!d)return;a=!1,i.forEach(k=>k(n()));const C=((b=r.onRehydrateStorage)==null?void 0:b.call(r,n()))||void 0;return St(d.getItem.bind(d))(r.name).then(k=>{if(k)return r.deserialize(k)}).then(k=>{if(k)if(typeof k.version=="number"&&k.version!==r.version){if(r.migrate)return r.migrate(k.state,k.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return k.state}).then(k=>{var T;return f=r.merge(k,(T=n())!=null?T:h),t(f,!0),p()}).then(()=>{C==null||C(f,void 0),a=!0,l.forEach(k=>k(f))}).catch(k=>{C==null||C(void 0,k)})};return o.persist={setOptions:b=>{r={...r,...b},b.getStorage&&(d=b.getStorage())},clearStorage:()=>{d==null||d.removeItem(r.name)},getOptions:()=>r,rehydrate:()=>y(),hasHydrated:()=>a,onHydrate:b=>(i.add(b),()=>{i.delete(b)}),onFinishHydration:b=>(l.add(b),()=>{l.delete(b)})},y(),f||h},ea=(s,e)=>(t,n,o)=>{let r={storage:Xr(()=>localStorage),partialize:y=>y,version:0,merge:(y,b)=>({...b,...y}),...e},a=!1;const i=new Set,l=new Set;let d=r.storage;if(!d)return s((...y)=>{console.warn(`[zustand persist middleware] Unable to update item '${r.name}', the given storage is currently unavailable.`),t(...y)},n,o);const u=()=>{const y=r.partialize({...n()});return d.setItem(r.name,{state:y,version:r.version})},p=o.setState;o.setState=(y,b)=>{p(y,b),u()};const m=s((...y)=>{t(...y),u()},n,o);o.getInitialState=()=>m;let h;const f=()=>{var y,b;if(!d)return;a=!1,i.forEach(k=>{var T;return k((T=n())!=null?T:m)});const C=((b=r.onRehydrateStorage)==null?void 0:b.call(r,(y=n())!=null?y:m))||void 0;return St(d.getItem.bind(d))(r.name).then(k=>{if(k)if(typeof k.version=="number"&&k.version!==r.version){if(r.migrate)return[!0,r.migrate(k.state,k.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,k.state];return[!1,void 0]}).then(k=>{var T;const[_,w]=k;if(h=r.merge(w,(T=n())!=null?T:m),t(h,!0),_)return u()}).then(()=>{C==null||C(h,void 0),h=n(),a=!0,l.forEach(k=>k(h))}).catch(k=>{C==null||C(void 0,k)})};return o.persist={setOptions:y=>{r={...r,...y},y.storage&&(d=y.storage)},clearStorage:()=>{d==null||d.removeItem(r.name)},getOptions:()=>r,rehydrate:()=>f(),hasHydrated:()=>a,onHydrate:y=>(i.add(y),()=>{i.delete(y)}),onFinishHydration:y=>(l.add(y),()=>{l.delete(y)})},r.skipHydration||f(),h||m},ta=(s,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((Qr?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),Zr(s,e)):ea(s,e),Xe=ta;let gn=!1;function Ae(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():(gn||(gn=!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 sa=4e3,De=be(s=>({toasts:[],addToast:(e,t,n)=>{const o=`toast-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,r={id:o,type:e,message:t,duration:n??sa,createdAt:Date.now()};s(a=>({toasts:[...a.toasts.slice(-9),r]})),r.duration>0&&setTimeout(()=>{s(a=>({toasts:a.toasts.filter(i=>i.id!==o)}))},r.duration)},dismissToast:e=>s(t=>({toasts:t.toasts.filter(n=>n.id!==e)})),clearAll:()=>s({toasts:[]})})),W={info:(s,e)=>De.getState().addToast("info",s,e),success:(s,e)=>De.getState().addToast("success",s,e),warning:(s,e)=>De.getState().addToast("warning",s,e),error:(s,e)=>De.getState().addToast("error",s,e??6e3)},na="deepseekcode-chat-store",oa=500;let jt=null;const ra=3e4;let ss=0;const aa={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)=>{jt&&clearTimeout(jt),jt=setTimeout(()=>{jt=null;try{localStorage.setItem(s,JSON.stringify(e)),ss=0}catch(t){console.error("[chatStore] localStorage 持久化失败,刷新页面将丢失历史消息:",t);const n=Date.now();if(n-ss>ra){ss=n;try{De.getState().addToast("warning","聊天记录保存失败:浏览器本地存储已满或不可用。刷新页面将丢失历史消息,建议导出会话或清理旧会话。",8e3)}catch{}}}},oa)},removeItem:s=>{localStorage.removeItem(s)}};function yn(s,e,t){const n=s.thinkingBlocks?s.thinkingBlocks.map(o=>({...o})):s.thinking?[{index:Number.MIN_SAFE_INTEGER,text:s.thinking}]:[];if(typeof t=="number"){const o=n.find(r=>r.index===t);o?o.text+=e:n.push({index:t,text:e})}else if(n.length>0){const o=n.length-1,r=n[o];r?n[o]={...r,text:r.text+e}:n.push({index:0,text:e})}else n.push({index:0,text:e});return n.sort((o,r)=>o.index-r.index),{...s,thinkingBlocks:n,thinking:n.map(o=>o.text).join("")}}const G=be()(Xe((s,e)=>({messagesBySession:{},generatingSessions:[],pausedSessions:[],sessionInputs:{},getMessages:t=>e().messagesBySession[t]||[],replaceMessages:(t,n)=>s(o=>({messagesBySession:{...o.messagesBySession,[t]:n.slice(-200)}})),addMessage:(t,n)=>s(o=>{const a=[...o.messagesBySession[t]||[],n].slice(-200);return{messagesBySession:{...o.messagesBySession,[t]:a}}}),updateLastMessage:(t,n)=>s(o=>{const r=(o.messagesBySession[t]||[]).map((a,i,l)=>i===l.length-1&&a.type==="assistant"?{...a,content:n}:a);return{messagesBySession:{...o.messagesBySession,[t]:r}}}),appendToLastMessage:(t,n)=>s(o=>{const r=o.messagesBySession[t];if(!r||r.length===0)return o;const a=r.length-1,i=r[a];if(i&&i.type==="assistant"){const l=r.slice();return l[a]={...i,content:i.content+n},{messagesBySession:{...o.messagesBySession,[t]:l}}}return{messagesBySession:{...o.messagesBySession,[t]:[...r,{id:Ae(),type:"assistant",content:n,timestamp:Date.now()}].slice(-200)}}}),setThinking:(t,n)=>s(o=>{const r=(o.messagesBySession[t]||[]).map((a,i,l)=>{var u;if(i!==l.length-1||a.type!=="assistant")return a;const d=(u=a.steps)==null?void 0:u.findIndex(p=>p.status==="running");if(d!==void 0&&d!==-1&&a.steps&&a.steps[d]){const p=a.steps.map((m,h)=>h===d?{...m,thought:n}:m);return{...a,steps:p}}return{...a,thinking:n,thinkingBlocks:n?[{index:0,text:n}]:[]}});return{messagesBySession:{...o.messagesBySession,[t]:r}}}),appendToLastMessageThinking:(t,n,o)=>s(r=>{var m,h;const a=r.messagesBySession[t];if(!a||a.length===0)return r;const i=a.length-1,l=a[i];if(!l||l.type!=="assistant")return{messagesBySession:{...r.messagesBySession,[t]:[...a,yn({id:Ae(),type:"assistant",content:"",timestamp:Date.now()},n,o)].slice(-200)}};let d;const u=(m=l.steps)==null?void 0:m.findIndex(f=>f.status==="running");if(u!==void 0&&u!==-1&&((h=l.steps)!=null&&h[u])){const f=l.steps.slice(),y=f[u];f[u]={...y,thought:(y.thought||"")+n},d={...l,steps:f}}else if(l.steps&&l.steps.length>0){const f=l.steps.length-1,y=l.steps.slice(),b=y[f];y[f]={...b,thought:(b.thought||"")+n},d={...l,steps:y}}else d=yn(l,n,o);const p=a.slice();return p[i]=d,{messagesBySession:{...r.messagesBySession,[t]:p}}}),addStep:(t,n)=>s(o=>{const r=(o.messagesBySession[t]||[]).map((a,i,l)=>{var m,h;if(i!==l.length-1||a.type!=="assistant")return a;const d=(m=a.toolCalls)==null?void 0:m.filter(f=>{var y;return!((y=a.steps)!=null&&y.some(b=>{var C;return(C=b.toolCalls)==null?void 0:C.some(k=>k.id===f.id)}))}),u={...n};d!=null&&d.length&&(u.toolCalls=[...u.toolCalls||[],...d]);let p=a.thinking||"";return p.trim().length>0&&(u.thought=(u.thought||"")+p,p=""),{...a,thinking:p,thinkingBlocks:[],toolCalls:d!=null&&d.length?(h=a.toolCalls)==null?void 0:h.filter(f=>!d.some(y=>y.id===f.id)):a.toolCalls,steps:[...a.steps||[],u]}});return{messagesBySession:{...o.messagesBySession,[t]:r}}}),updateStep:(t,n,o)=>s(r=>{const a=(r.messagesBySession[t]||[]).map((i,l,d)=>{if(l!==d.length-1||!i.steps)return i;const u=i.steps.findIndex(m=>m.id===n);if(u===-1)return i;const p=i.steps.map((m,h)=>h===u?{...m,...o}:m);return{...i,steps:p}});return{messagesBySession:{...r.messagesBySession,[t]:a}}}),addToolCall:(t,n)=>s(o=>{const r=(o.messagesBySession[t]||[]).map((a,i,l)=>{var u;if(i!==l.length-1||a.type!=="assistant")return a;const d=(u=a.steps)==null?void 0:u.findIndex(p=>p.status==="running");if(d!==void 0&&d!==-1&&a.steps&&a.steps[d]){const p=a.steps.map((m,h)=>h===d?{...m,toolCalls:[...m.toolCalls||[],n]}:m);return{...a,steps:p}}if(a.steps&&a.steps.length>0){const p=a.steps.length-1,m=a.steps.map((h,f)=>f===p?{...h,toolCalls:[...h.toolCalls||[],n]}:h);return{...a,steps:m}}return{...a,toolCalls:[...a.toolCalls||[],n]}});return{messagesBySession:{...o.messagesBySession,[t]:r}}}),updateToolCall:(t,n,o)=>s(r=>{const a=l=>{if(!l)return null;const d=l.findIndex(u=>u.id===n);return d===-1?null:l.map((u,p)=>p===d?{...u,...o}:u)},i=(r.messagesBySession[t]||[]).map((l,d,u)=>{var h,f;if(d!==u.length-1||l.type!=="assistant")return l;const p=(h=l.steps)==null?void 0:h.findIndex(y=>y.status==="running");if(p!==void 0&&p!==-1&&l.steps&&l.steps[p]){const y=a((f=l.steps[p])==null?void 0:f.toolCalls);if(y){const b=l.steps.map((C,k)=>k===p?{...C,toolCalls:y}:C);return{...l,steps:b}}}if(l.steps){let y=!1;const b=l.steps.map(C=>{if(y)return C;const k=a(C.toolCalls);return k?(y=!0,{...C,toolCalls:k}):C});if(y)return{...l,steps:b}}const m=a(l.toolCalls);return m?{...l,toolCalls:m}:l});return{messagesBySession:{...r.messagesBySession,[t]:i}}}),appendToLastToolCallArgs:(t,n,o,r)=>s(a=>{const i=u=>{let p=u.args;if(typeof p=="string")p=p+o;else if(typeof p=="object"&&p!==null){const m=o.trim();if(m.startsWith("{")&&m.endsWith("}"))try{const h=JSON.parse(m);typeof p=="string"?p={...h}:p={...p,...h}}catch{p=JSON.stringify(p).slice(0,-1)+","+m.slice(1)}else typeof p=="string"?p=p+m:p=JSON.stringify(p)+m}else p=o;return{...u,args:p}},l=u=>{if(!u)return null;const p=u.findIndex(m=>r!==void 0&&m.index===r||m.id===n);return p===-1?null:u.map((m,h)=>h===p?i(m):m)},d=(a.messagesBySession[t]||[]).map((u,p,m)=>{var y,b;if(p!==m.length-1||u.type!=="assistant")return u;const h=(y=u.steps)==null?void 0:y.findIndex(C=>C.status==="running");if(h!==void 0&&h!==-1&&u.steps&&u.steps[h]){const C=l((b=u.steps[h])==null?void 0:b.toolCalls);if(C){const k=u.steps.map((T,_)=>_===h?{...T,toolCalls:C}:T);return{...u,steps:k}}}if(u.steps){let C=!1;const k=u.steps.map(T=>{if(C)return T;const _=l(T.toolCalls);return _?(C=!0,{...T,toolCalls:_}):T});if(C)return{...u,steps:k}}const f=l(u.toolCalls);return f?{...u,toolCalls:f}:u});return{messagesBySession:{...a.messagesBySession,[t]:d}}}),startGeneration:t=>s(n=>({generatingSessions:n.generatingSessions.includes(t)?n.generatingSessions:[...n.generatingSessions,t]})),endGeneration:(t,n)=>s(o=>{var d,u,p;const r=o.messagesBySession[t]||[],a=Date.now(),i=r.map(m=>{var b,C;let h=!1;const f=(b=m.steps)==null?void 0:b.map(k=>{if(!k.toolCalls)return k;const T=k.toolCalls.map(_=>_.status!=="running"?_:(h=!0,{..._,status:"error",result:"生成已结束(工具执行超时或连接中断)",duration:Math.floor((a-(_.timestamp||a))/1e3)}));return T!==k.toolCalls?{...k,toolCalls:T}:k}),y=(C=m.toolCalls)==null?void 0:C.map(k=>k.status!=="running"?k:(h=!0,{...k,status:"error",result:"生成已结束(工具执行超时或连接中断)",duration:Math.floor((a-(k.timestamp||a))/1e3)}));return h?{...m,steps:f,toolCalls:y}:m}),l=i[i.length-1];if(l&&l.type==="assistant"&&!l.content&&!l.thinking&&!((d=l.thinkingBlocks)!=null&&d.length)&&!((u=l.steps)!=null&&u.length)&&!((p=l.toolCalls)!=null&&p.length)&&!l.hookApproval){const{[t]:m,...h}=o.messagesBySession;return{generatingSessions:o.generatingSessions.filter(f=>f!==t),pausedSessions:o.pausedSessions.filter(f=>f!==t),messagesBySession:{...h,[t]:i.slice(0,-1)}}}return{generatingSessions:o.generatingSessions.filter(m=>m!==t),pausedSessions:o.pausedSessions.filter(m=>m!==t),messagesBySession:{...o.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(o=>o!==t)})),clearMessages:t=>s(n=>{const{[t]:o,...r}=n.messagesBySession;return{messagesBySession:r}}),removeSession:t=>s(n=>{const{[t]:o,...r}=n.messagesBySession,{[t]:a,...i}=n.sessionInputs;return{messagesBySession:r,sessionInputs:i,generatingSessions:n.generatingSessions.filter(l=>l!==t)}}),setSessionInput:(t,n)=>s(o=>({sessionInputs:{...o.sessionInputs,[t]:n}})),getSessionInput:t=>e().sessionInputs[t]||"",attachHookApproval:(t,n)=>s(o=>{const r=o.messagesBySession[t]||[];if(r.length===0){const d={id:`hook-approval-${n.approvalId||Date.now()}`,type:"assistant",content:"",timestamp:Date.now(),hookApproval:n};return{messagesBySession:{...o.messagesBySession,[t]:[d]}}}const a=r.length-1,i=r[a];if(i&&i.type==="assistant"){const d=r.slice();return d[a]={...i,hookApproval:n},{messagesBySession:{...o.messagesBySession,[t]:d}}}const l={id:`hook-approval-${n.approvalId||Date.now()}`,type:"assistant",content:"",timestamp:Date.now(),hookApproval:n};return{messagesBySession:{...o.messagesBySession,[t]:[...r,l].slice(-200)}}}),updateHookApprovalStatus:(t,n,o)=>s(r=>{const a=r.messagesBySession[t];if(!a)return r;const i=a.map(l=>{var d;return((d=l.hookApproval)==null?void 0:d.approvalId)===n?{...l,hookApproval:{...l.hookApproval,status:o}}:l});return{messagesBySession:{...r.messagesBySession,[t]:i}}}),setMessageFileJob:(t,n)=>s(o=>{const r=o.messagesBySession[t]||[];if(r.length===0){const d={id:`filejob-${n.jobId}`,type:"assistant",content:"",timestamp:Date.now(),fileJob:n};return{messagesBySession:{...o.messagesBySession,[t]:[d]}}}const a=r.length-1,i=r[a];if(i&&i.type==="assistant"){const d=r.slice();return d[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:{...o.messagesBySession,[t]:d}}}const l={id:`filejob-${n.jobId}`,type:"assistant",content:"",timestamp:Date.now(),fileJob:n};return{messagesBySession:{...o.messagesBySession,[t]:[...r,l].slice(-200)}}}),attachErrorCard:(t,n)=>s(o=>{const r=o.messagesBySession[t];if(!r||r.length===0)return o;const a=r.length-1,i=r[a];if(i&&i.type==="assistant"){const l=r.slice();return l[a]={...i,errorCard:n},{messagesBySession:{...o.messagesBySession,[t]:l}}}return o}),setTurnSummary:(t,n)=>s(o=>{const r=o.messagesBySession[t];if(!r||r.length===0)return o;const a=r.length-1,i=r[a];if(!i||i.type!=="assistant")return o;const l=r.slice();return l[a]={...i,summary:n},{messagesBySession:{...o.messagesBySession,[t]:l}}}),applyTombstone:(t,n)=>s(o=>{const r=o.messagesBySession[t];if(!r||r.length===0)return o;const a=new Set(n),i=r.map(l=>a.has(l.id)?{...l,deleted:!0}:l);return{messagesBySession:{...o.messagesBySession,[t]:i}}}),isGenerating:t=>e().generatingSessions.includes(t),isPaused:t=>e().pausedSessions.includes(t)}),{name:na,storage:aa,partialize:s=>({messagesBySession:s.messagesBySession,sessionInputs:s.sessionInputs})})),Ve=24;function _s(s){if(s.preview){const o=String(s.preview).replace(/\s+/g," ").trim();return o.length>Ve?o.slice(0,Ve)+"…":o}const e=G.getState().getMessages(s.id);if(!e||e.length===0)return"";const t=e.find(o=>o.type==="user"&&!o.deleted)||e.find(o=>!o.deleted)||e[0],n=String((t==null?void 0:t.content)||"").replace(/\s+/g," ").trim();return n?n.length>Ve?n.slice(0,Ve)+"…":n:""}function Qn(s,e){if(!e)return!1;const t=s.replace(/\s+/g," ").replace(/\.\.\.$/,"");return t?!e.startsWith(t):!0}const ia=3e4;function Xn(s){let e=0;function t(a,i){try{return localStorage.setItem(a,JSON.stringify(i)),e=0,!0}catch{return!1}}return{getItem:a=>{const i=localStorage.getItem(a);if(!i)return null;try{const l=JSON.parse(i);return l&&typeof l=="object"&&"state"in l?l:{state:l,version:0}}catch{return null}},setItem:(a,i)=>{var u;if(t(a,i))return;let l=i;for(const p of s.trims??[]){try{l=p(l)}catch{continue}if(t(a,l))return}const d=Date.now();if(d-e>ia){e=d;const p=new Error(`localStorage 配额已满或不可用(${s.key}),已降级为仅内存持久化,刷新页面将丢失部分历史。`);console.warn(`[${s.key}] 持久化失败:`,p);try{(u=s.onFailure)==null||u.call(s,p)}catch{}}},removeItem:a=>{try{localStorage.removeItem(a)}catch{}}}}const bn=6,ns=50,xn=60,la=100,tt=2e3,st=(s,e)=>s&&(s.length>e?`${s.slice(0,e)}…`:s),Zn=s=>{const{logs:e,...t}=s;return{...t,description:st(t.description,tt),result:st(t.result,tt),error:st(t.error,tt),stepPrompt:st(t.stepPrompt,tt),context:t.context?Object.fromEntries(Object.entries(t.context).map(([n,o])=>[n,st(o,tt)??""])):void 0,children:t.children?t.children.map(Zn):void 0}},os=s=>[...s].sort((e,t)=>(t.lastActiveAt??t.createdAt??0)-(e.lastActiveAt??e.createdAt??0)),K=be()(Xe((s,e)=>({sessions:[],activeSessionId:null,sessionTabs:[],layout:"single",sessionWorkspaceDirs:{},tasksBySession:{},historySessions:[],addSession:t=>s(n=>({sessions:[t,...n.sessions].slice(0,xn),activeSessionId:t.id})),removeSession:t=>s(n=>{var o;return{sessions:n.sessions.filter(r=>r.id!==t),activeSessionId:n.activeSessionId===t?((o=n.sessions[0])==null?void 0:o.id)||null:n.activeSessionId}}),updateSession:(t,n)=>s(o=>({sessions:o.sessions.map(r=>r.id===t?{...r,...n}:r)})),setActiveSession:t=>s({activeSessionId:t}),setSessionWorkspaceDir:(t,n)=>s(o=>({sessionWorkspaceDirs:{...o.sessionWorkspaceDirs,[t]:n}})),getSessionWorkspaceDir:t=>e().sessionWorkspaceDirs[t]||"",addSessionTab:(t,n)=>{const o=e();if(o.sessionTabs.length>=bn){const m=o.sessionTabs.reduce((h,f)=>h.createdAt<f.createdAt?h:f);e().closeSessionTab(m.id)}const r=`session-${Date.now()}`,a=n&&n.split(/[\\/]/).filter(Boolean).pop()||void 0,i={id:r,title:t||`对话 ${o.sessionTabs.length+1}`,createdAt:Date.now(),lastActiveAt:Date.now(),project:a,status:"done"},l={id:r,title:t||`对话 ${o.sessionTabs.length+1}`,createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),messageCount:0},d={...o.sessionWorkspaceDirs};n&&(d[r]=n);const u={...o.tasksBySession};u[r]||(u[r]=[]);const p=[i,...o.historySessions.filter(m=>m.id!==r)].slice(0,ns);return s({sessionTabs:os([i,...o.sessionTabs]),sessions:[...o.sessions,l].slice(-xn),sessionWorkspaceDirs:d,tasksBySession:u,activeSessionId:r,historySessions:p}),r},closeSessionTab:t=>{var l;const n=e(),o=n.sessionTabs.find(d=>d.id===t),r=n.sessionTabs.filter(d=>d.id!==t);if(r.length===0)return;let a=n.historySessions;o&&(a=[o,...a.filter(d=>d.id!==t)].slice(0,ns));const i=r[r.length-1];s({sessionTabs:r,historySessions:a,activeSessionId:n.activeSessionId===t?i?i.id:((l=r[0])==null?void 0:l.id)||null:n.activeSessionId})},renameSessionTab:(t,n)=>s(o=>({sessionTabs:o.sessionTabs.map(r=>r.id===t?{...r,title:n}:r),sessions:o.sessions.map(r=>r.id===t?{...r,title:n,updatedAt:new Date().toISOString()}:r),historySessions:o.historySessions.map(r=>r.id===t?{...r,title:n}:r)})),getActiveSessionTab:()=>{const t=e();return t.sessionTabs.find(n=>n.id===t.activeSessionId)||null},getVisibleSessionTabs:()=>{const t=e(),n=t.sessionTabs.find(o=>o.id===t.activeSessionId);return n?[n]:t.sessionTabs.slice(0,1)},addSessionTask:(t,n,o,r)=>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:o,description:r};return{tasksBySession:{...a.tasksBySession,[t]:[...i,l]}}}),toggleSessionTask:(t,n)=>s(o=>{const r=o.tasksBySession[t]||[];return{tasksBySession:{...o.tasksBySession,[t]:r.map(a=>a.id===n?{...a,completed:!a.completed}:a)}}}),removeSessionTask:(t,n)=>s(o=>({tasksBySession:{...o.tasksBySession,[t]:(o.tasksBySession[t]||[]).filter(r=>r.id!==n)}})),updateSessionTask:(t,n,o)=>s(r=>{const a=r.tasksBySession[t]||[];return{tasksBySession:{...r.tasksBySession,[t]:a.map(i=>i.id===n?{...i,title:o.trim()}:i)}}}),getSessionTasks:t=>e().tasksBySession[t]||[],setSessionTasks:(t,n)=>s(o=>({tasksBySession:{...o.tasksBySession,[t]:n}})),updateTaskPlanStatus:(t,n,o)=>s(r=>{const a=r.tasksBySession[t]||[];return{tasksBySession:{...r.tasksBySession,[t]:a.map(i=>i.id===n?{...i,...o}:i)}}}),autoNameSession:(t,n)=>{const r=e().sessionTabs.find(l=>l.id===t);if(!r||!/^对话 \d+$/.test(r.title))return;const a=n.replace(/\s+/g," ").trim(),i=a.slice(0,20)+(a.length>20?"...":"");i&&e().renameSessionTab(t,i)},updateSessionStatus:(t,n)=>s(o=>({sessionTabs:o.sessionTabs.map(r=>r.id===t?{...r,status:n}:r)})),touchSession:(t,n)=>s(o=>{const r=Date.now();let a;if(n){const l=n.replace(/\s+/g," ").trim();a=l.length>Ve?l.slice(0,Ve)+"…":l}const i=l=>({...l,lastActiveAt:r,...a&&!l.preview?{preview:a}:{}});return{sessionTabs:os(o.sessionTabs.map(l=>l.id===t?i(l):l)),sessions:o.sessions.map(l=>l.id===t?{...l,updatedAt:new Date(r).toISOString()}:l),historySessions:o.historySessions.map(l=>l.id===t?i(l):l)}}),getHistorySessions:()=>e().historySessions,restoreHistorySession:t=>{const n=e(),o=n.historySessions.find(i=>i.id===t);if(!o)return;const r=n.historySessions.filter(i=>i.id!==t);if(n.sessionTabs.some(i=>i.id===t)){s({historySessions:r,activeSessionId:t});return}let a=n.sessionTabs;if(a.length>=bn){const i=a.reduce((l,d)=>l.createdAt<d.createdAt?l:d);a=a.filter(l=>l.id!==i.id),r.unshift(i)}s({sessionTabs:os([o,...a]),historySessions:r.slice(0,ns),activeSessionId:t})},clearHistorySessions:()=>s({historySessions:[]}),removeHistorySession:t=>s(n=>({historySessions:n.historySessions.filter(o=>o.id!==t)}))}),{name:"deepseekcode-session-storage",storage:Xn({key:"sessionStore",trims:[s=>({...s,state:{...s.state,tasksBySession:Object.fromEntries(Object.entries(s.state.tasksBySession).map(([e,t])=>[e,t.map(n=>({id:n.id,title:n.title,completed:n.completed,createdAt:n.createdAt,planStatus:n.planStatus,backendId:n.backendId,backendStatus:n.backendStatus,agentType:n.agentType,progress:n.progress}))]))}}),s=>{const e=new Set([...s.state.sessionTabs.map(t=>t.id),...s.state.historySessions.map(t=>t.id)]);return s.state.activeSessionId&&e.add(s.state.activeSessionId),{...s,state:{...s.state,tasksBySession:Object.fromEntries(Object.entries(s.state.tasksBySession).filter(([t])=>e.has(t)))}}},s=>({...s,state:{...s.state,tasksBySession:{}}})],onFailure:()=>{try{De.getState().addToast("warning","会话数据保存失败:浏览器本地存储已满或不可用。当前数据仅保留在内存中,刷新页面将丢失,建议清理旧会话或导出数据。",8e3)}catch{}}}),partialize:s=>{const e=new Set;for(const o of s.sessionTabs)e.add(o.id);for(const o of s.historySessions)e.add(o.id);s.activeSessionId&&e.add(s.activeSessionId);const t=s.sessions.filter(o=>e.has(o.id)),n={};for(const[o,r]of Object.entries(s.tasksBySession))e.has(o)&&(n[o]=r.slice(0,la).map(Zn));return{sessions:t,sessionTabs:s.sessionTabs,activeSessionId:s.activeSessionId,layout:s.layout,sessionWorkspaceDirs:s.sessionWorkspaceDirs,tasksBySession:n,historySessions:s.historySessions}}})),ca=be(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})})),kn={bg:"#0d1117",surface:"#161b22",border:"#30363d",text:"#c9d1d9",muted:"#8b949e",accentBlue:"#58a6ff",accentGreen:"#238636",accentRed:"#f85149",accentYellow:"#d29922",accentPurple:"#a855f7"},Ke=be()(Xe(s=>({theme:"light",themePresetId:"linear",language:"zh-CN",fontSize:14,streamingEnabled:!0,yolo:{enabled:!1},autoSwarm:{enabled:!1},workspaceDir:"",workspaceGuardBypass:!0,customTheme:kn,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:kn}),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}})),da=[{eventType:"connected",description:"WebSocket 已连接",category:"session",emittedBy:["server"],handledByCli:!0,handledByWeb:!0},{eventType:"session_created",description:"新会话已创建",category:"session",emittedBy:["server","core"],handledByCli:!0,handledByWeb:!0,note:"CLI/Web 均已处理(Web: systemHandlers session_created)"},{eventType:"session_resumed",description:"会话从存储中恢复",category:"session",emittedBy:["core","server"],handledByCli:!0,handledByWeb:!0,note:"CLI/Web 均已处理(Web: systemHandlers session_resumed)"},{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:!0,note:"CLI 已处理(2026-07-18); Web 已处理(切换 activeSessionId)"},{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:"tool_diff",description:"工具执行中的参数 diff 增量(P0-2 diffConsumer 生产者推送)",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:"web_search",description:"模型内置联网搜索状态(DeepSeek Responses web_search_call:searching/completed/failed)",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"由服务端执行搜索,客户端仅展示状态(🔍搜索中 → ✅完成)"},{eventType:"progress",description:"通用进度(当前未使用)",category:"stream",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,deprecated:!0,note:"已定义但从未发送;SendMessageTool 的 progress 是消息类型而非 WS 事件"},{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:!0,note:"由 StreamHeartbeat 或 StallDetector 触发;CLI/Web 显示重试进度"},{eventType:"task_interrupted",description:"任务中断(服务重启/异常退出)",category:"stream",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"服务启动扫描时将 running activeRun 标记为 interrupted 后触发;提示用户使用 /continue 恢复生成,或用 /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:!0,note:"CLI 已添加 handler(2026-07-01);Web planHandlers 已处理(2026-08-07)"},{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:!0,note:"CLI 已处理(2026-07-18); Web planHandlers 已处理(2026-08-07)"},{eventType:"plan_refine",description:"计划优化",category:"plan",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,deprecated:!0,note:"纯虚占位:核心未发射、无 handler,建议移除"},{eventType:"plan_waiting",description:"计划等待用户输入",category:"plan",emittedBy:["none"],handledByCli:!0,handledByWeb:!1,note:"核心未发射(仅 CLI 兼容订阅),已从 emittedBy 移除 core"},{eventType:"plan_continue",description:"计划继续执行",category:"plan",emittedBy:["none"],handledByCli:!0,handledByWeb:!1,note:"核心未发射(仅 CLI 兼容订阅),已从 emittedBy 移除 core"},{eventType:"plan_settled",description:"计划已定稿",category:"plan",emittedBy:["none"],handledByCli:!0,handledByWeb:!1,note:"核心未发射(仅 CLI 兼容订阅),已从 emittedBy 移除 core"},{eventType:"plan_cleared",description:"计划已清除",category:"plan",emittedBy:["none"],handledByCli:!0,handledByWeb:!1,note:"核心未发射(仅 CLI 兼容订阅),已从 emittedBy 移除 core"},{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,deprecated:!0,note:"功能存在但被 context_blocked 覆盖,事件未使用"},{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:"compaction_started",description:"压缩任务已启动(phase/trigger)",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"compaction_finished",description:"压缩任务结束(done/failed/aborted)",category:"context",emittedBy:["core"],handledByCli:!0,handledByWeb:!0},{eventType:"microcompact_progress",description:"微压缩进度",category:"context",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,deprecated:!0,note:"已被 compaction_progress(layer 字段区分)覆盖"},{eventType:"session_memory_update",description:"会话记忆更新",category:"context",emittedBy:["none"],handledByCli:!1,handledByWeb:!1,deprecated:!0,note:"已被 compaction_progress(layer=session_memory)覆盖"},{eventType:"tool_retry",description:"工具重试",category:"context",emittedBy:["none"],handledByCli:!1,handledByWeb:!0,deprecated:!0,note:"重试信息已含于 tool_result/error,Web handler 保留但路由不可达"},{eventType:"model_fallback",description:"模型回退",category:"context",emittedBy:["none"],handledByCli:!1,handledByWeb:!0,deprecated:!0,note:"降级信息已含于 degradation_update,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,deprecated:!0,note:"已被 workflow_resumed 覆盖,核心从未发送"},{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:!0,note:"CLI 已添加 handler(2026-07-01); Web systemHandlers 已处理(2026-08-07)"},{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:!0,note:"CLI 已处理(setDynamicCommands); Web systemHandlers 已处理(2026-08-07)"},{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:!0,note:"CLI 已处理(2026-07-18); Web 已处理(2026-08-07 通知)"},{eventType:"channel_status",description:"频道连接状态变更",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已处理(2026-07-18); Web 已处理(channelsStore)"},{eventType:"channel_error",description:"频道运行时错误",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"CLI 已处理(2026-07-18); Web 已处理(2026-08-07 通知)"},{eventType:"filejob_start",description:"文件处理任务开始(解析/渲染)",category:"task",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"对话内嵌文件处理面板;Web 已处理,CLI 已处理(2026-08-07 状态行)"},{eventType:"filejob_progress",description:"文件处理进度更新",category:"task",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"解析/渲染进度百分比"},{eventType:"filejob_result",description:"文件处理完成(结果文件列表)",category:"task",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"携带 RenderedFileResult[]"},{eventType:"filejob_error",description:"文件处理失败",category:"task",emittedBy:["core"],handledByCli:!0,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,deprecated:!0,note:"Web/CLI 本地消息删除渲染概念,无 WS 发射端"},{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:!0,note:"Web 已处理(2026-08-07 toast 提示)"},{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:!0,note:"Web useWebSocket 已处理(dismiss 提问弹窗)"},{eventType:"hook_auto_ack",description:"Hook 自动模式确认",category:"hook",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"Web 已处理(2026-08-07 toast 提示)"},{eventType:"tool.approval_required",description:"工具调用需要审批(停放入口)",category:"inbox",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"无人值守/定时运行时写操作先停放;CLI 状态提示,Web Inbox 视图消费(2026-08-07 标记修正)"},{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:!0,note:"Web 已处理(2026-08-07 toast 提示)"},{eventType:"pdca_phase",description:"PDCA 循环阶段",category:"system",emittedBy:["none"],handledByCli:!0,handledByWeb:!1,deprecated:!0,note:"已退役:5-phase light pipeline 被 WorkflowRuntime 取代"},{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:!0,note:"core TaskUpdateTool 在 completed/failed 时 emit,data 携带 id/title/status/result/error;CLI 与 Web 均更新看板并输出通知(toast / 状态区)"},{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,deprecated:!0,note:"Web systemHandler 有 case 但核心无发送方,保留兼容"},{eventType:"command_complete",description:"命令完成(Web 路由用)",category:"system",emittedBy:["none"],handledByCli:!1,handledByWeb:!0,deprecated:!0,note:"Web systemHandler 有 case 但核心无发送方,保留兼容"},{eventType:"command_error",description:"命令错误(Web 路由用)",category:"system",emittedBy:["core"],handledByCli:!0,handledByWeb:!0,note:"core index.ts:1270 真实 emit;CLI useStreamHandlers:741 与 Web systemHandlers 均已处理"}];function ve(s){return s==="auto-plan"?"plan":s==="auto-act"?"act":s==="auto-goal"?"goal":s}function qe(s){return s==="auto-plan"||s==="auto-act"||s==="auto-goal"}function ua(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 Ac=["plan","act","goal"];function Ts(s,e){return e?s==="plan"?"auto-plan":s==="act"?"auto-act":"auto-goal":s}function pa(s){const e=["plan","act","goal"],t=e.indexOf(ve(s)),n=e[(t+1)%e.length]??"act";return Ts(n,qe(s))}const ma={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"}},Ec={low:{label:"Low",accent:"green"},medium:{label:"Medium",accent:"cyan"},high:{label:"High",accent:"yellow"},critical:{label:"Critical",accent:"red"}},Bc={allow:{label:"Allow"},deny:{label:"Deny"},allow_session:{label:"Allow session"},auto:{label:"Auto mode"}};function ha(s){return s==="plan"||s==="auto-plan"||s==="act"||s==="auto-act"||s==="goal"||s==="auto-goal"?s:"act"}function nt(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${Math.round(s/1e3)}K`:String(s)}function fa(s){return s<=0?"":s>=100?`${Math.round(s)}t/s`:`${s.toFixed(1)}t/s`}function eo(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 ga(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 Pc(s){const e=Object.entries(s.toolCounts).filter(([,o])=>o>0).sort((o,r)=>r[1]-o[1]),t=s.headline||`Thought for ${eo(Math.max(1,Math.round(s.durationMs/1e3)))}`,n=e.map(([o,r])=>ga(o,r));return n.length>0?`${t}, ${n.join(", ")}`:t}function ya(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 ba(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}const Rc=["openai-chat-completions","openai-completions","openai-responses","anthropic-messages"];da.map(s=>s.eventType);function xa(){return`err-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}const Je=be(s=>({errors:[],push:(e,t,n,o)=>{const r=xa(),a={id:r,level:e,title:t,detail:n,action:o,timestamp:Date.now(),dismissed:!1};return s(i=>({errors:[...i.errors.slice(-49),a]})),r},dismiss:e=>s(t=>({errors:t.errors.map(n=>n.id===e?{...n,dismissed:!0}:n)})),clearAll:()=>s({errors:[]})})),X={info:(s,e)=>Je.getState().push("info",s,e),warn:(s,e)=>Je.getState().push("warning",s,e),error:(s,e)=>Je.getState().push("error",s,e),critical:(s,e)=>Je.getState().push("critical",s,e)},ot=20,ka=()=>{const s=window.location.protocol==="https:"?"wss:":"ws:",e=window.location.hostname,t=window.location.port,n=t?String(Number(t)+1):"",o=n?`${e}:${n}`:e;return`${s}//${o}/ws`},Sa=ka(),Sn="dscode_client_id";function va(){try{const s=localStorage.getItem(Sn);if(s)return s;const e=`web-${typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2,10)}`;return localStorage.setItem(Sn,e),e}catch{return`web-${Math.random().toString(36).slice(2,10)}`}}class wa{constructor(e){se(this,"ws",null);se(this,"url");se(this,"clientId",va());se(this,"messageHandlers",new Set);se(this,"openHandlers",new Set);se(this,"closeHandlers",new Set);se(this,"errorHandlers",new Set);se(this,"reconnectAttempts",0);se(this,"reconnectHandlers",new Set);se(this,"reconnectSuccessHandlers",new Set);se(this,"reconnectGiveUpHandlers",new Set);se(this,"isManualClose",!1);se(this,"authenticated",!1);se(this,"sessionId",null);se(this,"heartbeatInterval",null);se(this,"reconnectTimer",null);se(this,"lastPongTime",0);se(this,"HEARTBEAT_INTERVAL",15e3);se(this,"HEARTBEAT_TIMEOUT",45e3);this.url=e||Sa}setSessionId(e){this.sessionId=e}getSessionId(){return this.sessionId}getReconnectState(){var e;return{attempts:this.reconnectAttempts,maxAttempts:ot,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 n,o;if(((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN||((o=this.ws)==null?void 0:o.readyState)===WebSocket.CONNECTING)return;this.isManualClose=!1;const e=new URLSearchParams;this.sessionId&&e.set("sessionId",this.sessionId),e.set("clientId",this.clientId);const t=e.toString()?`${this.url}?${e.toString()}`:this.url;this.ws=new WebSocket(t),this.ws.binaryType="arraybuffer",this.ws.onopen=()=>{var a;console.log("WebSocket connected");const r=this.reconnectAttempts>0;this.reconnectAttempts=0,this.lastPongTime=Date.now(),r&&this.reconnectSuccessHandlers.forEach(i=>i()),((a=this.ws)==null?void 0:a.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"})),this.startHeartbeat(),this.openHandlers.forEach(i=>i())},this.ws.onclose=()=>{console.log("WebSocket closed"),this.stopHeartbeat(),this.closeHandlers.forEach(r=>r()),this.isManualClose||this.scheduleReconnect()},this.ws.onerror=r=>{X.error("WebSocket connection error",r.message||"Connection failed"),this.errorHandlers.forEach(a=>a())},this.ws.onmessage=r=>{this._onMessage(r)}}async _onMessage(e){var t,n;try{let o;if(e.data instanceof Blob?o=await e.data.text():e.data instanceof ArrayBuffer?o=new TextDecoder().decode(e.data):typeof e.data=="string"?o=e.data:o=String(e.data),o=o.trim(),!o)return;const r=JSON.parse(o);if(console.log("[WS←]",r.type,r.sessionId,JSON.stringify(r.data||r.message||"").slice(0,200)),(r.type==="pong"||r.type==="ping")&&(this.lastPongTime=Date.now(),r.type==="pong"))return;r.seq!==void 0&&r.seq>=0&&this.send({type:"message_ack",data:JSON.stringify({seq:r.seq})}),this.messageHandlers.forEach(a=>a(r))}catch(o){const r=((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{}}X.error("Failed to parse WebSocket message",`type=${r} data=${a} error=${o}`)}}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>ot){console.error(`[WS] Max reconnect attempts (${ot}) reached — giving up.`),X.error("WebSocket",`Connection lost — max reconnect attempts (${ot}) reached. Refresh the page to try again.`),this.reconnectGiveUpHandlers.forEach(o=>o());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(o=>o(this.reconnectAttempts,ot)),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 o=JSON.stringify(e);console.log("[WS→]",e.type,e.sessionId,o.slice(0,200)),this.ws.send(o)}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 F=new wa;function vn(s,e){return`ext:${s}:${e.toLowerCase()}`}const Me=be()(Xe((s,e)=>({pendingApprovals:[],autoMode:!1,sessionAllowList:[],showConfigHint:!0,addApproval:t=>s(n=>({pendingApprovals:[...n.pendingApprovals,t]})),removeApproval:t=>s(n=>({pendingApprovals:n.pendingApprovals.filter(o=>o.approvalId!==t)})),clearApprovals:()=>s({pendingApprovals:[]}),setAutoMode:t=>s({autoMode:t}),addToSessionAllowList:(t,n)=>s(o=>{const r=n?vn(t,n):t;return o.sessionAllowList.includes(r)?o:{sessionAllowList:[...o.sessionAllowList,r]}}),isSessionAllowed:(t,n)=>{const o=e().sessionAllowList;return n?o.includes(vn(t,n)):o.includes(t)},setShowConfigHint:t=>s({showConfigHint:t})}),{name:"deepseekcode-hook-approval",partialize:s=>({autoMode:s.autoMode,showConfigHint:s.showConfigHint})}));function Ca(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 Y=be((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 o=t.totalTokens??n.currentUsage.totalTokens,r=Date.now(),a=n._lastTotal,i=n._lastTotalTs;let l=n.tokenRate;if(i>0&&a>0&&r>i&&o>a){const d=o-a,u=(r-i)/1e3,p=d/u;l=l>0?l*.6+p*.4:p}return{currentUsage:{...n.currentUsage,...t},_hasBackendData:!0,tokenRate:l,_lastTotal:o,_lastTotalTs:r}}),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=>Ca(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 o=0,r=0;for(const l of t){let d=l.content||"";if(l.thinking&&(d+=" "+l.thinking),l.steps)for(const p of l.steps)p.thought&&(d+=" "+p.thought),p.action&&(d+=" "+p.action),p.result&&(d+=" "+p.result);if(l.toolCalls)for(const p of l.toolCalls)p.args&&(d+=" "+(typeof p.args=="string"?p.args:JSON.stringify(p.args)));const u=n(d);l.type==="user"?o+=u:r+=u}const a=o+r,i=o/1e6*.15+r/1e6*.6;s({currentUsage:{promptTokens:o,completionTokens:r,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}))})),to="";function _a(s){return`${to}${s}`}class Ta{constructor(e){se(this,"baseUrl");this.baseUrl=e}async request(e,t={}){try{const n=sessionStorage.getItem("auth_token")??localStorage.getItem("auth_token"),o={"Content-Type":"application/json",...t.headers};n&&(o.Authorization=`Bearer ${n}`);const r=await fetch(`${this.baseUrl}${e}`,{headers:o,...t}),a=await r.json();return r.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 ${r.status}`,data:a.data}}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 x=new Ta(to),V={providers:{presets:()=>x.get("/api/providers/presets"),refresh:()=>x.post("/api/providers/refresh")},models:{list:async()=>{var e;const s=await x.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=>x.get(`/api/models/${s}`),create:s=>x.post("/api/models",s),update:(s,e,t)=>x.post("/api/models/update",{provider:s,modelId:e,...t}),delete:(s,e)=>x.post("/api/models/delete",{provider:s,modelId:e}),test:s=>x.post(`/api/models/${s}/test`),fetch:(s,e)=>x.post("/api/models/fetch",{baseUrl:s,apiKey:e}),toggle:(s,e)=>x.post("/api/models/toggle",{provider:s,modelId:e}),setDefaults:s=>x.post("/api/models/defaults",s)},tools:{list:()=>x.get("/api/tools"),get:s=>x.get(`/api/tools/${s}`),update:(s,e)=>x.put(`/api/tools/${s}`,e),toggle:(s,e)=>x.post(`/api/tools/${s}/toggle`,{enabled:e})},connectors:{list:()=>x.get("/api/connectors"),get:s=>x.get(`/api/connectors/${encodeURIComponent(s)}`),toggle:(s,e,t)=>x.post(`/api/connectors/${encodeURIComponent(s)}/toggle`,{enabled:e,env:t}),addCustom:s=>x.post("/api/connectors/custom",s),removeCustom:s=>x.delete(`/api/connectors/custom/${encodeURIComponent(s)}`)},skills:{list:()=>x.get("/api/skills"),get:s=>x.get(`/api/skills/${s}`),create:s=>x.post("/api/skills",s),update:(s,e)=>x.put(`/api/skills/${s}`,e),toggle:(s,e)=>x.post(`/api/skills/${s}/toggle`,{enabled:e}),delete:s=>x.delete(`/api/skills/${s}`),import:s=>x.post("/api/skills/import",s),marketplaces:{list:()=>x.get("/api/skills/marketplaces"),add:s=>x.post("/api/skills/marketplaces",s),remove:s=>x.delete(`/api/skills/marketplaces/${s}`),get:s=>x.get(`/api/skills/marketplaces/${s}`),refresh:s=>x.post(`/api/skills/marketplaces/${s}/refresh`,{}),install:(s,e)=>x.post(`/api/skills/marketplaces/${s}/install`,{skillId:e})}},agents:{list:()=>x.get("/api/agents"),get:s=>x.get(`/api/agents/${s}`),create:s=>x.post("/api/agents",s),update:(s,e)=>x.put(`/api/agents/${s}`,e),delete:s=>x.delete(`/api/agents/${s}`),setActive:s=>x.post(`/api/agents/${s}/activate`),toggle:(s,e)=>x.post(`/api/agents/${s}/toggle`,{enabled:e}),setModelBinding:(s,e)=>x.post(`/api/agents/${s}/model`,e)},files:{list:s=>x.get(`/api/files${s?`?path=${encodeURIComponent(s)}`:""}`),read:s=>x.get(`/api/files/read?path=${encodeURIComponent(s)}`),create:(s,e)=>x.post("/api/files",{path:s,content:e}),update:(s,e)=>x.put("/api/files/write",{path:s,content:e}),delete:s=>x.delete(`/api/files?path=${encodeURIComponent(s)}`),download:async s=>{try{const e={},t=sessionStorage.getItem("auth_token")??localStorage.getItem("auth_token");t&&(e.Authorization=`Bearer ${t}`);const n=await fetch(_a(`/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 o=await n.blob(),r=URL.createObjectURL(o),a=document.createElement("a");return a.href=r,a.download=s.split(/[\\/]/).pop()||"download",a.click(),URL.revokeObjectURL(r),{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:"Download failed"}}},upload:async(s,e)=>{try{const t=await Na(s);return x.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:()=>x.get("/api/sessions"),get:s=>x.get(`/api/sessions/${s}`),create:s=>x.post("/api/sessions",{title:s}),delete:s=>x.delete(`/api/sessions/${s}`)},tasks:{list:s=>x.get(s?`/api/tasks?sessionId=${encodeURIComponent(s)}`:"/api/tasks"),get:s=>x.get(`/api/tasks/${s}`),create:s=>x.post("/api/tasks",s),update:(s,e)=>x.put(`/api/tasks/${s}`,e),updateStatus:(s,e)=>x.patch(`/api/tasks/${s}/status`,{status:e}),delete:s=>x.delete(`/api/tasks/${s}`),clearCompleted:()=>x.delete("/api/tasks")},config:{provider:{get:()=>x.get("/api/config/provider"),save:s=>x.post("/api/config/provider",s),delete:s=>x.post("/api/config/provider/remove",{provider:s}),setDefault:s=>x.post("/api/config/provider",{provider:s,setDefault:!0})},files:{list:()=>x.get("/api/config/files"),read:s=>x.get(`/api/config/files/read?file=${encodeURIComponent(s)}`),write:(s,e)=>x.put("/api/config/files/write",{file:s,content:e})}},git:{status:()=>x.get("/api/git/status"),branches:()=>x.get("/api/git/branches"),commit:s=>x.post("/api/git/commit",s),push:()=>x.post("/api/git/push"),checkout:s=>x.post("/api/git/checkout",{branch:s}),prStatus:()=>x.get("/api/repos/pr")},fileJob:{parse:s=>x.post("/api/filejob/parse",{files:s}),parsePaths:s=>x.post("/api/filejob/parse",{paths:s}),importPaths:s=>x.post("/api/filejob/import",{paths:s}),render:s=>x.post("/api/filejob/render",s)},system:{status:()=>x.get("/api/system/status"),restart:()=>x.post("/api/system/restart"),shutdown:()=>x.post("/api/system/shutdown")},observability:{summary:()=>x.get("/api/observability/summary"),costs:()=>x.get("/api/observability/costs"),listRuns:()=>x.get("/api/observability/runs"),getRun:s=>x.get(`/api/observability/runs/${encodeURIComponent(s)}`),getRunEvents:(s,e=0,t=50)=>x.get(`/api/observability/runs/${encodeURIComponent(s)}/events?page=${e}&size=${t}`)},templates:{list:()=>x.get("/api/templates"),get:s=>x.get(`/api/templates/${encodeURIComponent(s)}`),create:s=>x.post("/api/templates",s),update:(s,e)=>x.put(`/api/templates/${encodeURIComponent(s)}`,e),remove:s=>x.delete(`/api/templates/${encodeURIComponent(s)}`),versions:s=>x.get(`/api/templates/${encodeURIComponent(s)}/versions`),getVersion:(s,e)=>x.get(`/api/templates/${encodeURIComponent(s)}/versions/${e}`),render:(s,e)=>x.post(`/api/templates/${encodeURIComponent(s)}/render`,{inputs:e}),createFromRun:(s,e)=>x.post("/api/templates",{sourceRunId:s,generalize:(e==null?void 0:e.generalize)===!0,name:e==null?void 0:e.name,message:e==null?void 0:e.message})},workflows:{list:()=>x.get("/api/workflows"),start:s=>x.post("/api/workflows",s),get:s=>x.get(`/api/workflows/${encodeURIComponent(s)}`)},plans:{list:()=>x.get("/api/plans"),read:s=>x.get(`/api/plans/${encodeURIComponent(s)}`),delete:s=>x.delete(`/api/plans/${encodeURIComponent(s)}`)},logs:{list:()=>x.get("/api/logs"),read:(s,e)=>x.get(`/api/logs/read?file=${encodeURIComponent(s)}${e?`&maxLines=${e}`:""}`),downloadUrl:s=>`/api/logs/download?file=${encodeURIComponent(s)}`},stt:{status:()=>x.get("/api/stt/status"),transcribe:(s,e,t="wav")=>x.post("/api/stt/transcribe",{language:s,audio:e,format:t}),install:s=>x.post("/api/stt/install",{backend:s}),installStatus:()=>x.get("/api/stt/install/status"),cancelInstall:()=>x.post("/api/stt/install/cancel")},hooks:{list:()=>x.get("/api/hooks/rules"),get:s=>x.get(`/api/hooks/rules/${encodeURIComponent(s)}`),create:s=>x.post("/api/hooks/rules",s),update:(s,e)=>x.put(`/api/hooks/rules/${encodeURIComponent(s)}`,e),delete:s=>x.delete(`/api/hooks/rules/${encodeURIComponent(s)}`),batchDelete:s=>x.post("/api/hooks/rules/batch-delete",{names:s}),toggle:(s,e)=>x.patch(`/api/hooks/rules/${encodeURIComponent(s)}/toggle`,{enabled:e}),batchToggle:(s,e)=>x.post("/api/hooks/rules/batch-toggle",{names:s,enabled:e}),dryRun:s=>x.post("/api/hooks/dry-run",s),stats:()=>x.get("/api/hooks/stats"),events:()=>x.get("/api/hooks/events"),agents:()=>x.get("/api/hooks/agents"),export:()=>x.get("/api/hooks/export"),import:s=>x.post("/api/hooks/import",s)},channels:{list:()=>x.get("/api/channels"),create:s=>x.post("/api/channels",s),update:(s,e)=>x.put(`/api/channels/${encodeURIComponent(s)}`,e),delete:s=>x.delete(`/api/channels/${encodeURIComponent(s)}`),toggle:(s,e)=>x.patch(`/api/channels/${encodeURIComponent(s)}/toggle`,{enabled:e}),test:s=>x.post(`/api/channels/${encodeURIComponent(s)}/test`),wechat:{qrcode:(s,e)=>x.get(`/api/channels/${encodeURIComponent(s)}/wechat/qrcode?token=${encodeURIComponent(e)}`),qrcodeStatus:(s,e,t)=>x.get(`/api/channels/${encodeURIComponent(s)}/wechat/qrcode/status?token=${encodeURIComponent(e)}&qrcode=${encodeURIComponent(t)}`)},weixin:{bind:()=>x.get("/api/weixin/bind"),bindStatus:s=>x.get(`/api/weixin/bind/status?qrcode=${encodeURIComponent(s)}`)}},inbox:{list:s=>x.get(`/api/inbox?${new URLSearchParams(s).toString()}`),stats:()=>x.get("/api/inbox/stats"),resolve:(s,e)=>x.post(`/api/inbox/${encodeURIComponent(s)}/resolve`,{resolution:e})},audit:{query:s=>x.get(`/api/audit?${new URLSearchParams(Object.fromEntries(Object.entries(s||{}).map(([e,t])=>[e,String(t)]))).toString()}`),stats:()=>x.get("/api/audit/stats")},automations:{list:()=>x.get("/api/automations"),create:s=>x.post("/api/automations",s),update:(s,e)=>x.put(`/api/automations/${encodeURIComponent(s)}`,e),remove:s=>x.delete(`/api/automations/${encodeURIComponent(s)}`),toggle:(s,e)=>x.post(`/api/automations/${encodeURIComponent(s)}/toggle`,{enabled:e}),run:s=>x.post(`/api/automations/${encodeURIComponent(s)}/run`),runs:s=>x.get(`/api/automations/${encodeURIComponent(s)}/runs`),addPermission:(s,e,t)=>x.post(`/api/automations/${encodeURIComponent(s)}/permissions`,{tool:e,target:t}),revokePermission:(s,e)=>x.delete(`/api/automations/${encodeURIComponent(s)}/permissions`,{entry:e})}};function Na(s){return new Promise((e,t)=>{const n=new FileReader;n.onload=()=>{const o=n.result,r=o.indexOf(",");e(r>=0?o.slice(r+1):o)},n.onerror=()=>t(n.error||new Error("Failed to read file")),n.readAsDataURL(s)})}const ja=Object.freeze(Object.defineProperty({__proto__:null,api:V,apiClient:x,default:V},Symbol.toStringTag,{value:"Module"})),rs=s=>s==="normal"?"act":s;let At=0;const Aa=s=>s==="normal"?"normal":s==="auto"?"auto-act":ha(typeof s=="string"?s:void 0),rt=s=>s==="normal"?"act":qe(s)?"auto":ve(s),ft=be()(Xe((s,e)=>({mode:"act",currentPlanContent:null,modeHistory:[],thinkingStatusBySession:{},prePlanMode:null,setMode:t=>{const n=e().mode;if(n===t)return;s(d=>({mode:t,modeHistory:[...d.modeHistory,{previousMode:n,newMode:t,description:`Mode changed: ${n} -> ${t}`,timestamp:Date.now()}]})),Me.getState().setAutoMode(t!=="normal"&&qe(t));const o=rt(n),r=rt(t),a=n==="normal"?"act":ve(n),i=t==="normal"?"act":ve(t);if(a===i&&o===r)return;try{const d=K.getState().activeSessionId||F.getSessionId();d&&F.send({type:"plan_mode_change",sessionId:d,data:JSON.stringify({previousMode:rt(n),newMode:rt(t),frontendMode:t,timestamp:Date.now()})})}catch(d){console.warn("[ExecutionModeStore] Failed to notify mode change via WS:",d)}const l=++At;V.models.list().then(d=>{var y,b;if(l!==At||!d.success||!((y=d.data)!=null&&y.models))return;const u=d.data.models.filter(C=>C.enabled!==!1),p=ve(rs(t)),m=u.find(C=>C.defaultFor===p),h=u.find(C=>C.isDefault||C.defaultFor==="global"),f=(m==null?void 0:m.id)||(h==null?void 0:h.id)||((b=u[0])==null?void 0:b.id)||"";f&&Y.getState().setModel(f)}).catch(d=>{console.warn("[ExecutionModeStore] Failed to refresh models:",d)})},applyBackendMode:t=>{const n=e().mode;if(n===t)return;s(r=>({mode:t,prePlanMode:t!=="plan"?null:r.prePlanMode,modeHistory:[...r.modeHistory,{previousMode:n,newMode:t,description:`Backend mode changed: ${n} -> ${t}`,timestamp:Date.now()}]})),Me.getState().setAutoMode(t!=="normal"&&qe(t));const o=++At;V.models.list().then(r=>{var p,m;if(o!==At||!r.success||!((p=r.data)!=null&&p.models))return;const a=r.data.models.filter(h=>h.enabled!==!1),i=ve(rs(t)),l=a.find(h=>h.defaultFor===i),d=a.find(h=>h.isDefault||h.defaultFor==="global"),u=(l==null?void 0:l.id)||(d==null?void 0:d.id)||((m=a[0])==null?void 0:m.id)||"";u&&Y.getState().setModel(u)}).catch(r=>{console.warn("[ExecutionModeStore] Failed to refresh models after backend mode change:",r)})},toggleMode:()=>{const t=e().mode,n=t==="normal"?"act":pa(t);e().setMode(n)},setBaseMode:t=>{const n=e().mode,o=n!=="normal"&&qe(n);e().setMode(Ts(t,o))},setAuto:t=>{e().setMode(Ts(ve(rs(e().mode)),t))},toggleAuto:()=>{const t=e().mode;e().setMode(t==="normal"?"auto-act":ua(t))},enterPlanMode:(t,n)=>{const o=e().mode,r=o!=="normal"&&ve(o)!=="plan"?o:e().prePlanMode,a=o!=="normal"&&ve(o)==="goal"?"goal":"plan";s(i=>({mode:a,prePlanMode:r,modeHistory:[...i.modeHistory,{previousMode:o,newMode:a,description:`Enter ${a} mode: ${n}`,timestamp:Date.now()}]})),Me.getState().setAutoMode(!1)},exitPlanMode:(t,n)=>{const o=e().mode,r=e().prePlanMode,a=r&&(r==="normal"||ve(r)!=="plan")?r:"act";s(i=>({mode:a,prePlanMode:null,modeHistory:[...i.modeHistory,{previousMode:o,newMode:a,description:`Exit to ${a} mode: ${n}`,timestamp:Date.now()}]})),Me.getState().setAutoMode(a!=="normal"&&qe(a))},enterGoalMode:(t,n)=>{const o=e().mode;s(r=>({mode:"goal",modeHistory:[...r.modeHistory,{previousMode:o,newMode:"goal",description:`Enter Goal mode: ${n}`,timestamp:Date.now()}]})),Me.getState().setAutoMode(!1);try{const r=K.getState().activeSessionId||F.getSessionId()||void 0;F.send({type:"plan_mode_change",sessionId:r,data:JSON.stringify({previousMode:rt(o),newMode:"goal",frontendMode:"goal",goalDescription:n,timestamp:Date.now()})})}catch(r){console.warn("[ExecutionModeStore] Failed to notify goal mode change via WS:",r)}},exitGoalMode:()=>{const t=e().mode;s(n=>({mode:"act",modeHistory:[...n.modeHistory,{previousMode:t,newMode:"act",description:"Exit Goal mode",timestamp:Date.now()}]})),Me.getState().setAutoMode(!1)},setPlanContent:t=>s({currentPlanContent:t}),setThinkingStatus:(t,n)=>s(o=>({thinkingStatusBySession:{...o.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:Aa(t.mode)}},partialize:s=>({mode:s.mode,currentPlanContent:s.currentPlanContent,modeHistory:s.modeHistory})})),Ea={info:"bg-accent-blue",warn:"bg-accent-yellow",error:"bg-accent-red",success:"bg-accent-green",tool:"bg-accent-purple"};function Ba(s){return s==null||s===""?"-":new Date(s).toLocaleString()}function Pa(){const[s,e]=g.useState([]),[t,n]=g.useState(!0),[o,r]=g.useState(null),[a,i]=g.useState(null),[l,d]=g.useState(!1),u=g.useCallback(async()=>{n(!0);try{const f=await V.logs.list();f.success&&Array.isArray(f.data)&&e(f.data)}catch(f){console.error("Failed to load log files:",f)}n(!1)},[]);g.useEffect(()=>{u()},[u]);const p=g.useCallback(async f=>{if(!f.previewable)return;r(f),d(!0);const y=await V.logs.read(f.name,500);y.success&&y.data&&i(y.data),d(!1)},[]),m=g.useCallback(()=>{r(null),i(null)},[]),h=f=>f<1024?`${f} B`:f<1024*1024?`${(f/1024).toFixed(1)} KB`:`${(f/(1024*1024)).toFixed(1)} MB`;return o&&a?c.jsxs("div",{className:"flex flex-col min-h-0 h-full",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2 shrink-0",children:[c.jsx("button",{onClick:m,className:"p-1 rounded hover:bg-dark-hover transition-colors",title:"返回文件列表",children:c.jsx(Wn,{size:16})}),c.jsx("span",{className:"text-sm font-medium text-dark-text truncate flex-1",children:o.name}),c.jsxs("a",{href:V.logs.downloadUrl(o.name),download:o.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:[c.jsx(xs,{size:12}),"下载"]})]}),l?c.jsx("div",{className:"flex-1 flex items-center justify-center",children:c.jsx(bt,{size:20,className:"animate-spin text-accent-blue"})}):c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"text-[10px] text-dark-muted mb-1 shrink-0",children:[h(a.size)," · ",a.totalLines," 行",a.startLine>1&&` (显示最新 ${a.totalLines-a.startLine+1} 行)`]}),c.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||c.jsx("span",{className:"text-dark-muted italic",children:"(空文件)"})})]})]}):c.jsxs("div",{className:"flex flex-col min-h-0 h-full",children:[c.jsxs("div",{className:"flex items-center justify-between mb-2 shrink-0",children:[c.jsx("span",{className:"text-xs font-medium text-dark-text",children:"日志文件"}),c.jsx("button",{onClick:u,className:"px-2 py-1 text-[10px] bg-dark-hover rounded hover:bg-dark-border transition-colors",disabled:t,children:t?"刷新中...":"刷新"})]}),t?c.jsx("div",{className:"flex items-center justify-center py-8",children:c.jsx(bt,{size:16,className:"animate-spin text-accent-blue"})}):s.length===0?c.jsxs("div",{className:"text-center py-8 text-dark-muted",children:[c.jsx(bs,{size:32,className:"mx-auto mb-1 opacity-50"}),c.jsx("p",{className:"text-xs",children:"暂无日志文件"})]}):c.jsx("div",{className:"flex-1 overflow-y-auto min-h-0 space-y-1 custom-scrollbar",children:s.map(f=>c.jsxs("div",{className:"flex items-center gap-2 p-2 rounded hover:bg-dark-hover transition-colors group",children:[c.jsx(bs,{size:14,className:"text-accent-blue shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-dark-text truncate",children:f.name}),c.jsxs("div",{className:"text-[10px] text-dark-muted",children:[h(f.size)," · ",Ba(f.modified)]})]}),c.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[f.previewable&&c.jsx("button",{onClick:()=>p(f),className:"p-1.5 rounded hover:bg-dark-border transition-colors",title:"预览",children:c.jsx(Po,{size:14})}),c.jsx("a",{href:V.logs.downloadUrl(f.name),download:f.name,className:"p-1.5 rounded hover:bg-dark-border transition-colors block",title:"下载",children:c.jsx(xs,{size:14})})]})]},f.name))})]})}const wn=g.memo(g.forwardRef(function({logs:e},t){return c.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?c.jsxs("div",{className:"text-center text-dark-muted py-12",children:[c.jsx(Ye,{size:48,className:"mx-auto mb-2 opacity-50"}),c.jsx("p",{children:"暂无实时日志"})]}):e.map(n=>c.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:[c.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"})})," ",c.jsx("span",{className:`px-1.5 py-0.5 rounded text-white text-xs ${Ea[n.level]}`,children:n.level.toUpperCase()})," ",c.jsxs("span",{className:"text-dark-muted text-xs",children:["[",n.source,"]"]})," ",c.jsx("span",{className:"text-dark-text whitespace-pre-wrap break-all",children:n.message})]},n.id))})})),so=g.memo(function({logs:e,onClear:t,compact:n}){const[o,r]=g.useState("stream"),a=g.useRef(null),i=g.useRef(!0),l=g.useCallback(()=>{const u=a.current;return u?u.scrollHeight-u.scrollTop-u.clientHeight<50:!0},[]),d=g.useCallback(()=>{const u=a.current;u&&(u.scrollTop=u.scrollHeight)},[]);return g.useEffect(()=>{const u=a.current;if(!u)return;const p=()=>{i.current=l()};return u.addEventListener("scroll",p,{passive:!0}),()=>u.removeEventListener("scroll",p)},[l]),g.useEffect(()=>{i.current&&d()},[e,d]),g.useEffect(()=>{const u=a.current;if(!u)return;let p=u.clientHeight;const m=new ResizeObserver(()=>{const h=u.clientHeight;h>0&&p===0&&d(),p=h});return m.observe(u),()=>m.disconnect()},[d]),n?c.jsxs("div",{className:"flex flex-col min-h-0 flex-1 p-2",children:[c.jsxs("div",{className:"flex items-center justify-between mb-2 shrink-0",children:[c.jsxs("h2",{className:"flex items-center gap-2 text-xs font-semibold",children:[c.jsx(Ye,{size:14,className:"text-accent-blue"}),"日志",c.jsxs("span",{className:"text-sm font-normal text-dark-muted",children:["(",e.length,")"]})]}),c.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:"清空"})]}),c.jsx(wn,{ref:a,logs:e})]}):c.jsxs("div",{className:"flex flex-col min-h-0 flex-1 overflow-hidden p-4",children:[c.jsx("div",{className:"flex items-center justify-between mb-3 shrink-0",children:c.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold",children:[c.jsx(Ye,{size:18,className:"text-accent-blue"}),"后台日志"]})}),c.jsx("div",{className:"flex gap-1 mb-3 shrink-0 border-b border-dark-border",children:[["stream","实时日志流",Ye],["files","日志文件",bs]].map(([u,p,m])=>c.jsxs("button",{onClick:()=>r(u),className:`flex items-center gap-1.5 px-4 py-2 text-sm rounded-t transition-colors border-b-2 ${o===u?"border-accent-blue text-accent-blue bg-accent-blue/5":"border-transparent text-dark-muted hover:text-dark-text hover:bg-dark-hover"}`,children:[c.jsx(m,{size:14}),p,u==="stream"&&e.length>0&&c.jsxs("span",{className:"ml-1 text-[10px] text-dark-muted",children:["(",e.length,")"]})]},u))}),o==="stream"&&c.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[c.jsx("div",{className:"flex items-center justify-end mb-2 shrink-0",children:c.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:"清空"})}),c.jsx(wn,{ref:a,logs:e})]}),o==="files"&&c.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:c.jsx("div",{className:"border border-dark-border rounded-lg p-3 bg-dark-surface h-full",children:c.jsx(Pa,{})})})]})}),Ra=Object.freeze(Object.defineProperty({__proto__:null,LogsPanel:so},Symbol.toStringTag,{value:"Module"})),Cn=({id:s,label:e,badge:t,isOpen:n,onToggle:o,children:r})=>c.jsxs("div",{className:"border-b border-dark-border/40 last:border-b-0",children:[c.jsxs("button",{onClick:()=>o(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?c.jsx(Ct,{size:14,className:"shrink-0 text-dark-muted"}):c.jsx(Bs,{size:14,className:"shrink-0 text-dark-muted"}),c.jsx("span",{className:"font-medium truncate",children:e}),t!==void 0&&t>0&&c.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})]}),c.jsx("div",{className:`grid transition-[grid-template-rows] duration-200 ease-in-out ${n?"grid-rows-[1fr]":"grid-rows-[0fr]"}`,children:c.jsx("div",{className:"overflow-hidden min-h-0",children:c.jsx("div",{className:"px-3 pb-3 pt-1",children:r})})})]});function Ia({workspaceDir:s,onWorkspaceChange:e,logs:t,onClearLogs:n}){const{t:o}=Be(),[r,a]=g.useState(new Set(["workspace"])),i=g.useCallback(l=>{a(d=>{const u=new Set(d);return u.has(l)?u.delete(l):u.add(l),u})},[]);return c.jsxs("div",{className:"w-72 2xl:w-80 shrink-0 border-l border-dark-border bg-dark-surface flex flex-col overflow-hidden",children:[c.jsx("div",{className:"shrink-0 px-3 py-2.5 border-b border-dark-border bg-dark-surface",children:c.jsx("span",{className:"text-xs font-semibold text-dark-text",children:o("chat.panelTitle")})}),c.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar divide-y divide-dark-border/20",children:[c.jsx(Cn,{id:"workspace",label:o("chat.workingDir"),isOpen:r.has("workspace"),onToggle:i,children:c.jsxs("div",{className:"space-y-2",children:[c.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}),c.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:o("chat.switchDir")})]})}),c.jsx(Cn,{id:"logs",label:o("chat.backgroundLogs"),badge:t.length,isOpen:r.has("logs"),onToggle:i,children:c.jsx("div",{className:"max-h-[40vh] flex flex-col min-h-0 -mx-1",children:c.jsx(so,{logs:t,onClear:n,compact:!0})})})]})]})}function no(s){var e,t,n="";if(typeof s=="string"||typeof s=="number")n+=s;else if(typeof s=="object")if(Array.isArray(s)){var o=s.length;for(e=0;e<o;e++)s[e]&&(t=no(s[e]))&&(n&&(n+=" "),n+=t)}else for(t in s)s[t]&&(n&&(n+=" "),n+=t);return n}function Ma(){for(var s,e,t=0,n="",o=arguments.length;t<o;t++)(s=arguments[t])&&(e=no(s))&&(n&&(n+=" "),n+=e);return n}function we(...s){return Ma(s)}g.createContext(null);function Is({isOpen:s,onClose:e,title:t,children:n,size:o="md",className:r}){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","2xl":"max-w-3xl","3xl":"max-w-5xl"};return c.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center overflow-hidden p-4",children:[c.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:e}),c.jsxs("div",{className:we("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[o],r),children:[t&&c.jsxs("div",{className:"flex shrink-0 items-center justify-between px-6 py-4 border-b border-dark-border",children:[c.jsx("h2",{className:"text-lg font-semibold text-dark-text",children:t}),c.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:c.jsx(xt,{className:"w-5 h-5","aria-hidden":"true"})})]}),c.jsx("div",{className:"min-h-0 overflow-y-auto custom-scrollbar p-6",children:n})]})]})}function Ic({isOpen:s,onClose:e,onConfirm:t,title:n="确认",message:o,confirmText:r="确认",cancelText:a="取消",variant:i="default"}){const l=()=>{t(),e()};return c.jsxs(Is,{isOpen:s,onClose:e,title:n,size:"sm",children:[c.jsx("p",{className:"text-dark-muted mb-6",children:o}),c.jsxs("div",{className:"flex gap-3 justify-end",children:[c.jsx("button",{onClick:e,className:"px-4 py-2 rounded-lg border border-dark-border text-dark-text hover:bg-dark-hover transition-colors",children:a}),c.jsx("button",{onClick:l,className:we("px-4 py-2 rounded-lg text-white transition-colors",i==="danger"?"bg-accent-red hover:bg-accent-red/90":"bg-accent-blue hover:bg-accent-blue/90"),children:r})]})]})}function _n({children:s,variant:e="default",size:t="md",className:n}){const o={default:"bg-dark-border text-dark-muted",success:"bg-accent-green/20 text-accent-green",warning:"bg-accent-yellow/20 text-accent-yellow",error:"bg-accent-red/20 text-accent-red",info:"bg-accent-blue/20 text-accent-blue"},r={sm:"px-1.5 py-0.5 text-[10px]",md:"px-2 py-0.5 text-xs"};return c.jsx("span",{className:we("inline-flex items-center rounded-full font-medium",o[e],r[t],n),children:s})}const La={string:"文本",number:"数字",select:"选择",boolean:"开关",folder:"目录",connector:"连接器"};function Oa({template:s,onCancel:e,onSubmit:t,submitLabel:n="启动",busy:o=!1}){const r=s.inputs??[],a=g.useMemo(()=>{const h={};for(const f of r)f.default!==void 0&&f.default!==null&&(h[f.name]=f.default);return h},[r]),[i,l]=g.useState(a),[d,u]=g.useState({});if(r.length===0)return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-sm text-dark-muted",children:"该模板无需参数,直接启动。"}),c.jsx("div",{className:"text-xs text-dark-muted/80 break-all",children:s.description||"—"}),c.jsxs("div",{className:"flex justify-end gap-3",children:[c.jsx("button",{onClick:e,className:"px-4 py-2 rounded-lg border border-dark-border text-dark-text hover:bg-dark-hover transition-colors",children:"取消"}),c.jsx("button",{onClick:()=>t({}),disabled:o,className:"px-4 py-2 rounded-lg bg-accent-blue text-white hover:bg-accent-blue/90 disabled:opacity-50 transition-colors",children:o?"启动中…":n})]})]});const p=(h,f)=>{l(y=>({...y,[h]:f})),u(y=>{if(!y[h])return y;const b={...y};return delete b[h],b})},m=()=>{const h={},f={};for(const y of r){let b=i[y.name];typeof b=="string"&&(b=b.trim());const C=b==null||b==="";if(y.required&&C){h[y.name]="必填";continue}if(!C)if(y.type==="number"){const k=Number(b);if(!Number.isFinite(k)){h[y.name]="请输入数字";continue}f[y.name]=k}else f[y.name]=b}if(Object.keys(h).length>0){u(h);return}t(f)};return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-sm text-dark-muted",children:s.description||""}),r.map(h=>c.jsxs("div",{children:[c.jsxs("label",{className:"flex items-center gap-1.5 text-sm text-dark-text mb-1.5",children:[c.jsx("span",{children:h.label||h.name}),h.required&&c.jsx("span",{className:"text-accent-red",children:"*"}),h.type!=="boolean"&&c.jsx("span",{className:"text-[10px] text-dark-muted/70",children:La[h.type]})]}),$a(h,i[h.name],p),h.description&&c.jsx("div",{className:"mt-1 text-xs text-dark-muted/70",children:h.description}),d[h.name]&&c.jsx("div",{className:"mt-1 text-xs text-accent-red",children:d[h.name]})]},h.name)),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:e,className:"px-4 py-2 rounded-lg border border-dark-border text-dark-text hover:bg-dark-hover transition-colors",children:"取消"}),c.jsx("button",{onClick:m,disabled:o,className:"px-4 py-2 rounded-lg bg-accent-blue text-white hover:bg-accent-blue/90 disabled:opacity-50 transition-colors",children:o?"启动中…":n})]})]})}function $a(s,e,t){const n="w-full px-3 py-2 rounded-lg bg-dark-bg border border-dark-border text-sm text-dark-text focus:outline-none focus:ring-1 focus:ring-accent-blue placeholder:text-dark-muted/50";switch(s.type){case"select":return c.jsxs("select",{value:typeof e=="string"?e:s.default||"",onChange:o=>t(s.name,o.target.value),className:n,children:[!s.required&&c.jsx("option",{value:"",children:"(不选)"}),(s.options||[]).map(o=>c.jsx("option",{value:o,children:o},o))]});case"boolean":return c.jsx("button",{type:"button",onClick:()=>t(s.name,e!==!0),className:we("h-6 w-11 rounded-full transition-colors relative flex items-center px-0.5",e===!0?"bg-accent-blue":"bg-dark-border"),"aria-pressed":e===!0,children:c.jsx("span",{className:we("h-5 w-5 rounded-full bg-white transition-transform",e===!0&&"translate-x-5")})});case"number":return c.jsx("input",{type:"number",value:typeof e=="number"||typeof e=="string"?e:"",onChange:o=>t(s.name,o.target.value),placeholder:typeof s.default=="number"?String(s.default):"0",className:n});default:return c.jsx("input",{type:"text",value:typeof e=="string"?e:"",onChange:o=>t(s.name,o.target.value),placeholder:typeof s.default=="string"?s.default:"",className:n})}}function Da({collapsed:s=!1,onDirect:e,onStartTemplate:t,onManageTemplates:n}){const[o,r]=g.useState(!1),[a,i]=g.useState({kind:"list"}),[l,d]=g.useState([]),[u,p]=g.useState(!1),[m,h]=g.useState(""),[f,y]=g.useState({top:0,left:0}),b=g.useRef(null),C=g.useCallback(()=>{i({kind:"list"}),r(!0)},[]);g.useEffect(()=>{var N;if(!o)return;const E=(N=b.current)==null?void 0:N.getBoundingClientRect();E&&y({top:E.bottom+6,left:Math.max(8,E.left)})},[o,s]),g.useEffect(()=>{if(!o||a.kind!=="list")return;let E=!1;return p(!0),h(""),V.templates.list().then(N=>{E||(N.success&&N.data?d(N.data):h(N.error||"加载模板失败"))}).catch(()=>{E||h("加载模板失败")}).finally(()=>{E||p(!1)}),()=>{E=!0}},[o,a.kind]);const k=g.useMemo(()=>{const E=new Map;for(const N of l){const L=N.category||"其他",$=E.get(L)||[];$.push(N),E.set(L,$)}return[...E.entries()]},[l]),T=async E=>{const N=await V.templates.get(E.id);N.success&&N.data?i({kind:"form",template:N.data}):h(N.error||"加载模板失败")},_=E=>{a.kind==="form"&&(t(a.template,E),r(!1),i({kind:"list"}))},w={top:f.top,left:f.left,width:Math.min(360,typeof window<"u"?window.innerWidth-16:360)};return c.jsxs("div",{ref:b,className:"relative",children:[c.jsx("div",{className:"flex",children:s?c.jsx("button",{onClick:C,className:"btn btn-primary w-full !px-0 aspect-square",title:"新建会话","aria-label":"新建会话",children:c.jsx(Lt,{size:16,"aria-hidden":"true"})}):c.jsxs(c.Fragment,{children:[c.jsxs("button",{onClick:e,className:"btn btn-primary flex-1 !px-3 py-2 rounded-l-lg",children:[c.jsx(Lt,{size:15,"aria-hidden":"true"}),"新建会话"]}),c.jsx("button",{onClick:()=>o?r(!1):C(),className:"px-2.5 rounded-r-lg bg-accent-blue text-white border-l border-white/25 hover:opacity-95 flex items-center",title:"用模板新建","aria-label":"选择模板新建会话",children:c.jsx(Ct,{size:13,"aria-hidden":"true"})})]})}),o&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>r(!1)}),c.jsx("div",{className:"fixed z-50 bg-dark-surface border border-dark-border rounded-xl shadow-2xl p-1.5 max-h-[70vh] overflow-y-auto custom-scrollbar",style:w,children:a.kind==="form"?c.jsxs("div",{className:"p-2",children:[c.jsxs("button",{onClick:()=>i({kind:"list"}),className:"mb-2 inline-flex items-center gap-1 text-xs text-dark-muted hover:text-dark-text transition-colors",children:[c.jsx(Ro,{className:"w-3.5 h-3.5"})," 返回模板列表"]}),c.jsx("div",{className:"text-sm font-medium text-dark-text mb-3",children:a.template.name}),c.jsx(Oa,{template:a.template,onCancel:()=>i({kind:"list"}),onSubmit:_,submitLabel:"启动"})]}):c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-2 py-1 text-[10.5px] uppercase tracking-[0.06em] text-dark-muted/70 font-semibold",children:"开始一个会话"}),c.jsxs("button",{onClick:()=>{r(!1),e()},className:"w-full flex items-center gap-2.5 px-2 py-2 rounded-lg hover:bg-dark-hover text-left",children:[c.jsx("span",{className:"w-6 h-6 rounded-md bg-accent-blue/10 border border-accent-blue/30 grid place-items-center text-accent-blue shrink-0",children:c.jsx(Wt,{className:"w-3.5 h-3.5"})}),c.jsxs("span",{className:"min-w-0",children:[c.jsx("span",{className:"block text-[13px] font-medium text-dark-text",children:"直接对话"}),c.jsx("span",{className:"block text-[11px] text-dark-muted truncate",children:"不选模板,AI 现场拆解任务(动态工作流)"})]})]}),u&&c.jsxs("div",{className:"flex items-center gap-2 px-2 py-3 text-xs text-dark-muted",children:[c.jsx(bt,{className:"w-3.5 h-3.5 animate-spin"})," 加载模板…"]}),m&&!u&&c.jsx("div",{className:"px-2 py-2 text-xs text-accent-red",children:m}),!u&&!m&&k.length===0&&c.jsx("div",{className:"px-2 py-2 text-xs text-dark-muted",children:"暂无已保存模板。"}),k.map(([E,N])=>c.jsxs("div",{className:"mt-1",children:[c.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1",children:[c.jsx(Ot,{className:"w-3 h-3 text-dark-muted/70"}),c.jsx("span",{className:"text-[10px] uppercase tracking-[0.06em] text-dark-muted/70 font-semibold",children:E}),c.jsx(_n,{size:"sm",children:N.length})]}),N.map(L=>c.jsxs("button",{onClick:()=>void T(L),className:"w-full flex items-center gap-2.5 px-2 py-2 rounded-lg hover:bg-dark-hover text-left",children:[c.jsx("span",{className:"w-6 h-6 rounded-md bg-dark-border/60 border border-dark-border grid place-items-center text-dark-muted shrink-0",children:c.jsx(Ot,{className:"w-3.5 h-3.5"})}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx("span",{className:"block text-[13px] font-medium text-dark-text truncate",children:L.name}),c.jsxs(_n,{size:"sm",variant:"info",children:["v",L.version]})]}),L.description&&c.jsx("span",{className:"block text-[11px] text-dark-muted truncate",children:L.description})]})]},L.id))]},E)),c.jsx("div",{className:"border-t border-dark-border mt-1 pt-1",children:c.jsx("button",{onClick:()=>{r(!1),n()},className:"w-full px-2 py-1.5 rounded-lg hover:bg-dark-hover text-left text-[12.5px] text-dark-muted",children:"模板库…"})})]})})]})]})}function Ns(s,e=Date.now(),t){const n=typeof s=="number"?s:new Date(s).getTime();if(!Number.isFinite(n))return"";const o=e-n;if(o<6e4)return t?t("time.justNow"):"刚刚";const r=Math.floor(o/6e4);if(r<60)return t?t("time.minutesAgo",{count:r}):`${r}分钟前`;const a=Math.floor(r/60);if(a<24)return t?t("time.hoursAgo",{count:a}):`${a}小时前`;const i=Math.floor(a/24);if(i<7)return t?t("time.daysAgo",{count:i}):`${i}天前`;const l=new Date(n);return`${l.getFullYear()}-${String(l.getMonth()+1).padStart(2,"0")}-${String(l.getDate()).padStart(2,"0")}`}const at=10;function Fa({isOpen:s,onClose:e,onSwitchSession:t}){const{t:n}=Be(),o=K(b=>b.sessionTabs),r=K(b=>b.activeSessionId),a=G(b=>b.generatingSessions),[i,l]=g.useState(0),d=g.useMemo(()=>[...o].sort((b,C)=>(C.lastActiveAt??C.createdAt??0)-(b.lastActiveAt??b.createdAt??0)),[o]),u=Math.max(1,Math.ceil(d.length/at)),p=Math.min(i,u-1),m=g.useMemo(()=>{const b=new Map,C=p*at;for(const k of d.slice(C,C+at)){const T=k.project||"default",_=b.get(T)||[];_.push(k),b.set(T,_)}return Array.from(b.entries())},[d,p]),h=d.length===0?0:p*at+1,f=Math.min((p+1)*at,d.length),y=b=>a.includes(b.id)?"running":b.status||"done";return c.jsx(Is,{isOpen:s,onClose:e,title:n("chat.sessionPickerTitle"),size:"lg",children:c.jsxs("div",{className:"flex flex-col gap-3",children:[c.jsx("div",{className:"max-h-[320px] overflow-y-auto custom-scrollbar rounded-lg border border-dark-border bg-dark-bg p-1.5",children:d.length===0?c.jsx("div",{className:"px-3 py-6 text-center text-xs text-dark-muted/60",children:n("chat.noSessions")}):m.map(([b,C])=>c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 text-[10px] text-dark-muted/70",children:[c.jsx(Hn,{size:10,"aria-hidden":"true",className:"shrink-0 opacity-60"}),c.jsx("span",{className:"truncate",children:b==="default"?n("nav.mySessions"):b}),c.jsx("span",{className:"ml-auto text-[9px] text-dark-muted/40",children:C.length})]}),c.jsx("div",{className:"space-y-0.5",children:C.map(k=>{const T=k.id===r,_=y(k),w=Ns(k.lastActiveAt??k.createdAt,Date.now(),n),E=_s(k),N=Qn(k.title,E);return c.jsxs("button",{onClick:()=>{t(k.id),e()},title:n("chat.clickToOpenSession"),className:`group flex w-full cursor-pointer items-center gap-2 rounded-lg px-2.5 py-[7px] text-left text-[13px] transition-colors ${T?"bg-accent-blue/10 font-medium text-accent-blue":"text-dark-muted hover:bg-dark-hover/60 hover:text-dark-text"}`,children:[c.jsx(Wt,{size:13,"aria-hidden":"true",className:"shrink-0 opacity-60"}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx("span",{className:"min-w-0 flex-1 truncate",children:k.title}),_==="running"&&c.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-red animate-pulse",title:n("nav.sessionRunning")}),_==="waiting"&&c.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-yellow",title:n("nav.sessionWaiting")}),_==="failed"&&c.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-red",title:n("nav.sessionFailed")}),_==="done"&&c.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-green",title:n("nav.sessionDone")})]}),c.jsxs("span",{className:"mt-0.5 flex items-center gap-2 text-[11px] leading-tight text-dark-muted/60",children:[N&&c.jsx("span",{className:"min-w-0 flex-1 truncate",children:E}),c.jsx("span",{className:`shrink-0 ${N?"":"ml-auto"}`,children:w})]})]})]},k.id)})})]},b))}),c.jsxs("div",{className:"flex items-center justify-between text-xs text-dark-muted",children:[c.jsx("span",{children:n("common.pageInfo",{start:h,end:f,total:d.length})}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsxs("button",{onClick:()=>l(b=>Math.max(0,b-1)),disabled:p===0,className:"flex items-center gap-0.5 rounded-md border border-dark-border px-2 py-1 text-dark-muted transition-colors hover:bg-dark-hover hover:text-dark-text disabled:cursor-not-allowed disabled:opacity-40",children:[c.jsx(Wn,{size:13,"aria-hidden":"true"}),n("common.prevPage")]}),c.jsxs("span",{className:"min-w-[48px] text-center font-mono",children:[p+1,"/",u]}),c.jsxs("button",{onClick:()=>l(b=>Math.min(u-1,b+1)),disabled:p>=u-1,className:"flex items-center gap-0.5 rounded-md border border-dark-border px-2 py-1 text-dark-muted transition-colors hover:bg-dark-hover hover:text-dark-text disabled:cursor-not-allowed disabled:opacity-40",children:[n("common.nextPage"),c.jsx(Bs,{size:13,"aria-hidden":"true"})]})]})]})]})})}const Et=5,Wa=[{labelKey:"nav.groupWorkspace",ids:["chat","terminal","files"]},{labelKey:"nav.groupConfig",ids:["models","tools","skills","agents","templates","hooks","channels","connectors"]},{labelKey:"nav.groupSystem",ids:["logs","settings"]}],Ha=[{id:"pull-requests",icon:Ht,labelKey:"nav.pullRequests"},{id:"scheduled",icon:Ps,labelKey:"nav.scheduled"},{id:"plugins",icon:Ut,labelKey:"nav.plugins"}],Ua=(...s)=>s.filter(Boolean).join(" "),Tn=g.memo(function({collapsed:e,onToggleCollapse:t,tabs:n,activeTab:o,onTabChange:r,isConnected:a,onNewSession:i,onStartTemplate:l,onManageTemplates:d,onSwitchSession:u,onCloseSession:p,onRenameSession:m,getTabTitle:h}){const{t:f}=Be(),y=K(B=>B.sessionTabs),b=K(B=>B.activeSessionId),C=K(B=>B.historySessions),k=K(B=>B.restoreHistorySession),T=K(B=>B.removeHistorySession),[_,w]=g.useState(!1),[E,N]=g.useState(!1),[L,$]=g.useState(null),[U,de]=g.useState(""),A=g.useRef(null),S=g.useMemo(()=>Wa.map(B=>({...B,tabs:B.ids.map(D=>n.find(R=>R.id===D)).filter(D=>!!D)})).filter(B=>B.tabs.length>0),[n]),P=g.useCallback((B,D)=>{$(B),de(D),setTimeout(()=>{var R;return(R=A.current)==null?void 0:R.select()},50)},[]),H=g.useCallback(()=>{L&&U.trim()&&m(L,U.trim()),$(null)},[L,U,m]),q=g.useCallback((B,D)=>{var J;const R=G.getState().getMessages(B),M=[];M.push(`# ${D||f("nav.chat")}`),M.push(""),M.push(`> ${f("chat.exportMd")} · ${new Date().toLocaleString()}`),M.push(""),M.push("---"),M.push(""),(!R||R.length===0)&&(M.push(f("chat.noSessions")),M.push(""));for(const pe of R){if(pe.deleted)continue;const ie=pe.type==="user"?f("chat.you"):f("chat.assistantLabel");if(M.push(`## ${ie} · ${new Date(pe.timestamp).toLocaleString()}`),M.push(""),pe.thinking&&pe.thinking.trim()&&(M.push("<details>"),M.push(`<summary>💭 ${f("chat.thoughtProcess")}</summary>`),M.push(""),M.push(pe.thinking.trim()),M.push(""),M.push("</details>"),M.push("")),pe.content&&pe.content.trim()&&(M.push(pe.content.trim()),M.push("")),pe.steps&&pe.steps.length>0){M.push(`**${f("chat.runningSteps")}:**`),M.push("");for(const ke of pe.steps){if(M.push(`- **${ke.title}**${ke.status?` (\`${ke.status}\`)`:""}`),ke.thought&&M.push(` - 💭 ${ke.thought}`),(J=ke.toolCalls)!=null&&J.length)for(const _t of ke.toolCalls)M.push(` - 🛠 \`${_t.name}\``);ke.result&&M.push(` - ${ke.result}`)}M.push("")}M.push("---"),M.push("")}const ue=new Blob([M.join(`
|
|
6
|
+
`)],{type:"text/markdown;charset=utf-8"}),oe=URL.createObjectURL(ue),Le=document.createElement("a");Le.href=oe,Le.download=`${(D||"session").replace(/[\\/:*?"<>|]/g,"_").slice(0,80)}.md`,Le.click(),URL.revokeObjectURL(oe)},[f]),ne=g.useCallback(B=>{k(B),F.setSessionId(B)},[k]),ge=g.useCallback(B=>{u(B),o!=="chat"&&r("chat")},[u,r,o]),ae=G(B=>B.generatingSessions),Fe=g.useCallback(B=>ae.includes(B.id)?"running":B.status||"done",[ae]),te=g.useMemo(()=>{const B=new Map,D=[...y].sort((M,ue)=>(ue.lastActiveAt??ue.createdAt??0)-(M.lastActiveAt??M.createdAt??0));let R=D;if(D.length>Et){const M=D.slice(0,Et),ue=D.find(oe=>oe.id===b);ue&&!M.some(oe=>oe.id===ue.id)?R=[ue,...M.filter(oe=>oe.id!==ue.id)].slice(0,Et):R=M}for(const M of R){const ue=M.project||"default",oe=B.get(ue)||[];oe.push(M),B.set(ue,oe)}return Array.from(B.entries())},[y,b]);return c.jsxs("div",{className:"flex h-full flex-col",children:[c.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:[c.jsx("img",{src:"/logo.svg",alt:"deepseekcode",className:"h-7 w-7 rounded-lg shadow-sm"}),!e&&c.jsx("span",{className:"flex-1 truncate text-[15px] font-semibold tracking-tight text-dark-text",children:"deepseekcode"}),c.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:f("nav.collapseSidebar"),"aria-label":f("nav.collapseSidebar"),children:c.jsx(Io,{size:16,"aria-hidden":"true"})})]}),c.jsx("div",{className:e?"p-2":"px-3 pt-3",children:l&&d?c.jsx(Da,{collapsed:e,onDirect:i,onStartTemplate:l,onManageTemplates:d}):c.jsxs("button",{onClick:i,className:"btn btn-primary w-full",children:[c.jsx(Lt,{size:15,"aria-hidden":"true"}),f("chat.newSession")]})}),!e&&c.jsx("div",{className:"px-3 pt-2",children:c.jsx("div",{className:"flex items-center gap-1",children:Ha.map(B=>{const D=B.icon,R=o===B.id;return c.jsxs("button",{onClick:()=>r(B.id),className:Ua("flex flex-1 flex-col items-center gap-1 rounded-lg border px-1 py-1.5 text-[10px] transition-colors",R?"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:f(B.labelKey),children:[c.jsx(D,{size:14,"aria-hidden":"true"}),c.jsx("span",{className:"truncate",children:f(B.labelKey)})]},B.id)})})}),c.jsxs("div",{className:"flex-1 overflow-y-auto custom-scrollbar px-3 pb-2 min-h-0",children:[!e&&c.jsxs("div",{className:"pt-2",children:[c.jsxs("div",{className:"side-group-label flex items-center justify-between",children:[c.jsx("span",{children:f("nav.sessions")}),C.length>0&&c.jsxs("button",{onClick:()=>w(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:f("chat.sessionHistory"),"aria-expanded":_,children:[c.jsx(Ys,{size:11,"aria-hidden":"true"}),c.jsx(Ct,{size:11,"aria-hidden":"true",className:`transition-transform ${_?"":"-rotate-90"}`})]})]}),c.jsxs("div",{className:"space-y-1.5",children:[te.map(([B,D])=>c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center gap-1 px-2 py-0.5 text-[10px] text-dark-muted/70",children:[c.jsx(Hn,{size:10,"aria-hidden":"true",className:"shrink-0 opacity-60"}),c.jsx("span",{className:"truncate",children:B==="default"?f("nav.mySessions"):B}),c.jsx("span",{className:"ml-auto text-[9px] text-dark-muted/40",children:D.length})]}),c.jsx("div",{className:"space-y-0.5",children:D.map(R=>{const M=R.id===b,ue=L===R.id,oe=Fe(R),Le=Ns(R.lastActiveAt??R.createdAt,Date.now(),f),J=_s(R),pe=Qn(R.title,J);return c.jsxs("div",{onClick:()=>!ue&&ge(R.id),onDoubleClick:()=>P(R.id,R.title),className:`group flex cursor-pointer items-center gap-2 rounded-lg px-2.5 py-[6px] text-[13px] transition-colors ${M?"bg-dark-hover font-medium text-dark-text":"text-dark-muted hover:bg-dark-hover/60 hover:text-dark-text"}`,children:[c.jsx(Wt,{size:13,"aria-hidden":"true",className:"shrink-0 opacity-60"}),ue?c.jsx("input",{ref:A,value:U,onChange:ie=>de(ie.target.value),onBlur:H,onKeyDown:ie=>{ie.key==="Enter"?H():ie.key==="Escape"&&$(null)},onClick:ie=>ie.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}):c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsxs("span",{className:"flex items-center gap-1.5",children:[c.jsx("span",{className:"min-w-0 flex-1 truncate",children:R.title}),oe==="running"&&c.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-red animate-pulse",title:f("nav.sessionRunning")}),oe==="waiting"&&c.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-yellow",title:f("nav.sessionWaiting")}),oe==="failed"&&c.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-red",title:f("nav.sessionFailed")}),oe==="done"&&c.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full bg-accent-green",title:f("nav.sessionDone")})]}),c.jsxs("span",{className:"mt-0.5 flex items-center gap-2 text-[11px] leading-tight text-dark-muted/50",children:[pe&&c.jsx("span",{className:"min-w-0 flex-1 truncate",children:J}),c.jsx("span",{className:`shrink-0 ${pe?"":"ml-auto"}`,children:Le})]})]}),!ue&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:ie=>{ie.stopPropagation(),P(R.id,R.title)},className:"shrink-0 rounded p-0.5 opacity-0 transition-all hover:bg-dark-bg group-hover:opacity-100",title:f("chat.renameSession"),"aria-label":f("chat.renameSession"),children:c.jsx(Mo,{size:11,"aria-hidden":"true"})}),c.jsx("button",{onClick:ie=>{ie.stopPropagation(),q(R.id,R.title)},className:"shrink-0 rounded p-0.5 opacity-0 transition-all hover:bg-dark-bg group-hover:opacity-100",title:f("chat.exportMd"),"aria-label":f("chat.exportMd"),children:c.jsx(xs,{size:11,"aria-hidden":"true"})}),y.length>1&&c.jsx("button",{onClick:ie=>{ie.stopPropagation(),p(R.id)},className:"shrink-0 rounded p-0.5 opacity-0 transition-all hover:bg-dark-bg group-hover:opacity-100","aria-label":f("a11y.close"),children:c.jsx(xt,{size:12,"aria-hidden":"true"})})]})]},R.id)})})]},B)),y.length===0&&c.jsx("div",{className:"px-2.5 py-2 text-xs text-dark-muted/60",children:f("chat.noSessions")})]}),y.length>Et&&c.jsxs("button",{onClick:()=>N(!0),className:"mt-1.5 flex w-full items-center justify-center gap-1 rounded-lg border border-dashed border-dark-border px-2 py-1.5 text-xs text-dark-muted transition-colors hover:bg-dark-hover hover:text-dark-text",title:f("chat.viewAllSessions"),children:[c.jsx(Lo,{size:12,"aria-hidden":"true"}),f("chat.viewAllSessions"),c.jsxs("span",{className:"text-dark-muted/50",children:["(",y.length,")"]})]}),_&&C.length>0&&c.jsx("div",{className:"mt-1 space-y-0.5 border-t border-dark-border/50 pt-1",children:C.slice(0,10).map(B=>{const D=_s(B);return c.jsxs("div",{onClick:()=>ne(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:[c.jsx(Ys,{size:11,"aria-hidden":"true",className:"shrink-0 opacity-50"}),c.jsxs("span",{className:"min-w-0 flex-1",children:[c.jsx("span",{className:"block truncate",children:B.title}),D&&c.jsx("span",{className:"block truncate text-[10px] text-dark-muted/50",children:D})]}),c.jsx("span",{className:"shrink-0 text-[10px] text-dark-muted/50",children:Ns(B.lastActiveAt??B.createdAt,Date.now(),f)}),c.jsx("button",{onClick:R=>{R.stopPropagation(),T(B.id)},className:"shrink-0 rounded p-0.5 opacity-0 transition-all hover:bg-dark-bg group-hover:opacity-100","aria-label":f("chat.removeFromHistory"),children:c.jsx(xt,{size:11,"aria-hidden":"true"})})]},B.id)})})]}),c.jsx("nav",{className:e?"pt-2":"",children:S.map(B=>c.jsxs("div",{children:[!e&&c.jsx("div",{className:"side-group-label",children:f(B.labelKey)}),e&&c.jsx("div",{className:"mx-2 my-2 border-t border-dark-border/60"}),c.jsx("div",{className:`space-y-0.5 ${e?"flex flex-col items-center":""}`,children:B.tabs.map(D=>{const R=o===D.id,M=D.iconComponent;return e?c.jsx("button",{onClick:()=>r(D.id),className:`flex h-9 w-9 items-center justify-center rounded-lg transition-colors ${R?"bg-accent-blue/10 text-accent-blue":"text-dark-muted hover:bg-dark-hover hover:text-dark-text"}`,title:h(D.id,D.title),"aria-label":h(D.id,D.title),"aria-current":R?"page":void 0,children:M&&c.jsx(M,{size:17,"aria-hidden":"true"})},D.id):c.jsxs("button",{onClick:()=>r(D.id),className:"side-nav-item","data-active":R,"aria-current":R?"page":void 0,children:[M&&c.jsx(M,{size:15,"aria-hidden":"true",className:"shrink-0"}),c.jsx("span",{className:"truncate",children:h(D.id,D.title)})]},D.id)})})]},B.labelKey))})]}),c.jsxs("div",{className:`shrink-0 border-t border-dark-border/70 ${e?"p-2":"p-3"}`,children:[e&&c.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:f("nav.expandSidebar"),"aria-label":f("nav.expandSidebar"),children:c.jsx(Oo,{size:16,"aria-hidden":"true"})}),c.jsxs("div",{className:`flex items-center gap-2 text-xs text-dark-muted ${e?"justify-center":"px-1.5"}`,role:"status","aria-label":f("a11y.connectionStatus"),children:[c.jsx("span",{className:`h-1.5 w-1.5 shrink-0 rounded-full ${a?"bg-accent-green":"bg-accent-red"}`,"aria-hidden":"true"}),!e&&c.jsx("span",{className:"truncate",children:f(a?"chat.connected":"chat.disconnected")})]})]}),c.jsx(Fa,{isOpen:E,onClose:()=>N(!1),onSwitchSession:B=>ge(B)})]})}),as=200,Ka=(s,e)=>({runId:e,sessionId:s,status:"RUNNING",completedPhases:0,totalPhases:0,completedEffects:0,totalEffects:0,tokensUsed:0,tokensRemaining:0,updatedAt:Date.now()}),$e=()=>Date.now(),Ee=(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"},Nn=s=>s.id||`${s.type||"event"}-${s.timestamp||$e()}-${Math.random().toString(36).slice(2,8)}`,ce=be()(Xe((s,e)=>({bySession:{},byRun:{},agentsBySession:{},tasksBySession:{},eventsBySession:{},upsert:(t,n)=>s(o=>{const r=n.runId,a=o.byRun[r]||o.bySession[t]||Ka(t,r),i={...a.agentNodes||{}};n.agentNode&&(i[n.agentNode.nodeId]=n.agentNode);const{agentNode:l,...d}=n,u={...a,...d,agentNodes:i,sessionId:t,runId:r,updatedAt:$e()},p={...o.agentsBySession[t]||{}};l&&(p[l.nodeId]={...p[l.nodeId]||{},id:l.nodeId,sessionId:t,name:l.role,role:l.role,source:"workflow",runId:r,phase:l.phase,status:l.status,tokens:l.tokens,error:l.error,updatedAt:l.updatedAt||$e()});const m=n.lastEventType||n.status||"workflow_update",f=[{id:Nn({type:m}),sessionId:t,type:m,source:"workflow",timestamp:$e(),status:u.status,runId:r,agentId:l==null?void 0:l.nodeId,message:u.error,data:d},...o.eventsBySession[t]||[]].slice(0,as);return{bySession:{...o.bySession,[t]:u},byRun:{...o.byRun,[r]:u},agentsBySession:{...o.agentsBySession,[t]:p},eventsBySession:{...o.eventsBySession,[t]:f}}}),fail:(t,n,o)=>e().upsert(t,{runId:n,status:"ERROR",error:o,lastEventType:"workflow_error"}),getForSession:t=>e().bySession[t],upsertAgent:(t,n)=>s(o=>{var i;const r=(i=o.agentsBySession[t])==null?void 0:i[n.id],a={id:n.id,sessionId:t,name:n.name||n.role||(r==null?void 0:r.name)||n.id,role:n.role||(r==null?void 0:r.role)||n.name||n.id,source:n.source||(r==null?void 0:r.source)||"agent",status:n.status||(r==null?void 0:r.status)||"idle",runId:n.runId??(r==null?void 0:r.runId),phase:n.phase??(r==null?void 0:r.phase),taskId:n.taskId??(r==null?void 0:r.taskId),currentTask:n.currentTask??(r==null?void 0:r.currentTask),tokens:n.tokens??(r==null?void 0:r.tokens),error:n.error??(r==null?void 0:r.error),updatedAt:n.updatedAt||$e()};return{agentsBySession:{...o.agentsBySession,[t]:{...o.agentsBySession[t]||{},[n.id]:a}}}}),upsertTask:(t,n)=>s(o=>{var d;const r=(d=o.tasksBySession[t])==null?void 0:d[n.id],a=$e(),i=n.status||(r==null?void 0:r.status)||"pending",l={id:n.id,sessionId:t,title:n.title||(r==null?void 0:r.title)||n.description||n.id,status:i,source:n.source||(r==null?void 0:r.source)||"task",description:n.description??(r==null?void 0:r.description),agentType:n.agentType??(r==null?void 0:r.agentType),progress:n.progress??(r==null?void 0:r.progress),result:n.result??(r==null?void 0:r.result),error:n.error??(r==null?void 0:r.error),runId:n.runId??(r==null?void 0:r.runId),dependencies:n.dependencies??(r==null?void 0:r.dependencies),startedAt:n.startedAt??(r==null?void 0:r.startedAt)??(i==="running"?a:void 0),completedAt:n.completedAt??(r==null?void 0:r.completedAt)??(i==="completed"||i==="failed"?a:void 0),createdAt:n.createdAt||(r==null?void 0:r.createdAt)||a,updatedAt:n.updatedAt||a,raw:n.raw??(r==null?void 0:r.raw)};return{tasksBySession:{...o.tasksBySession,[t]:{...o.tasksBySession[t]||{},[n.id]:l}}}}),setTasks:(t,n,o="plan")=>s(r=>{const a=r.tasksBySession[t]||{},i=Object.fromEntries(Object.entries(a).filter(([,u])=>u.source!==o)),l=$e(),d=Object.fromEntries(n.map((u,p)=>{const m=a[u.id],h=u.status||(m==null?void 0:m.status)||"pending",f={id:u.id,sessionId:t,title:u.title||(m==null?void 0:m.title)||u.description||`Task ${p+1}`,status:h,source:u.source||o,description:u.description??(m==null?void 0:m.description),agentType:u.agentType??(m==null?void 0:m.agentType),progress:u.progress??(m==null?void 0:m.progress),result:u.result??(m==null?void 0:m.result),error:u.error??(m==null?void 0:m.error),runId:u.runId??(m==null?void 0:m.runId),dependencies:u.dependencies??(m==null?void 0:m.dependencies),startedAt:u.startedAt??(m==null?void 0:m.startedAt),completedAt:u.completedAt??(m==null?void 0:m.completedAt),createdAt:u.createdAt||(m==null?void 0:m.createdAt)||l+p,updatedAt:u.updatedAt||l,raw:u.raw??(m==null?void 0:m.raw)};return[f.id,f]}));return{tasksBySession:{...r.tasksBySession,[t]:{...i,...d}}}}),recordEvent:(t,n)=>s(o=>{const r={id:Nn(n),sessionId:t,type:n.type,source:n.source||"system",timestamp:n.timestamp||$e(),title:n.title,message:n.message,status:n.status,runId:n.runId,agentId:n.agentId,taskId:n.taskId,data:n.data};return{eventsBySession:{...o.eventsBySession,[t]:[r,...o.eventsBySession[t]||[]].slice(0,as)}}}),getAgentsForSession:t=>Object.values(e().agentsBySession[t]||{}).sort((n,o)=>o.updatedAt-n.updatedAt),getTasksForSession:t=>Object.values(e().tasksBySession[t]||{}).sort((n,o)=>{const r={running:0,pending:1,failed:2,completed:3,skipped:4};return r[n.status]-r[o.status]||n.createdAt-o.createdAt}),getEventsForSession:t=>e().eventsBySession[t]||[],getAgentTree:t=>{const n=Object.values(e().agentsBySession[t]||{}),o=new Map(n.map(l=>[l.id,l])),r=n.filter(l=>!l.parentId||!o.has(l.parentId)),a=l=>n.filter(d=>d.parentId===l),i=l=>({agent:l,children:a(l.id).map(i),isRunning:l.status==="running",tokensUsed:l.tokens||0});return r.map(i)},getRunningAgentCount:t=>Object.values(e().agentsBySession[t]||{}).filter(o=>o.status==="running").length}),{name:"deepseekcode-workflow-store",storage:Xn({key:"workflowStore",trims:[s=>({...s,state:{...s.state,eventsBySession:Object.fromEntries(Object.entries(s.state.eventsBySession).map(([e,t])=>[e,t.slice(-50)])),tasksBySession:Object.fromEntries(Object.entries(s.state.tasksBySession).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([n,o])=>[n,{...o,result:o.result?String(o.result).slice(0,1e3):void 0,error:o.error?String(o.error).slice(0,1e3):void 0}]))]))}}),s=>({...s,state:{...s.state,eventsBySession:{}}}),s=>({...s,state:{...s.state,tasksBySession:{},agentsBySession:{}}})],onFailure:()=>{try{De.getState().addToast("warning","任务看板数据保存失败:浏览器本地存储已满或不可用。当前数据仅保留在内存中,刷新页面将丢失。",8e3)}catch{}}}),partialize:s=>({bySession:s.bySession,byRun:s.byRun,agentsBySession:s.agentsBySession,tasksBySession:Object.fromEntries(Object.entries(s.tasksBySession).map(([e,t])=>[e,Object.fromEntries(Object.entries(t).map(([n,o])=>{const{raw:r,...a}=o;return[n,a]}))])),eventsBySession:Object.fromEntries(Object.entries(s.eventsBySession).map(([e,t])=>[e,t.slice(-as).map(n=>{const{data:o,...r}=n;return r})]))})})),Ga=s=>{if(s==null||s==="")return{};if(typeof s!="string")return s;try{return JSON.parse(s)}catch{return s}},it=(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||""),za=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:[],is=(s,e,t=0)=>{const n=String(s.id||s.taskId||s.backendId||`plan-task-${t+1}`),o=Ee(s.status||s.planStatus,s.completed),r=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:o,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):o==="running"?r:void 0,completedAt:s.completedAt?Number(s.completedAt):o==="completed"||o==="failed"?r:void 0,createdAt:s.createdAt&&Number(s.createdAt)||r,updatedAt:r,raw:s}},jn=(s,e,t=0)=>{const n=String(s.id||s.taskId||s.backendId||`goal-task-${t+1}`),o=Ee(s.status),r=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:o,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):o==="running"?r:void 0,completedAt:s.completedAt?Number(s.completedAt):o==="completed"||o==="failed"?r:void 0,createdAt:s.createdAt&&Number(s.createdAt)||r,updatedAt:s.updatedAt?Number(s.updatedAt):r,raw:s}},Va=(s,e)=>{const t=String((e==null?void 0:e.taskId)||(e==null?void 0:e.id)||"");if(!t)return;const n=ce.getState().getTasksForSession(s).find(i=>i.id===t),o=K.getState().getSessionTasks(s).find(i=>i.id===t||i.backendId===t),r=e!=null&&e.status?Ee(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)||(o==null?void 0:o.title)||t,description:(e==null?void 0:e.description)??(n==null?void 0:n.description)??(o==null?void 0:o.description),status:r,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:r==="running"?Date.now():n==null?void 0:n.startedAt,completedAt:r==="completed"||r==="failed"?Date.now():n==null?void 0:n.completedAt,createdAt:(n==null?void 0:n.createdAt)||Date.now(),updatedAt:Date.now(),raw:e};return ce.getState().upsertTask(s,a),js(s,a),a},Mt=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}),js=(s,e)=>{const t=K.getState(),n=t.getSessionTasks(s),o=Mt(e);if(n.some(r=>r.id===e.id||r.backendId===e.id)){t.updateTaskPlanStatus(s,e.id,o);return}t.setSessionTasks(s,[...n,o])},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 ls(s,e,t){const n=ft.getState(),o=G.getState(),r=ce.getState(),a=Ga(e);switch(s){case"plan_start":{o.startGeneration(t),Bt(t);const i=it(a,"Plan started");i&&n.setThinkingStatus(t,i),r.recordEvent(t,{type:s,source:"plan",title:"Plan started",message:i,status:"running",data:a});break}case"plan_thinking":{const i=it(a,"Analyzing request...");n.setThinkingStatus(t,i),Bt(t),o.setThinking(t,i),r.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=o.getMessages(t),d=l[l.length-1];(d==null?void 0:d.type)==="assistant"&&!d.content.trim()&&o.updateLastMessage(t,String(i))}else{const l=[...o.getMessages(t)].reverse().find(d=>d.type==="assistant");l!=null&&l.content&&n.setPlanContent(l.content)}o.endGeneration(t),r.recordEvent(t,{type:s,source:"plan",title:"Plan complete",message:it(a,"Plan complete"),status:"completed",data:a});break}case"plan_error":{const i=it(a,"Plan failed");Bt(t),o.updateLastMessage(t,`Plan failed: ${i}`),o.endGeneration(t,i),r.recordEvent(t,{type:s,source:"plan",title:"Plan failed",message:i,status:"failed",data:a});break}case"plan_tasks":{const i=za(a).map((l,d)=>is(l,t,d));r.setTasks(t,i,"plan"),K.getState().setSessionTasks(t,i.map(Mt)),r.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=is(a,t),l=s==="plan_task_start"?"running":Ee(s==="plan_task_result"?a.status||(a.error?"failed":"completed"):a.status||a.planStatus),d={...i,status:l,startedAt:i.startedAt||(l==="running"?Date.now():void 0),completedAt:i.completedAt||(l==="completed"||l==="failed"?Date.now():void 0)};r.upsertTask(t,d),js(t,d),r.recordEvent(t,{type:s,source:"plan",title:d.title,message:d.result||d.error||d.description,status:d.status,taskId:d.id,data:a});break}case"plan_task_complete":{const i=is(a,t),l=String(a.status||"")==="failed"||!!a.error,u={...i,status:l?"failed":"completed",completedAt:i.completedAt||Date.now()};r.upsertTask(t,u),js(t,u),r.recordEvent(t,{type:s,source:"plan",title:u.title,message:u.result||u.error||u.description,status:u.status,taskId:u.id,data:a});const p=u.title||`task ${u.id}`;l?W.error(`✘ ${p} 失败`,6e3):W.success(`✓ ${p} 完成`,4e3);break}case"step_prompt":{const i=it(a),l=(a==null?void 0:a.taskId)||(a==null?void 0:a.id);l&&r.upsertTask(t,{id:String(l),title:a.title||a.step||String(l),status:"running",source:"plan",description:i}),r.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 d=l?` [plan: ${l}]`:"";r.recordEvent(t,{type:s,source:"system",title:"Mode changed",message:`${(a==null?void 0:a.previousMode)||"unknown"} -> ${i||"unknown"}${d}`,status:(a==null?void 0:a.success)===!1?"failed":"completed",data:a});break}case"goal_created":{r.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,d)=>jn(l,t,d)):[];i.length>0&&(r.setTasks(t,i,"goal"),K.getState().setSessionTasks(t,i.map(Mt))),r.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=Va(t,a);r.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,d)=>jn(l,t,d)):[];i.length>0&&(r.setTasks(t,i,"goal"),K.getState().setSessionTasks(t,i.map(Mt))),r.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?Ee(a.status):void 0,data:a});break}}}function qa(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:Ja(s,t),detail:s,retryable:t!=="auth",timestamp:Date.now()}}function Ja(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 Ya(s,e,t){var o,r;const n=G.getState();switch(s){case"start":n.startGeneration(t),n.addMessage(t,{id:Ae(),type:"assistant",content:"",timestamp:Date.now()}),K.getState().touchSession(t);break;case"content":{let a=String(e||"");try{const l=JSON.parse(e);a=l.text||l.content||a}catch{}const i=a.replace(/\[FINISH\]/g,"");i&&n.appendToLastMessage(t,i)}break;case"thinking":{let a=String(e||""),i;try{const l=JSON.parse(e);a=l.text||l.content||a,i=typeof l.index=="number"?l.index:void 0}catch{}a&&n.appendToLastMessageThinking(t,a,i)}break;case"tool_call":try{const a=JSON.parse(e||"{}"),i=a.id||Ae(),l=typeof a.index=="number"?a.index:void 0,d=a.args||a.arguments||"",u=n.messagesBySession[t]||[],p=u[u.length-1];[...((o=p==null?void 0:p.steps)==null?void 0:o.flatMap(f=>f.toolCalls||[]))||[],...(p==null?void 0:p.toolCalls)||[]].find(f=>l!==void 0&&f.index===l||f.id===i)?n.updateToolCall(t,i,{args:d}):n.addToolCall(t,{id:i,index:l,name:a.name||"Unknown",args:d,status:"running",timestamp:Date.now()})}catch(a){X.warn("Failed to parse tool call",String(a))}break;case"tool_result":try{const a=JSON.parse(e||"{}"),l=G.getState().messagesBySession[t]||[],d=[];for(const f of l){const y=f.steps||[];for(const b of y)b.toolCalls&&d.push(...b.toolCalls);f.toolCalls&&d.push(...f.toolCalls)}const u=a.toolName,p=a.id,m=typeof a.index=="number"?a.index:void 0;let h;if(p&&(h=d.find(f=>f.id===p)),!h&&m!==void 0&&(h=d.find(f=>f.index===m&&f.name===u)),!h){const f=d.filter(y=>y.name===u&&y.status==="running");f.sort((y,b)=>(y.timestamp||0)-(b.timestamp||0)),h=f[0]}if(!h){const f=d.filter(y=>y.name===u&&y.status==="error"&&y.result==="生成已结束(工具执行超时或连接中断)");f.sort((y,b)=>(b.timestamp||0)-(y.timestamp||0)),h=f[0]}if(h){const f=Math.floor((Date.now()-(h.timestamp||Date.now()))/1e3),y=typeof a.result=="string"&&a.result.startsWith("Error:");n.updateToolCall(t,h.id,{status:y?"error":"completed",result:a.result,duration:f,...a.diff!==void 0?{diff:String(a.diff)}:{}})}}catch(a){X.warn("Failed to parse tool result",String(a))}break;case"tool_diff":try{const a=JSON.parse(e||"{}"),l=G.getState().messagesBySession[t]||[],d=[];for(const m of l){const h=m.steps||[];for(const f of h)f.toolCalls&&d.push(...f.toolCalls);m.toolCalls&&d.push(...m.toolCalls)}const u=d.filter(m=>m.name===a.toolName&&m.status==="running");u.sort((m,h)=>(m.timestamp||0)-(h.timestamp||0));const p=u[0];p&&typeof a.diff=="string"&&n.updateToolCall(t,p.id,{diff:a.diff})}catch(a){X.warn("Failed to parse tool diff",String(a))}break;case"turn_summary":{try{const a=JSON.parse(e||"{}"),i={};if(a.toolCounts&&typeof a.toolCounts=="object"&&!Array.isArray(a.toolCounts))for(const[l,d]of Object.entries(a.toolCounts)){const u=Number(d);Number.isFinite(u)&&u>0&&(i[l]=u)}n.setTurnSummary(t,{thoughtMs:Number(a.thoughtMs??a.durationMs??0)||0,durationMs:Number(a.durationMs??a.thoughtMs??0)||0,toolCounts:i,...typeof a.headline=="string"&&a.headline?{headline:a.headline}:{}})}catch(a){X.warn("Failed to parse turn_summary",String(a))}break}case"web_search":try{const a=JSON.parse(e||"{}"),i=a.callId||`web-search-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,l=typeof a.index=="number"?a.index:void 0,d=a.status==="searching"||a.status==="in_progress",u=a.status==="failed",p=n.messagesBySession[t]||[],m=p[p.length-1],f=[...((r=m==null?void 0:m.steps)==null?void 0:r.flatMap(y=>y.toolCalls||[]))||[],...(m==null?void 0:m.toolCalls)||[]].find(y=>y.id===i||l!==void 0&&y.index===l&&y.name==="web_search");f?d||n.updateToolCall(t,f.id,{status:u?"error":"completed",result:u?"❌ 联网搜索失败":a.searchUrl?`✅ 搜索完成:${a.searchUrl}`:"✅ 搜索完成"}):n.addToolCall(t,{id:i,index:l,name:"web_search",args:"{}",status:d?"running":"completed",result:d?void 0:u?"❌ 联网搜索失败":a.searchUrl?`✅ 搜索完成:${a.searchUrl}`:"✅ 搜索完成",timestamp:Date.now()})}catch(a){X.warn("Failed to parse web_search",String(a))}break;case"complete":n.endGeneration(t);{const a=G.getState().messagesBySession[t]||[];a.length>0&&Y.getState().recalculateFromMessages(a)}K.getState().touchSession(t);break;case"generation_paused":n.pauseGeneration(t);break;case"generation_resumed":n.resumeGeneration(t);break;case"compaction_progress":try{const a=JSON.parse(e||"{}");Y.getState().setCompactionProgress({stage:a.stage||"",percent:a.percent||0,message:a.message||""})}catch(a){console.error("Failed to parse compaction_progress:",a)}break;case"context_compressed":try{const a=JSON.parse(e||"{}"),i=`Context compressed: ${a.originalCount} -> ${a.compressedCount} msgs, freed ${a.tokensSaved} tokens`;n.appendToLastMessage(t,`
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
${i}
|
|
11
|
+
|
|
12
|
+
`),W.info(i,5e3),Y.getState().setCompacting({originalCount:a.originalCount||0,compressedCount:a.compressedCount||0,tokensSaved:a.tokensSaved||0}),Y.getState().setCompactionProgress(null)}catch(a){console.error("Failed to parse context_compressed:",a)}break;case"error":{n.endGeneration(t);const a=typeof e=="string"?e:String(e||"Error occurred"),i=qa(a),l=n.messagesBySession[t]||[],d=l[l.length-1];d&&d.type==="assistant"&&!d.errorCard?n.attachErrorCard(t,i):n.addMessage(t,{id:Ae(),type:"assistant",content:"",timestamp:Date.now(),errorCard:i}),K.getState().touchSession(t);break}case"context_analysis":try{const a=JSON.parse(e||"{}");a&&a.total!==void 0&&Y.getState().setContextDistribution(a)}catch(a){console.error("Failed to parse context_analysis:",a)}break;case"threshold_warning":try{const a=JSON.parse(e||"{}");Y.getState().setThresholdWarning(a);const i=a.percentLeft!==void 0?a.percentLeft:0;i<=5?console.warn(`Context nearly full (${i}% remaining)`):i<=15&&console.info(`Context running low (${i}% remaining)`)}catch(a){console.error("Failed to parse threshold_warning:",a)}break;case"blocking_limit":try{const a=JSON.parse(e||"{}");Y.getState().setThresholdWarning(a),console.error(a.message||"Context blocked")}catch(a){console.error("Failed to parse blocking_limit:",a)}break;case"context_blocked":try{const a=JSON.parse(e||"{}");Y.getState().setThresholdWarning(a),console.error(a.message||"Context is full — generation blocked")}catch(a){console.error("Failed to parse context_blocked:",a)}break;case"tool_retry":try{const a=JSON.parse(e||"{}");Y.getState().setRetryState({active:a.attempt<(a.maxRetries||3),attempt:a.attempt||0,maxRetries:a.maxRetries||3,errorCategory:a.errorCategory||"unknown",toolName:a.toolName})}catch(a){console.error("Failed to parse tool_retry:",a)}break;case"model_fallback":try{const a=JSON.parse(e||"{}");console.warn(`Model fallback: ${a.fromModel||"?"} → ${a.toModel||"?"}`)}catch(a){console.error("Failed to parse model_fallback:",a)}break;case"tombstone":try{const i=JSON.parse(e||"{}").messageIds||[];i.length>0&&n.applyTombstone(t,i)}catch(a){X.warn("Failed to parse tombstone",String(a))}break;case"stall_detected":try{const a=JSON.parse(e||"{}"),i=a.attempt||0,l=a.maxRetries||3,d=a.reason||"no response from model";a.recovering?W.warning(`⚠ Generation stalled (${d}) — retrying ${i}/${l}`,8e3):W.error(`⚠ Generation stalled (${d}) — giving up`,1e4)}catch(a){X.warn("Failed to parse stall_detected",String(a))}break}}const Ms=be()((s,e)=>({backendCommands:[],loaded:!1,setBackendCommands:t=>{s({backendCommands:t,loaded:!0})},getAllCommands:()=>e().backendCommands}));async function Qa(s="",e){try{let t=`${s}/api/commands`;e&&(t+=`?lang=${encodeURIComponent(e)}`);const n=await fetch(t);if(!n.ok)return[];const o=await n.json(),r=Array.isArray(o==null?void 0:o.data)?o.data:[];return Ms.getState().setBackendCommands(r),r}catch{return[]}}function cs(s,e,t,n,o){var r,a,i;switch(s){case"token_update":try{const d=typeof e=="string"?JSON.parse(e):e||{};if(d.source==="workflow"){Y.getState().addWorkflowTokens(Number(d.workflowNodeTokens)||0);break}d.totalTokens>0&&Y.getState().updateUsage({promptTokens:d.promptTokens||0,completionTokens:d.completionTokens||0,totalTokens:d.totalTokens||0}),d.model&&Y.getState().setModel(d.model)}catch{}break;case"model_name":try{const d=o&&typeof o.model=="string"&&o.model||(typeof e=="string"?e:(e==null?void 0:e.model)||"");d&&Y.getState().setModel(d)}catch{}break;case"auth_required":let l=localStorage.getItem("auth_token");l||(l="default-token",localStorage.setItem("auth_token",l)),F.setToken(l),F.setAuthenticated(!1),F.send({type:"auth",token:l});break;case"auth_success":F.setAuthenticated(!0),F.send({type:"subscribe_logs"});{const d=Ke.getState();Qa("",(r=d.language)!=null&&r.startsWith("zh")?"zh":"en");const u=d.workspaceDir;u&&F.send({type:"workspace",message:u})}break;case"auth_failed":X.error("Auth failed",String(e));break;case"log":try{const d=typeof e=="string"?JSON.parse(e):e,u={id:`log-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,level:d.level||"info",source:d.source||"System",message:d.message||"",timestamp:d.timestamp||Date.now()};n.setLogs(p=>[...p,u].slice(-500)),n.activeTab!=="logs"&&n.setUnreadLogs(p=>p+1)}catch(d){X.warn("Failed to parse log entry",String(d))}break;case"commands_list":try{const d=JSON.parse(e||"[]");Ms.getState().setBackendCommands(Array.isArray(d)?d:[])}catch(d){X.warn("Failed to parse commands list",String(d))}break;case"command_start":break;case"command_complete":try{const u=((typeof e=="string"?JSON.parse(e):e||{}).result||"").toString();W.success(u.length>120?u.slice(0,120)+"...":u||"Command completed",4e3)}catch{}break;case"command_error":try{const d=typeof e=="string"?JSON.parse(e):e||{};W.error((d.error||"Command failed").toString(),6e3)}catch{}break;case"ping":F.send({type:"pong",data:Date.now().toString()});break;case"workspace_changed":try{const d=JSON.parse(e||"{}");d.newDir&&Ke.getState().setWorkspaceDir(d.newDir)}catch{}break;case"degradation_update":try{const d=typeof e=="string"?JSON.parse(e):e||{},u=d.active,p=d.mode||"normal",m=Number(d.retryCount)||0,h=Number(d.maxRetries)||0,f=d.message||"",b={normal:"normal",retrying:"retrying",alternative:"alternative model",degraded:"degraded",verifying:"verifying",verified_fail:"verify failed"}[p]||p;if(Y.getState().setDegradation({active:u,retryCount:m,maxRetries:h,mode:p,message:f,label:b}),u){const C=m>0?` (${m}/${h})`:"";W.warning(f||`API Degraded: ${b}${C}`,8e3),n.setLogs(k=>[...k,{id:`deg-${Date.now()}`,level:"warn",source:"Infrastructure",message:`Degradation: ${b} | ${f||"no details"}`,timestamp:Date.now()}].slice(-500))}else W.success("API Normal")}catch(d){X.warn("Degradation update parse error",String(d))}break;case"doctor_result":try{const d=typeof e=="string"?JSON.parse(e):e||{},u=d.overallStatus||d.status||"unknown",p=d.healthRate,m=d.issues||[],f={healthy:"healthy",degraded:"degraded",unhealthy:"unhealthy",unknown:"unknown"}[u]||u,y=typeof p=="number"?` (${Math.round(p*100)}%)`:"";if(u==="healthy")W.success(`Doctor: ${f}${y}`);else if(W.warning(`Doctor: ${f}${y}`,1e4),m&&m.length>0)for(const b of m)n.setLogs(C=>[...C,{id:`doctor-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,level:"warn",source:"Doctor",message:typeof b=="string"?b:b.message||JSON.stringify(b),timestamp:Date.now()}].slice(-500))}catch(d){X.warn("Doctor result parse error",String(d))}break;case"session_created":{try{const d=typeof e=="string"?JSON.parse(e):e||{};d.id&&(F.setSessionId(d.id),K.getState().updateSession(d.id,d))}catch{}typeof e=="string"&&e&&X.info(`Session event: ${s}`);break}case"session_resumed":{try{const d=typeof e=="string"?JSON.parse(e):e||{};if((a=d.session)!=null&&a.id&&(F.setSessionId(d.session.id),K.getState().updateSession(d.session.id,d.session)),d.messages&&Array.isArray(d.messages)){const u=((i=d.session)==null?void 0:i.id)||t;G.getState().replaceMessages(u,d.messages.map(h=>({id:h.id||`msg-${h.timestamp||Date.now()}`,type:h.type==="user"?"user":"assistant",content:h.content||"",timestamp:h.timestamp||Date.now(),thinking:h.thinking||void 0})));const p=d.messages.find(h=>h.type==="user"&&!h.deleted),m=typeof(p==null?void 0:p.content)=="string"?p.content.replace(/\s+/g," ").trim():"";K.getState().touchSession(u,m||void 0)}}catch(d){X.warn("Failed to process session_resumed",String(d))}typeof e=="string"&&e&&X.info(`Session event: ${s}`);break}case"mcp_update":try{const d=typeof e=="string"?JSON.parse(e):e||{},u=d.server||d.name||"MCP",p=d.action||d.status||"updated";X.info(`MCP ${u}: ${p}`)}catch{}break}}function Mc(s,e){switch(ya(s,e)){case"critical":return{level:"CRITICAL",reasonKey:"risk_critical"};case"high":return{level:"HIGH",reasonKey:/rm\s+-rf|sudo|chmod\s+777|curl.*\|\s*(ba)?sh|wget.*-O|>\/dev\/|mkfs/i.test(e)?"risk_critical_cmd":/write|edit|save|upload|deploy|publish/i.test(s)?"risk_high_file":/install|uninstall|npm|pip|cargo|gem|apt|brew|choco|yum|dnf/i.test(s)?"risk_high_pkg":"risk_high_shell"};case"low":return{level:"LOW",reasonKey:"risk_low"};default:return{level:"MEDIUM",reasonKey:/git|commit|push|merge|rebase/i.test(s)?"risk_git":"risk_network"}}}const Lc={CRITICAL:{bg:"bg-red-900/20",border:"border-red-500/40",text:"text-red-400",badge:"bg-red-500/20 text-red-400 border-red-500/30",icon:"🚨"},HIGH:{bg:"bg-orange-900/15",border:"border-orange-500/30",text:"text-orange-400",badge:"bg-orange-500/20 text-orange-400 border-orange-500/30",icon:"⚠️"},MEDIUM:{bg:"bg-yellow-900/10",border:"border-yellow-500/25",text:"text-yellow-400",badge:"bg-yellow-500/15 text-yellow-400 border-yellow-500/25",icon:"📋"},LOW:{bg:"bg-blue-900/10",border:"border-blue-500/25",text:"text-blue-400",badge:"bg-blue-500/15 text-blue-400 border-blue-500/25",icon:"✅"}};function Oc(s,e){return ba(s,e)}function Xa(s){try{const e=JSON.parse(s),t=e.payload&&typeof e.payload=="object"?e.payload:e,n=t.resolvedPath;if(typeof n=="string"&&n)return n;const o=t.requestedPath;return typeof o=="string"&&o?o:null}catch{return null}}function Za(s,e){var t;try{const n=typeof s=="string"?JSON.parse(s):s||{},o=Me.getState(),{approvalId:r,toolName:a,askPayload:i,timeoutMs:l,timeoutAction:d}=n,u=Ke.getState(),p=Xa(String(i||""));if(o.isSessionAllowed(a,p??void 0)||o.autoMode||(t=u==null?void 0:u.yolo)!=null&&t.enabled){F.send({type:"hook_allow",data:JSON.stringify({approvalId:r})});return}G.getState().addMessage(e,{id:`hook-approval-${r||Date.now()}`,type:"assistant",content:"",timestamp:Date.now(),hookApproval:{approvalId:r||"",toolName:a||"unknown",askPayload:i||"",status:"pending",timestamp:Date.now(),timeoutMs:typeof l=="number"?l:void 0,timeoutAction:d==="allow"||d==="deny"?d:void 0}}),o.addApproval({approvalId:r||"",toolName:a||"unknown",askPayload:i||"",timestamp:Date.now(),timeoutMs:typeof l=="number"?l:void 0,timeoutAction:d==="allow"||d==="deny"?d:void 0}),window.dispatchEvent(new CustomEvent("hook-approval-required"))}catch{}}function ds(s,e){try{const t=typeof s=="string"?JSON.parse(s):s||{};typeof t.sessionId=="string"&&t.sessionId&&(e=t.sessionId);const n=K.getState(),o=ce.getState(),{action:r,taskId:a,data:i}=t;if(r==="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},d=n.tasksBySession[e]||[];n.setSessionTasks(e,[...d,l]),o.upsertTask(e,{id:l.id,title:l.title,description:l.description,status:Ee(i.status),source:"task",progress:i.progress!=null?Number(i.progress):void 0,raw:t})}else if((r==="updated"||r==="status_changed")&&i)n.updateTaskPlanStatus(e,a,{backendStatus:i.status,progress:i.progress}),o.upsertTask(e,{id:a,title:i.title||a,description:i.description,status:Ee(i.status),source:"task",progress:i.progress!=null?Number(i.progress):void 0,raw:t});else if(r==="deleted"){const l=n.tasksBySession[e]||[];n.setSessionTasks(e,l.filter(d=>d.id!==a&&d.backendId!==a))}else if(t&&!r&&(t.id||t.taskId)){const l=String(t.id||t.taskId),d=t,u=String(d.status||"").toUpperCase()==="COMPLETED",p={id:l,title:String(d.title||d.name||l),completed:u,createdAt:Date.parse(d.createdAt)||Date.now(),backendId:l,backendStatus:d.status,description:d.description,progress:d.progress!=null?Number(d.progress):void 0},m=n.getSessionTasks(e);m.some(h=>h.id===l||h.backendId===l)?n.updateTaskPlanStatus(e,l,{backendStatus:d.status,progress:p.progress,completed:u}):n.setSessionTasks(e,[...m,p]),o.upsertTask(e,{id:l,title:p.title,description:p.description,status:Ee(d.status),source:"task",progress:p.progress,raw:t})}o.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:r||"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 ei(s,e,t,n){try{const o=JSON.parse(e||"{}"),r=n(t,s,o);if(r){const a=G.getState();switch(s){case"step_start":a.updateStep(t,r.id,{title:o.step||r.title,description:o.description||r.description,status:o.status==="start"?"running":o.status||"running"});break;case"step_thinking":a.updateStep(t,r.id,{thought:o.thought});break;case"step_action":a.updateStep(t,r.id,{action:o.action});break;case"step_complete":a.updateStep(t,r.id,{status:o.status??"success",result:o.result});break}}}catch(o){X.warn("Failed to parse "+s,String(o))}}function ti(s,e){var t,n;try{const o=typeof s=="string"?JSON.parse(s):s||{};let r=[];if(Array.isArray(o)?r=o:(t=o.tasks)!=null&&t.length?r=o.tasks:(n=o.items)!=null&&n.length&&(r=o.items),r.length>0&&e){const a=K.getState(),i=ce.getState();r.forEach(l=>{const d=l.content||l.title||l.name||"";if(d.trim()){if(!a.getSessionTasks(e).find(f=>f.title===d.trim())&&(a.addSessionTask(e,d.trim()),l.completed||l.status==="completed"||l.status==="COMPLETED"||l.status==="done"||l.activeForm==="completed")){const b=a.getSessionTasks(e).find(C=>C.title===d.trim());b&&a.toggleSessionTask(e,b.id)}const m=String(l.id||l.taskId||d.trim()),h=l.completed||l.status==="completed"||l.status==="COMPLETED"||l.status==="done"||l.activeForm==="completed";i.upsertTask(e,{id:m,title:d.trim(),description:l.description,status:Ee(l.status,h),source:"todo",raw:l})}}),i.recordEvent(e,{type:"todo_update",source:"todo",title:"Todo list updated",message:`${r.length} items`,status:"updated",data:o})}}catch{}}function si(s,e){try{const t=typeof s=="string"?JSON.parse(s):s||{},n=t.questionId||"",o=t.question||"";if(!n||!o)return;const r=Array.isArray(t.questions)?t.questions.map(a=>({question:String(a.question||""),header:a.header?String(a.header):void 0,options:Array.isArray(a.options)?a.options:void 0,multiSelect:a.multiSelect===!0})).filter(a=>a.question):[{question:o,header:t.header||void 0,options:Array.isArray(t.options)?t.options:void 0,multiSelect:t.multiSelect===!0}];window.__pendingQuestion={questionId:n,question:o,header:t.header||void 0,options:Array.isArray(t.options)?t.options:void 0,multiSelect:t.multiSelect===!0,autoResolutionMs:typeof t.autoResolutionMs=="number"?t.autoResolutionMs:void 0,questions:r},window.dispatchEvent(new CustomEvent("ask-question-required"))}catch{}}function ni(s,e){try{const t=typeof s=="string"?JSON.parse(s):s||{},n=t.title||t.name||"";if(n&&e){const r=K.getState().getSessionTasks(e).find(a=>a.title===n&&!a.completed);r&&K.getState().toggleSessionTask(e,r.id),ce.getState().upsertTask(e,{id:(r==null?void 0:r.id)||n,title:n,status:"completed",source:"todo"}),ce.getState().recordEvent(e,{type:"todo_item_done",source:"todo",title:n,status:"completed",taskId:(r==null?void 0:r.id)||n,data:t})}}catch{}}function lt(s){if(!s)return null;try{return JSON.parse(s)}catch{return null}}const ct=be((s,e)=>({items:[],pendingCount:0,audit:[],auditTotal:0,automations:[],runsByAutomation:{},loading:!1,error:null,fetchInbox:async()=>{const t=await V.inbox.list({state:"all"});if(t.success&&t.data){const n=t.data.items;s({items:n,pendingCount:n.filter(o=>o.state==="pending").length})}else s({error:t.error||"加载 Inbox 失败"})},resolveInbox:async(t,n)=>{const o=await V.inbox.resolve(t,n);return o.success?(await e().fetchInbox(),!0):(s({error:o.error||"解决失败"}),!1)},fetchAudit:async t=>{const n=await V.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 V.automations.list();t.success&&t.data?s({automations:t.data}):s({error:t.error||"加载自动化失败"})},createAutomation:async t=>{const n=await V.automations.create(t);return n.success&&n.data?(await e().fetchAutomations(),n.data):(s({error:n.error||"创建自动化失败"}),null)},deleteAutomation:async t=>{const n=await V.automations.remove(t);return n.success?(await e().fetchAutomations(),!0):(s({error:n.error||"删除失败"}),!1)},toggleAutomation:async(t,n)=>{const o=await V.automations.toggle(t,n);o.success?await e().fetchAutomations():s({error:o.error||"切换失败"})},runAutomation:async t=>{const n=await V.automations.run(t);n.success?(await e().fetchRuns(t),await e().fetchAutomations()):s({error:n.error||"触发失败"})},fetchRuns:async t=>{const n=await V.automations.runs(t);n.success&&n.data&&s(o=>({runsByAutomation:{...o.runsByAutomation,[t]:n.data}}))},onInboxPending:t=>{s(n=>({items:[t,...n.items.filter(o=>o.id!==t.id)],pendingCount:n.pendingCount+1}))},onInboxResolved:t=>{s(n=>{var o;return{items:n.items.map(r=>r.id===t.id?t:r),pendingCount:Math.max(0,n.pendingCount-(t.state==="resolved"&&((o=n.items.find(r=>r.id===t.id))==null?void 0:o.state)==="pending"?1:0))}})},onAuditRecord:t=>{s(n=>({audit:[t,...n.audit].slice(0,200)}))},onAutomationUpdate:t=>{s(n=>({automations:n.automations.some(r=>r.id===t.id)?n.automations.map(r=>r.id===t.id?t:r):[...n.automations,t]}))},onAutomationRun:t=>{s(n=>({runsByAutomation:{...n.runsByAutomation,[t.automationId]:[t,...n.runsByAutomation[t.automationId]||[]].slice(0,50)}}))}})),dt={pending:s=>{const e=lt(s);e&&ct.getState().onInboxPending(e)},resolved:s=>{const e=lt(s);e&&ct.getState().onInboxResolved(e)},auditRecord:s=>{const e=lt(s);e&&ct.getState().onAuditRecord(e)},automationUpdate:s=>{const e=lt(s);e!=null&&e.automation&&ct.getState().onAutomationUpdate(e.automation)},automationRun:s=>{const e=lt(s);e!=null&&e.run&&ct.getState().onAutomationRun(e.run)}};function oi(s,e,t){let n={};if(e&&typeof e=="object")n=e;else try{n=JSON.parse(String(e||"{}"))}catch{}const o=String(n.jobId||`fjob-${Date.now()}`),r=n.stage||(s==="filejob_result"?"complete":s==="filejob_error"?"error":"uploaded"),a={jobId:o,stage:r,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 ri=be((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 V.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 r=n[0].type;s({selectedType:r})}},create:async t=>{const n=await V.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 o=await V.channels.update(t,n);return o.success?(await e().load(),s({formOpen:!1,editing:null}),!0):(s({error:o.error??"Update failed"}),!1)},remove:async t=>{const n=await V.channels.delete(t);return n.success?(s(o=>({channels:o.channels.filter(r=>r.id!==t)})),!0):(s({error:n.error??"Delete failed"}),!1)},toggle:async(t,n)=>(await V.channels.toggle(t,n)).success?(s(r=>({channels:r.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(o=>o.id===t.channelId?{...o,connected:t.connected,_state:t.state}:o)}))}})),ai=["start","content","thinking","tool_call","tool_result","tool_diff","turn_summary","web_search","complete","generation_paused","generation_resumed","error","context_compressed","compaction_progress","tombstone","context_analysis","threshold_warning","blocking_limit","tool_retry","model_fallback","context_blocked","stall_detected"],As=(s,e=[])=>{if(!s)return e;if(Array.isArray(s))return s.forEach(o=>As(o,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(([o,r])=>{o!=="content"&&o!=="structuredOutput"&&As(r,e)}),e},ii=s=>{const e=As(s);return e[e.length-1]||""};function li({activeTab:s,setLogs:e,setUnreadLogs:t}){const n=G,o=g.useCallback(d=>{if(!d)return{};if(typeof d=="object")return d;if(typeof d!="string")return{};try{return JSON.parse(d)}catch{return{}}},[]),r=g.useCallback((d,u,p)=>{const m=o(u),h=m.runId||"";if(!h)return;const f=ce.getState(),y=G.getState();if(d==="workflow_error"){f.fail(p,h,m.error||"Workflow failed"),(y.isGenerating(p)||y.isPaused(p))&&y.endGeneration(p,m.error||"Workflow failed");return}const b=d==="workflow_finished"?m.status||"COMPLETED":d==="workflow_started"?m.status||"RUNNING":d==="workflow_paused"?m.status||"PAUSED":d==="workflow_resumed"?m.status||"RESUMING":d==="workflow_cancelled"?m.status||"CANCELLED":d==="workflow_recovered"?m.status||"RUNNING":m.status||void 0,C=m.type||d,k=m.data&&typeof m.data=="object"?m.data:{},T=String(m.kind||k.kind||""),_=m.nodeId||m.node_id||k.nodeId||k.node_id,w=m.role||m.agentRole||m.agent_role||k.role||k.agentRole||k.agent_role,E=m.phase||m.phaseId||k.phase||k.phaseId,N=m.effectId||k.effectId||_,L=m.toolName||m.tool_name||k.toolName||k.tool_name,$=m.error||k.error,U=["effect.scheduled","effect.completed","effect.failed"].includes(C)&&_&&T!=="tool",de=["effect.scheduled","effect.completed","effect.failed"].includes(C)&&T==="tool"&&(L||_),A=_?f.getAgentsForSession(p).find(S=>S.id===String(_)):void 0;if(f.upsert(p,{runId:h,status:b,completedPhases:Number(m.completedPhases||0),totalPhases:Number(m.totalPhases||0),completedEffects:Number(m.completedEffects||0),totalEffects:Number(m.totalEffects||0),tokensUsed:Number(m.tokensUsed||0),tokensRemaining:Number(m.tokensRemaining||0),lastEventType:C,agentNode:U?{nodeId:String(_),role:String(w||(A==null?void 0:A.role)||(A==null?void 0:A.name)||"agent"),phase:E?String(E):A==null?void 0:A.phase,status:C==="effect.failed"?"failed":C==="effect.completed"?"completed":"scheduled",tokens:m.tokensUsed!=null?Number(m.tokensUsed):k.tokens!=null&&typeof k.tokens=="number"?Number(k.tokens):void 0,error:$?String($):void 0,updatedAt:Date.now()}:void 0}),de){const S=C==="effect.failed"?"failed":C==="effect.completed"?"completed":"running",P=String(N||`${h}-${L||_}`);f.upsertTask(p,{id:P,title:String(L||_),description:_?String(_):void 0,status:S,source:"workflow",runId:h,result:k.artifactRef?String(k.artifactRef):void 0,error:$?String($):void 0,raw:m}),f.recordEvent(p,{type:C,source:"workflow",title:String(L||_),status:S,runId:h,taskId:P,message:$?String($):void 0,data:m})}if(d==="workflow_started")y.startGeneration(p);else if(d==="workflow_finished"){const S=ii(m.output);if(S){const P=y.getMessages(p),H=P[P.length-1];(H==null?void 0:H.type)==="assistant"?y.appendToLastMessage(p,S):y.addMessage(p,{id:Ae(),type:"assistant",content:S,timestamp:Date.now()})}y.endGeneration(p)}else b==="PAUSED"?y.pauseGeneration(p):(b==="RUNNING"||b==="RESUMING")&&y.resumeGeneration(p)},[o]),a=g.useCallback(d=>{var h;const p=n.getState().messagesBySession[d]||[],m=p[p.length-1];return(h=m==null?void 0:m.steps)==null?void 0:h[m.steps.length-1]},[n]),i=g.useCallback((d,u,p)=>{const m=a(d),h=u==="step_complete",f=m&&(m.status==="success"||m.status==="error");if(!m||f&&!h){const y=(p==null?void 0:p.step)||u.replace("step_","").replace("_"," ");return n.getState().addStep(d,{id:`step-${Date.now()}`,title:y,description:(p==null?void 0:p.description)||"Executing...",status:"running",timestamp:Date.now()}),a(d)}return m},[a,n]),l=g.useCallback(d=>{const u=d.type,p=d.data;if(u==="model_name"){cs(u,p,d.sessionId||"",{activeTab:s,setLogs:e,setUnreadLogs:t},d);return}if(u==="models_updated"||u==="models.updated"){window.dispatchEvent(new CustomEvent("models-updated"));return}if(u==="workspace_changed"){cs(u,p,d.sessionId||"",{activeTab:s,setLogs:e,setUnreadLogs:t});return}const m=d.sessionId||"";if(!m){if(u==="task_update"||u==="task_finished"||u==="task_error"){const h=o(p);h&&typeof h.sessionId=="string"&&h.sessionId&&ds(p,h.sessionId)}return}if(u==="hook_ask"){Za(p,m);return}if(u==="ask_user_question"){si(p);return}if(u==="question_answer_ack"){window.dispatchEvent(new CustomEvent("ask-question-dismiss"));return}if(u==="task_update"){ds(p,m);return}if(u==="task_output"){try{n.getState().appendToLastMessage(m,String(p||""))}catch{}return}if(u==="task_finished"||u==="task_error"){u==="task_error"?X.error("Task error",String(p)):ds(p,m);return}if(u==="filejob_start"||u==="filejob_progress"||u==="filejob_result"||u==="filejob_error"){oi(u,p,m);return}if(u.startsWith("step_")){ei(u,p,m,i);return}if(u.startsWith("plan_")){try{ls(u,p,m)}catch(h){X.error(`Failed to handle ${u}`,String(h))}return}if(u.startsWith("goal_")){try{ls(u,p,m)}catch(h){X.error(`Failed to handle ${u}`,String(h))}return}if(u==="step_prompt"){try{ls(u,p,m)}catch(h){X.error(`Failed to handle ${u}`,String(h))}return}if(u==="todo_update"){ti(p,m);return}if(u==="todo_item_done"){ni(p,m);return}if(u!=="todo_progress"){if(u==="inbox.pending"){dt.pending(p);return}if(u==="inbox.resolved"){dt.resolved(p);return}if(u==="audit.record"){dt.auditRecord(p);return}if(u==="automation.update"){dt.automationUpdate(p);return}if(u==="automation.run"){dt.automationRun(p);return}if(u!=="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(u)){r(u,p,m);return}if(ai.includes(u)){Ya(u,p,m);return}if(u==="channel_status"){try{const h=JSON.parse(p||"{}");ri.getState().updateChannelStatus(h)}catch{}return}if(u==="channel_message"||u==="channel_error"){try{const h=typeof p=="string"?JSON.parse(p):p||{},f=h.channel||h.platform||"Channel";if(u==="channel_error")W.error(`${f}: ${h.error||h.message||"channel error"}`);else{const y=h.from||h.sender||"",b=h.text||h.content||h.message||"";b&&W.info(`📨 ${f}${y?` · ${y}`:""}: ${String(b).slice(0,120)}`)}}catch{}return}if(u==="session_switched"){try{const h=typeof p=="string"?JSON.parse(p):p||{},f=h.id||h.sessionId||(typeof p=="string"?p:"");f&&K.getState().setActiveSession(String(f))}catch{}return}if(u==="task_interrupted"){try{const h=typeof p=="string"?JSON.parse(p):p||{},f=h.title||h.taskId||"Task";W.warning(`⏸ ${f} interrupted — 使用 /continue 恢复生成`,1e4)}catch{W.warning("A running task was interrupted",1e4)}return}if(u==="code_review_ready"){try{const h=typeof p=="string"?JSON.parse(p):p||{},f=h.title||h.skillId||"Code Review",y=h.summary||"";W.success(`🔍 ${f} ready${y?`: ${String(y).slice(0,120)}`:""}`,8e3)}catch{W.success("🔍 Code review ready",8e3)}return}if(u==="hook_auto_ack"){try{const h=typeof p=="string"?JSON.parse(p):p||{};W.info(`Hook auto-approved: ${h.tool||h.name||"tool"}`,4e3)}catch{}return}if(u==="throttle"){try{const h=typeof p=="string"?JSON.parse(p):p||{},f=h.limit||h.remaining!=null?` (${h.remaining} left)`:"";W.warning(`⚠ Rate limited${f}`,6e3)}catch{}return}if(["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(u)){cs(u,p,m,{activeTab:s,setLogs:e,setUnreadLogs:t});return}}}},[s,i,r,o,e,t]);g.useEffect(()=>{F.connect();const d=F.onMessage(l),u=F.onClose(()=>{const p=G.getState();for(const m of p.generatingSessions)p.endGeneration(m,"WebSocket disconnected")});return()=>{d(),u()}},[l])}const gt={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"}}},Es="linear";function An(s,e,t){const n=gt[s]||gt[Es];if(!n)return{bg:"#fcfaf8",surface:"#f6f1ea",border:"#e7dfd5",text:"#26251e",muted:"#5a574f",accentBlue:"#26251e",accentGreen:"#1f7a4d",accentRed:"#b84f42",accentYellow:"#a16b2d",accentPurple:"#7a5c8f"};const o={...e==="dark"?n.dark:n.light};return t&&Object.assign(o,t),o}const Ne=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}`},ci=(s,e,t)=>{const n=[parseInt(s.slice(1,3),16),parseInt(s.slice(3,5),16),parseInt(s.slice(5,7),16)],o=[parseInt(e.slice(1,3),16),parseInt(e.slice(3,5),16),parseInt(e.slice(5,7),16)];return n.map((r,a)=>Math.round(r+((o[a]??r)-r)*t)).join(" ")};function En(s,e,t,n,o){t.classList.toggle("dark",s==="dark"),t.classList.toggle("light",s==="light"),t.style.setProperty("--color-bg",Ne(e.bg)),t.style.setProperty("--color-surface",Ne(e.surface)),t.style.setProperty("--color-border",Ne(e.border)),t.style.setProperty("--color-text",Ne(e.text)),t.style.setProperty("--color-muted",Ne(e.muted)),t.style.setProperty("--color-accent-blue",Ne(e.accentBlue)),t.style.setProperty("--color-accent-green",Ne(e.accentGreen)),t.style.setProperty("--color-accent-red",Ne(e.accentRed)),t.style.setProperty("--color-accent-yellow",Ne(e.accentYellow)),t.style.setProperty("--color-accent-purple",Ne(e.accentPurple)),t.style.setProperty("--color-hover",ci(e.surface,e.text,.06)),n&&n.setAttribute("content",e.bg),o&&o.setAttribute("content",s)}function di({theme:s,themePresetId:e,customTheme:t,customThemeEnabled:n}){g.useEffect(()=>{const o=document.documentElement,r=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,d=An(e||Es,i,l);if(En(i,d,o,r,a),s==="auto"){const u=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{const m=u.matches?"dark":"light",h=An(e||Es,m,l);En(m,h,o,r,a)};return u.addEventListener("change",p),()=>u.removeEventListener("change",p)}},[s,e,t,n])}class Bn extends g.Component{constructor(t){super(t);se(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:c.jsx("div",{className:"flex items-center justify-center h-full w-full bg-dark-bg",children:c.jsxs("div",{className:"max-w-md p-8 text-center",children:[c.jsx("div",{className:"flex justify-center mb-4",children:c.jsx("div",{className:"w-16 h-16 rounded-full bg-accent-red/10 flex items-center justify-center",children:c.jsx(Rs,{size:32,className:"text-accent-red"})})}),c.jsx("h2",{className:"text-xl font-semibold text-dark-text mb-2",children:"页面出现错误"}),c.jsx("p",{className:"text-sm text-dark-muted mb-6",children:((t=this.state.error)==null?void 0:t.message)||"发生了未知错误,请尝试刷新页面"}),c.jsxs("div",{className:"flex items-center justify-center gap-3",children:[c.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:[c.jsx(Un,{size:16}),"重试"]}),c.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 ui=g.memo(function(e){const{t}=Be(),n=Y(S=>S.currentUsage),o=Y(S=>S.maxContextTokens),r=Y(S=>S.model),a=Y(S=>S.tokenRate),i=Y(S=>S.compactingUntil),l=Y(S=>S.lastCompactInfo),d=Y(S=>S.degradation),u=Y(S=>S.compactionProgress),p=K(S=>S.activeSessionId),m=G(S=>p?S.isGenerating(p):!1),h=ce(S=>p?S.bySession[p]:void 0),f=ce(S=>p?S.getRunningAgentCount(p):0),y=ft(S=>S.mode),b=Me(S=>S.autoMode),[C,k]=g.useState(0),T=g.useRef(0);g.useEffect(()=>{if(m&&!T.current&&(T.current=Date.now()),!m){T.current=0,k(0);return}const S=setInterval(()=>k(Math.floor((Date.now()-T.current)/1e3)),1e3);return()=>clearInterval(S)},[m]);const _=n.totalTokens,w=n.promptTokens,E=n.completionTokens,N=o>0?Math.min(100,Math.round(n.totalTokens/o*100)):0,L=fa(a),$=y==="normal"?"act":y,U=ma[$],de=ve($),A=de==="plan"?"border-accent-blue/30 text-accent-blue":de==="goal"?"border-accent-purple/30 text-accent-purple":"border-accent-green/30 text-accent-green";return c.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:[c.jsx("span",{className:"font-semibold text-dark-text whitespace-nowrap",children:"DeepSeekCode"}),c.jsx("span",{className:`px-2 py-0.5 rounded-full border whitespace-nowrap ${A}`,children:U.label}),b&&c.jsx("span",{className:"px-2 py-0.5 rounded-full border border-accent-yellow/30 text-accent-yellow whitespace-nowrap",children:"Auto"}),c.jsx("span",{className:"text-dark-muted truncate max-w-[14rem]",children:r||t("common.connecting")}),c.jsxs("span",{className:"hidden md:inline-flex items-center gap-1 text-dark-muted whitespace-nowrap",children:[c.jsx("span",{className:"text-dark-text",children:nt(w)}),c.jsx("span",{className:"text-dark-muted/60",children:"+"}),c.jsx("span",{className:"text-accent-green",children:nt(E)}),c.jsx("span",{className:"text-dark-muted/60",children:"="}),c.jsx("span",{className:"text-dark-text",children:nt(_)}),c.jsx("span",{className:"text-dark-muted/60",children:"/"}),c.jsx("span",{children:nt(o)})]}),c.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[c.jsx("span",{className:"w-16 lg:w-20 h-1.5 bg-dark-border/70 rounded-full overflow-hidden inline-flex",children:c.jsx("span",{className:`h-full transition-all rounded-full ${N>=90?"bg-accent-red":N>=70?"bg-accent-yellow":"bg-dark-text/70"}`,style:{width:`${N}%`}})}),c.jsxs("span",{className:N>=90?"text-accent-red font-bold":N>=70?"text-accent-yellow":"",children:[N,"%"]})]}),m&&c.jsxs(c.Fragment,{children:[c.jsxs("span",{className:"text-dark-text flex items-center gap-1 whitespace-nowrap",children:[c.jsx(bt,{size:12,className:"animate-spin"}),eo(C)]}),L&&c.jsx("span",{className:"text-accent-purple whitespace-nowrap",children:L})]}),f>0&&c.jsxs("span",{className:"text-dark-text whitespace-nowrap",children:[f," agent",f>1?"s":""]}),c.jsx("div",{className:"flex-1"}),h&&c.jsxs("span",{className:"hidden xl:flex items-center gap-2 text-[11px] text-dark-text whitespace-nowrap",children:[c.jsx("span",{className:"text-dark-muted",children:"wf"}),c.jsx("span",{className:"font-mono",children:h.status}),c.jsxs("span",{children:[h.completedPhases,"/",h.totalPhases||0]}),c.jsx("span",{className:"text-dark-muted",children:nt(h.tokensUsed)})]}),u&&c.jsxs("span",{className:"hidden lg:flex items-center gap-2 text-[11px] text-dark-text whitespace-nowrap",children:[c.jsx("span",{children:"compact"}),c.jsxs("span",{children:[u.percent,"%"]}),c.jsx("span",{className:"w-20 h-1.5 bg-dark-border/70 rounded-full overflow-hidden",children:c.jsx("span",{className:"h-full bg-dark-text/70 rounded-full block",style:{width:`${u.percent}%`}})})]}),!u&&Date.now()<i&&l&&c.jsxs("span",{className:"hidden lg:inline text-dark-muted text-[11px] whitespace-nowrap",children:[l.originalCount," ","->"," ",l.compressedCount]}),(d==null?void 0:d.active)&&c.jsxs("span",{className:"text-accent-yellow text-[11px] whitespace-nowrap",children:[d.label," ",d.retryCount>0?`${d.retryCount}/${d.maxRetries}`:""]})]})}),_e=be()((s,e)=>({status:null,branches:null,loading:!1,refreshing:!1,lastAction:null,busy:!1,refreshStatus:async()=>{const t=await V.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 V.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 V.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 V.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 V.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}})),us="dsc-git-commit-draft",pi=g.memo(function(){const{t:e}=Be(),t=_e(w=>w.status),n=_e(w=>w.branches),o=_e(w=>w.busy),r=_e(w=>w.lastAction),a=Ke(w=>w.workspaceDir),[i,l]=g.useState(!1),[d,u]=g.useState(""),[p,m]=g.useState(!1),[h,f]=g.useState(null),y=g.useRef(null);g.useEffect(()=>{_e.getState().refreshAll();const w=setInterval(()=>{document.visibilityState==="visible"&&_e.getState().refreshStatus()},3e4);return()=>clearInterval(w)},[]),g.useEffect(()=>{const w=localStorage.getItem(us);w&&u(w)},[]);const b=g.useCallback(async()=>{try{const{api:w}=await he(async()=>{const{api:N}=await Promise.resolve().then(()=>ja);return{api:N}},void 0),E=await w.git.prStatus();E.success&&f(E.data||{available:!1,message:""})}catch{}},[]);g.useEffect(()=>{b()},[b]),g.useEffect(()=>{if(!i)return;const w=E=>{y.current&&!y.current.contains(E.target)&&l(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[i]);const C=g.useCallback(async()=>{const w=d.trim();if(!w){W.warning(e("git.emptyCommitMsg"));return}const N=await _e.getState().commit(w);N.ok?(W.success(e("git.commitSuccess")),m(!1),localStorage.removeItem(us),u("")):W.error(N.error||e("git.commitFailed"))},[d,e]),k=g.useCallback(async()=>{const E=await _e.getState().push();E.ok?W.success(e("git.pushSuccess")):W.error(E.error||e("git.pushFailed"))},[e]),T=g.useCallback(async w=>{const N=await _e.getState().checkout(w);N.ok?W.success(e("git.checkoutSuccess",{branch:w})):W.error(N.error||e("git.checkoutFailed"))},[e]),_=t&&t.available===!1;return c.jsxs("div",{ref:y,className:"relative",children:[c.jsxs("button",{onClick:()=>l(w=>!w),className:we("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:[c.jsx(Qs,{size:13,className:we(_?"text-dark-muted/50":"text-accent-blue")}),c.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)&&c.jsxs("span",{className:"hidden sm:flex items-center gap-1 text-[10px] font-mono tabular-nums",children:[c.jsxs("span",{className:"text-accent-green",children:["+",t.totalAdded??0]}),c.jsxs("span",{className:"text-accent-red",children:["−",t.totalRemoved??0]})]}),c.jsx(Ct,{size:11,className:we("transition-transform",i&&"rotate-180")})]}),i&&c.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:[c.jsxs("div",{className:"flex items-center gap-2 px-3.5 py-2.5 border-b border-dark-border bg-dark-surface",children:[c.jsx(Qs,{size:14,className:"text-accent-blue"}),c.jsx("span",{className:"text-xs font-medium text-dark-text",children:e("git.panelTitle")}),c.jsx("div",{className:"flex-1"}),c.jsx("button",{onClick:()=>void _e.getState().refreshAll(),className:"rounded p-1 text-dark-muted hover:text-dark-text hover:bg-dark-hover transition-colors",title:e("git.refresh"),children:c.jsx(Un,{size:12,className:we(_e.getState().refreshing&&"animate-spin")})})]}),_?c.jsxs("div",{className:"px-3.5 py-4 text-center",children:[c.jsx($o,{size:20,className:"mx-auto mb-2 text-dark-muted/50"}),c.jsx("div",{className:"text-xs text-dark-muted",children:e("git.notGitDesc")}),c.jsx("div",{className:"mt-1 text-[10px] font-mono text-dark-muted/60 break-all",children:a})]}):t?c.jsxs("div",{className:"p-3.5 space-y-3 max-h-[60vh] overflow-y-auto custom-scrollbar",children:[c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[c.jsx("span",{className:"text-[11px] text-dark-muted",children:e("git.changes")}),c.jsxs("span",{className:"text-[11px] font-mono tabular-nums",children:[c.jsxs("span",{className:"text-accent-green",children:["+",t.totalAdded??0]}),c.jsx("span",{className:"text-dark-muted/40",children:" / "}),c.jsxs("span",{className:"text-accent-red",children:["−",t.totalRemoved??0]})]})]}),c.jsxs("div",{className:"space-y-0.5 max-h-40 overflow-y-auto custom-scrollbar",children:[(t.changes||[]).slice(0,30).map(w=>c.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-mono",children:[c.jsx("span",{className:we("w-6 shrink-0 rounded px-1 text-center text-[9px]",w.status.includes("?")?"bg-accent-purple/15 text-accent-purple":w.status===w.status.toUpperCase()&&w.status.trim()?"bg-accent-green/15 text-accent-green":"bg-accent-yellow/15 text-accent-yellow"),children:w.status}),c.jsx("span",{className:"flex-1 truncate text-dark-text",children:w.path}),c.jsxs("span",{className:"shrink-0 text-[10px] tabular-nums text-dark-muted/60",children:[w.added>0&&c.jsxs("span",{className:"text-accent-green",children:["+",w.added]}),w.removed>0&&c.jsxs("span",{className:"text-accent-red",children:["−",w.removed]})]})]},w.path)),(t.changes||[]).length===0&&c.jsx("div",{className:"py-2 text-center text-[11px] text-dark-muted/60",children:e("git.clean")})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-[11px] text-dark-muted mb-1",children:e("git.branch")}),c.jsx("div",{className:"flex flex-wrap gap-1",children:((n==null?void 0:n.branches)||[t.branch||""]).slice(0,8).map(w=>c.jsx("button",{onClick:()=>w!==t.branch&&T(w),disabled:w===t.branch,className:we("rounded-md px-2 py-1 text-[11px] font-mono transition-colors",w===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:w},w))}),(t.ahead??0)>0||(t.behind??0)>0?c.jsxs("div",{className:"mt-1 text-[10px] text-dark-muted/70",children:[(t.ahead??0)>0&&c.jsxs("span",{className:"text-accent-green",children:["↑ ",t.ahead," "]}),(t.behind??0)>0&&c.jsxs("span",{className:"text-accent-yellow",children:["↓ ",t.behind]}),e("git.upstream")]}):null]}),c.jsx("div",{children:p?c.jsxs("div",{className:"space-y-1.5",children:[c.jsx("textarea",{value:d,onChange:w=>{u(w.target.value),localStorage.setItem(us,w.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"}),c.jsxs("div",{className:"flex gap-1.5",children:[c.jsxs("button",{onClick:C,disabled:o||!d.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:[o?c.jsx(bt,{size:12,className:"animate-spin"}):c.jsx(Xs,{size:12}),e("git.commitConfirm")]}),c.jsx("button",{onClick:()=>m(!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")})]})]}):c.jsxs("div",{className:"flex gap-1.5",children:[c.jsxs("button",{onClick:()=>m(!0),disabled:o,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:[c.jsx(Xs,{size:13}),e("git.commit")]}),c.jsxs("button",{onClick:k,disabled:o||!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:[c.jsx(Do,{size:13}),e("git.push")]})]})}),c.jsxs("div",{className:"flex items-center gap-1.5 rounded-md bg-dark-bg border border-dark-border px-2.5 py-2",children:[c.jsx(Ht,{size:13,className:"text-accent-purple shrink-0"}),c.jsx("span",{className:"text-[11px] text-dark-muted truncate",children:h?h.available?e("git.prReady"):h.message||e("git.prUnavailable"):e("git.prLoading")})]}),c.jsxs("div",{className:"rounded-md bg-dark-bg border border-dark-border px-2.5 py-2 space-y-0.5",children:[c.jsx("div",{className:"text-[10px] text-dark-muted",children:e("git.environment")}),c.jsx("div",{className:"text-[11px] font-mono text-dark-text/80 break-all",children:a||"—"}),t.lastCommit&&c.jsxs("div",{className:"text-[10px] font-mono text-dark-muted/60 truncate",children:[t.lastCommit.hash.slice(0,7)," ",t.lastCommit.subject]})]}),r&&c.jsxs("div",{className:we("flex items-center gap-1.5 text-[11px]",r.ok?"text-accent-green":"text-accent-red"),children:[r.ok?c.jsx(Fo,{size:12}):c.jsx(Wo,{size:12}),c.jsx("span",{className:"truncate",children:r.ok?e("git.ok"):r.error||""})]})]}):c.jsx("div",{className:"px-3.5 py-4 text-center text-xs text-dark-muted",children:e("git.loading")})]})]})}),mi={info:Gn,success:Ho,warning:Rs,error:Kn},hi={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"},fi=g.memo(function(){const{toasts:e,dismissToast:t}=De();return e.length===0?null:c.jsx("div",{className:"fixed bottom-20 right-4 z-[100] flex flex-col gap-2 max-w-sm",children:e.map(n=>{const o=mi[n.type];return c.jsxs("div",{className:`flex items-start gap-2 px-3 py-2.5 rounded-lg border shadow-lg animate-fade-in-up ${hi[n.type]}`,children:[c.jsx(o,{size:16,className:"shrink-0 mt-0.5"}),c.jsx("span",{className:"text-xs flex-1",children:n.message}),c.jsx("button",{onClick:()=>t(n.id),className:"shrink-0 p-0.5 rounded hover:bg-dark-hover/50 transition-colors",children:c.jsx(xt,{size:12})})]},n.id)})})}),gi={critical:{icon:Uo,border:"border-accent-red",bg:"bg-accent-red/10",text:"text-accent-red"},error:{icon:Kn,border:"border-accent-red/60",bg:"bg-accent-red/5",text:"text-accent-red"},warning:{icon:Rs,border:"border-accent-yellow/60",bg:"bg-accent-yellow/5",text:"text-accent-yellow"},info:{icon:Gn,border:"border-accent-blue/60",bg:"bg-accent-blue/5",text:"text-accent-blue"}},yi=g.memo(function(){const e=Je(n=>n.errors.filter(o=>!o.dismissed)),t=Je(n=>n.dismiss);return e.length===0?null:c.jsx("div",{className:"fixed bottom-4 right-4 z-[110] flex flex-col gap-2 max-w-sm",children:e.map(n=>{const o=gi[n.level],r=o.icon;return c.jsx(bi,{entry:n,icon:r,config:o,onDismiss:()=>t(n.id)},n.id)})})});function bi({entry:s,icon:e,config:t,onDismiss:n}){const[o,r]=g.useState(!1);return c.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:[c.jsxs("div",{className:"flex items-start gap-2",children:[c.jsx(e,{size:16,className:`shrink-0 mt-0.5 ${t.text}`}),c.jsx("span",{className:`text-xs flex-1 ${t.text}`,children:s.title}),c.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[s.detail&&c.jsx("button",{onClick:()=>r(!o),className:"p-0.5 rounded hover:bg-dark-hover/50 transition-colors",children:o?c.jsx(Ct,{size:12}):c.jsx(Bs,{size:12})}),c.jsx("button",{onClick:n,className:"p-0.5 rounded hover:bg-dark-hover/50 transition-colors",children:c.jsx(xt,{size:12})})]})]}),o&&s.detail&&c.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&&c.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 xi(s){const{t:e}=Be(),{setActiveTab:t,createNewSession:n,clearMessages:o,setTheme:r,setThemePreset:a,toggleTerminal:i,setLogs:l,setUnreadLogs:d}=s,u=Ms(S=>S.backendCommands),p=Array.isArray(u)?u:[],[m,h]=g.useState(!1),[f,y]=g.useState(""),[b,C]=g.useState(0),k=g.useRef(null),T=g.useCallback((S,P)=>{const H=K.getState().activeSessionId;return H?(F.setSessionId(H),F.send({type:"command_execute",sessionId:H,data:JSON.stringify({command:`/${S}`,args:P||""})}),{success:!0,message:e("slashCommands.sent_command")+`/${S}`}):{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"),d(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:()=>(o(),{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:S=>{const P=S.trim().toLowerCase();if(["dark","light","auto"].includes(P))return r(P),{success:!0,message:e("slashCommands.theme_result")+P};if(gt[P])return a?(a(P),{success:!0,message:e("slashCommands.theme_preset_result")+gt[P].nameKey}):{success:!1,message:e("slashCommands.theme_preset_unavailable")};const H=Object.keys(gt).join("|");return{success:!1,message:e("slashCommands.theme_error",{presets:H})}}},{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([]),d(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:S=>T("compact",S)},{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:S=>T("cost",S)},{id:"model",name:"model",description:e("slashCommands.model_desc"),args:"[model-name]",icon:"🤖",local:!1,action:S=>T("model",S)},{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:S=>T("config",S)},{id:"exit",name:"exit",description:e("slashCommands.exit_desc"),icon:"🚪",local:!1,action:()=>{const S=K.getState().activeSessionId;return S&&(F.setSessionId(S),F.send({type:"exit",sessionId:S})),{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:S=>T("test",S)}],[t,n,o,r,a,i,l,d,T,e]),w=g.useMemo(()=>p.map(S=>{const P=e(`slashCommands.${S.name}_desc`,S.description||S.usage||"");return{id:`backend-${S.name}`,name:S.name,description:P,icon:"🔌",local:!1,action:H=>{const q=K.getState().activeSessionId;return q?(F.setSessionId(q),F.send({type:"command_execute",sessionId:q,data:JSON.stringify({command:`/${S.name}`,args:H||""})}),{success:!0,message:e("slashCommands.sent_command")+`/${S.name}`}):{success:!1,message:e("slashCommands.noActiveSession")}}}}),[p,e]),E=g.useMemo(()=>{const S=new Set;return[..._,...w].filter(P=>S.has(P.name)?!1:(S.add(P.name),!0))},[_,w]),N=g.useMemo(()=>{if(!f)return E;const S=f.toLowerCase();return E.filter(P=>P.name.toLowerCase().includes(S)||P.description.toLowerCase().includes(S))},[E,f]),L=g.useCallback(()=>{h(!0),y(""),C(0)},[]),$=g.useCallback(()=>{h(!1),y(""),C(0)},[]),U=g.useCallback(()=>{C(S=>S>=N.length-1?0:S+1)},[N.length]),de=g.useCallback(()=>{C(S=>S<=0?N.length-1:S-1)},[N.length]),A=g.useCallback((S,P)=>{const H=S.action(P);return $(),H},[$]);return g.useEffect(()=>{if(m&&k.current){const S=k.current.querySelector(`[data-index="${b}"]`);S&&S.scrollIntoView({block:"nearest"})}},[b,m]),{isOpen:m,filter:f,setFilter:y,selectedIndex:b,setSelectedIndex:C,filteredCommands:N,allCommands:E,openMenu:L,closeMenu:$,selectNext:U,selectPrev:de,executeCommand:A,containerRef:k,commands:_}}function $c(s){const e=s.trim();if(!e.startsWith("/"))return null;const n=e.slice(1).split(/\s+/),o=n[0]||"",r=n.slice(1).join(" ");return{command:o,args:r}}function ki({open:s,onClose:e,options:t}){const{t:n}=Be(),{filter:o,setFilter:r,filteredCommands:a,selectedIndex:i,setSelectedIndex:l,selectNext:d,selectPrev:u,executeCommand:p,openMenu:m,closeMenu:h}=xi(t),f=g.useRef(null),y=g.useRef(null),[b,C]=g.useState(!1);if(g.useEffect(()=>{s?(m(),C(!1),setTimeout(()=>{var _;return(_=f.current)==null?void 0:_.focus()},0)):h()},[s,m,h]),g.useEffect(()=>{if(!s||!y.current)return;const _=y.current.querySelector(`[data-cmd-index="${i}"]`);_&&_.scrollIntoView({block:"nearest"})},[i,s]),!s)return null;const k=_=>{_.local||(C(!0),W.info(n("palette.running")));const w=p(_,"");_.local&&(w!=null&&w.message)&&W.success(w.message),e()},T=_=>{if(_.key==="ArrowDown")_.preventDefault(),d();else if(_.key==="ArrowUp")_.preventDefault(),u();else if(_.key==="Enter"){_.preventDefault();const w=a[i];w&&k(w)}else _.key==="Escape"&&(_.preventDefault(),e())};return c.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:c.jsxs("div",{className:"w-full max-w-xl bg-dark-surface border border-dark-border rounded-xl shadow-2xl overflow-hidden",onClick:_=>_.stopPropagation(),children:[c.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-dark-border",children:[c.jsx(Ko,{size:16,className:"text-dark-muted shrink-0","aria-hidden":"true"}),c.jsx("input",{ref:f,value:o,onChange:_=>{r(_.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"}),b&&c.jsx("span",{className:"text-[10px] text-accent-blue animate-pulse-soft shrink-0",children:n("palette.running")})]}),c.jsx("div",{ref:y,className:"max-h-[50vh] overflow-y-auto custom-scrollbar py-1",children:a.length===0?c.jsx("div",{className:"px-4 py-8 text-center text-sm text-dark-muted",children:n("palette.empty")}):a.map((_,w)=>c.jsxs("button",{"data-cmd-index":w,onClick:()=>k(_),onMouseEnter:()=>l(w),className:`w-full px-4 py-2.5 flex items-center gap-3 text-left transition-colors ${w===i?"bg-accent-blue/10 border-l-2 border-accent-blue":"border-l-2 border-transparent hover:bg-dark-hover"}`,children:[c.jsx("span",{className:"text-lg shrink-0","aria-hidden":"true",children:_.icon}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsxs("span",{className:"text-sm font-medium text-dark-text",children:["/",_.name]}),_.args&&c.jsx("span",{className:"text-xs text-dark-muted",children:_.args}),!_.local&&c.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")})]}),c.jsx("div",{className:"text-xs text-dark-muted truncate",children:_.description})]}),w===i&&c.jsx(Go,{size:14,className:"text-dark-muted shrink-0","aria-hidden":"true"})]},_.id))}),c.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 Re({keys:s,label:e}){return c.jsxs("div",{className:"flex items-center justify-between py-2 border-b border-dark-border/50 last:border-0",children:[c.jsx("span",{className:"text-sm text-dark-text",children:e}),c.jsx("span",{className:"flex items-center gap-1",children:s.map(t=>c.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 Si({open:s,onClose:e}){const{t}=Be(),n=navigator.platform.toLowerCase().includes("mac")?"⌘":"Ctrl";return c.jsx(Is,{isOpen:s,onClose:e,title:t("shortcuts.title"),size:"md",children:c.jsxs("div",{className:"space-y-0.5",children:[c.jsx(Re,{keys:[n,"K"],label:t("shortcuts.commandPalette")}),c.jsx(Re,{keys:[n,"L"],label:t("shortcuts.clearLogs")}),c.jsx(Re,{keys:[n,"/"],label:t("shortcuts.help")}),c.jsx(Re,{keys:[n,"Enter"],label:t("shortcuts.submit")}),c.jsx(Re,{keys:["Shift","Enter"],label:t("shortcuts.newline")}),c.jsx(Re,{keys:["/"],label:t("shortcuts.slashCommand")}),c.jsx(Re,{keys:["@"],label:t("shortcuts.fileRef")}),c.jsx(Re,{keys:["Esc"],label:t("shortcuts.closeDialog")}),c.jsx(Re,{keys:["Esc","Esc"],label:t("shortcuts.stopGen")})]})})}const vi={"pull-requests":Ht,scheduled:Ps,plugins:Ut},wi={"pull-requests":"Agent 发起的 PR 列表将在这里展示。配置 git 远端与 PR 提供方(如 GitHub CLI)后可用。",scheduled:"定时任务(如每晚跑测试数据)将在这里管理。",plugins:"插件管理入口。可启停文件处理技能等扩展能力。"};function Ci({tabId:s}){const{t:e}=Be(),t=vi[s]||Ut;return c.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-3 px-6 text-center",children:[c.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-2xl border border-dark-border bg-dark-surface",children:c.jsx(t,{size:24,className:"text-accent-blue"})}),c.jsx("h2",{className:"text-sm font-medium text-dark-text",children:e(`nav.${s}`)}),c.jsx("p",{className:"max-w-sm text-xs leading-relaxed text-dark-muted",children:wi[s]||"功能开发中…"}),c.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 _i=g.lazy(()=>he(()=>import("./ModelsView-CwhL9YPX.js"),__vite__mapDeps([0,1,2,3,4])).then(s=>({default:s.ModelsView}))),Ti=g.lazy(()=>he(()=>import("./ToolsView-CQgPyD6U.js"),__vite__mapDeps([5,1,2,3,4])).then(s=>({default:s.ToolsView}))),Ni=g.lazy(()=>he(()=>import("./AgentFlowView-qR01S0jV.js"),__vite__mapDeps([6,1,2,3,4])).then(s=>({default:s.AgentFlowView}))),ji=g.lazy(()=>he(()=>import("./SkillsView-DznSS50I.js"),__vite__mapDeps([7,1,2,3,4])).then(s=>({default:s.SkillsView}))),Ai=g.lazy(()=>he(()=>import("./AgentsView-CLvG8aae.js"),__vite__mapDeps([8,1,2,3,4])).then(s=>({default:s.AgentsView}))),Ei=g.lazy(()=>he(()=>import("./TemplatesTab-BPD0hvrG.js"),__vite__mapDeps([9,1,2,3,4])).then(s=>({default:s.TemplatesTab}))),Bi=g.lazy(()=>he(()=>import("./HookConfigView-BugHBHlO.js"),__vite__mapDeps([10,1,2,4,3])).then(s=>({default:s.HookConfigView}))),Pi=g.lazy(()=>he(()=>import("./FileTreeView-DL66cxki.js"),__vite__mapDeps([11,1,2,3,4])).then(s=>({default:s.FileTreeView}))),Ri=g.lazy(()=>he(()=>import("./TerminalView-B4WUBGzA.js"),__vite__mapDeps([12,1,2,13,3,4,14])).then(s=>({default:s.TerminalView}))),Ii=g.lazy(()=>he(()=>import("./SessionGrid-CC1NAZ45.js"),__vite__mapDeps([15,1,2,3,4])).then(s=>({default:s.SessionGrid}))),Mi=g.lazy(()=>he(()=>import("./SettingsPanel-n1UbEjzX.js"),__vite__mapDeps([16,1,2,3,4])).then(s=>({default:s.SettingsPanel}))),Li=g.lazy(()=>he(()=>Promise.resolve().then(()=>Ra),void 0).then(s=>({default:s.LogsPanel}))),Oi=g.lazy(()=>he(()=>import("./ChannelConfigView-DM70m5RE.js"),__vite__mapDeps([17,1,2,3,4])).then(s=>({default:s.ChannelConfigView}))),$i=g.lazy(()=>he(()=>import("./ConnectorsView-B5ndd8pU.js"),__vite__mapDeps([18,1,2,3,4])).then(s=>({default:s.ConnectorsView}))),Di=g.lazy(()=>he(()=>import("./InboxView-DLPWNrqG.js"),__vite__mapDeps([19,1,2,3,4])).then(s=>({default:s.InboxView}))),Fi=g.lazy(()=>he(()=>import("./AutomationView-wrcdqhJY.js"),__vite__mapDeps([20,1,2,3,4])).then(s=>({default:s.AutomationView}))),Wi=g.lazy(()=>he(()=>import("./AuditView-CMYlGV9S.js"),__vite__mapDeps([21,1,2,3,4])).then(s=>({default:s.AuditView}))),Pn=()=>c.jsx("div",{className:"flex-1 flex items-center justify-center bg-dark-bg",children:c.jsx("div",{className:"w-5 h-5 border-2 border-accent-blue border-t-transparent rounded-full animate-spin"})}),Ls=[{id:"chat",labelKey:"nav.chat",icon:Wt},{id:"terminal",labelKey:"nav.terminal",icon:zo},{id:"files",labelKey:"nav.files",icon:Vo},{id:"models",labelKey:"nav.models",icon:qo},{id:"tools",labelKey:"nav.tools",icon:Jo},{id:"skills",labelKey:"nav.skills",icon:Yo},{id:"agents",labelKey:"nav.agents",icon:Qo},{id:"templates",labelKey:"nav.templates",icon:Ot},{id:"hooks",labelKey:"nav.hooks",icon:Xo},{id:"channels",labelKey:"nav.channels",icon:Zo},{id:"connectors",labelKey:"nav.connectors",icon:er},{id:"inbox",labelKey:"nav.inbox",icon:tr},{id:"audit",labelKey:"nav.audit",icon:Ye},{id:"scheduled",labelKey:"nav.scheduled",icon:Ps},{id:"logs",labelKey:"nav.logs",icon:Ye},{id:"settings",labelKey:"nav.settings",icon:sr},{id:"pull-requests",labelKey:"nav.pullRequests",icon:Ht},{id:"plugins",labelKey:"nav.plugins",icon:Ut}],ps=Object.fromEntries(Ls.map(s=>[s.id,s.labelKey])),Hi=Ls.map(s=>({id:s.id,title:s.labelKey})),Ui=Object.fromEntries(Ls.map(s=>[s.id,s.icon]));function Ki(){const[s,e]=g.useState("chat"),[t,n]=g.useState(!1),[o,r]=g.useState([]),[,a]=g.useState(0),[i,l]=g.useState(!1),[d,u]=g.useState(!1),[p,m]=g.useState(!1),[h,f]=g.useState(!1),[y,b]=g.useState(null),[C,k]=g.useState(!1),[T,_]=g.useState(!1),[w,E]=g.useState({}),[N,L]=g.useState(()=>window.innerWidth>=1400),[$,U]=g.useState(()=>localStorage.getItem("dsc-sidebar-collapsed")==="1"),de=g.useCallback(()=>{U(v=>(localStorage.setItem("dsc-sidebar-collapsed",v?"0":"1"),!v))},[]);g.useEffect(()=>{const v=window.matchMedia("(min-width: 1400px)"),j=I=>L(I.matches);return v.addEventListener("change",j),()=>v.removeEventListener("change",j)},[]);const{t:A,i18n:S}=Be(),{toggleTerminal:P}=ca(),{theme:H,setTheme:q,setThemePreset:ne,language:ge,workspaceDir:ae,setWorkspaceDir:Fe}=Ke(),te=Me();g.useEffect(()=>{ge&&S.language!==ge&&S.changeLanguage(ge)},[ge,S]);const B=g.useMemo(()=>Hi.filter(v=>!(v.id==="terminal"&&y===!1)),[y]),D=g.useMemo(()=>B.map(v=>({...v,iconComponent:Ui[v.id]})),[B]),R=g.useCallback(v=>{g.startTransition(()=>{e(v)})},[]),[M,ue]=g.useState(null),oe=g.useCallback(v=>{ue({section:v,nonce:Date.now()})},[]);g.useEffect(()=>{const v=I=>{const z=I.message||A("common.unknownError"),re=I.filename||"global";re.includes("chrome-extension://")||re.includes("moz-extension://")||r(Z=>[...Z,{id:`error-${Date.now()}-${Ae()}`,level:"error",source:"Browser",message:`${A("toast.uncaughtError")}${z}`,timestamp:Date.now()}].slice(-500))},j=I=>{var re;const z=((re=I.reason)==null?void 0:re.message)||I.reason||A("toast.unknownReason");r(Z=>[...Z,{id:`rejection-${Date.now()}-${Ae()}`,level:"error",source:"Promise",message:`${A("toast.uncaughtRejection")}${z}`,timestamp:Date.now()}].slice(-500))};return window.addEventListener("error",v),window.addEventListener("unhandledrejection",j),()=>{window.removeEventListener("error",v),window.removeEventListener("unhandledrejection",j)}},[A]);const{sessionTabs:Le,activeSessionId:J,setActiveSession:pe,addSessionTab:ie,closeSessionTab:ke,renameSessionTab:_t,getVisibleSessionTabs:mo,autoNameSession:Fs,touchSession:Gt}=K(),zt=J?w[J]??!0:!0,ho=ce(v=>J?Object.keys(v.tasksBySession[J]||{}).length:0),Ws=g.useCallback(()=>{E(v=>J?{...v,[J]:!(v[J]??!0)}:v)},[J]),{clearMessages:Hs}=G(),{customTheme:fo,customThemeEnabled:go,themePresetId:yo}=Ke();di({theme:H,themePresetId:yo,customTheme:fo,customThemeEnabled:go}),li({activeTab:s,setLogs:r,setUnreadLogs:a}),g.useEffect(()=>{x.get("/api/terminal/status").then(v=>b(v.success&&v.data?v.data.ttydAvailable!==!1:!1)).catch(()=>b(!1))},[]),g.useEffect(()=>{const v=j=>{const I=j.detail,z=typeof I=="string"?I:I==null?void 0:I.tab,re=typeof I=="string"||I==null?void 0:I.section;z&&z!==s&&R(z),z==="settings"&&re&&oe(re)};return window.addEventListener("switch-tab",v),()=>window.removeEventListener("switch-tab",v)},[s,R,oe]);const Tt=g.useCallback(()=>{const v=window.location.hash.replace(/^#\/?/,"");if(!v)return;const[j,I]=v.split("/");j&&j in ps&&R(j),j==="settings"&&I==="stt"&&oe("stt")},[R,oe]);g.useEffect(()=>(Tt(),window.addEventListener("hashchange",Tt),()=>window.removeEventListener("hashchange",Tt)),[Tt]),g.useEffect(()=>{const v=F.onOpen(()=>{n(!0),W.success(A("toast.backendConnected"))}),j=F.onClose(()=>{t&&W.warning(A("toast.backendDisconnected")),n(!1)});return()=>{v(),j()}},[t,A]),g.useEffect(()=>{Le.length===0&&ie(A("chat.defaultSessionTitle",{n:1}))},[]),g.useEffect(()=>{const v=()=>u(!0);return window.addEventListener("hook-approval-required",v),()=>window.removeEventListener("hook-approval-required",v)},[]),g.useEffect(()=>{const v=()=>m(!0);return window.addEventListener("ask-question-required",v),()=>window.removeEventListener("ask-question-required",v)},[]),g.useEffect(()=>{te.autoMode&&te.pendingApprovals.length>0&&u(!1),te.pendingApprovals.length>0&&!te.autoMode&&u(!0)},[te.autoMode,te.pendingApprovals.length]);const Us=g.useRef(0);g.useEffect(()=>{const v=j=>{var le,Se;if(j.key!=="Escape"||j.defaultPrevented)return;const I=(le=j.target)==null?void 0:le.tagName;if(I==="INPUT"||I==="TEXTAREA"||(Se=j.target)!=null&&Se.isContentEditable)return;const z=G.getState(),Z=K.getState().activeSessionId;if(!Z||!z.isGenerating(Z))return;j.preventDefault();const me=Date.now(),xe=Us.current;Us.current=me,xe>0&&me-xe<500?(F.send({type:"stop",sessionId:Z}),W.info(A("toast.terminated"))):(F.send({type:"pause",sessionId:Z}),W.info(A("toast.paused")))};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[A]);const[Vt,Ks]=g.useState(!1),Ge=g.useCallback(()=>{g.startTransition(()=>{const v=ie(void 0,ae);F.setSessionId(v),ft.getState().setMode("act"),R("chat")})},[ie,ae,R]),bo=g.useCallback(v=>{g.startTransition(()=>{const j=K.getState();let I=j.activeSessionId;I||(I=j.addSessionTab(void 0,ae),F.setSessionId(I)),G.getState().setSessionInput(I,`$${v.id} `),R("chat")})},[ae,R]),qt=g.useCallback(()=>R("templates"),[R]),Jt=g.useCallback(async(v,j)=>{var xe;const I=await V.templates.render(v.id,j);if(!I.success||!I.data){W.error(I.error||"模板渲染失败");return}const z=I.data,re=ie(v.name,ae);F.setSessionId(re),ft.getState().setMode("act"),R("chat");const Z=`wf-${Date.now()}-${Ae()}`;ce.getState().upsert(re,{runId:Z,status:"RUNNING",completedPhases:0,totalPhases:((xe=z.nodes)==null?void 0:xe.length)??0,completedEffects:0,totalEffects:0,tokensUsed:0,tokensRemaining:0,lastEventType:"workflow_start"});const me=await V.workflows.start({sessionId:re,runId:Z,workflow:z,message:`[模板] ${v.name}`});if(!me.success||!me.data){W.error(me.error||"工作流启动失败"),ce.getState().fail(re,Z,me.error||"启动失败");return}if(me.data.status==="FAILED"){const le=me.data.error||"模板定义无效";W.error(`工作流启动失败: ${le}`),ce.getState().fail(re,Z,le)}},[ie,ae,R]),xo=g.useCallback(async()=>{if(Vt||!J)return;const v=ce.getState().getForSession(J),j=v==null?void 0:v.runId;if(!j){W.info("当前会话没有可保存的工作流运行");return}Ks(!0),W.info("正在泛化为模板…");try{const I=await V.templates.createFromRun(j,{generalize:!0});I.success&&I.data?I.data.degraded?W.warning(`已保存为模板「${I.data.name}」(v${I.data.version}),但 LLM 泛化失败,已原样保存${I.data.degradeReason?`:${I.data.degradeReason}`:""}`):W.success(`已保存为模板「${I.data.name}」(v${I.data.version})`):W.error(I.error||"保存模板失败")}finally{Ks(!1)}},[J,Vt]),Gs=g.useCallback(v=>{pe(v),F.setSessionId(v)},[pe]),zs=g.useCallback(v=>{ke(v)},[ke]),Vs=g.useCallback((v,j)=>{_t(v,j)},[_t]),Yt=g.useCallback(()=>{J&&Hs(J)},[J,Hs]);g.useEffect(()=>{if(!J)return;const v=G.getState().messagesBySession[J];v&&v.length>0&&Y.getState().recalculateFromMessages(v)},[J]);const Qt=g.useCallback(async(v,j,I,z)=>{if(!j.trim())return;G.getState().isGenerating(v)&&(console.warn(`[sendMessage] Session ${v} stuck in generating state — force-ending`),G.getState().endGeneration(v,"Force-ended: new message"));const Z=ft.getState();G.getState().resumeGeneration(v),F.setSessionId(v),G.getState().getMessages(v).some(Oe=>Oe.type==="user")?Gt(v):(Fs(v,j.trim()),Gt(v,j.trim()));let le=j.trim();if(I&&I.length>0){const Oe=[],jo=[...I].sort((We,He)=>He.length-We.length);for(const We of jo){le=le.split(`@${We}`).join("").trim();try{const He=await V.files.read(We),Js=He.success&&He.data?He.data:null;if(Js){const Ao=We.split(".").pop()||"";Oe.push(`<context ref="${We}">
|
|
13
|
+
\`\`\`${Ao}
|
|
14
|
+
${Js}
|
|
15
|
+
\`\`\`
|
|
16
|
+
</context>`)}}catch(He){console.warn(`Failed to read @-referenced file: ${We}`,He)}}Oe.length>0&&(le=Oe.join(`
|
|
17
|
+
|
|
18
|
+
`)+`
|
|
19
|
+
|
|
20
|
+
`+le.trim(),le=le.trim())}z!=null&&z.skipAddUserMessage||G.getState().addMessage(v,{id:`msg-${Date.now()}`,type:"user",content:le,timestamp:Date.now()});const Se=Z.mode,qs=ve(Se==="normal"?"act":Se);if(qs==="plan")F.send({type:"plan",sessionId:v,message:le});else if(qs==="goal"){const Oe=`wf-${Date.now()}-${Ae()}`;G.getState().startGeneration(v),ce.getState().upsert(v,{runId:Oe,status:"RUNNING",completedPhases:0,totalPhases:0,completedEffects:0,totalEffects:0,tokensUsed:0,tokensRemaining:0,lastEventType:"workflow_start"}),F.send({type:"workflow_start",sessionId:v,runId:Oe,message:le,projectId:ae,memoryEnabled:!0,checkpointPolicy:"phase-and-token"})}else F.send({type:"chat",sessionId:v,message:le})},[Fs,Gt,ae]),ko=g.useCallback((v,j)=>{var xe,le;const I=G.getState(),z=I.getMessages(v),re=z.findIndex(Se=>Se.id===j);if(re===-1)return;let Z=-1;for(let Se=re-1;Se>=0;Se--)if(((xe=z[Se])==null?void 0:xe.type)==="user"){Z=Se;break}if(Z===-1)return;const me=z[Z];(le=me==null?void 0:me.content)!=null&&le.trim()&&(I.replaceMessages(v,z.slice(0,Z+1)),Qt(v,me.content,void 0,{skipAddUserMessage:!0}))},[Qt]),So=g.useCallback((v,j)=>{G.getState().applyTombstone(v,[j]),W.success(A("chat.messageDeleted"))},[A]),vo=g.useCallback(v=>{const j=ce.getState().getForSession(v);j&&!["COMPLETED","CANCELLED","ERROR","FAILED"].includes(j.status)?F.send({type:"workflow_cancel",sessionId:v,runId:j.runId}):F.send({type:"stop",sessionId:v}),G.getState().endGeneration(v)},[]),wo=g.useCallback(v=>{const j=ce.getState().getForSession(v);j&&["RUNNING","RESUMING"].includes(j.status)?F.send({type:"workflow_pause",sessionId:v,runId:j.runId}):F.send({type:"pause",sessionId:v}),G.getState().pauseGeneration(v)},[]),Co=g.useCallback(v=>{const j=ce.getState().getForSession(v);j&&j.status==="PAUSED"?F.send({type:"workflow_resume",sessionId:v,runId:j.runId}):F.send({type:"resume",sessionId:v}),G.getState().resumeGeneration(v)},[]),_o=g.useCallback(()=>{g.startTransition(()=>{const v=window.prompt(A("chat.switchDirPrompt"),ae);if(v&&v.trim()&&v.trim()!==ae){const j=v.trim();Fe(j),F.send({type:"workspace",message:j}),K.getState().sessionTabs.forEach(z=>{G.getState().clearMessages(z.id)}),K.setState({sessionTabs:[],sessions:[],sessionWorkspaceDirs:{},activeSessionId:null}),setTimeout(()=>{K.getState().addSessionTab(A("chat.defaultSessionTitle",{n:1}),j)},0)}})},[ae,Fe,A]),Xt=()=>{r([]),a(0)},To=g.useMemo(()=>({setActiveTab:R,createNewSession:Ge,clearMessages:Yt,setTheme:q,setThemePreset:ne,toggleTerminal:P,setLogs:r,setUnreadLogs:a}),[R,Ge,Yt,q,ne,P]);g.useEffect(()=>{const v=j=>{var Z,me;const I=j.ctrlKey||j.metaKey,z=(Z=j.target)==null?void 0:Z.tagName,re=z==="INPUT"||z==="TEXTAREA"||((me=j.target)==null?void 0:me.isContentEditable);if(j.key==="Escape"){if(C){j.preventDefault(),k(!1);return}if(T){j.preventDefault(),_(!1);return}if(i){j.preventDefault(),l(!1);return}return}if(I)if(j.key==="k"||j.key==="K")j.preventDefault(),_(!1),k(xe=>!xe);else if(j.key==="l"||j.key==="L"){if(re)return;j.preventDefault(),Xt(),W.success(A("slashCommands.logs_clear_result"))}else j.key==="/"&&(j.preventDefault(),k(!1),_(xe=>!xe))};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[C,T,i,A]);const Zt=(v,j)=>ps[v]?A(ps[v]):j,No=v=>{switch(v){case"chat":{const j=mo(),I=Le.find(z=>z.id===J);return c.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[c.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:[c.jsx("button",{onClick:()=>f(z=>!z),className:`p-1.5 rounded-lg transition-colors ${h?"bg-accent-blue/10 text-accent-blue":"text-dark-muted hover:bg-dark-hover hover:text-dark-text"}`,title:A("a11y.toggleAgentFlow"),"aria-label":A("a11y.toggleAgentFlow"),"aria-expanded":h,children:c.jsx(or,{size:16,"aria-hidden":"true"})}),c.jsx("span",{className:"ml-1 truncate text-[13px] font-medium text-dark-text",children:(I==null?void 0:I.title)||A("nav.chat")}),c.jsx("div",{className:"flex-1"}),c.jsx(pi,{}),c.jsx("button",{onClick:qt,className:"p-1.5 rounded-lg text-dark-muted hover:bg-dark-hover hover:text-dark-text transition-colors",title:"模板库","aria-label":"模板库",children:c.jsx(Ot,{size:16,"aria-hidden":"true"})}),c.jsx("button",{onClick:()=>void xo(),disabled:Vt,className:"p-1.5 rounded-lg text-dark-muted hover:bg-dark-hover hover:text-dark-text disabled:opacity-40 transition-colors",title:"保存当前工作流为模板","aria-label":"保存当前工作流为模板",children:c.jsx(rr,{size:16,"aria-hidden":"true"})}),ho>0&&c.jsx("button",{onClick:Ws,className:`p-1.5 rounded-lg transition-colors ${zt?"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":zt,children:c.jsx(ar,{size:16,"aria-hidden":"true"})}),c.jsx("button",{onClick:()=>L(z=>!z),className:`p-1.5 rounded-lg transition-colors ${N?"bg-accent-blue/10 text-accent-blue":"text-dark-muted hover:bg-dark-hover hover:text-dark-text"}`,title:"右侧面板","aria-label":"切换右侧面板","aria-expanded":N,children:c.jsx(ir,{size:16,"aria-hidden":"true"})})]}),c.jsx(Ii,{tabs:j,activeSessionId:J,onSend:Qt,onStop:vo,onPause:wo,onResume:Co,activeTab:s,setActiveTab:R,createNewSession:Ge,clearMessages:Yt,setTheme:q,setThemePreset:ne,toggleTerminal:P,setLogs:r,setUnreadLogs:a,showTaskBoard:zt,onToggleTaskBoard:Ws,onRegenerate:ko,onDeleteMessage:So,hookDrawerOpen:d,onCloseHookDrawer:()=>u(!1),questionDrawerOpen:p,onCloseQuestionDrawer:()=>m(!1)})]})}case"terminal":return c.jsx(Ri,{});case"files":return c.jsx(Pi,{});case"models":return c.jsx(_i,{});case"tools":return c.jsx(Ti,{});case"skills":return c.jsx(ji,{onUseSkill:bo});case"agents":return c.jsx(Ai,{});case"templates":return c.jsx(Ei,{onLaunch:Jt});case"hooks":return c.jsx(Bi,{});case"channels":return c.jsx(Oi,{});case"connectors":return c.jsx($i,{});case"inbox":return c.jsx(Di,{});case"audit":return c.jsx(Wi,{});case"scheduled":return c.jsx(Fi,{});case"logs":return c.jsx(Li,{logs:o,onClear:Xt});case"settings":return c.jsx(Mi,{onNavigate:R,focusSection:M});case"pull-requests":case"plugins":return c.jsx(Ci,{tabId:v});default:return null}};return c.jsxs(Bn,{children:[c.jsxs("div",{className:"h-screen w-full flex bg-dark-bg text-dark-text overflow-hidden",children:[c.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 ${$?"w-14":"w-60"}`,children:c.jsx(Tn,{collapsed:$,onToggleCollapse:de,tabs:D,activeTab:s,onTabChange:R,isConnected:t,onNewSession:Ge,onStartTemplate:Jt,onManageTemplates:qt,onSwitchSession:Gs,onCloseSession:zs,onRenameSession:Vs,getTabTitle:Zt})}),i&&c.jsxs("div",{className:"md:hidden fixed inset-0 z-50",children:[c.jsx("div",{className:"absolute inset-0 bg-black/40 backdrop-blur-[2px]",onClick:()=>l(!1)}),c.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:c.jsx(Tn,{collapsed:!1,onToggleCollapse:()=>l(!1),tabs:D,activeTab:s,onTabChange:v=>{R(v),l(!1)},isConnected:t,onNewSession:()=>{Ge(),l(!1)},onStartTemplate:Jt,onManageTemplates:()=>{qt(),l(!1)},onSwitchSession:v=>{Gs(v),l(!1)},onCloseSession:zs,onRenameSession:Vs,getTabTitle:Zt})})]}),c.jsxs("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:[c.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:[c.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":A("a11y.openMenu"),children:c.jsx(nr,{size:18,"aria-hidden":"true"})}),c.jsx("span",{className:"text-sm font-semibold truncate",children:Zt(s,"")}),c.jsx("div",{className:"flex-1"}),s==="chat"&&c.jsx("button",{onClick:Ge,className:"p-2 rounded-lg text-dark-muted hover:bg-dark-hover hover:text-dark-text transition-colors","aria-label":A("chat.newSession"),children:c.jsx(Lt,{size:18,"aria-hidden":"true"})})]}),c.jsxs("div",{className:"flex-1 flex overflow-hidden min-h-0",children:[s==="chat"&&c.jsx("div",{className:`shrink-0 border-r border-dark-border bg-dark-surface transition-all duration-200 ease-in-out overflow-hidden ${h?"w-80 xl:w-[420px]":"w-0 border-r-0"}`,children:h&&c.jsx(g.Suspense,{fallback:c.jsx(Pn,{}),children:c.jsx(Ni,{})})}),c.jsx("div",{className:"flex-1 flex flex-col min-w-0 min-h-0",children:c.jsx(g.Suspense,{fallback:c.jsx(Pn,{}),children:c.jsx(Bn,{children:No(s)})})}),s==="chat"&&N&&c.jsx(Ia,{workspaceDir:ae,onWorkspaceChange:_o,logs:o,onClearLogs:Xt})]}),c.jsx(ui,{activeTab:s})]})]}),c.jsx(ki,{open:C,onClose:()=>k(!1),options:To}),c.jsx(Si,{open:T,onClose:()=>_(!1)}),c.jsx(fi,{}),c.jsx(yi,{})]})}const Gi={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:"默认"},zi={chat:"对话",terminal:"终端",files:"文件",models:"模型",tools:"工具",skills:"技能",agents:"Agents",templates:"模板",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:"失败",sessionDone:"已完成",connectors:"连接器"},Vi={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:"从历史移除",viewAllSessions:"更多会话",allSessions:"全部会话",sessionPickerTitle:"选择会话",clickToOpenSession:"打开会话",workingDir:"工作目录",switchDir:"切换",clickToSwitchDir:"点击切换工作目录",switchDirPrompt:"请输入新的工作目录路径:",addTask:"添加",addTaskPlaceholder:"添加任务...",noTasks:"暂无任务,在上方输入添加",taskBoardDragHint:"下拉展开 · 上推收起 · 点击切换",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:"思考中"},qi={title:"键盘快捷键",commandPalette:"打开命令面板",clearLogs:"清空日志",help:"显示快捷键帮助",submit:"提交输入",newline:"换行",closeDialog:"关闭弹窗 / 暂停生成",slashCommand:"快捷命令",fileRef:"引用文件",stopGen:"终止生成(连按两次 Esc)"},Ji={placeholder:"搜索命令或跳转面板...",navGroup:"导航",commandGroup:"命令",empty:"没有匹配的命令",hint:"↑↓ 选择 · Enter 执行 · Esc 关闭",running:"执行中..."},Yi={openMenu:"打开菜单",closeMenu:"关闭菜单",close:"关闭",expand:"展开",collapse:"折叠",delete:"删除",remove:"移除",send:"发送消息",newSession:"新建会话",messageInput:"消息输入框",connectionStatus:"连接状态",loading:"加载中",toggleAgentFlow:"切换 Agent 信息流",commandPalette:"命令面板",shortcutsHelp:"快捷键帮助"},Qi={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:"正在分析需求..."},Xi={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"},Zi={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 (自定义)"},el={title:"工具列表",searchTools:"搜索工具...",disabled:"禁用",enabled:"启用",params:"参数",loadFailed:"加载工具失败",noTools:"暂无工具"},tl={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 文件",marketplace:"技能市场",marketplaceDesc:"从远程市场浏览并安装技能",marketplaceTitle:"技能市场",addMarketplace:"添加市场",addMarketplaceTitle:"添加技能市场",marketplaceUrl:"市场地址",marketplaceUrlPlaceholder:"GitHub 仓库 / index.json 链接 / 本地技能文件夹,如 https://github.com/obra/superpowers 或 D:\\agent\\agentic-awesome-skills",marketplaceName:"市场名称(可选)",marketplaceHint:"支持 GitHub 仓库(自动扫描 skills/ 目录)、返回 index.json 的 URL、或本机技能文件夹(完全离线,直接浏览/安装磁盘上的技能库)。GitHub 无法访问时可设置 DEEPSEEKCODE_GITHUB_MIRROR 镜像加速。",marketFilterPlaceholder:"在当前市场搜索技能...",marketCategoryAll:"全部分类",riskCritical:"高危",riskUnknown:"风险未知",refreshMarketplace:"刷新",removeMarketplace:"移除市场",installSkill:"安装",installed:"已安装",installFail:"安装失败",loadMarketplaceFail:"加载技能市场失败",noMarketplaces:"暂无市场,先添加一个",noSkillsInMarket:"该市场暂无技能",marketplaceError:"市场索引加载失败:{{error}}",retryMarket:"重试",presets:"内置市场",marketplaces:"已添加的市场",skillCount:"{{count}} 个技能",installedSkills:"已安装技能",addFail:"添加市场失败",installing:"安装中...",adding:"添加中...",marketplaceTab:"技能市场",mineTab:"我的技能",installedTab:"已安装",uninstall:"卸载",uninstallConfirm:"确定卸载已安装技能「{{name}}」?",uninstalling:"卸载中...",uninstallFail:"卸载失败",pagePrev:"上一页",pageNext:"下一页",pageOf:"第 {{page}} / {{total}} 页",emptyInstalled:"还没有已安装的市场技能",emptyInstalledHint:"前往「技能市场」浏览并下载安装",browseMarket:"去市场逛逛",use:"使用",useHint:"使用此技能:将 $技能名 插入输入框,补充任务描述后发送",pickTitle:"选择技能",pickPlaceholder:"搜索技能...",pickEmpty:"没有可用的技能",pickUse:"点击使用"},sl={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:"清空日志"},nl={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}}",optionAllowPathHint:"不再询问该外部路径",timeoutWaitUser:"等待用户输入(无超时)",optionAutoMode:"自动模式 — 全部允许",optionAutoModeHint:"之后所有 Hook 将自动批准",shortcutHint:"快捷键: 1-4 选择 · Enter 允许 · Esc 拒绝",lastItem:"最后一项",modalHint:"请在弹窗中处理此审批请求",clickToSelect:"点击选择 · 1/2/3/4 键盘快捷键",verbRunCommand:"运行命令",verbWriteFile:"写入文件",verbEditFile:"编辑文件",verbReadFile:"读取文件",verbDeleteFile:"删除文件",verbFindFiles:"查找文件",verbSearchContents:"搜索内容",verbFetchUrl:"请求网络",verbSearchWeb:"搜索网络",verbGit:"Git 操作",verbInstall:"安装依赖",verbSendMessage:"发送消息",verbRunTool:"执行操作",scopeLocal:"作用于当前工作区",scopeExternal:"外部路径",showAllLines:"展开全部 {{n}} 行",showAll:"显示完整内容",showLess:"收起"},ol={pending:"等待",thinking:"思考",action:"执行",result:"结果",running:"运行中",error:"错误",completed:"完成",params:"参数"},rl={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:"无活跃会话",unknownCommand:"未知命令 {{cmd}} — 输入 /help 查看可用命令"},al={pageError:"页面出现错误",unknownError:"发生了未知错误,请尝试刷新页面",refreshPage:"刷新页面",genEnded:"生成已结束(工具执行超时或连接中断)"},il={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:"关闭检查模式"},ll={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"}},cl={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"},dl={reconnecting:"重连中 {{attempt}}/{{max}}",hint:"正在重新连接后端…"},ul={title:"Full access(自动批准)已开启",desc:"Agent 可不经确认直接编辑文件和执行命令,存在数据丢失风险。",dismiss:"本次关闭",neverShow:"不再显示"},pl={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:"请输入提交信息"},ml={retry:"重试",details:"详情",modelSettings:"模型设置"},hl={comingSoon:"即将上线"},fl={lspGroup:"语言服务器 (LSP)",mcpGroup:"MCP 服务器",notInstalled:"未安装",installed:"已安装",ready:"已连接",connecting:"连接中",installing:"安装中…",error:"错误",disabled:"已禁用",toolCount:"{{count}} 个工具",docs:"文档",official:"官方",cloud:"云端",local:"本地",needCredentials:"此连接器需要凭据才能启动:",connect:"连接",missing:"未配置",envConfigured:"已配置",searchPlaceholder:"搜索连接器(名称、id、描述)…",all:"全部",noResults:"没有匹配的连接器。",custom:"自定义",addCustom:"添加自定义",customTitle:"添加自定义 MCP 服务器(来自 awesome-mcp-servers 或自建)",customName:"名称 (id)",customCommand:"启动命令",customArgs:"参数(空格分隔)",customEnv:"环境变量(KEY=value,逗号分隔)",customUrl:"MCP 端点 URL",customHeaders:"请求头(KEY=value,逗号分隔)",customLocal:"本地命令",customFormRequired:"名称和启动命令/URL 必填。",removeCustom:"删除此自定义连接器",add:"添加"},gl={justNow:"刚刚",minutesAgo:"{{count}}分钟前",hoursAgo:"{{count}}小时前",daysAgo:"{{count}}天前"},yl={title:"语音输入(英语 whisper / 中文 FunASR)",stopTitle:"停止录音并转写",langToggle:"切换识别语言:英语(whisper)/ 中文(FunASR)",noSpeech:"未识别到语音内容,请重试",backendMissing:"语音服务未就绪,已打开设置页引导安装",setup:{title:"语音服务",envCard:"运行环境检测",envChecking:"检测中…",recheck:"重新检测",pythonOk:"Python {{version}} 已就绪",pythonMissing:"未检测到 Python,请先安装 Python 3.10+",pythonGuide:"下载安装 Python",pipOk:"pip 可用",pipMissing:"pip 缺失,请先安装 pip 后再安装语音引擎",pipGuide:"执行以下命令修复 pip(再失败可参考 get-pip.py 官方方案):",whisperTitle:"Whisper · 英语",whisperDesc:"英语语音识别",funasrTitle:"FunASR · 中文",funasrDesc:"中文语音识别",installed:"已安装",notInstalled:"未安装",install:"一键安装",installing:"安装中…",cancel:"取消安装",installDone:"安装完成,可回到聊天页使用语音输入",installFailed:"安装失败",installTimeout:"安装超时",installCancelled:"安装已取消",jobInProgress:"已有安装任务进行中,正在接管进度",manualCommand:"手动安装命令",copyCommand:"复制命令",copySuccess:"已复制到剪贴板",copyFailed:"复制失败",torchHint:"中文引擎需安装 torch,体积较大,请耐心等待",logWaiting:"正在准备安装…",chooseHint:"环境已就绪,请选择上方引擎进行安装",defaultEngine:"默认识别引擎",defaultEngineHint:"选择语音输入默认使用的引擎,可在聊天输入框随时切换",inUse:"使用中",engineNotInstalledHint:"该引擎尚未安装,选中后录音时会引导安装"}},Rn={common:Gi,nav:zi,chat:Vi,shortcuts:qi,palette:Ji,a11y:Yi,plan:Qi,settings:Xi,models:Zi,tools:el,skills:tl,agents:sl,hook:nl,step:ol,slashCommands:rl,error:al,toast:il,channels:ll,fileJob:cl,reconnect:dl,autoAccess:ul,git:pl,errorCard:ml,placeholder:hl,connectors:fl,time:gl,stt:yl},bl={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"},xl={chat:"Chat",terminal:"Terminal",files:"Files",models:"Models",tools:"Tools",skills:"Skills",agents:"Agents",templates:"Templates",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",sessionDone:"Completed",connectors:"Connectors"},kl={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",viewAllSessions:"More sessions",allSessions:"All sessions",sessionPickerTitle:"Select session",clickToOpenSession:"Open session",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",taskBoardDragHint:"Drag down to expand · drag up to collapse · click to toggle",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"},Sl={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)"},vl={placeholder:"Search commands or jump to panel...",navGroup:"Navigation",commandGroup:"Commands",empty:"No matching commands",hint:"↑↓ Select · Enter Run · Esc Close",running:"Running..."},wl={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"},Cl={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..."},_l={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"},Tl={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"},Nl={title:"Tool List",searchTools:"Search tools...",disabled:"Disable",enabled:"Enable",params:"Parameters",loadFailed:"Failed to load tools",noTools:"No tools available"},jl={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.",marketplace:"Marketplace",marketplaceDesc:"Browse and install skills from remote marketplaces",marketplaceTitle:"Skill Marketplace",addMarketplace:"Add Marketplace",addMarketplaceTitle:"Add Skill Marketplace",marketplaceUrl:"Marketplace URL",marketplaceUrlPlaceholder:"GitHub repo / index.json link / local skills folder, e.g. https://github.com/obra/superpowers or D:\\agent\\agentic-awesome-skills",marketplaceName:"Marketplace name (optional)",marketplaceHint:"Supports GitHub repos (auto-scans skills/ dir), an index.json URL, or a local skills folder (fully offline — browse & install from disk). If GitHub is unreachable, set the DEEPSEEKCODE_GITHUB_MIRROR env var to a mirror prefix.",marketFilterPlaceholder:"Search skills in this marketplace...",marketCategoryAll:"All categories",riskCritical:"High risk",riskUnknown:"Risk unknown",refreshMarketplace:"Refresh",removeMarketplace:"Remove",installSkill:"Install",installed:"Installed",installFail:"Install failed",loadMarketplaceFail:"Failed to load skill marketplace",noMarketplaces:"No marketplaces yet — add one",noSkillsInMarket:"No skills in this marketplace",marketplaceError:"Marketplace index failed to load: {{error}}",retryMarket:"Retry",presets:"Built-in marketplaces",marketplaces:"Added marketplaces",skillCount:"{{count}} skills",installedSkills:"Installed skills",addFail:"Failed to add marketplace",installing:"Installing...",adding:"Adding...",marketplaceTab:"Marketplace",mineTab:"My Skills",installedTab:"Installed",uninstall:"Uninstall",uninstallConfirm:'Uninstall installed skill "{{name}}"?',uninstalling:"Uninstalling...",uninstallFail:"Uninstall failed",pagePrev:"Prev",pageNext:"Next",pageOf:"Page {{page}} / {{total}}",emptyInstalled:"No marketplace skills installed yet",emptyInstalledHint:"Head to the Marketplace tab to browse and install",browseMarket:"Go to Marketplace",use:"Use",useHint:"Insert $skill into the input box, then add your task and send",pickTitle:"Pick a Skill",pickPlaceholder:"Search skills...",pickEmpty:"No usable skills",pickUse:"Use it"},Al={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"},El={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}}",optionAllowPathHint:"Don't ask again for this external path",timeoutWaitUser:"waiting for user (no timeout)",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",verbRunCommand:"Run command",verbWriteFile:"Write file",verbEditFile:"Edit file",verbReadFile:"Read file",verbDeleteFile:"Delete file",verbFindFiles:"Find files",verbSearchContents:"Search contents",verbFetchUrl:"Fetch URL",verbSearchWeb:"Search web",verbGit:"Git operation",verbInstall:"Install package",verbSendMessage:"Send message",verbRunTool:"Run operation",scopeLocal:"acts on this workspace",scopeExternal:"external path",showAllLines:"Show all {{n}} lines",showAll:"Show the full message",showLess:"Show less"},Bl={pending:"Waiting",thinking:"Thinking",action:"Action",result:"Result",running:"Running",error:"Error",completed:"Completed",params:"Parameters"},Pl={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",unknownCommand:"Unknown command {{cmd}} — type /help to see available commands"},Rl={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)"},Il={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"},Ml={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"}},Ll={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"},Ol={reconnecting:"Reconnecting {{attempt}}/{{max}}",hint:"正在重新连接后端…"},$l={title:"Full access(自动批准)已开启",desc:"Agent 可不经确认直接编辑文件和执行命令,存在数据丢失风险。",dismiss:"本次关闭",neverShow:"不再显示"},Dl={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:"请输入提交信息"},Fl={retry:"重试",details:"详情",modelSettings:"模型设置"},Wl={comingSoon:"即将上线"},Hl={lspGroup:"Language Servers (LSP)",mcpGroup:"MCP Servers",notInstalled:"Not installed",installed:"Installed",ready:"Ready",connecting:"Connecting",installing:"Installing…",error:"Error",disabled:"Disabled",toolCount:"{{count}} tools",docs:"Docs",official:"Official",cloud:"Cloud",local:"Local",needCredentials:"This connector needs credentials to start:",connect:"Connect",missing:"missing",envConfigured:"credentials set",searchPlaceholder:"Search connectors (name, id, description)…",all:"All",noResults:"No connectors match your search/filter.",custom:"Custom",addCustom:"Add custom",customTitle:"Add custom MCP server (from awesome-mcp-servers or your own)",customName:"Name (id)",customCommand:"Command",customArgs:"Args (space separated)",customEnv:"Env (KEY=value, comma separated)",customUrl:"MCP endpoint URL",customHeaders:"Headers (KEY=value, comma separated)",customLocal:"Local command",customFormRequired:"Name and command/URL are required.",removeCustom:"Remove this custom connector",add:"Add"},Ul={justNow:"just now",minutesAgo:"{{count}}m ago",hoursAgo:"{{count}}h ago",daysAgo:"{{count}}d ago"},Kl={title:"Voice input (English: whisper / Chinese: FunASR)",stopTitle:"Stop recording and transcribe",langToggle:"Switch recognition language: English (whisper) / Chinese (FunASR)",noSpeech:"No speech detected, please try again",backendMissing:"STT service not ready — opened settings to guide installation",setup:{title:"Voice Service",envCard:"Environment check",envChecking:"Checking…",recheck:"Re-check",pythonOk:"Python {{version}} ready",pythonMissing:"Python not detected. Please install Python 3.10+ first",pythonGuide:"Download Python",pipOk:"pip available",pipMissing:"pip is missing. Install pip first, then install the speech engine",pipGuide:"Run the command below to repair pip (see get-pip.py docs if it fails):",whisperTitle:"Whisper · English",whisperDesc:"English speech recognition",funasrTitle:"FunASR · Chinese",funasrDesc:"Chinese speech recognition",installed:"Installed",notInstalled:"Not installed",install:"Install",installing:"Installing…",cancel:"Cancel install",installDone:"Install complete — voice input is ready",installFailed:"Install failed",installTimeout:"Install timed out",installCancelled:"Install cancelled",jobInProgress:"An install task is already running, taking over its progress",manualCommand:"Manual install command",copyCommand:"Copy",copySuccess:"Copied to clipboard",copyFailed:"Copy failed",torchHint:"Chinese engine requires torch — large download, please wait",logWaiting:"Preparing install…",chooseHint:"Environment ready — pick an engine above to install",defaultEngine:"Default recognition engine",defaultEngineHint:"Choose the default engine for voice input. You can switch anytime in the chat input.",inUse:"In use",engineNotInstalledHint:"This engine is not installed yet. Recording will guide you to install it."}},In={common:bl,nav:xl,chat:kl,shortcuts:Sl,palette:vl,a11y:wl,plan:Cl,settings:_l,models:Tl,tools:Nl,skills:jl,agents:Al,hook:El,step:Bl,slashCommands:Pl,error:Rl,toast:Il,channels:Ml,fileJob:Ll,reconnect:Ol,autoAccess:$l,git:Dl,errorCard:Fl,placeholder:Wl,connectors:Hl,time:Ul,stt:Kl},Gl=Ke.getState().language||"zh-CN";ye.use(Gr).init({resources:{"zh-CN":{translation:Rn,hook:Rn.hook},en:{translation:In,hook:In.hook}},lng:Gl,fallbackLng:"zh-CN",interpolation:{escapeValue:!1}});let Pt=new Set;function zl(s){function e(){t(window)}function t(u){u&&typeof u.addEventListener=="function"&&(u.addEventListener("click",r,!0),u.addEventListener("mousedown",a,!0),u.addEventListener("mouseover",a,!0),u.addEventListener("mouseup",a,!0),u.addEventListener("pointerdown",i,!0),u.addEventListener("pointerover",l,!0),u.addEventListener("pointerup",d,!0))}function n(){o(window),Pt.forEach(u=>{try{o(u.contentWindow)}catch{}}),Pt=new Set}function o(u){u&&typeof u.removeEventListener=="function"&&(u.removeEventListener("click",r,!0),u.removeEventListener("mousedown",a,!0),u.removeEventListener("mouseover",a,!0),u.removeEventListener("mouseup",a,!0),u.removeEventListener("pointerdown",i,!0),u.removeEventListener("pointerover",l,!0),u.removeEventListener("pointerup",d,!0))}function r(u){var p;u.preventDefault(),u.stopPropagation(),n(),(p=s.onClick)===null||p===void 0||p.call(s,u.target)}function a(u){u.preventDefault(),u.stopPropagation()}function i(u){u.preventDefault(),u.stopPropagation()}function l(u){var p;u.preventDefault(),u.stopPropagation();const m=u.target;if(m.tagName==="IFRAME"){const h=m;try{if(!Pt.has(h)){const f=h.contentWindow;t(f),Pt.add(h)}}catch{}}(p=s.onPointerOver)===null||p===void 0||p.call(s,u.target)}function d(u){u.preventDefault(),u.stopPropagation()}return e(),n}const Vl=s=>typeof(s==null?void 0:s.type)=="string",oo=s=>{var e;return typeof((e=s==null?void 0:s.type)===null||e===void 0?void 0:e.$$typeof)=="symbol"},ql=s=>{var e;return((e=s==null?void 0:s.type)===null||e===void 0?void 0:e.$$typeof)===Symbol.for("react.forward_ref")},Jl=s=>{const e=Object.keys(s).find(t=>t.startsWith("__reactInternalInstance$")||t.startsWith("__reactFiber$"));if(e)return s[e]},Os=s=>{if(!s)return;const e=Jl(s);return e||Os(s.parentElement)},Yl=s=>{let e=s.return;for(;e;){if(!oo(e))return e;e=e.return}return null},ro=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},Ql=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:o,lineNumber:r,columnNumber:a}=n;if(o&&r)return{lineNumber:String(r),columnNumber:String(a??1),absolutePath:o.match(/^<.*>$/)?o.replace(/^<|>$/g,""):o}},Xl=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}},$s=s=>{const e=[Ql(s),Xl(s)].filter(Boolean);if(e.length)return Object.assign({},...e)},ao=s=>{if(!s)return;const e=Yl(s);if(!e)return;const t=Vl(e),n=!e.child.sibling;let o=!t&&n?e:s;const r=o;for(;o;){if($s(o))return o;o=o.return}return r},Mn=s=>{const e=Os(s),t=ao(e);return $s(t)},Zl=s=>{var e,t;let n=s,o;for(;n;){let r=(e=n.return)!==null&&e!==void 0?e:void 0,a;for(;oo(r);)ql(r)&&(a=r),r=(t=r==null?void 0:r.return)!==null&&t!==void 0?t:void 0;if(a&&(n=a),ro(n)&&(o||(o=n),$s(n)))return n;n=r}return o},Ln=s=>{const e=Os(s),t=ao(e),n=Zl(t),o=ro(n),r=s.nodeName.toLowerCase(),a=o?`${r} in <${o}>`:r;return{fiber:t,name:o,title:a}};function On(s){return s.getBoundingClientRect()}function ec(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 tc="/__open-stack-frame-in-editor";const $n=lr(tc),sc=s=>"codeInfo"in s?s.codeInfo:s,nc=s=>{if(!s)return;const e=sc(s),{lineNumber:t,columnNumber:n,relativePath:o,absolutePath:r}=e,a=!!o,i=a?o:r;if(!i){console.error("[react-dev-inspector] Cannot open editor without source fileName",e);return}const l={fileName:i,lineNumber:t,colNumber:n},d=a?`${$n}/relative`:$n;fetch(`${d}?${new URLSearchParams(l)}`)},ms=typeof navigator<"u"?navigator.userAgent.toLowerCase().indexOf("firefox")>0:!1;function hs(s,e,t,n){s.addEventListener?s.addEventListener(e,t,n):s.attachEvent&&s.attachEvent("on".concat(e),t)}function ut(s,e,t,n){s.removeEventListener?s.removeEventListener(e,t,n):s.detachEvent&&s.detachEvent("on".concat(e),t)}function io(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 lo(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 oc(s,e){const t=s.length>=e.length?s:e,n=s.length>=e.length?e:s;let o=!0;for(let r=0;r<t.length;r++)n.indexOf(t[r])===-1&&(o=!1);return o}const vt={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,"-":ms?173:189,"=":ms?61:187,";":ms?59:186,"'":222,"{":219,"}":221,"[":219,"]":221,"\\":220},Te={"⇧":16,shift:16,"⌥":18,alt:18,option:18,"⌃":17,ctrl:17,control:17,"⌘":91,cmd:91,meta:91,command:91},pt={16:"shiftKey",18:"altKey",17:"ctrlKey",91:"metaKey",shiftKey:16,ctrlKey:17,altKey:18,metaKey:91},fe={16:!1,18:!1,17:!1,91:!1},ee={};for(let s=1;s<20;s++)vt["f".concat(s)]=111+s;let Q=[],yt=null,co="all";const Ie=new Map,Ze=s=>vt[s.toLowerCase()]||Te[s.toLowerCase()]||s.toUpperCase().charCodeAt(0),rc=s=>Object.keys(vt).find(e=>vt[e]===s),ac=s=>Object.keys(Te).find(e=>Te[e]===s);function uo(s){co=s||"all"}function wt(){return co||"all"}function ic(){return Q.slice(0)}function lc(){return Q.map(s=>rc(s)||ac(s)||String.fromCharCode(s))}function cc(){const s=[];return Object.keys(ee).forEach(e=>{ee[e].forEach(t=>{let{key:n,scope:o,mods:r,shortcut:a}=t;s.push({scope:o,shortcut:a,mods:r,keys:n.split("+").map(i=>Ze(i))})})}),s}function dc(s){const e=s.target||s.srcElement,{tagName:t}=e;let n=!0;const o=t==="INPUT"&&!["checkbox","radio","range","button","file","reset","submit","color"].includes(e.type);return(e.isContentEditable||(o||t==="TEXTAREA"||t==="SELECT")&&!e.readOnly)&&(n=!1),n}function uc(s){return typeof s=="string"&&(s=Ze(s)),Q.indexOf(s)!==-1}function pc(s,e){let t,n;s||(s=wt());for(const o in ee)if(Object.prototype.hasOwnProperty.call(ee,o))for(t=ee[o],n=0;n<t.length;)t[n].scope===s?t.splice(n,1).forEach(a=>{let{element:i}=a;return Ds(i)}):n++;wt()===s&&uo(e||"all")}function mc(s){let e=s.keyCode||s.which||s.charCode;s.key&&s.key.toLowerCase()==="capslock"&&(e=Ze(s.key));const t=Q.indexOf(e);if(t>=0&&Q.splice(t,1),s.key&&s.key.toLowerCase()==="meta"&&Q.splice(0,Q.length),(e===93||e===224)&&(e=91),e in fe){fe[e]=!1;for(const n in Te)Te[n]===e&&(Ce[n]=!1)}}function po(s){if(typeof s>"u")Object.keys(ee).forEach(o=>{Array.isArray(ee[o])&&ee[o].forEach(r=>Rt(r)),delete ee[o]}),Ds(null);else if(Array.isArray(s))s.forEach(o=>{o.key&&Rt(o)});else if(typeof s=="object")s.key&&Rt(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[o,r]=t;typeof o=="function"&&(r=o,o=""),Rt({key:s,scope:o,method:r,splitKey:"+"})}}const Rt=s=>{let{key:e,scope:t,method:n,splitKey:o="+"}=s;lo(e).forEach(a=>{const i=a.split(o),l=i.length,d=i[l-1],u=d==="*"?"*":Ze(d);if(!ee[u])return;t||(t=wt());const p=l>1?io(Te,i):[],m=[];ee[u]=ee[u].filter(h=>{const y=(n?h.method===n:!0)&&h.scope===t&&oc(h.mods,p);return y&&m.push(h.element),!y}),m.forEach(h=>Ds(h))})};function Dn(s,e,t,n){if(e.element!==n)return;let o;if(e.scope===t||e.scope==="all"){o=e.mods.length>0;for(const r in fe)Object.prototype.hasOwnProperty.call(fe,r)&&(!fe[r]&&e.mods.indexOf(+r)>-1||fe[r]&&e.mods.indexOf(+r)===-1)&&(o=!1);(e.mods.length===0&&!fe[16]&&!fe[18]&&!fe[17]&&!fe[91]||o||e.shortcut==="*")&&(e.keys=[],e.keys=e.keys.concat(Q),e.method(s,e)===!1&&(s.preventDefault?s.preventDefault():s.returnValue=!1,s.stopPropagation&&s.stopPropagation(),s.cancelBubble&&(s.cancelBubble=!0)))}}function Fn(s,e){const t=ee["*"];let n=s.keyCode||s.which||s.charCode;if(s.key&&s.key.toLowerCase()==="capslock"||!Ce.filter.call(this,s))return;if((n===93||n===224)&&(n=91),Q.indexOf(n)===-1&&n!==229&&Q.push(n),["metaKey","ctrlKey","altKey","shiftKey"].forEach(i=>{const l=pt[i];s[i]&&Q.indexOf(l)===-1?Q.push(l):!s[i]&&Q.indexOf(l)>-1?Q.splice(Q.indexOf(l),1):i==="metaKey"&&s[i]&&(Q=Q.filter(d=>d in pt||d===n))}),n in fe){fe[n]=!0;for(const i in Te)if(Object.prototype.hasOwnProperty.call(Te,i)){const l=pt[Te[i]];Ce[i]=s[l]}if(!t)return}for(const i in fe)Object.prototype.hasOwnProperty.call(fe,i)&&(fe[i]=s[pt[i]]);s.getModifierState&&!(s.altKey&&!s.ctrlKey)&&s.getModifierState("AltGraph")&&(Q.indexOf(17)===-1&&Q.push(17),Q.indexOf(18)===-1&&Q.push(18),fe[17]=!0,fe[18]=!0);const o=wt();if(t)for(let i=0;i<t.length;i++)t[i].scope===o&&(s.type==="keydown"&&t[i].keydown||s.type==="keyup"&&t[i].keyup)&&Dn(s,t[i],o,e);if(!(n in ee))return;const r=ee[n],a=r.length;for(let i=0;i<a;i++)if((s.type==="keydown"&&r[i].keydown||s.type==="keyup"&&r[i].keyup)&&r[i].key){const l=r[i],{splitKey:d}=l,u=l.key.split(d),p=[];for(let m=0;m<u.length;m++)p.push(Ze(u[m]));p.sort().join("")===Q.sort().join("")&&Dn(s,l,o,e)}}function Ce(s,e,t){Q=[];const n=lo(s);let o=[],r="all",a=document,i=0,l=!1,d=!0,u="+",p=!1,m=!1;for(t===void 0&&typeof e=="function"&&(t=e),Object.prototype.toString.call(e)==="[object Object]"&&(e.scope&&(r=e.scope),e.element&&(a=e.element),e.keyup&&(l=e.keyup),e.keydown!==void 0&&(d=e.keydown),e.capture!==void 0&&(p=e.capture),typeof e.splitKey=="string"&&(u=e.splitKey),e.single===!0&&(m=!0)),typeof e=="string"&&(r=e),m&&po(s,r);i<n.length;i++)s=n[i].split(u),o=[],s.length>1&&(o=io(Te,s)),s=s[s.length-1],s=s==="*"?"*":Ze(s),s in ee||(ee[s]=[]),ee[s].push({keyup:l,keydown:d,scope:r,mods:o,shortcut:n[i],method:t,key:n[i],splitKey:u,element:a});if(typeof a<"u"&&window){if(!Ie.has(a)){const h=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;return Fn(y,a)},f=function(){let y=arguments.length>0&&arguments[0]!==void 0?arguments[0]:window.event;Fn(y,a),mc(y)};Ie.set(a,{keydownListener:h,keyupListenr:f,capture:p}),hs(a,"keydown",h,p),hs(a,"keyup",f,p)}if(!yt){const h=()=>{Q=[]};yt={listener:h,capture:p},hs(window,"focus",h,p)}}}function hc(s){let e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"all";Object.keys(ee).forEach(t=>{ee[t].filter(o=>o.scope===e&&o.shortcut===s).forEach(o=>{o&&o.method&&o.method()})})}function Ds(s){const e=Object.values(ee).flat();if(e.findIndex(n=>{let{element:o}=n;return o===s})<0){const{keydownListener:n,keyupListenr:o,capture:r}=Ie.get(s)||{};n&&o&&(ut(s,"keyup",o,r),ut(s,"keydown",n,r),Ie.delete(s))}if((e.length<=0||Ie.size<=0)&&(Object.keys(Ie).forEach(o=>{const{keydownListener:r,keyupListenr:a,capture:i}=Ie.get(o)||{};r&&a&&(ut(o,"keyup",a,i),ut(o,"keydown",r,i),Ie.delete(o))}),Ie.clear(),Object.keys(ee).forEach(o=>delete ee[o]),yt)){const{listener:o,capture:r}=yt;ut(window,"focus",o,r),yt=null}}const fs={getPressedKeyString:lc,setScope:uo,getScope:wt,deleteScope:pc,getPressedKeyCodes:ic,getAllKeyCodes:cc,isPressed:uc,filter:dc,trigger:hc,unbind:po,keyMap:vt,modifier:Te,modifierMap:pt};for(const s in fs)Object.prototype.hasOwnProperty.call(fs,s)&&(Ce[s]=fs[s]);if(typeof window<"u"){const s=window.hotkeys;Ce.noConflict=e=>(e&&window.hotkeys===Ce&&(window.hotkeys=s),Ce),window.hotkeys=Ce}var gs;const fc=typeof window<"u"&&(!((gs=window==null?void 0:window.document)===null||gs===void 0)&&gs.createElement)?g.useLayoutEffect:g.useEffect,ze=s=>{const e=g.useRef(s);e.current=g.useMemo(()=>s,[s]);const t=g.useRef();return t.current||(t.current=function(...n){var o;return(o=e.current)===null||o===void 0?void 0:o.apply(this,n)}),t.current},gc=({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 yc{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=It.border,this.padding.style.borderColor=It.padding,this.content.style.backgroundColor=It.background,Object.assign(this.node.style,{borderColor:It.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){ys(t,"margin",this.node),ys(t,"border",this.border),ys(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 bc{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,o){this.titleDiv.textContent=e,this.infoDiv.textContent=t??"",this.dimSpan.textContent=`${Math.round(n)}px × ${Math.round(o)}px`}updatePosition(e,t){const n=this.tip.getBoundingClientRect(),o=kc(e,t,{width:n.width,height:n.height});Object.assign(this.tip.style,o.style)}}class xc{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 bc(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 o;const r=e.filter(l=>l.nodeType===Node.ELEMENT_NODE);for(;this.rects.length>r.length;){const l=this.rects.pop();l==null||l.remove()}if(r.length===0)return;for(;this.rects.length<r.length;)this.rects.push(new yc(this.window.document,this.container));const a={top:Number.POSITIVE_INFINITY,right:Number.NEGATIVE_INFINITY,bottom:Number.NEGATIVE_INFINITY,left:Number.POSITIVE_INFINITY};if(r.forEach((l,d)=>{const u=On(l,this.window),p=ec(l);a.top=Math.min(a.top,u.top-p.marginTop),a.right=Math.max(a.right,u.left+u.width+p.marginRight),a.bottom=Math.max(a.bottom,u.top+u.height+p.marginBottom),a.left=Math.min(a.left,u.left-p.marginLeft),this.rects[d].update(u,p)}),!t){t=r[0].nodeName.toLowerCase();const l=r[0],d=(o=l.ownerDocument.defaultView)===null||o===void 0?void 0:o.__REACT_DEVTOOLS_GLOBAL_HOOK__;if(d!=null&&d.rendererInterfaces){let u=null;for(const p of d.rendererInterfaces.values()){const m=p.getFiberIDForNative(l,!0);if(m!==null){u=p.getDisplayNameForFiberID(m,!0);break}}u&&(t+=` (in ${u})`)}}this.tip.updateText(t,n,a.right-a.left,a.bottom-a.top);const i=On(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 kc(s,e,t){const n=Math.max(t.height,20),o=Math.max(t.width,60),r=5;let a;s.top+s.height+n<=e.top+e.height?s.top+s.height<e.top+0?a=e.top+r:a=s.top+s.height+r:s.top-n<=e.top+e.height?s.top-n-r<e.top+r?a=e.top+r:a=s.top-n-r:a=e.top+e.height-n-r;let i=s.left+r;return s.left<e.left&&(i=e.left+r),s.left+o>e.left+e.width&&(i=e.left+e.width-o-r),{style:{top:`${a}px`,left:`${i}px`}}}function ys(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 It={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)"},Sc=()=>{var s;return!((s=navigator.platform)===null||s===void 0)&&s.startsWith("Mac")?["Ctrl","Shift","Command","C"]:["Ctrl","Shift","Alt","C"]},vc=s=>{const{keys:e,onHoverElement:t,onClickElement:n,onInspectElement:o,active:r,onActiveChange:a,disableLaunchEditor:i,disable:l=!0,children:d}=s,[u,p]=g.useState(r??!1);fc(()=>{r!==void 0&&p(r)},[r]),g.useEffect(()=>(u?C():k(),k),[u]);const m=e===null?null:(e??[]).join("+"),h=g.useRef(),f=gc({disable:l}),y=ze(()=>{a==null||a(!0),r===void 0&&p(!0)}),b=ze(()=>{a==null||a(!1),r===void 0&&p(!1)}),C=ze(()=>{if(h.current||l)return;const w=new xc;h.current=w,Ce("esc",b);const E=zl({onPointerOver:T,onClick:_});w.setRemoveCallback(E);const N=f.current,L=document.elementFromPoint(N.x,N.y);L&&T(L)}),k=ze(()=>{var w;(w=h.current)===null||w===void 0||w.remove(),h.current=void 0,Ce.unbind("esc",b)}),T=ze(w=>{var E;const N=h.current,L=Mn(w),$=L==null?void 0:L.relativePath,U=L==null?void 0:L.absolutePath,{fiber:de,name:A,title:S}=Ln(w);(E=N==null?void 0:N.inspect)===null||E===void 0||E.call(N,[w],S,$??U),t==null||t({element:w,fiber:de,codeInfo:L,name:A})}),_=ze(w=>{b();const E=Mn(w),{fiber:N,name:L}=Ln(w);n==null||n({element:w,fiber:N,codeInfo:E,name:L}),N&&E&&(o==null||o({element:w,fiber:N,codeInfo:E,name:L}),!o&&!i&&nc(E))});return g.useEffect(()=>{const w=()=>{h.current?b():y()},E=m===null||l?null:m||Sc().join("+");if(E)return Ce(E,w),()=>{Ce.unbind(E,w)}},[m,l]),c.jsx(c.Fragment,{children:d??null})};function wc(){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(o=>!o))};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)},[]),c.jsxs(c.Fragment,{children:[c.jsx(vc,{active:s,onActiveChange:e}),c.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:c.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"3"}),c.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"}),c.jsx("path",{d:"M12 2v20"}),c.jsx("path",{d:"M2 12h20"})]})})]})}ks.createRoot(document.getElementById("root")).render(c.jsxs(cr.StrictMode,{children:[c.jsx(wc,{}),c.jsx(Ki,{})]}));export{Bc as A,_n as B,Ic as C,Es as D,ct as E,ja as F,Oa as I,Is as M,Rc as P,Lc as R,gt as T,Ac as W,he as _,V as a,ve as b,K as c,ce as d,Be as e,ca as f,Ke as g,x as h,we as i,Xa as j,Mc as k,Me as l,G as m,Pc as n,ma as o,qe as p,Y as q,xi as r,$c as s,W as t,ft as u,Ec as v,F as w,Oc as x,eo as y,ri as z};
|