@yeaft/webchat-agent 1.0.472 → 1.0.474
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/local-runtime/version.json +1 -1
- package/local-runtime/web/app.bundle.js +40 -26
- package/local-runtime/web/app.bundle.js.gz +0 -0
- package/local-runtime/web/index.html +2 -2
- package/local-runtime/web/style.bundle.css +1 -1
- package/local-runtime/web/style.bundle.css.gz +0 -0
- package/package.json +1 -1
|
@@ -303,7 +303,7 @@ The agent will restart after upgrading.`,"chat.agent.alreadyLatest":"Agent is al
|
|
|
303
303
|
</template>
|
|
304
304
|
</div>
|
|
305
305
|
</div>
|
|
306
|
-
`,setup(){let e=$e(),t=Vue.inject("t"),s=Vue.inject("locale"),n=Vue.ref(""),r=Vue.ref(""),i=Vue.ref(""),o=Vue.ref(""),a=Vue.ref(""),l=Vue.ref(null),c=Vue.ref(null),d=Vue.ref(null),u=Vue.ref(null),p=Vue.ref(null),f=Vue.ref(null),g=Vue.ref(""),h=Vue.ref(localStorage.getItem("loginMode")==="credentials"?"credentials":"oauth");Vue.watch(h,de=>localStorage.setItem("loginMode",de));let m=Vue.ref(""),y=Vue.ref(""),v=Vue.ref(""),k=Vue.ref(""),w=Vue.ref(""),b=Vue.ref(!1),C=Vue.ref(""),S=Vue.ref(""),M=Vue.ref(""),N=Vue.ref(""),q=Vue.ref(""),L=Vue.ref(""),V=Vue.ref(!1),$=Vue.ref(!1),T=()=>{a.value="",e.error=null,C.value="email",S.value="",N.value="",q.value="",L.value="",M.value="",$.value=!1},I=()=>{C.value="",M.value="",$.value=!1},R=async()=>{if(a.value="",!S.value||!/.+@.+\..+/.test(S.value)){a.value=t("login.forgot.emailInvalid");return}V.value=!0;try{let de=await e.requestPasswordReset(S.value.trim());if(!de)return;M.value=de,C.value="verify"}finally{V.value=!1}},D=async()=>{if(a.value="",!N.value){a.value=t("login.error.enterVerifyCode");return}if(!q.value||q.value.length<6){a.value=t("login.error.passwordMinLen");return}if(q.value!==L.value){a.value=t("login.error.passwordMismatch");return}V.value=!0;try{await e.verifyPasswordReset(M.value,N.value,q.value)&&($.value=!0,setTimeout(()=>{I(),h.value="credentials"},1500))}finally{V.value=!1}},E={alipay:'<svg viewBox="0 0 32 32" width="22" height="22" aria-hidden="true"><rect width="32" height="32" rx="6" fill="#1677FF"/><path fill="#fff" d="M25 18.6c-1.5-.5-3-1-4.6-1.7.4-.8.8-1.6 1.1-2.5h-2.9v-1h3.4v-.5h-3.4v-1.6h-1.4c-.3 0-.3.3-.3.3v1.3h-3.6v.5h3.6v1H11v.5h5.7c-.2.6-.4 1.2-.7 1.7-1.7-.5-3.4-.8-4.7-.8-2.2 0-3.7 1-3.8 2.5-.1 1.4.9 3 3.4 3 1.8 0 3.4-.9 4.7-2.5 2.2 1 4.2 2 6.6 2.9.3-.4.5-.8.7-1.2.2-.4.1-.9-.1-1.3zM11 19.7c-1.8 0-2.3-1.3-2.1-2 .1-.4.6-.9 1.4-1.1.4-.1 1.4-.1 2.4.2.9.2 1.8.5 2.7.8-.7 1.4-2.1 2.1-4.4 2.1z"/></svg>',microsoft:'<svg viewBox="0 0 21 21" width="20" height="20" aria-hidden="true"><rect x="1" y="1" width="9" height="9" fill="#f25022"/><rect x="1" y="11" width="9" height="9" fill="#00a4ef"/><rect x="11" y="1" width="9" height="9" fill="#7fba00"/><rect x="11" y="11" width="9" height="9" fill="#ffb900"/></svg>',github:'<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="currentColor" d="M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2c-3.3.7-4-1.6-4-1.6-.5-1.4-1.3-1.7-1.3-1.7-1.1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1.1 1.8 2.8 1.3 3.4 1 .1-.8.4-1.3.8-1.6-2.7-.3-5.5-1.3-5.5-6 0-1.3.5-2.3 1.2-3.2-.1-.3-.5-1.5.1-3.2 0 0 1-.3 3.3 1.2A11.5 11.5 0 0 1 12 5.8c1 0 2 .1 3 .4 2.3-1.5 3.3-1.2 3.3-1.2.6 1.7.2 2.9.1 3.2.7.9 1.2 1.9 1.2 3.2 0 4.6-2.8 5.7-5.5 6 .4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6A12 12 0 0 0 12 .3"/></svg>',google:'<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23z"/><path fill="#FBBC05" d="M5.84 14.1A6.6 6.6 0 0 1 5.5 12c0-.73.13-1.44.34-2.1V7.07H2.18A11 11 0 0 0 1 12c0 1.77.42 3.45 1.18 4.93l3.66-2.83z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 0 0 2.18 7.07l3.66 2.83C6.71 7.31 9.14 5.38 12 5.38z"/></svg>',wechat:'<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="#07C160" d="M9.5 4C5.36 4 2 6.91 2 10.5c0 2.07 1.13 3.91 2.86 5.09L4 18l2.7-1.41c.85.22 1.76.34 2.7.34h.51c-.13-.42-.21-.86-.21-1.32 0-3 2.91-5.43 6.5-5.43.32 0 .64.02.95.06C16.63 7.32 13.4 4 9.5 4zM7 8.5a1 1 0 110 2 1 1 0 010-2zm5 0a1 1 0 110 2 1 1 0 010-2zm4.21 3.66c-3.04 0-5.5 1.92-5.5 4.29 0 1.39.91 2.65 2.34 3.46l-.46 1.5 1.93-.95c.55.13 1.13.2 1.69.2 3.04 0 5.5-1.92 5.5-4.21 0-2.37-2.46-4.29-5.5-4.29zm-1.71 2.21a.75.75 0 110 1.5.75.75 0 010-1.5zm3.42 0a.75.75 0 110 1.5.75.75 0 010-1.5z"/></svg>'},Y=Vue.computed(()=>["alipay","microsoft","github","google","wechat"].filter(Z=>Z==="microsoft"?e.aadEnabled:!!e.ssoProviders[Z]).map(Z=>({key:Z,label:t(`login.${Z}`),icon:E[Z]}))),Q=()=>{c.value&&c.value.focus()},re=()=>{h.value="credentials",Vue.nextTick(()=>{l.value&&l.value.focus()})},fe=()=>{let de=e.qrPanel;if(!de||!de.authorizeUrl)return;let Z=`alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(de.authorizeUrl)}`;window.location.href=Z},me=de=>{if(a.value="",de==="microsoft"){e.loginWithMicrosoft();return}if(de==="alipay"){Ni()?e.loginWithSso(de):vn()?e.loginWithAlipayMobile():e.startSsoQr(de).then(Z=>{Z&&W()});return}if(de==="wechat"){if(vn()||Bi()){a.value=t("login.wechat.mobileUnsupported");return}e.startSsoQr(de).then(Z=>{Z&&W()});return}e.loginWithSso(de)},le=async()=>{if(!n.value){a.value=t("login.error.enterUsername");return}if(!r.value){a.value=t("login.error.enterPassword");return}a.value="",await e.login(n.value,r.value),Vue.nextTick(()=>{(e.loginStep==="totp"||e.loginStep==="totp-setup")&&u.value?u.value.focus():e.loginStep==="verification"&&d.value&&d.value.focus()})},W=()=>{if(e.qrPanel&&typeof qrcode=="function")try{let de=qrcode(0,"M");de.addData(e.qrPanel.authorizeUrl,"Byte"),de.make(),g.value=de.createDataURL(6,4)}catch{}},ne=Vue.computed(()=>{let de=e.qrPanel?.provider;return t(de==="alipay"?"login.qr.titleAlipay":de==="wechat"?"login.qr.titleWechat":"login.qr.title")});Vue.watch(()=>e.qrPanel?.authorizeUrl,de=>{de?W():g.value=""});let oe=async()=>{if(!o.value||o.value.length!==6){a.value=t("login.error.enter6Digit");return}a.value="",await e.verifyTotpCode(o.value)&&e.loginStep==="verification"&&(o.value="",Vue.nextTick(()=>{d.value&&d.value.focus()}))},U=async()=>{if(!o.value||o.value.length!==6){a.value=t("login.error.enter6Digit");return}a.value="",await e.completeTotpSetup(o.value)&&e.loginStep==="verification"&&(o.value="",Vue.nextTick(()=>{d.value&&d.value.focus()}))},ce=async()=>{if(a.value="",b.value=!1,!y.value||y.value.length<2){a.value=t("login.error.usernameMinLen");return}if(!v.value||v.value.length<6){a.value=t("login.error.passwordMinLen");return}if(v.value!==k.value){a.value=t("login.error.passwordMismatch");return}await e.register(y.value,v.value,w.value||void 0,m.value)&&(b.value=!0,n.value=y.value,m.value="",y.value="",v.value="",k.value="",w.value="",setTimeout(()=>e.backToCredentials(),1500))},Ae=async()=>{if(!i.value){a.value=t("login.error.enterVerifyCode");return}a.value="",await e.verifyCode(i.value)};return Vue.onMounted(async()=>{await e.checkAuthMode(),Y.value.length===0&&h.value==="oauth"&&(h.value="credentials"),e.loginStep==="credentials"&&h.value==="credentials"&&l.value&&l.value.focus()}),Vue.watch(()=>e.loginStep,de=>{Vue.nextTick(()=>{de==="credentials"&&h.value==="credentials"&&l.value?l.value.focus():(de==="totp"||de==="totp-setup")&&u.value?u.value.focus():de==="verification"&&d.value?d.value.focus():de==="register"&&p.value&&p.value.focus()})}),{authStore:e,currentLocale:s,toggleLang:()=>{Yn(s.value==="zh-CN"?"en":"zh-CN")},loginMode:h,switchToCredentials:re,enabledProviders:Y,handleProviderClick:me,relaunchAlipayMobile:fe,qrCanvas:f,qrDataUrl:g,qrPanelTitle:ne,username:n,password:r,verificationCode:i,totpCode:o,localError:a,usernameInput:l,passwordInput:c,codeInput:d,totpInput:u,regCodeInput:p,regInvitationCode:m,regUsername:y,regPassword:v,regPasswordConfirm:k,regEmail:w,registerSuccess:b,focusPassword:Q,login:le,verify:Ae,verifyTotp:oe,setupTotp:U,doRegister:ce,forgotStep:C,forgotEmail:S,forgotResetToken:M,forgotCode:N,forgotNewPassword:q,forgotConfirm:L,forgotLoading:V,forgotSuccess:$,enterForgotMode:T,exitForgotMode:I,submitForgotEmail:R,submitForgotReset:D}}}});function xl(){return Cl||(Cl=Vue.reactive({open:!1,id:0,type:"alert",title:"",message:"",value:"",confirmLabel:"",cancelLabel:"",destructive:!1})),Cl}function Gp(){dt||Al.length===0||(dt=Al.shift(),Object.assign(xl(),{open:!0,id:dt.id,type:dt.type,title:dt.options.title||"",message:dt.options.message||"",value:dt.options.defaultValue||"",confirmLabel:dt.options.confirmLabel||"",cancelLabel:dt.options.cancelLabel||"",destructive:dt.options.destructive===!0}))}function Tl(e,t,s={}){return new Promise(n=>{Al.push({id:++ub,type:e,options:{...s,message:String(t||"")},resolve:n}),Gp()})}function it(e,t){return Tl("alert",e,t)}function
|
|
306
|
+
`,setup(){let e=$e(),t=Vue.inject("t"),s=Vue.inject("locale"),n=Vue.ref(""),r=Vue.ref(""),i=Vue.ref(""),o=Vue.ref(""),a=Vue.ref(""),l=Vue.ref(null),c=Vue.ref(null),d=Vue.ref(null),u=Vue.ref(null),p=Vue.ref(null),f=Vue.ref(null),g=Vue.ref(""),h=Vue.ref(localStorage.getItem("loginMode")==="credentials"?"credentials":"oauth");Vue.watch(h,de=>localStorage.setItem("loginMode",de));let m=Vue.ref(""),y=Vue.ref(""),v=Vue.ref(""),k=Vue.ref(""),w=Vue.ref(""),b=Vue.ref(!1),C=Vue.ref(""),S=Vue.ref(""),M=Vue.ref(""),N=Vue.ref(""),q=Vue.ref(""),L=Vue.ref(""),V=Vue.ref(!1),$=Vue.ref(!1),T=()=>{a.value="",e.error=null,C.value="email",S.value="",N.value="",q.value="",L.value="",M.value="",$.value=!1},I=()=>{C.value="",M.value="",$.value=!1},R=async()=>{if(a.value="",!S.value||!/.+@.+\..+/.test(S.value)){a.value=t("login.forgot.emailInvalid");return}V.value=!0;try{let de=await e.requestPasswordReset(S.value.trim());if(!de)return;M.value=de,C.value="verify"}finally{V.value=!1}},D=async()=>{if(a.value="",!N.value){a.value=t("login.error.enterVerifyCode");return}if(!q.value||q.value.length<6){a.value=t("login.error.passwordMinLen");return}if(q.value!==L.value){a.value=t("login.error.passwordMismatch");return}V.value=!0;try{await e.verifyPasswordReset(M.value,N.value,q.value)&&($.value=!0,setTimeout(()=>{I(),h.value="credentials"},1500))}finally{V.value=!1}},E={alipay:'<svg viewBox="0 0 32 32" width="22" height="22" aria-hidden="true"><rect width="32" height="32" rx="6" fill="#1677FF"/><path fill="#fff" d="M25 18.6c-1.5-.5-3-1-4.6-1.7.4-.8.8-1.6 1.1-2.5h-2.9v-1h3.4v-.5h-3.4v-1.6h-1.4c-.3 0-.3.3-.3.3v1.3h-3.6v.5h3.6v1H11v.5h5.7c-.2.6-.4 1.2-.7 1.7-1.7-.5-3.4-.8-4.7-.8-2.2 0-3.7 1-3.8 2.5-.1 1.4.9 3 3.4 3 1.8 0 3.4-.9 4.7-2.5 2.2 1 4.2 2 6.6 2.9.3-.4.5-.8.7-1.2.2-.4.1-.9-.1-1.3zM11 19.7c-1.8 0-2.3-1.3-2.1-2 .1-.4.6-.9 1.4-1.1.4-.1 1.4-.1 2.4.2.9.2 1.8.5 2.7.8-.7 1.4-2.1 2.1-4.4 2.1z"/></svg>',microsoft:'<svg viewBox="0 0 21 21" width="20" height="20" aria-hidden="true"><rect x="1" y="1" width="9" height="9" fill="#f25022"/><rect x="1" y="11" width="9" height="9" fill="#00a4ef"/><rect x="11" y="1" width="9" height="9" fill="#7fba00"/><rect x="11" y="11" width="9" height="9" fill="#ffb900"/></svg>',github:'<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="currentColor" d="M12 .3a12 12 0 0 0-3.8 23.4c.6.1.8-.3.8-.6v-2c-3.3.7-4-1.6-4-1.6-.5-1.4-1.3-1.7-1.3-1.7-1.1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1.1 1.8 2.8 1.3 3.4 1 .1-.8.4-1.3.8-1.6-2.7-.3-5.5-1.3-5.5-6 0-1.3.5-2.3 1.2-3.2-.1-.3-.5-1.5.1-3.2 0 0 1-.3 3.3 1.2A11.5 11.5 0 0 1 12 5.8c1 0 2 .1 3 .4 2.3-1.5 3.3-1.2 3.3-1.2.6 1.7.2 2.9.1 3.2.7.9 1.2 1.9 1.2 3.2 0 4.6-2.8 5.7-5.5 6 .4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6A12 12 0 0 0 12 .3"/></svg>',google:'<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23z"/><path fill="#FBBC05" d="M5.84 14.1A6.6 6.6 0 0 1 5.5 12c0-.73.13-1.44.34-2.1V7.07H2.18A11 11 0 0 0 1 12c0 1.77.42 3.45 1.18 4.93l3.66-2.83z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 0 0 2.18 7.07l3.66 2.83C6.71 7.31 9.14 5.38 12 5.38z"/></svg>',wechat:'<svg viewBox="0 0 24 24" width="20" height="20" aria-hidden="true"><path fill="#07C160" d="M9.5 4C5.36 4 2 6.91 2 10.5c0 2.07 1.13 3.91 2.86 5.09L4 18l2.7-1.41c.85.22 1.76.34 2.7.34h.51c-.13-.42-.21-.86-.21-1.32 0-3 2.91-5.43 6.5-5.43.32 0 .64.02.95.06C16.63 7.32 13.4 4 9.5 4zM7 8.5a1 1 0 110 2 1 1 0 010-2zm5 0a1 1 0 110 2 1 1 0 010-2zm4.21 3.66c-3.04 0-5.5 1.92-5.5 4.29 0 1.39.91 2.65 2.34 3.46l-.46 1.5 1.93-.95c.55.13 1.13.2 1.69.2 3.04 0 5.5-1.92 5.5-4.21 0-2.37-2.46-4.29-5.5-4.29zm-1.71 2.21a.75.75 0 110 1.5.75.75 0 010-1.5zm3.42 0a.75.75 0 110 1.5.75.75 0 010-1.5z"/></svg>'},Y=Vue.computed(()=>["alipay","microsoft","github","google","wechat"].filter(Z=>Z==="microsoft"?e.aadEnabled:!!e.ssoProviders[Z]).map(Z=>({key:Z,label:t(`login.${Z}`),icon:E[Z]}))),Q=()=>{c.value&&c.value.focus()},re=()=>{h.value="credentials",Vue.nextTick(()=>{l.value&&l.value.focus()})},fe=()=>{let de=e.qrPanel;if(!de||!de.authorizeUrl)return;let Z=`alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(de.authorizeUrl)}`;window.location.href=Z},me=de=>{if(a.value="",de==="microsoft"){e.loginWithMicrosoft();return}if(de==="alipay"){Ni()?e.loginWithSso(de):vn()?e.loginWithAlipayMobile():e.startSsoQr(de).then(Z=>{Z&&W()});return}if(de==="wechat"){if(vn()||Bi()){a.value=t("login.wechat.mobileUnsupported");return}e.startSsoQr(de).then(Z=>{Z&&W()});return}e.loginWithSso(de)},le=async()=>{if(!n.value){a.value=t("login.error.enterUsername");return}if(!r.value){a.value=t("login.error.enterPassword");return}a.value="",await e.login(n.value,r.value),Vue.nextTick(()=>{(e.loginStep==="totp"||e.loginStep==="totp-setup")&&u.value?u.value.focus():e.loginStep==="verification"&&d.value&&d.value.focus()})},W=()=>{if(e.qrPanel&&typeof qrcode=="function")try{let de=qrcode(0,"M");de.addData(e.qrPanel.authorizeUrl,"Byte"),de.make(),g.value=de.createDataURL(6,4)}catch{}},ne=Vue.computed(()=>{let de=e.qrPanel?.provider;return t(de==="alipay"?"login.qr.titleAlipay":de==="wechat"?"login.qr.titleWechat":"login.qr.title")});Vue.watch(()=>e.qrPanel?.authorizeUrl,de=>{de?W():g.value=""});let oe=async()=>{if(!o.value||o.value.length!==6){a.value=t("login.error.enter6Digit");return}a.value="",await e.verifyTotpCode(o.value)&&e.loginStep==="verification"&&(o.value="",Vue.nextTick(()=>{d.value&&d.value.focus()}))},U=async()=>{if(!o.value||o.value.length!==6){a.value=t("login.error.enter6Digit");return}a.value="",await e.completeTotpSetup(o.value)&&e.loginStep==="verification"&&(o.value="",Vue.nextTick(()=>{d.value&&d.value.focus()}))},ce=async()=>{if(a.value="",b.value=!1,!y.value||y.value.length<2){a.value=t("login.error.usernameMinLen");return}if(!v.value||v.value.length<6){a.value=t("login.error.passwordMinLen");return}if(v.value!==k.value){a.value=t("login.error.passwordMismatch");return}await e.register(y.value,v.value,w.value||void 0,m.value)&&(b.value=!0,n.value=y.value,m.value="",y.value="",v.value="",k.value="",w.value="",setTimeout(()=>e.backToCredentials(),1500))},Ae=async()=>{if(!i.value){a.value=t("login.error.enterVerifyCode");return}a.value="",await e.verifyCode(i.value)};return Vue.onMounted(async()=>{await e.checkAuthMode(),Y.value.length===0&&h.value==="oauth"&&(h.value="credentials"),e.loginStep==="credentials"&&h.value==="credentials"&&l.value&&l.value.focus()}),Vue.watch(()=>e.loginStep,de=>{Vue.nextTick(()=>{de==="credentials"&&h.value==="credentials"&&l.value?l.value.focus():(de==="totp"||de==="totp-setup")&&u.value?u.value.focus():de==="verification"&&d.value?d.value.focus():de==="register"&&p.value&&p.value.focus()})}),{authStore:e,currentLocale:s,toggleLang:()=>{Yn(s.value==="zh-CN"?"en":"zh-CN")},loginMode:h,switchToCredentials:re,enabledProviders:Y,handleProviderClick:me,relaunchAlipayMobile:fe,qrCanvas:f,qrDataUrl:g,qrPanelTitle:ne,username:n,password:r,verificationCode:i,totpCode:o,localError:a,usernameInput:l,passwordInput:c,codeInput:d,totpInput:u,regCodeInput:p,regInvitationCode:m,regUsername:y,regPassword:v,regPasswordConfirm:k,regEmail:w,registerSuccess:b,focusPassword:Q,login:le,verify:Ae,verifyTotp:oe,setupTotp:U,doRegister:ce,forgotStep:C,forgotEmail:S,forgotResetToken:M,forgotCode:N,forgotNewPassword:q,forgotConfirm:L,forgotLoading:V,forgotSuccess:$,enterForgotMode:T,exitForgotMode:I,submitForgotEmail:R,submitForgotReset:D}}}});function xl(){return Cl||(Cl=Vue.reactive({open:!1,id:0,type:"alert",title:"",message:"",value:"",confirmLabel:"",cancelLabel:"",destructive:!1})),Cl}function Gp(){dt||Al.length===0||(dt=Al.shift(),Object.assign(xl(),{open:!0,id:dt.id,type:dt.type,title:dt.options.title||"",message:dt.options.message||"",value:dt.options.defaultValue||"",confirmLabel:dt.options.confirmLabel||"",cancelLabel:dt.options.cancelLabel||"",destructive:dt.options.destructive===!0}))}function Tl(e,t,s={}){return new Promise(n=>{Al.push({id:++ub,type:e,options:{...s,message:String(t||"")},resolve:n}),Gp()})}function it(e,t){return Tl("alert",e,t)}function De(e,t){return Tl("confirm",e,t)}function Ml(e,t="",s={}){return Tl("prompt",e,{...s,defaultValue:t})}function Wi(e,t=""){if(!dt)return;let s=dt;dt=null,xl().open=!1,s.type==="alert"?s.resolve(void 0):s.type==="confirm"?s.resolve(e===!0):s.resolve(e?t:null),Vue.nextTick(Gp)}function Qp(){return xl()}var Al,dt,ub,Cl,ot=F(()=>{Al=[],dt=null,ub=0,Cl=null});var ji,Pl=F(()=>{ot();ji={name:"ChatHeader",emits:["toggle-sidebar","close-pane"],props:{conversationId:{type:String,default:null},paneId:{type:String,default:null},showClosePane:{type:Boolean,default:!1},canUseWorkbench:{type:Boolean,default:!1}},template:`
|
|
307
307
|
<header class="chat-header">
|
|
308
308
|
<!-- Mobile sidebar toggle \u2014 hidden on desktop and in split mode -->
|
|
309
309
|
<button class="header-sidebar-toggle" v-if="!store.isSplitMode"
|
|
@@ -408,7 +408,7 @@ The agent will restart after upgrading.`,"chat.agent.alreadyLatest":"Agent is al
|
|
|
408
408
|
</button>
|
|
409
409
|
</div>
|
|
410
410
|
</header>
|
|
411
|
-
`,setup(e){let t=Pinia.useChatStore(),s=Vue.inject("t"),n=Vue.computed(()=>e.conversationId||t.currentConversation),r=Vue.computed(()=>n.value&&t.conversations.find(W=>W.id===n.value)||null),i=Vue.computed(()=>r.value?.capabilities||null),o=Vue.computed(()=>n.value?(r.value?.provider||"claude-code")==="claude-code":!0),a=(W,ne=!0)=>{let oe=i.value;return oe?!!oe[W]:o.value?ne:!1},l=Vue.computed(()=>a("compact")),c=Vue.computed(()=>a("clear")),d=Vue.computed(()=>a("expert")),u=Vue.computed(()=>a("mcp")),p=Vue.computed(()=>{if(!n.value)return"Yeaft";let W=t.getConversationTitle(n.value);if(W)return W;let oe=t.conversations.find(U=>U.id===n.value)?.workDir||t.currentWorkDir;if(oe){let U=oe.split(/[/\\]/);return U[U.length-1]||U[U.length-2]||oe}return s("chatHeader.newConv")}),f=Vue.computed(()=>{if(!n.value)return"";let ne=t.conversations.find(U=>U.id===n.value)?.agentId;return ne&&t.agents.find(U=>U.id===ne)?.name||""}),g=Vue.computed(()=>t.clearStatus?.conversationId===n.value?!0:t.compactStatus?t.compactStatus.conversationId===n.value:!1),h=Vue.computed(()=>t.clearStatus?.conversationId===n.value?t.clearStatus.status==="clearing"?"compacting":"completed":t.compactStatus?t.compactStatus.status==="compacting"?"compacting":"completed":""),m=Vue.computed(()=>t.clearStatus?.conversationId===n.value?t.clearStatus.status==="clearing":t.compactStatus?.status==="compacting"),y=Vue.computed(()=>t.clearStatus?.conversationId===n.value?t.clearStatus.status==="clearing"?s("chatHeader.clearing"):s("chatHeader.clearDone"):t.compactStatus?t.compactStatus.status==="compacting"?t.compactStatus.message||s("chatHeader.compacting"):t.compactStatus.message||s("chatHeader.compactDone"):""),v=Vue.computed(()=>n.value&&(t.conversations.find(ne=>ne.id===n.value)?.workDir||t.currentWorkDir)||""),k=Vue.computed(()=>!t.contextUsage||t.contextUsage.conversationId!==n.value?null:t.contextUsage),w=Vue.computed(()=>{let W=k.value?.percentage||0;return W>=80?"context-danger":W>=50?"context-warn":"context-ok"}),b=Vue.computed(()=>{if(!k.value)return"";let W=(k.value.inputTokens/1e3).toFixed(0),ne=(k.value.maxTokens/1e3).toFixed(0);return`Context: ${W}k / ${ne}k`}),C=Vue.computed(()=>t.isRefreshingSession(n.value)),S=Vue.computed(()=>t.compactStatus?.status==="compacting"&&t.compactStatus?.conversationId===n.value),M=Vue.computed(()=>t.clearStatus?.status==="clearing"&&t.clearStatus?.conversationId===n.value),N=Vue.computed(()=>n.value?!t.isRefreshingSession(n.value):!1),q=()=>{if(t.isRefreshingSession(n.value)||!n.value)return;t.setRefreshingSession(n.value,!0),t.startRefreshTimeout(n.value),t.requestChatHistory(n.value,{mode:"recent",turns:5})||t.setRefreshingSession(n.value,!1)},L=()=>{S.value||t.sendMessage("/compact")},V=()=>{window.location.reload()},$=async()=>{M.value||await
|
|
411
|
+
`,setup(e){let t=Pinia.useChatStore(),s=Vue.inject("t"),n=Vue.computed(()=>e.conversationId||t.currentConversation),r=Vue.computed(()=>n.value&&t.conversations.find(W=>W.id===n.value)||null),i=Vue.computed(()=>r.value?.capabilities||null),o=Vue.computed(()=>n.value?(r.value?.provider||"claude-code")==="claude-code":!0),a=(W,ne=!0)=>{let oe=i.value;return oe?!!oe[W]:o.value?ne:!1},l=Vue.computed(()=>a("compact")),c=Vue.computed(()=>a("clear")),d=Vue.computed(()=>a("expert")),u=Vue.computed(()=>a("mcp")),p=Vue.computed(()=>{if(!n.value)return"Yeaft";let W=t.getConversationTitle(n.value);if(W)return W;let oe=t.conversations.find(U=>U.id===n.value)?.workDir||t.currentWorkDir;if(oe){let U=oe.split(/[/\\]/);return U[U.length-1]||U[U.length-2]||oe}return s("chatHeader.newConv")}),f=Vue.computed(()=>{if(!n.value)return"";let ne=t.conversations.find(U=>U.id===n.value)?.agentId;return ne&&t.agents.find(U=>U.id===ne)?.name||""}),g=Vue.computed(()=>t.clearStatus?.conversationId===n.value?!0:t.compactStatus?t.compactStatus.conversationId===n.value:!1),h=Vue.computed(()=>t.clearStatus?.conversationId===n.value?t.clearStatus.status==="clearing"?"compacting":"completed":t.compactStatus?t.compactStatus.status==="compacting"?"compacting":"completed":""),m=Vue.computed(()=>t.clearStatus?.conversationId===n.value?t.clearStatus.status==="clearing":t.compactStatus?.status==="compacting"),y=Vue.computed(()=>t.clearStatus?.conversationId===n.value?t.clearStatus.status==="clearing"?s("chatHeader.clearing"):s("chatHeader.clearDone"):t.compactStatus?t.compactStatus.status==="compacting"?t.compactStatus.message||s("chatHeader.compacting"):t.compactStatus.message||s("chatHeader.compactDone"):""),v=Vue.computed(()=>n.value&&(t.conversations.find(ne=>ne.id===n.value)?.workDir||t.currentWorkDir)||""),k=Vue.computed(()=>!t.contextUsage||t.contextUsage.conversationId!==n.value?null:t.contextUsage),w=Vue.computed(()=>{let W=k.value?.percentage||0;return W>=80?"context-danger":W>=50?"context-warn":"context-ok"}),b=Vue.computed(()=>{if(!k.value)return"";let W=(k.value.inputTokens/1e3).toFixed(0),ne=(k.value.maxTokens/1e3).toFixed(0);return`Context: ${W}k / ${ne}k`}),C=Vue.computed(()=>t.isRefreshingSession(n.value)),S=Vue.computed(()=>t.compactStatus?.status==="compacting"&&t.compactStatus?.conversationId===n.value),M=Vue.computed(()=>t.clearStatus?.status==="clearing"&&t.clearStatus?.conversationId===n.value),N=Vue.computed(()=>n.value?!t.isRefreshingSession(n.value):!1),q=()=>{if(t.isRefreshingSession(n.value)||!n.value)return;t.setRefreshingSession(n.value,!0),t.startRefreshTimeout(n.value),t.requestChatHistory(n.value,{mode:"recent",turns:5})||t.setRefreshingSession(n.value,!1)},L=()=>{S.value||t.sendMessage("/compact")},V=()=>{window.location.reload()},$=async()=>{M.value||await De(s("chatHeader.confirmClear"),{destructive:!0})&&(t.clearStatus={conversationId:n.value,status:"clearing"},t.sendMessage("/clear"))},T=Vue.computed(()=>t.getPaneRightPanel(e.paneId)),I=Vue.ref(null),R=Vue.computed(()=>{if(!t.mcpPanelOpen||!I.value)return null;let W=I.value.getBoundingClientRect();return{top:`${W.bottom+6}px`,right:`${window.innerWidth-W.right}px`}}),D=Vue.computed(()=>t.currentMcpServers.filter(W=>W.enabled).length),E=Vue.computed(()=>!!t.conversations.find(ne=>ne.id===n.value)?.needRestart),Y=()=>{t.mcpPanelOpen=!t.mcpPanelOpen},Q=()=>{t.togglePaneRightPanel("experts",e.paneId)},re=()=>{t.togglePaneRightPanel("subagents",e.paneId)},fe=Vue.computed(()=>t.runningSubagentCount),me=(W,ne)=>{t.toggleConversationMcp(W,ne)},le=W=>{t.mcpPanelOpen&&!W.target.closest(".mcp-dropdown")&&!W.target.closest(".mcp-config-wrapper")&&(t.mcpPanelOpen=!1)};return Vue.onMounted(()=>{document.addEventListener("click",le)}),Vue.onUnmounted(()=>{document.removeEventListener("click",le)}),{store:t,effectiveConvId:n,effectiveRightPanel:T,isClaudeCode:o,canCompact:l,canClear:c,canExpert:d,canMcp:u,headerTitle:p,showStatusBanner:g,statusBannerClass:h,statusBannerSpinner:m,statusBannerMessage:y,contextUsage:k,contextColorClass:w,contextLabel:b,isRefreshing:C,isCompacting:S,isClearing:M,canRefresh:N,refreshSession:q,reloadPage:V,compactContext:L,clearMessages:$,mcpBtnRef:I,mcpDropdownStyle:R,mcpEnabledCount:D,currentConvNeedRestart:E,toggleMcpPanel:Y,toggleMcpServer:me,toggleExpertPanel:Q,toggleSubAgentPanel:re,runningSubagentCount:fe}}}});function yn(e=globalThis.location){let t=e?.protocol==="https:"?"wss:":"ws:",s=e?.host||"localhost";return`${t}//${s}`}function Ui(){return"npm install -g @yeaft/webchat-agent"}function Ki(){return"yeaft-agent llm use github-copilot --model gpt-5.5"}function zi(e=null){let t=e&&(e.username||e.displayName)||"agent",s=2166136261;for(let i=0;i<t.length;i++)s^=t.charCodeAt(i),s=s+((s<<1)+(s<<4)+(s<<7)+(s<<8)+(s<<24))>>>0;let n=s.toString(16).padStart(8,"0").slice(0,6);return`${String(t).replace(/[^A-Za-z0-9_-]/g,"-").replace(/^-+|-+$/g,"")||"agent"}-${n}`}function Yi({profile:e=null,agentSecret:t="",serverWsUrl:s=yn()}={}){if(!t)return"";let n=zi(e);return`yeaft-agent install --server ${s} --secret ${t} --name ${n}`}function Xp({profile:e=null,agentSecret:t="",serverWsUrl:s=yn()}={}){if(!t)return"";let n=zi(e);return`yeaft-agent container install --server ${s} --secret ${t} --name ${n}`}var Rl=F(()=>{});function pb(e,t){return typeof e=="string"?e?{src:e,alt:t}:null:!e||typeof e!="object"||!e.src?null:{src:e.src,alt:e.alt||t}}function bn(e,{alt:t="Preview",closeLabel:s="Close",previousLabel:n="Previous image",nextLabel:r="Next image",positionLabel:i=(c,d)=>`${c} / ${d}`,gallery:o=null,initialIndex:a=null,trigger:l=null}={}){if(!e)return null;let c=(Array.isArray(o)?o:[e]).map(N=>pb(N,t)).filter(Boolean);c.length===0&&c.push({src:e,alt:t});let d=Number.isInteger(a)&&a>=0&&a<c.length?a:c.findIndex(N=>N.src===e);d<0&&(d=0);let u=document.createElement("div");u.className="image-preview-overlay",u.setAttribute("role","dialog"),u.setAttribute("aria-modal","true"),u.setAttribute("aria-label",t);let p=document.createElement("img");p.className="image-preview-img",p.draggable=!1;let f=document.createElement("button");f.type="button",f.className="image-preview-close",f.setAttribute("aria-label",s),f.setAttribute("title",s),f.textContent="\xD7";let g=null,h=null,m=null;c.length>1&&(g=document.createElement("button"),g.type="button",g.className="image-preview-navigation image-preview-previous",g.setAttribute("aria-label",n),g.setAttribute("title",n),g.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="m15 18-6-6 6-6"/></svg>',h=document.createElement("button"),h.type="button",h.className="image-preview-navigation image-preview-next",h.setAttribute("aria-label",r),h.setAttribute("title",r),h.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="m9 18 6-6-6-6"/></svg>',m=document.createElement("div"),m.className="image-preview-position",m.setAttribute("aria-live","polite"));let y=()=>{let N=c[d];p.src=N.src,p.alt=N.alt,u.setAttribute("aria-label",N.alt),m&&(m.textContent=typeof i=="function"?i(d+1,c.length):`${d+1} / ${c.length}`)},v=N=>{d=(d+N+c.length)%c.length,y()};y(),u.append(p),g&&h&&m&&u.append(g,h,m),u.append(f),document.body.appendChild(u),u.offsetHeight,u.classList.add("visible"),f.focus();let k=!1,w=null,b=()=>{w&&clearTimeout(w),w=null,u.isConnected&&u.remove()},C=()=>{k||(k=!0,u.classList.remove("visible"),u.addEventListener("transitionend",b,{once:!0}),w=setTimeout(b,250),document.removeEventListener("keydown",M),l?.isConnected&&typeof l.focus=="function"&&l.focus())},S=[g,h,f].filter(Boolean),M=N=>{if(N.key==="Escape"){N.preventDefault(),C();return}if(c.length>1&&(N.key==="ArrowLeft"||N.key==="ArrowRight")){N.preventDefault(),v(N.key==="ArrowLeft"?-1:1);return}if(N.key==="Tab"){N.preventDefault();let q=S.indexOf(document.activeElement),L=N.shiftKey?-1:1,V=q<0?0:(q+L+S.length)%S.length;S[V].focus()}};return f.addEventListener("click",C),g?.addEventListener("click",()=>v(-1)),h?.addEventListener("click",()=>v(1)),u.addEventListener("click",N=>{N.target===u&&C()}),document.addEventListener("keydown",M),u}var Gi=F(()=>{});function hb(e){let t=[];for(let s of e)s==="\b"?t.pop():t.push(s);return t.join("")}function mb(e){let t=e.split("\r"),s=t[t.length-1]||"";return hb(s)}function sf(e){return e.replace(/\r\n/g,`
|
|
412
412
|
`).split(`
|
|
413
413
|
`).map(t=>mb(t)).join(`
|
|
414
414
|
`)}function nf(e){return e.replace(fb,"").replace(gb,"")}function vb(e){return e?e.split(";").filter(t=>t!=="").map(t=>Number(t)).filter(Number.isFinite):[0]}function Zp(e,t){let s=t==="bg"&&e>=30&&e<=37||t==="bg"&&e>=90&&e<=97?e+10:e;return t==="bg"?Ll.get(s):El.get(s)}function Jp(e,t,s){let n=$l[0],r=1/0;for(let i of $l){let o=(i.r-e)**2+(i.g-t)**2+(i.b-s)**2;o<r&&(n=i,r=o)}return n.code}function yb(e){if(e<0||e>255)return null;if(e<16){let s=$l[e];return{r:s.r,g:s.g,b:s.b}}if(e>=232){let s=8+(e-232)*10;return{r:s,g:s,b:s}}let t=e-16;return{r:Dl[Math.floor(t/36)],g:Dl[Math.floor(t%36/6)],b:Dl[t%6]}}function ef(e,t,s,n){let r=s[n+1];if(r===5){let i=s[n+2];if(Number.isFinite(i)){let o=yb(i);o&&(e[t]=Zp(Jp(o.r,o.g,o.b),t)||"")}return n+3}if(r===2){let i=s[n+2],o=s[n+3],a=s[n+4];return Number.isFinite(i)&&Number.isFinite(o)&&Number.isFinite(a)&&(e[t]=Zp(Jp(i,o,a),t)||""),n+5}return n+2}function bb(e,t){let s={...e},n=t.length?t:[0];for(let r=0;r<n.length;){let i=n[r];if(i===0)s.fg="",s.bg="",s.bold=!1,s.dim=!1,s.italic=!1,s.underline=!1;else if(i===1)s.bold=!0,s.dim=!1;else if(i===2)s.dim=!0,s.bold=!1;else if(i===3)s.italic=!0;else if(i===4)s.underline=!0;else if(i===22)s.bold=!1,s.dim=!1;else if(i===23)s.italic=!1;else if(i===24)s.underline=!1;else if(i===39)s.fg="";else if(i===49)s.bg="";else if(El.has(i))s.fg=El.get(i);else if(Ll.has(i))s.bg=Ll.get(i);else if(i===38){r=ef(s,"fg",n,r);continue}else if(i===48){r=ef(s,"bg",n,r);continue}r+=1}return s}function wb(e){return[e.fg,e.bg,e.bold&&"terminal-bold",e.dim&&"terminal-dim",e.italic&&"terminal-italic",e.underline&&"terminal-underline"].filter(Boolean).join(" ")}function tf(e,t,s){let n=nf(t);if(!n)return;let r=wb(s),i=e[e.length-1];i&&i.className===r?i.text+=n:e.push({text:n,className:r})}function Qt(e){if(e==null)return"";let t=typeof e=="string"?e:String(e);return t?nf(sf(t)):""}function rf(e){if(e==null)return[];let t=typeof e=="string"?e:String(e);if(!t)return[];let s=sf(t),n=[],r={fg:"",bg:"",bold:!1,dim:!1,italic:!1,underline:!1},i=0;_l.lastIndex=0;for(let o=_l.exec(s);o;o=_l.exec(s))tf(n,s.slice(i,o.index),r),r=bb(r,vb(o[1])),i=o.index+o[0].length;return tf(n,s.slice(i),r),n}var fb,_l,gb,El,Ll,$l,Dl,Cr=F(()=>{fb=/[\u001b\u009b](?:[\[\]()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]|\][^\u0007]*(?:\u0007|\u001b\\)|[PX^_][\s\S]*?\u001b\\)/g,_l=/(?:\u001b\[|\u009b)([0-9;]*)m/g,gb=/[\u0000-\u0008\u000b\u000c\u000e-\u001a\u001c-\u001f\u007f-\u009f]/g,El=new Map([[30,"terminal-fg-black"],[31,"terminal-fg-red"],[32,"terminal-fg-green"],[33,"terminal-fg-yellow"],[34,"terminal-fg-blue"],[35,"terminal-fg-magenta"],[36,"terminal-fg-cyan"],[37,"terminal-fg-white"],[90,"terminal-fg-bright-black"],[91,"terminal-fg-bright-red"],[92,"terminal-fg-bright-green"],[93,"terminal-fg-bright-yellow"],[94,"terminal-fg-bright-blue"],[95,"terminal-fg-bright-magenta"],[96,"terminal-fg-bright-cyan"],[97,"terminal-fg-bright-white"]]),Ll=new Map([[40,"terminal-bg-black"],[41,"terminal-bg-red"],[42,"terminal-bg-green"],[43,"terminal-bg-yellow"],[44,"terminal-bg-blue"],[45,"terminal-bg-magenta"],[46,"terminal-bg-cyan"],[47,"terminal-bg-white"],[100,"terminal-bg-bright-black"],[101,"terminal-bg-bright-red"],[102,"terminal-bg-bright-green"],[103,"terminal-bg-bright-yellow"],[104,"terminal-bg-bright-blue"],[105,"terminal-bg-bright-magenta"],[106,"terminal-bg-bright-cyan"],[107,"terminal-bg-bright-white"]]),$l=[{code:30,r:0,g:0,b:0},{code:31,r:170,g:0,b:0},{code:32,r:0,g:170,b:0},{code:33,r:170,g:85,b:0},{code:34,r:0,g:0,b:170},{code:35,r:170,g:0,b:170},{code:36,r:0,g:170,b:170},{code:37,r:170,g:170,b:170},{code:90,r:85,g:85,b:85},{code:91,r:255,g:85,b:85},{code:92,r:85,g:255,b:85},{code:93,r:255,g:255,b:85},{code:94,r:85,g:85,b:255},{code:95,r:255,g:85,b:255},{code:96,r:85,g:255,b:255},{code:97,r:255,g:255,b:255}],Dl=[0,95,135,175,215,255]});var wn,Qi=F(()=>{Gi();hr();Cr();ps();wn={name:"MessageItem",props:{message:{type:Object,required:!0},sessionActions:{type:Boolean,default:!1},externalAttachmentOpen:{type:Boolean,default:!1}},emits:["quote","edit-as-new","open-attachment"],template:`
|
|
@@ -2011,9 +2011,9 @@ ${String(e||"").trim()}
|
|
|
2011
2011
|
<div class="placeholder-text">{{ $t('terminal.autoCreate') }}</div>
|
|
2012
2012
|
</div>
|
|
2013
2013
|
</div>
|
|
2014
|
-
`,setup(e){let t=xn(Pinia.useChatStore(),e),s=Vue.inject("t"),n=Vue.reactive({}),r=Vue.reactive({}),i=Vue.reactive({}),o=Vue.ref(""),a={},l=!1,c=Vue.computed(()=>{let I=t.currentConversation;return I&&r[I]||null}),d=Vue.computed(()=>{let I=t.currentConversation;return I&&i[I]||""}),u=Vue.computed(()=>!!d.value),p=(I,R)=>{if(R){let D=a[I];if(a[I]=R,D&&D!==R){let E=n[I];E?.terminal?.element&&(R.innerHTML="",R.appendChild(E.terminal.element),Vue.nextTick(()=>{try{E.fitAddon?.fit()}catch{}}))}}},f=I=>{let R=t.currentConversation;R&&(i[R]=I)};async function g(){if(l)return!0;let I=typeof Terminal<"u"?Terminal.Terminal||Terminal:null,R=typeof FitAddon<"u"?FitAddon.FitAddon||FitAddon:null;if(!I||!R)try{await ec("vendor/xterm.min.js"),await ec("vendor/xterm-addon-fit.min.js"),I=typeof Terminal<"u"?Terminal.Terminal||Terminal:null,R=typeof FitAddon<"u"?FitAddon.FitAddon||FitAddon:null}catch{}return!I||!R?(o.value=s("terminal.xtermNotLoaded"),!1):(l=!0,!0)}function h(){let I=document.documentElement.getAttribute("data-theme")==="dark",D=getComputedStyle(document.documentElement).getPropertyValue("--bg-main").trim()||(I?"#212121":"#ffffff");return I?{background:D,foreground:"#d4d4d4",cursor:"#a0a0a0",selectionBackground:"rgba(255,255,255,0.12)",black:"#3a3a3a",red:"#f48771",green:"#89d185",yellow:"#e5c07b",blue:"#6cb6ff",magenta:"#d670d6",cyan:"#56d4dd",white:"#cccccc",brightBlack:"#555555",brightRed:"#f48771",brightGreen:"#89d185",brightYellow:"#e5c07b",brightBlue:"#6cb6ff",brightMagenta:"#d670d6",brightCyan:"#56d4dd",brightWhite:"#e8e8e8"}:{background:D,foreground:"#383a42",cursor:"#526fff",selectionBackground:"rgba(0,0,0,0.07)",black:"#383a42",red:"#e45649",green:"#50a14f",yellow:"#c18401",blue:"#4078f2",magenta:"#a626a4",cyan:"#0184bc",white:"#a0a1a7",brightBlack:"#4f525e",brightRed:"#e45649",brightGreen:"#50a14f",brightYellow:"#c18401",brightBlue:"#4078f2",brightMagenta:"#a626a4",brightCyan:"#0184bc",brightWhite:"#fafafa"}}async function m(I){if(!I||!t.currentAgent||!await g())return null;let R=fg(I),D=Terminal.Terminal||Terminal,E=FitAddon.FitAddon||FitAddon,Y=new D({cursorBlink:!0,fontSize:13,fontFamily:"'SF Mono', 'Fira Code', 'Consolas', monospace, 'Symbols Nerd Font Mono', 'Apple Color Emoji', 'Segoe UI Emoji', 'Noto Color Emoji'",theme:h(),allowProposedApi:!0}),Q=new E;return Y.loadAddon(Q),Y.attachCustomKeyEventHandler(re=>!((re.ctrlKey||re.metaKey)&&re.key==="v"||(re.ctrlKey||re.metaKey)&&re.key==="c"&&Y.hasSelection())),n[R]={created:!0,connected:!1,terminal:Y,fitAddon:Q},Y.onData(re=>{t.sendWsMessage({type:"terminal_input",agentId:t.currentAgent,conversationId:I,terminalId:R,data:re,_clientId:t.clientId})}),R}async function y(I,R){let D=n[R];if(!D)return!1;let E=null;for(let Y=0;Y<10&&(await Vue.nextTick(),E=a[R],!(E||Y>=2&&(await new Promise(Q=>setTimeout(Q,50)),E=a[R],E)));Y++);return E?(D.terminal.open(E),D.fitAddon.fit(),t.sendWsMessage({type:"terminal_create",agentId:t.currentAgent,conversationId:I,terminalId:R,workDir:e.workDir,cols:D.terminal.cols,rows:D.terminal.rows,_clientId:t.clientId}),!0):(o.value=s("terminal.mountFailed"),D.terminal.dispose(),delete n[R],!1)}let v=!1;async function k(){let I=t.currentConversation;if(!I||!t.currentAgent||r[I]||v)return;v=!0,o.value="";let R=await m(I);if(!R){v=!1;return}r[I]=Vue.reactive({type:"pane",terminalId:R}),i[I]=R,await y(I,R)||(delete r[I],delete i[I]),v=!1}async function w(I){let R=t.currentConversation;if(!R||!i[R])return;let D=i[R],E=await m(R);if(!E)return;let Y=Vue.reactive({type:"split",direction:I,ratio:.5,first:{type:"pane",terminalId:D},second:{type:"pane",terminalId:E}}),Q=yo(r[R],D,Y);if(r[R]=Vue.reactive(Q),i[R]=E,!await y(R,E)){let fe=ys(r[R],E);fe&&(r[R]=Vue.reactive(fe)),i[R]=D;return}await Vue.nextTick(),S(R)}function b(I){let R=t.currentConversation;if(!R)return;let D=n[I];D&&(t.sendWsMessage({type:"terminal_close",agentId:t.currentAgent,conversationId:R,terminalId:I,_clientId:t.clientId}),D.terminal?.dispose(),delete n[I],delete a[I]);let E=ys(r[R],I);E?(r[R]=Vue.reactive(E),i[R]===I&&(i[R]=bo(r[R])||""),Vue.nextTick(()=>S(R))):(delete r[R],delete i[R],Vue.nextTick(()=>k()))}function C(){let I=t.currentConversation;!I||!i[I]||b(i[I])}function S(I){if(I||(I=t.currentConversation),!I||!r[I])return;let R=$r(r[I]);for(let D of R){let E=n[D];if(E?.fitAddon&&E.connected)try{E.fitAddon.fit(),t.sendWsMessage({type:"terminal_resize",agentId:t.currentAgent,conversationId:I,terminalId:D,cols:E.terminal.cols,rows:E.terminal.rows,_clientId:t.clientId})}catch{}}}function M(I){let R=I.detail;if(!(!R||!Tn(R,e.routeKey,e.workspaceGeneration))&&!(e.routeKey&&Ot(R,e.routeKey)!=="main"))switch(R.type){case"terminal_created":{let D=R.terminalId||R.conversationId,E=n[D];if(E)if(R.success)E.connected=!0,o.value="";else{o.value=R.error||s("terminal.createFailed"),E.terminal?.dispose(),delete n[D];let Y=R.conversationId;if(Y&&r[Y]){let Q=ys(r[Y],D);Q?r[Y]=Vue.reactive(Q):(delete r[Y],delete i[Y])}}break}case"terminal_output":{let D=R.terminalId||R.conversationId,E=n[D];E?.terminal&&E.terminal.write(R.data);break}case"terminal_closed":{let D=R.terminalId||R.conversationId,E=n[D];if(E){E.terminal?.dispose(),delete n[D],delete a[D];let Y=R.conversationId;if(Y&&r[Y]){let Q=ys(r[Y],D);Q?(r[Y]=Vue.reactive(Q),i[Y]===D&&(i[Y]=bo(r[Y])||"")):(delete r[Y],delete i[Y])}}break}case"terminal_error":{o.value=R.message||s("terminal.error");let D=R.terminalId;if(D&&n[D]&&!n[D].connected){n[D].terminal?.dispose(),delete n[D];let E=R.conversationId;if(E&&r[E]){let Y=ys(r[E],D);Y?r[E]=Vue.reactive(Y):(delete r[E],delete i[E])}}break}}}let N=null;function q(){clearTimeout(N),N=setTimeout(()=>S(),100)}function L(){S()}function V(I){let{conversationId:R}=I.detail;if(R&&r[R]){let D=$r(r[R]);for(let E of D){let Y=n[E];Y&&(t.sendWsMessage({type:"terminal_close",terminalId:E,_clientId:t.clientId}),Y.terminal?.dispose(),delete n[E],delete a[E])}delete r[R],delete i[R]}}let $=Vue.ref(!0);Vue.onMounted(()=>{window.addEventListener("workbench-message",M),window.addEventListener("resize",q),window.addEventListener("terminal-fit-all",L),window.addEventListener("conversation-deleted",V)}),Vue.onActivated(()=>{$.value=!0,Vue.nextTick(()=>{k(),S()})}),Vue.onDeactivated(()=>{$.value=!1}),Vue.onUnmounted(()=>{window.removeEventListener("workbench-message",M),window.removeEventListener("resize",q),window.removeEventListener("terminal-fit-all",L),window.removeEventListener("conversation-deleted",V),clearTimeout(N);for(let I of Object.keys(n))t.sendWsMessage({type:"terminal_close",terminalId:I,_clientId:t.clientId}),n[I]?.terminal?.dispose()}),Vue.watch(()=>[t.currentConversation,t.workbenchExpanded],()=>{Vue.nextTick(()=>{if(!t.currentConversation||!t.workbenchExpanded||!$.value)return;let R=document.querySelector(".terminal-tab");R&&R.offsetParent!==null&&k()})},{immediate:!0}),Vue.watch(()=>t.connectionState,(I,R)=>{if(I==="connected"&&R&&R!=="connected"){for(let D of Object.keys(n))n[D]?.terminal?.dispose(),delete n[D],delete a[D];for(let D of Object.keys(r))delete r[D],delete i[D];Vue.nextTick(()=>k())}}),Vue.watch(()=>t.currentConversation,()=>{Vue.nextTick(()=>S())});let T=null;return Vue.onMounted(()=>{let I=()=>{let D=document.querySelector(".terminal-tab");$.value&&D&&D.offsetParent!==null&&(k(),S())};T=new MutationObserver(()=>{setTimeout(I,50)});let R=document.querySelector(".workbench-tab-content");R&&T.observe(R,{attributes:!0,subtree:!0,attributeFilter:["style"]})}),Vue.onUnmounted(()=>{T&&T.disconnect()}),{store:t,terminals:n,currentTree:c,currentActivePane:d,hasActivePane:u,terminalError:o,setMountRef:p,activatePane:f,splitPane:w,closeActivePane:C,closePane:b}}}});function wo(e){if(!e)return Or(te.default);let t=e.toLowerCase();if(sc[t])return sc[t]();let s=t.lastIndexOf(".");if(s>=0){let n=t.slice(s+1);if(wg[n])return wg[n]();let r=t;for(let[i,o]of Object.entries(sc))if(r===i||r.endsWith("/"+i))return o()}return Or(te.default)}function ko(e=!1){return mw(te.folder,e)}var te,Or,mw,J,wg,sc,nc=F(()=>{te={js:"#F1C40F",ts:"#3178C6",jsx:"#61DAFB",tsx:"#3178C6",py:"#3776AB",rb:"#CC342D",go:"#00ADD8",rs:"#DEA584",java:"#E76F00",cs:"#68217A",cpp:"#00599C",c:"#A8B9CC",html:"#E44D26",css:"#1572B6",scss:"#CF649A",less:"#1D365D",json:"#F1C40F",yaml:"#CB171E",xml:"#E44D26",md:"#519ABA",txt:"#8E8E8E",log:"#8E8E8E",sh:"#4EAA25",ps1:"#012456",sql:"#E38C00",svg:"#FFB13B",img:"#26A69A",git:"#F05032",docker:"#2496ED",config:"#6D8086",lock:"#8E8E8E",env:"#ECD53F",vue:"#41B883",react:"#61DAFB",angular:"#DD0031",svelte:"#FF3E00",php:"#777BB4",swift:"#FA7343",kt:"#7F52FF",lua:"#000080",r:"#276DC3",dart:"#00B4AB",liquid:"#67B6E4",folder:"#90A4AE",folderOpen:"#90A4AE",default:"#8E8E8E"},Or=e=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M14 2H6C4.9 2 4 2.9 4 4v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6z" fill="${e}" opacity="0.85"/><path d="M14 2v6h6" fill="${e}" opacity="0.5"/></svg>`,mw=(e,t)=>t?`<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z" fill="${e}" opacity="0.9"/></svg>`:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z" fill="${e}" opacity="0.9"/></svg>`,J=(e,t)=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M14 2H6C4.9 2 4 2.9 4 4v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6z" fill="${e}" opacity="0.2"/><path d="M14 2v6h6" fill="${e}" opacity="0.15"/><path d="M14 2H6C4.9 2 4 2.9 4 4v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6z" stroke="${e}" stroke-width="1.2" fill="none"/><text x="12" y="17" text-anchor="middle" font-size="7" font-weight="700" font-family="system-ui,sans-serif" fill="${e}">${t}</text></svg>`,wg={js:()=>J(te.js,"JS"),mjs:()=>J(te.js,"JS"),cjs:()=>J(te.js,"JS"),ts:()=>J(te.ts,"TS"),mts:()=>J(te.ts,"TS"),jsx:()=>J(te.jsx,"JSX"),tsx:()=>J(te.tsx,"TSX"),html:()=>J(te.html,"</>"),htm:()=>J(te.html,"</>"),css:()=>J(te.css,"CSS"),scss:()=>J(te.scss,"SC"),sass:()=>J(te.scss,"SA"),less:()=>J(te.less,"LS"),vue:()=>J(te.vue,"V"),svelte:()=>J(te.svelte,"SV"),json:()=>J(te.json,"{ }"),yaml:()=>J(te.yaml,"YML"),yml:()=>J(te.yaml,"YML"),toml:()=>J(te.config,"TML"),xml:()=>J(te.xml,"</>"),csv:()=>J(te.config,"CSV"),md:()=>J(te.md,"MD"),markdown:()=>J(te.md,"MD"),txt:()=>Or(te.txt),log:()=>Or(te.log),pdf:()=>J("#E53935","PDF"),py:()=>J(te.py,"PY"),rb:()=>J(te.rb,"RB"),go:()=>J(te.go,"GO"),rs:()=>J(te.rs,"RS"),java:()=>J(te.java,"JA"),cs:()=>J(te.cs,"C#"),cpp:()=>J(te.cpp,"C+"),cc:()=>J(te.cpp,"C+"),c:()=>J(te.c,"C"),h:()=>J(te.c,"H"),hpp:()=>J(te.cpp,"H+"),swift:()=>J(te.swift,"SW"),kt:()=>J(te.kt,"KT"),php:()=>J(te.php,"PHP"),lua:()=>J(te.lua,"LUA"),r:()=>J(te.r,"R"),dart:()=>J(te.dart,"DA"),sh:()=>J(te.sh,">_"),bash:()=>J(te.sh,">_"),zsh:()=>J(te.sh,">_"),fish:()=>J(te.sh,">_"),ps1:()=>J(te.ps1,"PS"),bat:()=>J(te.ps1,"BAT"),cmd:()=>J(te.ps1,"CMD"),sql:()=>J(te.sql,"SQL"),db:()=>J(te.sql,"DB"),sqlite:()=>J(te.sql,"DB"),svg:()=>J(te.svg,"SVG"),png:()=>J(te.img,"PNG"),jpg:()=>J(te.img,"JPG"),jpeg:()=>J(te.img,"JPG"),gif:()=>J(te.img,"GIF"),ico:()=>J(te.img,"ICO"),webp:()=>J(te.img,"WP"),lock:()=>Or(te.lock),env:()=>J(te.env,"ENV"),ini:()=>J(te.config,"INI"),cfg:()=>J(te.config,"CFG"),conf:()=>J(te.config,"CNF"),liquid:()=>J(te.liquid,"LQ"),ejs:()=>J(te.html,"EJS"),hbs:()=>J(te.html,"HBS"),pug:()=>J(te.html,"PUG"),wasm:()=>J("#654FF0","WA"),proto:()=>J(te.config,"PB"),graphql:()=>J("#E535AB","GQL"),gql:()=>J("#E535AB","GQL")},sc={dockerfile:()=>J(te.docker,"DK"),"docker-compose.yml":()=>J(te.docker,"DC"),"docker-compose.yaml":()=>J(te.docker,"DC"),".gitignore":()=>J(te.git,"GI"),".gitattributes":()=>J(te.git,"GA"),".gitmodules":()=>J(te.git,"GM"),".env":()=>J(te.env,"ENV"),".env.local":()=>J(te.env,"ENV"),".env.development":()=>J(te.env,"ENV"),".env.production":()=>J(te.env,"ENV"),"package.json":()=>J("#CB3837","NPM"),"package-lock.json":()=>J("#CB3837","NPM"),"tsconfig.json":()=>J(te.ts,"TSC"),eslintrc:()=>J("#4B32C3","ESL"),".eslintrc.js":()=>J("#4B32C3","ESL"),".eslintrc.json":()=>J("#4B32C3","ESL"),".prettierrc":()=>J("#F7B93E","PR"),makefile:()=>J(te.config,"MK"),"cmakelists.txt":()=>J("#064F8C","CM"),"readme.md":()=>J(te.md,"RM"),license:()=>J("#F5C518","LIC"),"license.md":()=>J("#F5C518","LIC"),"cargo.toml":()=>J(te.rs,"CG"),"go.mod":()=>J(te.go,"MOD"),"go.sum":()=>J(te.go,"SUM"),gemfile:()=>J(te.rb,"GEM"),rakefile:()=>J(te.rb,"RK"),"requirements.txt":()=>J(te.py,"REQ"),pipfile:()=>J(te.py,"PIP"),csproj:()=>J(te.cs,"CSP"),".sln":()=>J(te.cs,"SLN"),slnx:()=>J(te.cs,"SLN")}});function Ws(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function vw(e,t){if(!e||!t)return Ws(e);let s=[],n=(a,l)=>{if(!a)return;let c=new RegExp(a.source,a.flags),d;for(;(d=c.exec(e))!==null;){let u=d[1]!==void 0?d[1]:d[0],p=d.index+(d[1]!==void 0?d[0].indexOf(d[1]):0);if(s.push({start:p,end:p+u.length,cls:l}),!c.global)break}},r=t.commentType||"slash";if((r==="slash"||r==="both")&&(n(Pn.comment1,De.comment),n(Pn.commentBlock,De.comment)),(r==="hash"||r==="both")&&n(Pn.commentHash,De.comment),r==="html"&&n(t.commentHtml,De.comment),t.commentLine&&n(t.commentLine,De.comment),t.commentBlock&&n(t.commentBlock,De.comment),n(Pn.string,De.string),n(Pn.number,De.number),t.keywords&&n(t.keywords,De.keyword),t.builtins&&n(t.builtins,De.builtin),t.operators&&n(t.operators,De.operator),t.decorators&&n(t.decorators,De.decorator),t.macros&&n(t.macros,De.macro),t.preprocessor&&n(t.preprocessor,De.preprocessor),t.attributes&&n(t.attributes,De.attribute),t.tags&&n(t.tags,De.tag),t.properties&&n(t.properties,De.property),t.variables&&n(t.variables,De.variable),t.headings&&n(t.headings,De.heading),t.bold&&n(t.bold,De.bold),t.links&&n(t.links,De.link),t.keys&&n(t.keys,De.key),t.sections&&n(t.sections,De.section),t.selectors&&n(t.selectors,De.keyword),t.values&&n(t.values,De.number),t.code&&n(t.code,De.string),t.italic&&n(t.italic,De.builtin),t.attrs&&n(t.attrs,De.attribute),s.length===0)return Ws(e);s.sort((a,l)=>a.start-l.start||l.end-l.start-(a.end-a.start));let i="",o=0;for(let a of s)a.start<o||(a.start>o&&(i+=Ws(e.slice(o,a.start))),i+=`<span class="${a.cls}">${Ws(e.slice(a.start,a.end))}</span>`,o=a.end);return o<e.length&&(i+=Ws(e.slice(o))),i}function yw(e){if(!e)return null;let t=e.split(".").pop()?.toLowerCase();if(!t)return null;let s=kg[t];return typeof s=="string"&&(s=kg[s]),s||null}function Sg(e,t){if(!e)return Ws(e||"");let s=yw(t);return s?vw(e,s):Ws(e)}var Pn,kg,De,Ig=F(()=>{Pn={string:/("(?:[^"\\]|\\.)*")|('(?:[^'\\]|\\.)*')|(`(?:[^`\\]|\\.)*`)/g,number:/\b(\d+\.?\d*(?:[eE][+-]?\d+)?|0x[\da-fA-F]+|0b[01]+|0o[0-7]+)\b/g,comment1:/(\/\/.*$)/gm,commentHash:/(#.*$)/gm,commentBlock:/(\/\*.*?\*\/)/g},kg={js:{keywords:/\b(const|let|var|function|class|extends|return|if|else|for|while|do|switch|case|break|continue|new|this|super|import|export|from|default|async|await|yield|try|catch|finally|throw|typeof|instanceof|in|of|delete|void|null|undefined|true|false|NaN|Infinity)\b/g,builtins:/\b(console|window|document|Math|JSON|Array|Object|String|Number|Boolean|Promise|Map|Set|WeakMap|WeakSet|Symbol|Proxy|Reflect|RegExp|Error|Date|parseInt|parseFloat|setTimeout|setInterval|clearTimeout|clearInterval|fetch|require|module|exports|process)\b/g,operators:/(=>|\.\.\.|\?\.|&&|\|\||===|!==|==|!=|>=|<=|>>>=|>>>|>>=|<<=|\+\+|--|[+\-*/%&|^~!<>]=?|\?|:)/g},ts:"js",jsx:"js",tsx:"js",mjs:"js",cjs:"js",vue:"js",py:{keywords:/\b(def|class|return|if|elif|else|for|while|break|continue|pass|import|from|as|with|try|except|finally|raise|yield|lambda|and|or|not|is|in|True|False|None|global|nonlocal|del|assert|async|await)\b/g,builtins:/\b(print|len|range|int|float|str|bool|list|dict|set|tuple|type|isinstance|super|property|staticmethod|classmethod|enumerate|zip|map|filter|sorted|reversed|open|input|hasattr|getattr|setattr|id|hex|oct|bin|abs|max|min|sum|all|any|iter|next)\b/g,decorators:/(@\w+)/g,commentType:"hash"},rb:{keywords:/\b(def|class|module|end|return|if|elsif|else|unless|for|while|until|do|break|next|case|when|begin|rescue|ensure|raise|yield|require|include|extend|attr_accessor|attr_reader|attr_writer|self|super|nil|true|false|and|or|not|then|puts|print)\b/g,commentType:"hash"},go:{keywords:/\b(func|package|import|var|const|type|struct|interface|map|chan|go|select|switch|case|default|if|else|for|range|break|continue|return|defer|fallthrough|nil|true|false|iota)\b/g,builtins:/\b(fmt|make|len|cap|append|copy|delete|close|panic|recover|new|error|string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|complex64|complex128)\b/g},rs:{keywords:/\b(fn|let|mut|const|pub|mod|use|struct|enum|impl|trait|where|for|loop|while|if|else|match|return|break|continue|move|ref|self|Self|super|crate|as|in|unsafe|async|await|dyn|true|false|Some|None|Ok|Err)\b/g,builtins:/\b(String|Vec|Box|Rc|Arc|Option|Result|HashMap|HashSet|println|eprintln|format|panic|todo|unimplemented|assert|assert_eq|assert_ne|dbg|cfg|derive|macro_rules)\b/g,macros:/(\w+!)/g},java:{keywords:/\b(class|interface|extends|implements|public|private|protected|static|final|abstract|synchronized|volatile|transient|native|new|return|if|else|for|while|do|switch|case|default|break|continue|try|catch|finally|throw|throws|import|package|this|super|void|null|true|false|instanceof)\b/g,builtins:/\b(System|String|Integer|Long|Double|Float|Boolean|List|ArrayList|Map|HashMap|Set|HashSet|Optional|Stream|Object|Exception|RuntimeException|Thread|Runnable|Override|Deprecated)\b/g},cs:{keywords:/\b(class|struct|interface|enum|record|delegate|event|namespace|using|public|private|protected|internal|static|readonly|const|sealed|abstract|virtual|override|new|return|if|else|for|foreach|while|do|switch|case|default|break|continue|try|catch|finally|throw|async|await|yield|var|dynamic|is|as|in|out|ref|params|this|base|null|true|false|void|get|set|init|required|partial|where|select|from|orderby|group|join|let|into)\b/g,builtins:/\b(Console|String|Int32|Int64|Double|Boolean|List|Dictionary|HashSet|Task|IEnumerable|ILogger|IOptions|IFeatures|Exception|Guid|DateTime|TimeSpan|CancellationToken|Action|Func|Span|Memory|ReadOnlySpan)\b/g,attributes:/(\[[\w]+(?:\(.*?\))?\])/g},cpp:{keywords:/\b(class|struct|enum|union|namespace|using|template|typename|public|private|protected|static|const|constexpr|volatile|virtual|override|final|explicit|inline|extern|auto|decltype|new|delete|return|if|else|for|while|do|switch|case|default|break|continue|try|catch|throw|sizeof|alignof|typeid|static_cast|dynamic_cast|reinterpret_cast|const_cast|nullptr|true|false|void|this|operator|friend|noexcept|co_await|co_yield|co_return|concept|requires)\b/g,builtins:/\b(std|string|vector|map|unordered_map|set|array|pair|tuple|shared_ptr|unique_ptr|weak_ptr|optional|variant|any|cout|cin|endl|printf|scanf|malloc|free|sizeof|size_t|int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t)\b/g,preprocessor:/(#\s*(?:include|define|undef|if|ifdef|ifndef|else|elif|endif|pragma|error|warning).*$)/gm},c:"cpp",h:"cpp",hpp:"cpp",html:{tags:/(<\/?[\w-]+|>|\/>)/g,attrs:/\b([\w-]+)(?==)/g,commentType:"html",commentHtml:/(<!--[\s\S]*?-->)/g},xml:"html",svg:"html",css:{selectors:/([\w.#\[\]:,>+~*-]+)\s*\{/g,properties:/\b([\w-]+)(?=\s*:)/g,values:/:\s*([^;{}]+)/g,commentType:"block"},scss:"css",less:"css",json:{keys:/("[\w.-]+")\s*:/g,commentType:"none"},yaml:{keys:/([\w.-]+)\s*:/g,commentType:"hash"},yml:"yaml",md:{headings:/^(#{1,6}\s.*)$/gm,bold:/(\*\*[^*]+\*\*|__[^_]+__)/g,italic:/(\*[^*]+\*|_[^_]+_)/g,code:/(`[^`]+`)/g,links:/(\[[^\]]+\]\([^)]+\))/g,commentType:"none"},sh:{keywords:/\b(if|then|else|elif|fi|for|while|do|done|case|esac|function|return|exit|echo|export|local|readonly|unset|set|shift|eval|exec|trap|source|alias|cd|pwd|ls|mkdir|rm|cp|mv|cat|grep|sed|awk|find|xargs|sort|uniq|wc|head|tail|tee|cut|tr|test)\b/g,variables:/(\$\{?\w+\}?|\$\(|\$\{)/g,commentType:"hash"},bash:"sh",zsh:"sh",sql:{keywords:/\b(SELECT|FROM|WHERE|AND|OR|NOT|IN|LIKE|BETWEEN|JOIN|LEFT|RIGHT|INNER|OUTER|FULL|ON|AS|GROUP|BY|ORDER|HAVING|LIMIT|OFFSET|INSERT|INTO|VALUES|UPDATE|SET|DELETE|CREATE|ALTER|DROP|TABLE|INDEX|VIEW|TRIGGER|FUNCTION|PROCEDURE|BEGIN|END|IF|ELSE|THEN|CASE|WHEN|DECLARE|EXEC|UNION|ALL|DISTINCT|TOP|EXISTS|NULL|IS|ASC|DESC|PRIMARY|KEY|FOREIGN|REFERENCES|CONSTRAINT|DEFAULT|CHECK|UNIQUE|CASCADE|TRUNCATE|COMMIT|ROLLBACK|GRANT|REVOKE)\b/gi,commentType:"both"},lua:{keywords:/\b(and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/g,builtins:/\b(print|type|tostring|tonumber|pairs|ipairs|next|select|unpack|error|pcall|xpcall|assert|require|table|string|math|io|os|coroutine|setmetatable|getmetatable|rawget|rawset)\b/g,commentLine:/(--(?!\[).*$)/gm,commentBlock:/(--\[\[[\s\S]*?\]\])/g},php:{keywords:/\b(function|class|interface|trait|extends|implements|public|private|protected|static|final|abstract|const|var|new|return|if|else|elseif|for|foreach|while|do|switch|case|default|break|continue|try|catch|finally|throw|use|namespace|require|include|require_once|include_once|echo|print|die|exit|null|true|false|array|list|match|fn|yield|from)\b/g,variables:/(\$\w+)/g},swift:{keywords:/\b(func|class|struct|enum|protocol|extension|let|var|guard|if|else|for|while|repeat|switch|case|default|break|continue|return|throw|try|catch|defer|import|typealias|associatedtype|init|deinit|subscript|operator|precedencegroup|self|Self|super|nil|true|false|is|as|in|inout|throws|rethrows|where|some|any|weak|unowned|lazy|mutating|nonmutating|override|final|required|convenience|optional|dynamic|async|await|actor|nonisolated|isolated|sending|consuming|borrowing)\b/g},kt:{keywords:/\b(fun|class|object|interface|val|var|if|else|when|for|while|do|return|break|continue|throw|try|catch|finally|import|package|as|is|in|out|by|init|constructor|companion|data|sealed|enum|abstract|open|override|private|protected|internal|public|inline|reified|suspend|coroutine|null|true|false|this|super|it|typealias|annotation|lateinit|lazy|get|set)\b/g},dart:{keywords:/\b(class|extends|implements|with|mixin|abstract|sealed|base|interface|final|const|var|late|required|dynamic|void|static|return|if|else|for|while|do|switch|case|default|break|continue|try|catch|finally|throw|rethrow|assert|new|this|super|null|true|false|is|as|in|async|await|yield|import|export|library|part|show|hide|deferred|typedef|enum|extension|on)\b/g},r:{keywords:/\b(if|else|for|while|repeat|function|return|break|next|in|TRUE|FALSE|NULL|NA|Inf|NaN|library|require|source|print|cat|paste|paste0|sprintf|stop|warning|message)\b/g,commentType:"hash"},toml:{keys:/([\w.-]+)\s*=/g,sections:/(\[[\w.]+\])/g,commentType:"hash"},proto:{keywords:/\b(syntax|package|import|option|message|enum|service|rpc|returns|repeated|optional|required|map|oneof|reserved|extensions|extend|group|default|packed|deprecated|java_package|java_outer_classname|optimize_for|cc_enable_arenas|objc_class_prefix|csharp_namespace|swift_prefix|php_class_prefix|php_namespace|ruby_package|string|int32|int64|uint32|uint64|sint32|sint64|fixed32|fixed64|sfixed32|sfixed64|float|double|bool|bytes)\b/g}},De={keyword:"hl-kw",builtin:"hl-bi",string:"hl-st",number:"hl-nm",comment:"hl-cm",operator:"hl-op",decorator:"hl-dc",macro:"hl-mc",preprocessor:"hl-pp",attribute:"hl-at",tag:"hl-tg",property:"hl-pr",variable:"hl-vr",heading:"hl-hd",bold:"hl-bd",link:"hl-lk",key:"hl-ky",section:"hl-sc"}});function Cg(e,t,s){let n=[],r=0,i=0;if(t!=null){let f=t.split(`
|
|
2014
|
+
`,setup(e){let t=xn(Pinia.useChatStore(),e),s=Vue.inject("t"),n=Vue.reactive({}),r=Vue.reactive({}),i=Vue.reactive({}),o=Vue.ref(""),a={},l=!1,c=Vue.computed(()=>{let I=t.currentConversation;return I&&r[I]||null}),d=Vue.computed(()=>{let I=t.currentConversation;return I&&i[I]||""}),u=Vue.computed(()=>!!d.value),p=(I,R)=>{if(R){let D=a[I];if(a[I]=R,D&&D!==R){let E=n[I];E?.terminal?.element&&(R.innerHTML="",R.appendChild(E.terminal.element),Vue.nextTick(()=>{try{E.fitAddon?.fit()}catch{}}))}}},f=I=>{let R=t.currentConversation;R&&(i[R]=I)};async function g(){if(l)return!0;let I=typeof Terminal<"u"?Terminal.Terminal||Terminal:null,R=typeof FitAddon<"u"?FitAddon.FitAddon||FitAddon:null;if(!I||!R)try{await ec("vendor/xterm.min.js"),await ec("vendor/xterm-addon-fit.min.js"),I=typeof Terminal<"u"?Terminal.Terminal||Terminal:null,R=typeof FitAddon<"u"?FitAddon.FitAddon||FitAddon:null}catch{}return!I||!R?(o.value=s("terminal.xtermNotLoaded"),!1):(l=!0,!0)}function h(){let I=document.documentElement.getAttribute("data-theme")==="dark",D=getComputedStyle(document.documentElement).getPropertyValue("--bg-main").trim()||(I?"#212121":"#ffffff");return I?{background:D,foreground:"#d4d4d4",cursor:"#a0a0a0",selectionBackground:"rgba(255,255,255,0.12)",black:"#3a3a3a",red:"#f48771",green:"#89d185",yellow:"#e5c07b",blue:"#6cb6ff",magenta:"#d670d6",cyan:"#56d4dd",white:"#cccccc",brightBlack:"#555555",brightRed:"#f48771",brightGreen:"#89d185",brightYellow:"#e5c07b",brightBlue:"#6cb6ff",brightMagenta:"#d670d6",brightCyan:"#56d4dd",brightWhite:"#e8e8e8"}:{background:D,foreground:"#383a42",cursor:"#526fff",selectionBackground:"rgba(0,0,0,0.07)",black:"#383a42",red:"#e45649",green:"#50a14f",yellow:"#c18401",blue:"#4078f2",magenta:"#a626a4",cyan:"#0184bc",white:"#a0a1a7",brightBlack:"#4f525e",brightRed:"#e45649",brightGreen:"#50a14f",brightYellow:"#c18401",brightBlue:"#4078f2",brightMagenta:"#a626a4",brightCyan:"#0184bc",brightWhite:"#fafafa"}}async function m(I){if(!I||!t.currentAgent||!await g())return null;let R=fg(I),D=Terminal.Terminal||Terminal,E=FitAddon.FitAddon||FitAddon,Y=new D({cursorBlink:!0,fontSize:13,fontFamily:"'SF Mono', 'Fira Code', 'Consolas', monospace, 'Symbols Nerd Font Mono', 'Apple Color Emoji', 'Segoe UI Emoji', 'Noto Color Emoji'",theme:h(),allowProposedApi:!0}),Q=new E;return Y.loadAddon(Q),Y.attachCustomKeyEventHandler(re=>!((re.ctrlKey||re.metaKey)&&re.key==="v"||(re.ctrlKey||re.metaKey)&&re.key==="c"&&Y.hasSelection())),n[R]={created:!0,connected:!1,terminal:Y,fitAddon:Q},Y.onData(re=>{t.sendWsMessage({type:"terminal_input",agentId:t.currentAgent,conversationId:I,terminalId:R,data:re,_clientId:t.clientId})}),R}async function y(I,R){let D=n[R];if(!D)return!1;let E=null;for(let Y=0;Y<10&&(await Vue.nextTick(),E=a[R],!(E||Y>=2&&(await new Promise(Q=>setTimeout(Q,50)),E=a[R],E)));Y++);return E?(D.terminal.open(E),D.fitAddon.fit(),t.sendWsMessage({type:"terminal_create",agentId:t.currentAgent,conversationId:I,terminalId:R,workDir:e.workDir,cols:D.terminal.cols,rows:D.terminal.rows,_clientId:t.clientId}),!0):(o.value=s("terminal.mountFailed"),D.terminal.dispose(),delete n[R],!1)}let v=!1;async function k(){let I=t.currentConversation;if(!I||!t.currentAgent||r[I]||v)return;v=!0,o.value="";let R=await m(I);if(!R){v=!1;return}r[I]=Vue.reactive({type:"pane",terminalId:R}),i[I]=R,await y(I,R)||(delete r[I],delete i[I]),v=!1}async function w(I){let R=t.currentConversation;if(!R||!i[R])return;let D=i[R],E=await m(R);if(!E)return;let Y=Vue.reactive({type:"split",direction:I,ratio:.5,first:{type:"pane",terminalId:D},second:{type:"pane",terminalId:E}}),Q=yo(r[R],D,Y);if(r[R]=Vue.reactive(Q),i[R]=E,!await y(R,E)){let fe=ys(r[R],E);fe&&(r[R]=Vue.reactive(fe)),i[R]=D;return}await Vue.nextTick(),S(R)}function b(I){let R=t.currentConversation;if(!R)return;let D=n[I];D&&(t.sendWsMessage({type:"terminal_close",agentId:t.currentAgent,conversationId:R,terminalId:I,_clientId:t.clientId}),D.terminal?.dispose(),delete n[I],delete a[I]);let E=ys(r[R],I);E?(r[R]=Vue.reactive(E),i[R]===I&&(i[R]=bo(r[R])||""),Vue.nextTick(()=>S(R))):(delete r[R],delete i[R],Vue.nextTick(()=>k()))}function C(){let I=t.currentConversation;!I||!i[I]||b(i[I])}function S(I){if(I||(I=t.currentConversation),!I||!r[I])return;let R=$r(r[I]);for(let D of R){let E=n[D];if(E?.fitAddon&&E.connected)try{E.fitAddon.fit(),t.sendWsMessage({type:"terminal_resize",agentId:t.currentAgent,conversationId:I,terminalId:D,cols:E.terminal.cols,rows:E.terminal.rows,_clientId:t.clientId})}catch{}}}function M(I){let R=I.detail;if(!(!R||!Tn(R,e.routeKey,e.workspaceGeneration))&&!(e.routeKey&&Ot(R,e.routeKey)!=="main"))switch(R.type){case"terminal_created":{let D=R.terminalId||R.conversationId,E=n[D];if(E)if(R.success)E.connected=!0,o.value="";else{o.value=R.error||s("terminal.createFailed"),E.terminal?.dispose(),delete n[D];let Y=R.conversationId;if(Y&&r[Y]){let Q=ys(r[Y],D);Q?r[Y]=Vue.reactive(Q):(delete r[Y],delete i[Y])}}break}case"terminal_output":{let D=R.terminalId||R.conversationId,E=n[D];E?.terminal&&E.terminal.write(R.data);break}case"terminal_closed":{let D=R.terminalId||R.conversationId,E=n[D];if(E){E.terminal?.dispose(),delete n[D],delete a[D];let Y=R.conversationId;if(Y&&r[Y]){let Q=ys(r[Y],D);Q?(r[Y]=Vue.reactive(Q),i[Y]===D&&(i[Y]=bo(r[Y])||"")):(delete r[Y],delete i[Y])}}break}case"terminal_error":{o.value=R.message||s("terminal.error");let D=R.terminalId;if(D&&n[D]&&!n[D].connected){n[D].terminal?.dispose(),delete n[D];let E=R.conversationId;if(E&&r[E]){let Y=ys(r[E],D);Y?r[E]=Vue.reactive(Y):(delete r[E],delete i[E])}}break}}}let N=null;function q(){clearTimeout(N),N=setTimeout(()=>S(),100)}function L(){S()}function V(I){let{conversationId:R}=I.detail;if(R&&r[R]){let D=$r(r[R]);for(let E of D){let Y=n[E];Y&&(t.sendWsMessage({type:"terminal_close",terminalId:E,_clientId:t.clientId}),Y.terminal?.dispose(),delete n[E],delete a[E])}delete r[R],delete i[R]}}let $=Vue.ref(!0);Vue.onMounted(()=>{window.addEventListener("workbench-message",M),window.addEventListener("resize",q),window.addEventListener("terminal-fit-all",L),window.addEventListener("conversation-deleted",V)}),Vue.onActivated(()=>{$.value=!0,Vue.nextTick(()=>{k(),S()})}),Vue.onDeactivated(()=>{$.value=!1}),Vue.onUnmounted(()=>{window.removeEventListener("workbench-message",M),window.removeEventListener("resize",q),window.removeEventListener("terminal-fit-all",L),window.removeEventListener("conversation-deleted",V),clearTimeout(N);for(let I of Object.keys(n))t.sendWsMessage({type:"terminal_close",terminalId:I,_clientId:t.clientId}),n[I]?.terminal?.dispose()}),Vue.watch(()=>[t.currentConversation,t.workbenchExpanded],()=>{Vue.nextTick(()=>{if(!t.currentConversation||!t.workbenchExpanded||!$.value)return;let R=document.querySelector(".terminal-tab");R&&R.offsetParent!==null&&k()})},{immediate:!0}),Vue.watch(()=>t.connectionState,(I,R)=>{if(I==="connected"&&R&&R!=="connected"){for(let D of Object.keys(n))n[D]?.terminal?.dispose(),delete n[D],delete a[D];for(let D of Object.keys(r))delete r[D],delete i[D];Vue.nextTick(()=>k())}}),Vue.watch(()=>t.currentConversation,()=>{Vue.nextTick(()=>S())});let T=null;return Vue.onMounted(()=>{let I=()=>{let D=document.querySelector(".terminal-tab");$.value&&D&&D.offsetParent!==null&&(k(),S())};T=new MutationObserver(()=>{setTimeout(I,50)});let R=document.querySelector(".workbench-tab-content");R&&T.observe(R,{attributes:!0,subtree:!0,attributeFilter:["style"]})}),Vue.onUnmounted(()=>{T&&T.disconnect()}),{store:t,terminals:n,currentTree:c,currentActivePane:d,hasActivePane:u,terminalError:o,setMountRef:p,activatePane:f,splitPane:w,closeActivePane:C,closePane:b}}}});function wo(e){if(!e)return Or(te.default);let t=e.toLowerCase();if(sc[t])return sc[t]();let s=t.lastIndexOf(".");if(s>=0){let n=t.slice(s+1);if(wg[n])return wg[n]();let r=t;for(let[i,o]of Object.entries(sc))if(r===i||r.endsWith("/"+i))return o()}return Or(te.default)}function ko(e=!1){return mw(te.folder,e)}var te,Or,mw,J,wg,sc,nc=F(()=>{te={js:"#F1C40F",ts:"#3178C6",jsx:"#61DAFB",tsx:"#3178C6",py:"#3776AB",rb:"#CC342D",go:"#00ADD8",rs:"#DEA584",java:"#E76F00",cs:"#68217A",cpp:"#00599C",c:"#A8B9CC",html:"#E44D26",css:"#1572B6",scss:"#CF649A",less:"#1D365D",json:"#F1C40F",yaml:"#CB171E",xml:"#E44D26",md:"#519ABA",txt:"#8E8E8E",log:"#8E8E8E",sh:"#4EAA25",ps1:"#012456",sql:"#E38C00",svg:"#FFB13B",img:"#26A69A",git:"#F05032",docker:"#2496ED",config:"#6D8086",lock:"#8E8E8E",env:"#ECD53F",vue:"#41B883",react:"#61DAFB",angular:"#DD0031",svelte:"#FF3E00",php:"#777BB4",swift:"#FA7343",kt:"#7F52FF",lua:"#000080",r:"#276DC3",dart:"#00B4AB",liquid:"#67B6E4",folder:"#90A4AE",folderOpen:"#90A4AE",default:"#8E8E8E"},Or=e=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M14 2H6C4.9 2 4 2.9 4 4v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6z" fill="${e}" opacity="0.85"/><path d="M14 2v6h6" fill="${e}" opacity="0.5"/></svg>`,mw=(e,t)=>t?`<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M20 6h-8l-2-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 12H4V8h16v10z" fill="${e}" opacity="0.9"/></svg>`:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M10 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8l-2-2z" fill="${e}" opacity="0.9"/></svg>`,J=(e,t)=>`<svg width="16" height="16" viewBox="0 0 24 24" fill="none"><path d="M14 2H6C4.9 2 4 2.9 4 4v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6z" fill="${e}" opacity="0.2"/><path d="M14 2v6h6" fill="${e}" opacity="0.15"/><path d="M14 2H6C4.9 2 4 2.9 4 4v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8l-6-6z" stroke="${e}" stroke-width="1.2" fill="none"/><text x="12" y="17" text-anchor="middle" font-size="7" font-weight="700" font-family="system-ui,sans-serif" fill="${e}">${t}</text></svg>`,wg={js:()=>J(te.js,"JS"),mjs:()=>J(te.js,"JS"),cjs:()=>J(te.js,"JS"),ts:()=>J(te.ts,"TS"),mts:()=>J(te.ts,"TS"),jsx:()=>J(te.jsx,"JSX"),tsx:()=>J(te.tsx,"TSX"),html:()=>J(te.html,"</>"),htm:()=>J(te.html,"</>"),css:()=>J(te.css,"CSS"),scss:()=>J(te.scss,"SC"),sass:()=>J(te.scss,"SA"),less:()=>J(te.less,"LS"),vue:()=>J(te.vue,"V"),svelte:()=>J(te.svelte,"SV"),json:()=>J(te.json,"{ }"),yaml:()=>J(te.yaml,"YML"),yml:()=>J(te.yaml,"YML"),toml:()=>J(te.config,"TML"),xml:()=>J(te.xml,"</>"),csv:()=>J(te.config,"CSV"),md:()=>J(te.md,"MD"),markdown:()=>J(te.md,"MD"),txt:()=>Or(te.txt),log:()=>Or(te.log),pdf:()=>J("#E53935","PDF"),py:()=>J(te.py,"PY"),rb:()=>J(te.rb,"RB"),go:()=>J(te.go,"GO"),rs:()=>J(te.rs,"RS"),java:()=>J(te.java,"JA"),cs:()=>J(te.cs,"C#"),cpp:()=>J(te.cpp,"C+"),cc:()=>J(te.cpp,"C+"),c:()=>J(te.c,"C"),h:()=>J(te.c,"H"),hpp:()=>J(te.cpp,"H+"),swift:()=>J(te.swift,"SW"),kt:()=>J(te.kt,"KT"),php:()=>J(te.php,"PHP"),lua:()=>J(te.lua,"LUA"),r:()=>J(te.r,"R"),dart:()=>J(te.dart,"DA"),sh:()=>J(te.sh,">_"),bash:()=>J(te.sh,">_"),zsh:()=>J(te.sh,">_"),fish:()=>J(te.sh,">_"),ps1:()=>J(te.ps1,"PS"),bat:()=>J(te.ps1,"BAT"),cmd:()=>J(te.ps1,"CMD"),sql:()=>J(te.sql,"SQL"),db:()=>J(te.sql,"DB"),sqlite:()=>J(te.sql,"DB"),svg:()=>J(te.svg,"SVG"),png:()=>J(te.img,"PNG"),jpg:()=>J(te.img,"JPG"),jpeg:()=>J(te.img,"JPG"),gif:()=>J(te.img,"GIF"),ico:()=>J(te.img,"ICO"),webp:()=>J(te.img,"WP"),lock:()=>Or(te.lock),env:()=>J(te.env,"ENV"),ini:()=>J(te.config,"INI"),cfg:()=>J(te.config,"CFG"),conf:()=>J(te.config,"CNF"),liquid:()=>J(te.liquid,"LQ"),ejs:()=>J(te.html,"EJS"),hbs:()=>J(te.html,"HBS"),pug:()=>J(te.html,"PUG"),wasm:()=>J("#654FF0","WA"),proto:()=>J(te.config,"PB"),graphql:()=>J("#E535AB","GQL"),gql:()=>J("#E535AB","GQL")},sc={dockerfile:()=>J(te.docker,"DK"),"docker-compose.yml":()=>J(te.docker,"DC"),"docker-compose.yaml":()=>J(te.docker,"DC"),".gitignore":()=>J(te.git,"GI"),".gitattributes":()=>J(te.git,"GA"),".gitmodules":()=>J(te.git,"GM"),".env":()=>J(te.env,"ENV"),".env.local":()=>J(te.env,"ENV"),".env.development":()=>J(te.env,"ENV"),".env.production":()=>J(te.env,"ENV"),"package.json":()=>J("#CB3837","NPM"),"package-lock.json":()=>J("#CB3837","NPM"),"tsconfig.json":()=>J(te.ts,"TSC"),eslintrc:()=>J("#4B32C3","ESL"),".eslintrc.js":()=>J("#4B32C3","ESL"),".eslintrc.json":()=>J("#4B32C3","ESL"),".prettierrc":()=>J("#F7B93E","PR"),makefile:()=>J(te.config,"MK"),"cmakelists.txt":()=>J("#064F8C","CM"),"readme.md":()=>J(te.md,"RM"),license:()=>J("#F5C518","LIC"),"license.md":()=>J("#F5C518","LIC"),"cargo.toml":()=>J(te.rs,"CG"),"go.mod":()=>J(te.go,"MOD"),"go.sum":()=>J(te.go,"SUM"),gemfile:()=>J(te.rb,"GEM"),rakefile:()=>J(te.rb,"RK"),"requirements.txt":()=>J(te.py,"REQ"),pipfile:()=>J(te.py,"PIP"),csproj:()=>J(te.cs,"CSP"),".sln":()=>J(te.cs,"SLN"),slnx:()=>J(te.cs,"SLN")}});function Ws(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function vw(e,t){if(!e||!t)return Ws(e);let s=[],n=(a,l)=>{if(!a)return;let c=new RegExp(a.source,a.flags),d;for(;(d=c.exec(e))!==null;){let u=d[1]!==void 0?d[1]:d[0],p=d.index+(d[1]!==void 0?d[0].indexOf(d[1]):0);if(s.push({start:p,end:p+u.length,cls:l}),!c.global)break}},r=t.commentType||"slash";if((r==="slash"||r==="both")&&(n(Pn.comment1,Ee.comment),n(Pn.commentBlock,Ee.comment)),(r==="hash"||r==="both")&&n(Pn.commentHash,Ee.comment),r==="html"&&n(t.commentHtml,Ee.comment),t.commentLine&&n(t.commentLine,Ee.comment),t.commentBlock&&n(t.commentBlock,Ee.comment),n(Pn.string,Ee.string),n(Pn.number,Ee.number),t.keywords&&n(t.keywords,Ee.keyword),t.builtins&&n(t.builtins,Ee.builtin),t.operators&&n(t.operators,Ee.operator),t.decorators&&n(t.decorators,Ee.decorator),t.macros&&n(t.macros,Ee.macro),t.preprocessor&&n(t.preprocessor,Ee.preprocessor),t.attributes&&n(t.attributes,Ee.attribute),t.tags&&n(t.tags,Ee.tag),t.properties&&n(t.properties,Ee.property),t.variables&&n(t.variables,Ee.variable),t.headings&&n(t.headings,Ee.heading),t.bold&&n(t.bold,Ee.bold),t.links&&n(t.links,Ee.link),t.keys&&n(t.keys,Ee.key),t.sections&&n(t.sections,Ee.section),t.selectors&&n(t.selectors,Ee.keyword),t.values&&n(t.values,Ee.number),t.code&&n(t.code,Ee.string),t.italic&&n(t.italic,Ee.builtin),t.attrs&&n(t.attrs,Ee.attribute),s.length===0)return Ws(e);s.sort((a,l)=>a.start-l.start||l.end-l.start-(a.end-a.start));let i="",o=0;for(let a of s)a.start<o||(a.start>o&&(i+=Ws(e.slice(o,a.start))),i+=`<span class="${a.cls}">${Ws(e.slice(a.start,a.end))}</span>`,o=a.end);return o<e.length&&(i+=Ws(e.slice(o))),i}function yw(e){if(!e)return null;let t=e.split(".").pop()?.toLowerCase();if(!t)return null;let s=kg[t];return typeof s=="string"&&(s=kg[s]),s||null}function Sg(e,t){if(!e)return Ws(e||"");let s=yw(t);return s?vw(e,s):Ws(e)}var Pn,kg,Ee,Ig=F(()=>{Pn={string:/("(?:[^"\\]|\\.)*")|('(?:[^'\\]|\\.)*')|(`(?:[^`\\]|\\.)*`)/g,number:/\b(\d+\.?\d*(?:[eE][+-]?\d+)?|0x[\da-fA-F]+|0b[01]+|0o[0-7]+)\b/g,comment1:/(\/\/.*$)/gm,commentHash:/(#.*$)/gm,commentBlock:/(\/\*.*?\*\/)/g},kg={js:{keywords:/\b(const|let|var|function|class|extends|return|if|else|for|while|do|switch|case|break|continue|new|this|super|import|export|from|default|async|await|yield|try|catch|finally|throw|typeof|instanceof|in|of|delete|void|null|undefined|true|false|NaN|Infinity)\b/g,builtins:/\b(console|window|document|Math|JSON|Array|Object|String|Number|Boolean|Promise|Map|Set|WeakMap|WeakSet|Symbol|Proxy|Reflect|RegExp|Error|Date|parseInt|parseFloat|setTimeout|setInterval|clearTimeout|clearInterval|fetch|require|module|exports|process)\b/g,operators:/(=>|\.\.\.|\?\.|&&|\|\||===|!==|==|!=|>=|<=|>>>=|>>>|>>=|<<=|\+\+|--|[+\-*/%&|^~!<>]=?|\?|:)/g},ts:"js",jsx:"js",tsx:"js",mjs:"js",cjs:"js",vue:"js",py:{keywords:/\b(def|class|return|if|elif|else|for|while|break|continue|pass|import|from|as|with|try|except|finally|raise|yield|lambda|and|or|not|is|in|True|False|None|global|nonlocal|del|assert|async|await)\b/g,builtins:/\b(print|len|range|int|float|str|bool|list|dict|set|tuple|type|isinstance|super|property|staticmethod|classmethod|enumerate|zip|map|filter|sorted|reversed|open|input|hasattr|getattr|setattr|id|hex|oct|bin|abs|max|min|sum|all|any|iter|next)\b/g,decorators:/(@\w+)/g,commentType:"hash"},rb:{keywords:/\b(def|class|module|end|return|if|elsif|else|unless|for|while|until|do|break|next|case|when|begin|rescue|ensure|raise|yield|require|include|extend|attr_accessor|attr_reader|attr_writer|self|super|nil|true|false|and|or|not|then|puts|print)\b/g,commentType:"hash"},go:{keywords:/\b(func|package|import|var|const|type|struct|interface|map|chan|go|select|switch|case|default|if|else|for|range|break|continue|return|defer|fallthrough|nil|true|false|iota)\b/g,builtins:/\b(fmt|make|len|cap|append|copy|delete|close|panic|recover|new|error|string|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|float32|float64|bool|byte|rune|complex64|complex128)\b/g},rs:{keywords:/\b(fn|let|mut|const|pub|mod|use|struct|enum|impl|trait|where|for|loop|while|if|else|match|return|break|continue|move|ref|self|Self|super|crate|as|in|unsafe|async|await|dyn|true|false|Some|None|Ok|Err)\b/g,builtins:/\b(String|Vec|Box|Rc|Arc|Option|Result|HashMap|HashSet|println|eprintln|format|panic|todo|unimplemented|assert|assert_eq|assert_ne|dbg|cfg|derive|macro_rules)\b/g,macros:/(\w+!)/g},java:{keywords:/\b(class|interface|extends|implements|public|private|protected|static|final|abstract|synchronized|volatile|transient|native|new|return|if|else|for|while|do|switch|case|default|break|continue|try|catch|finally|throw|throws|import|package|this|super|void|null|true|false|instanceof)\b/g,builtins:/\b(System|String|Integer|Long|Double|Float|Boolean|List|ArrayList|Map|HashMap|Set|HashSet|Optional|Stream|Object|Exception|RuntimeException|Thread|Runnable|Override|Deprecated)\b/g},cs:{keywords:/\b(class|struct|interface|enum|record|delegate|event|namespace|using|public|private|protected|internal|static|readonly|const|sealed|abstract|virtual|override|new|return|if|else|for|foreach|while|do|switch|case|default|break|continue|try|catch|finally|throw|async|await|yield|var|dynamic|is|as|in|out|ref|params|this|base|null|true|false|void|get|set|init|required|partial|where|select|from|orderby|group|join|let|into)\b/g,builtins:/\b(Console|String|Int32|Int64|Double|Boolean|List|Dictionary|HashSet|Task|IEnumerable|ILogger|IOptions|IFeatures|Exception|Guid|DateTime|TimeSpan|CancellationToken|Action|Func|Span|Memory|ReadOnlySpan)\b/g,attributes:/(\[[\w]+(?:\(.*?\))?\])/g},cpp:{keywords:/\b(class|struct|enum|union|namespace|using|template|typename|public|private|protected|static|const|constexpr|volatile|virtual|override|final|explicit|inline|extern|auto|decltype|new|delete|return|if|else|for|while|do|switch|case|default|break|continue|try|catch|throw|sizeof|alignof|typeid|static_cast|dynamic_cast|reinterpret_cast|const_cast|nullptr|true|false|void|this|operator|friend|noexcept|co_await|co_yield|co_return|concept|requires)\b/g,builtins:/\b(std|string|vector|map|unordered_map|set|array|pair|tuple|shared_ptr|unique_ptr|weak_ptr|optional|variant|any|cout|cin|endl|printf|scanf|malloc|free|sizeof|size_t|int8_t|int16_t|int32_t|int64_t|uint8_t|uint16_t|uint32_t|uint64_t)\b/g,preprocessor:/(#\s*(?:include|define|undef|if|ifdef|ifndef|else|elif|endif|pragma|error|warning).*$)/gm},c:"cpp",h:"cpp",hpp:"cpp",html:{tags:/(<\/?[\w-]+|>|\/>)/g,attrs:/\b([\w-]+)(?==)/g,commentType:"html",commentHtml:/(<!--[\s\S]*?-->)/g},xml:"html",svg:"html",css:{selectors:/([\w.#\[\]:,>+~*-]+)\s*\{/g,properties:/\b([\w-]+)(?=\s*:)/g,values:/:\s*([^;{}]+)/g,commentType:"block"},scss:"css",less:"css",json:{keys:/("[\w.-]+")\s*:/g,commentType:"none"},yaml:{keys:/([\w.-]+)\s*:/g,commentType:"hash"},yml:"yaml",md:{headings:/^(#{1,6}\s.*)$/gm,bold:/(\*\*[^*]+\*\*|__[^_]+__)/g,italic:/(\*[^*]+\*|_[^_]+_)/g,code:/(`[^`]+`)/g,links:/(\[[^\]]+\]\([^)]+\))/g,commentType:"none"},sh:{keywords:/\b(if|then|else|elif|fi|for|while|do|done|case|esac|function|return|exit|echo|export|local|readonly|unset|set|shift|eval|exec|trap|source|alias|cd|pwd|ls|mkdir|rm|cp|mv|cat|grep|sed|awk|find|xargs|sort|uniq|wc|head|tail|tee|cut|tr|test)\b/g,variables:/(\$\{?\w+\}?|\$\(|\$\{)/g,commentType:"hash"},bash:"sh",zsh:"sh",sql:{keywords:/\b(SELECT|FROM|WHERE|AND|OR|NOT|IN|LIKE|BETWEEN|JOIN|LEFT|RIGHT|INNER|OUTER|FULL|ON|AS|GROUP|BY|ORDER|HAVING|LIMIT|OFFSET|INSERT|INTO|VALUES|UPDATE|SET|DELETE|CREATE|ALTER|DROP|TABLE|INDEX|VIEW|TRIGGER|FUNCTION|PROCEDURE|BEGIN|END|IF|ELSE|THEN|CASE|WHEN|DECLARE|EXEC|UNION|ALL|DISTINCT|TOP|EXISTS|NULL|IS|ASC|DESC|PRIMARY|KEY|FOREIGN|REFERENCES|CONSTRAINT|DEFAULT|CHECK|UNIQUE|CASCADE|TRUNCATE|COMMIT|ROLLBACK|GRANT|REVOKE)\b/gi,commentType:"both"},lua:{keywords:/\b(and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/g,builtins:/\b(print|type|tostring|tonumber|pairs|ipairs|next|select|unpack|error|pcall|xpcall|assert|require|table|string|math|io|os|coroutine|setmetatable|getmetatable|rawget|rawset)\b/g,commentLine:/(--(?!\[).*$)/gm,commentBlock:/(--\[\[[\s\S]*?\]\])/g},php:{keywords:/\b(function|class|interface|trait|extends|implements|public|private|protected|static|final|abstract|const|var|new|return|if|else|elseif|for|foreach|while|do|switch|case|default|break|continue|try|catch|finally|throw|use|namespace|require|include|require_once|include_once|echo|print|die|exit|null|true|false|array|list|match|fn|yield|from)\b/g,variables:/(\$\w+)/g},swift:{keywords:/\b(func|class|struct|enum|protocol|extension|let|var|guard|if|else|for|while|repeat|switch|case|default|break|continue|return|throw|try|catch|defer|import|typealias|associatedtype|init|deinit|subscript|operator|precedencegroup|self|Self|super|nil|true|false|is|as|in|inout|throws|rethrows|where|some|any|weak|unowned|lazy|mutating|nonmutating|override|final|required|convenience|optional|dynamic|async|await|actor|nonisolated|isolated|sending|consuming|borrowing)\b/g},kt:{keywords:/\b(fun|class|object|interface|val|var|if|else|when|for|while|do|return|break|continue|throw|try|catch|finally|import|package|as|is|in|out|by|init|constructor|companion|data|sealed|enum|abstract|open|override|private|protected|internal|public|inline|reified|suspend|coroutine|null|true|false|this|super|it|typealias|annotation|lateinit|lazy|get|set)\b/g},dart:{keywords:/\b(class|extends|implements|with|mixin|abstract|sealed|base|interface|final|const|var|late|required|dynamic|void|static|return|if|else|for|while|do|switch|case|default|break|continue|try|catch|finally|throw|rethrow|assert|new|this|super|null|true|false|is|as|in|async|await|yield|import|export|library|part|show|hide|deferred|typedef|enum|extension|on)\b/g},r:{keywords:/\b(if|else|for|while|repeat|function|return|break|next|in|TRUE|FALSE|NULL|NA|Inf|NaN|library|require|source|print|cat|paste|paste0|sprintf|stop|warning|message)\b/g,commentType:"hash"},toml:{keys:/([\w.-]+)\s*=/g,sections:/(\[[\w.]+\])/g,commentType:"hash"},proto:{keywords:/\b(syntax|package|import|option|message|enum|service|rpc|returns|repeated|optional|required|map|oneof|reserved|extensions|extend|group|default|packed|deprecated|java_package|java_outer_classname|optimize_for|cc_enable_arenas|objc_class_prefix|csharp_namespace|swift_prefix|php_class_prefix|php_namespace|ruby_package|string|int32|int64|uint32|uint64|sint32|sint64|fixed32|fixed64|sfixed32|sfixed64|float|double|bool|bytes)\b/g}},Ee={keyword:"hl-kw",builtin:"hl-bi",string:"hl-st",number:"hl-nm",comment:"hl-cm",operator:"hl-op",decorator:"hl-dc",macro:"hl-mc",preprocessor:"hl-pp",attribute:"hl-at",tag:"hl-tg",property:"hl-pr",variable:"hl-vr",heading:"hl-hd",bold:"hl-bd",link:"hl-lk",key:"hl-ky",section:"hl-sc"}});function Cg(e,t,s){let n=[],r=0,i=0;if(t!=null){let f=t.split(`
|
|
2015
2015
|
`);for(let g=0;g<f.length;g++)n.push({type:"addition",oldNum:"",oldText:"",newNum:g+1,newText:f[g]}),r++;return{lines:n,stats:{additions:r,deletions:0},content:t}}if(!e||e.trim()==="")return{lines:[{type:"context",oldNum:"",oldText:s("git.noDiff"),newNum:"",newText:s("git.noDiff")}],stats:{additions:0,deletions:0},content:""};if(e.includes("Binary files")&&e.includes("differ"))return{lines:[{type:"context",oldNum:"",oldText:s("git.binaryFile"),newNum:"",newText:s("git.binaryFile")}],stats:{additions:0,deletions:0},content:e};let o=e.split(`
|
|
2016
|
-
`),a=0,l=0,c=!1,d=[],u=[],p=()=>{let f=Math.max(d.length,u.length);for(let g=0;g<f;g++){let h=d[g],m=u[g];h&&m?n.push({type:"modification",oldNum:h.num,oldText:h.text,newNum:m.num,newText:m.text}):h?n.push({type:"deletion",oldNum:h.num,oldText:h.text,newNum:"",newText:""}):m&&n.push({type:"addition",oldNum:"",oldText:"",newNum:m.num,newText:m.text})}d=[],u=[]};for(let f of o){if(f.startsWith("diff --git")||f.startsWith("index ")||f.startsWith("---")||f.startsWith("+++")||f.startsWith("\\"))continue;let g=f.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(g){p(),a=parseInt(g[1]),l=parseInt(g[2]),c=!0,n.push({type:"hunk",oldNum:"\xB7\xB7\xB7",oldText:f,newNum:"\xB7\xB7\xB7",newText:f});continue}if(c)if(f.startsWith("-"))u.length>0&&d.length===0&&p(),d.push({num:a++,text:f.substring(1)}),i++;else if(f.startsWith("+"))u.push({num:l++,text:f.substring(1)}),r++;else{p();let h=f.startsWith(" ")?f.substring(1):f;n.push({type:"context",oldNum:a++,oldText:h,newNum:l++,newText:h})}}return p(),{lines:n,stats:{additions:r,deletions:i},content:e}}var Ag=F(()=>{});function xg(e,t){let{effectiveGitWorkDir:s,gitOperating:n,gitOpFeedback:r,commitMessage:i}=t,o=null,a=null,l=(w,b)=>{o&&clearTimeout(o),r.value={ok:w,message:b},o=setTimeout(()=>{r.value=null},4e3)},c=(w,b)=>{e.currentAgent&&(w.value=!0,b.value="",e.sendWsMessage({type:"git_status",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,workDir:s.value,_clientId:e.clientId}))},d=(w,b={})=>{e.currentAgent&&(n.value=!0,a&&clearTimeout(a),a=setTimeout(()=>{n.value&&(n.value=!1,l(!1,"Operation timed out"))},15e3),e.sendWsMessage({type:w,conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,workDir:s.value,_clientId:e.clientId,...b}))};return{showFeedback:l,loadGitStatus:c,gitOp:d,stageFile:w=>d("git_add",{filePath:w}),unstageFile:w=>d("git_reset",{filePath:w}),discardFile:async w=>{await
|
|
2016
|
+
`),a=0,l=0,c=!1,d=[],u=[],p=()=>{let f=Math.max(d.length,u.length);for(let g=0;g<f;g++){let h=d[g],m=u[g];h&&m?n.push({type:"modification",oldNum:h.num,oldText:h.text,newNum:m.num,newText:m.text}):h?n.push({type:"deletion",oldNum:h.num,oldText:h.text,newNum:"",newText:""}):m&&n.push({type:"addition",oldNum:"",oldText:"",newNum:m.num,newText:m.text})}d=[],u=[]};for(let f of o){if(f.startsWith("diff --git")||f.startsWith("index ")||f.startsWith("---")||f.startsWith("+++")||f.startsWith("\\"))continue;let g=f.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(g){p(),a=parseInt(g[1]),l=parseInt(g[2]),c=!0,n.push({type:"hunk",oldNum:"\xB7\xB7\xB7",oldText:f,newNum:"\xB7\xB7\xB7",newText:f});continue}if(c)if(f.startsWith("-"))u.length>0&&d.length===0&&p(),d.push({num:a++,text:f.substring(1)}),i++;else if(f.startsWith("+"))u.push({num:l++,text:f.substring(1)}),r++;else{p();let h=f.startsWith(" ")?f.substring(1):f;n.push({type:"context",oldNum:a++,oldText:h,newNum:l++,newText:h})}}return p(),{lines:n,stats:{additions:r,deletions:i},content:e}}var Ag=F(()=>{});function xg(e,t){let{effectiveGitWorkDir:s,gitOperating:n,gitOpFeedback:r,commitMessage:i}=t,o=null,a=null,l=(w,b)=>{o&&clearTimeout(o),r.value={ok:w,message:b},o=setTimeout(()=>{r.value=null},4e3)},c=(w,b)=>{e.currentAgent&&(w.value=!0,b.value="",e.sendWsMessage({type:"git_status",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,workDir:s.value,_clientId:e.clientId}))},d=(w,b={})=>{e.currentAgent&&(n.value=!0,a&&clearTimeout(a),a=setTimeout(()=>{n.value&&(n.value=!1,l(!1,"Operation timed out"))},15e3),e.sendWsMessage({type:w,conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,workDir:s.value,_clientId:e.clientId,...b}))};return{showFeedback:l,loadGitStatus:c,gitOp:d,stageFile:w=>d("git_add",{filePath:w}),unstageFile:w=>d("git_reset",{filePath:w}),discardFile:async w=>{await De("Discard changes to "+w+"?",{destructive:!0})&&d("git_restore",{filePath:w})},stageAll:()=>d("git_add",{addAll:!0}),unstageAll:()=>d("git_reset",{resetAll:!0}),commitChanges:()=>{let w=i.value.trim();w&&d("git_commit",{commitMessage:w})},pushChanges:()=>d("git_push"),handleGitOpResult:(w,b)=>{n.value=!1,a&&(clearTimeout(a),a=null),w.success?(l(!0,w.message||w.operation+" succeeded"),w.operation==="commit"&&(i.value=""),b()):l(!1,w.error||w.operation+" failed")},cleanup:()=>{o&&clearTimeout(o),a&&clearTimeout(a)}}}var Tg=F(()=>{ot()});function Mg(e,t){let s=Vue.ref(!1),n=Vue.ref(""),r=Vue.ref([]),i=Vue.ref(!1),o=Vue.ref(""),a=g=>{i.value=!0,o.value="",e.sendWsMessage({type:"list_directory",conversationId:"_git_folder_picker",agentId:e.currentAgent,dirPath:g,workDir:t.value,_clientId:e.clientId})};return{folderPickerOpen:s,folderPickerPath:n,folderPickerEntries:r,folderPickerLoading:i,folderPickerSelected:o,openFolderPicker:()=>{s.value=!0,o.value="",i.value=!0;let g=t.value||"";n.value=g,r.value=[],e.sendWsMessage({type:"list_directory",conversationId:"_git_folder_picker",agentId:e.currentAgent,dirPath:g,workDir:t.value,_clientId:e.clientId})},folderPickerNavigateUp:()=>{if(!n.value)return;let g=n.value.includes("\\"),h=g?"\\":"/",m=n.value.replace(/[/\\]$/,"").split(/[/\\]/);if(m.pop(),m.length===0)n.value="",a("");else if(g&&m.length===1&&/^[A-Za-z]:$/.test(m[0]))n.value=m[0]+"\\",a(m[0]+"\\");else{let y=m.join(h);n.value=y,a(y)}},folderPickerSelectItem:g=>{o.value=g.name},folderPickerEnter:g=>{let h=n.value.includes("\\")||/^[A-Z]:/.test(g.name)?"\\":"/",m;n.value?m=n.value.replace(/[/\\]$/,"")+h+g.name:m=g.name+(g.name.endsWith("\\")?"":"\\"),n.value=m,a(m)},confirmFolderPicker:(g,h)=>{let m=n.value;if(m){if(o.value){let y=m.includes("\\")?"\\":"/";m=m.replace(/[/\\]$/,"")+y+o.value}g.value=m,s.value=!1,h()}},handleDirectoryListing:g=>g.conversationId!=="_git_folder_picker"?!1:(i.value=!1,r.value=(g.entries||[]).filter(h=>h.type==="directory").sort((h,m)=>h.name.localeCompare(m.name)),g.dirPath!=null&&(n.value=g.dirPath),!0)}}var Pg=F(()=>{});var Rg,_g=F(()=>{nc();Ig();Ag();Tg();Pg();Mn();Rg={name:"GitStatusTab",props:{routeKey:{type:String,required:!0},runtimeProvider:{type:String,required:!0},agentId:{type:String,required:!0},sessionId:{type:String,required:!0},conversationId:{type:String,required:!0},workDir:{type:String,default:""},workspaceGeneration:{type:String,required:!0}},template:`
|
|
2017
2017
|
<div class="git-status-tab git-three-col">
|
|
2018
2018
|
<!-- \u5DE6\u680F: \u6587\u4EF6\u5217\u8868 -->
|
|
2019
2019
|
<div class="git-col-files">
|
|
@@ -2257,7 +2257,7 @@ ${String(e||"").trim()}
|
|
|
2257
2257
|
</div>
|
|
2258
2258
|
</div>
|
|
2259
2259
|
</div>
|
|
2260
|
-
`,setup(e){let t=xn(Pinia.useChatStore(),e),s=Vue.inject("t"),n=_=>_.split(/[/\\]/).pop()||_,r=_=>{let P=_.split(/[/\\]/);return P.pop(),P.join("/")},i=_=>wo(n(_)),o=Vue.ref(null),a=Vue.reactive({staged:!1,modified:!1,untracked:!1}),l=_=>{a[_]=!a[_]},c=Vue.ref(!1),d=Vue.ref(""),u=Vue.ref(null),p=Vue.ref([]),f=Vue.computed(()=>t.effectiveWorkDir||""),g=Vue.ref(""),h=Vue.computed(()=>g.value.trim()||f.value),m=Vue.ref(null),y=Vue.ref(!1),v=Vue.ref(!1),k=Vue.ref(""),w=Vue.ref(null),b=Vue.ref([]),C=Vue.ref(null),S=Vue.ref(!0),M=Vue.ref(!1),N=Vue.ref(""),q=Vue.ref(null),L=Vue.ref(0),V=Vue.ref(0),$=_=>_==null||_===""?"":Sg(_,m.value||""),T=Vue.ref(parseInt(localStorage.getItem("gitDiffFontSize"))||12),I=_=>{T.value=Math.max(8,Math.min(24,_)),localStorage.setItem("gitDiffFontSize",T.value.toString())},R=()=>I(T.value+1),D=()=>I(T.value-1),E=_=>{_.deltaY<0?R():_.deltaY>0&&D()},Y=Vue.computed(()=>{let _=b.value;if(!_||_.length===0)return[];let P=_.length,j=[],K=0;for(;K<P;){let B=_[K];if(B.type==="addition"||B.type==="deletion"||B.type==="modification"){let G=B.type==="modification"?"modification":B.type,ie=K;for(;K<P&&(_[K].type===G||_[K].type==="modification"&&G!=="modification");)K++;let ke=K-ie;j.push({type:G,top:ie/P*100,height:Math.max(ke/P*100,.5)})}else K++}return j}),Q=_=>{let P=o.value;if(!P)return;let j=_.currentTarget.getBoundingClientRect(),K=(_.clientY-j.top)/j.height;P.scrollTop=K*(P.scrollHeight-P.clientHeight)},re=Vue.computed(()=>p.value.filter(_=>_.indexStatus!==" "&&_.indexStatus!=="?")),fe=Vue.computed(()=>p.value.filter(_=>_.workTreeStatus==="M"||_.workTreeStatus==="D")),me=Vue.computed(()=>p.value.filter(_=>_.indexStatus==="?"&&_.workTreeStatus==="?")),le=xg(t,{effectiveGitWorkDir:h,gitOperating:M,gitOpFeedback:q,commitMessage:N}),W=()=>le.loadGitStatus(c,d),ne=()=>{W()},oe=Mg(t,h),U=_=>ko(_),ce=()=>oe.confirmFolderPicker(g,W),Ae=(_,P)=>{m.value=_.path,y.value=P,v.value=!0,k.value="",w.value=null,b.value=[],C.value=null;let j=_.indexStatus==="?"&&_.workTreeStatus==="?";t.sendWsMessage({type:"git_diff",conversationId:t.currentConversation||"_explorer",agentId:t.currentAgent,workDir:h.value,filePath:_.path,staged:P,untracked:j,fullFile:S.value,_clientId:t.clientId})},Re=()=>{if(S.value=!S.value,m.value){let _=p.value.find(P=>P.path===m.value);_&&Ae(_,y.value)}},de=_=>{let P=_.detail;if(!(!P||!Tn(P,e.routeKey,e.workspaceGeneration)))switch(P.type){case"directory_listing":{Ot(P,e.routeKey)==="git-folder-picker"&&oe.handleDirectoryListing({...P,conversationId:"_git_folder_picker"});break}case"git_status_result":{if(e.routeKey&&Ot(P,e.routeKey)!=="main")return;if(c.value=!1,P.error){d.value=P.error,u.value=null,p.value=[];return}if(d.value="",u.value=P.branch||"HEAD",p.value=P.files||[],L.value=P.ahead||0,V.value=P.behind||0,m.value){let j=p.value.find(K=>K.path===m.value);if(j){let K=j.indexStatus!==" "&&j.indexStatus!=="?";y.value=K}else m.value=null,w.value=null,b.value=[],C.value=null}break}case"git_diff_result":{if(e.routeKey&&Ot(P,e.routeKey)!=="main")return;if(v.value=!1,P.error){k.value=P.error;return}k.value="";let j=Cg(P.diff,P.newFileContent,s);C.value=j.stats,b.value=j.lines,w.value=j.content;break}case"git_op_result":{if(e.routeKey&&Ot(P,e.routeKey)!=="main")return;le.handleGitOpResult(P,W);break}}};Vue.watch(()=>t.currentAgent,()=>{u.value=null,p.value=[],d.value="",m.value=null,w.value=null,t.currentAgent&&Vue.nextTick(()=>W())}),Vue.watch(()=>t.currentConversation,()=>{t.currentAgent&&(m.value=null,w.value=null,b.value=[],C.value=null,Vue.nextTick(()=>W()))});let Z=()=>W();return Vue.onMounted(()=>{window.addEventListener("workbench-message",de),t.currentAgent&&W()}),Vue.onUnmounted(()=>{window.removeEventListener("workbench-message",de),le.cleanup()}),{store:t,getFileName:n,getDirName:r,getFileIconHtml:i,hlLine:$,collapsedGroups:a,toggleGroup:l,gitLoading:c,gitError:d,gitBranch:u,gitFiles:p,gitWorkDir:g,defaultWorkDir:f,changeGitWorkDir:ne,stagedFiles:re,modifiedFiles:fe,untrackedFiles:me,selectedGitFile:m,selectedStaged:y,diffLoading:v,diffError:k,diffContent:w,diffLines:b,diffStats:C,diffFullFile:S,toggleDiffMode:Re,scrollMarkers:Y,diffScrollContainer:o,onMarkerClick:Q,fontSize:T,zoomIn:R,zoomOut:D,onWheel:E,gitOperating:M,commitMessage:N,gitOpFeedback:q,gitAhead:L,gitBehind:V,stageFile:le.stageFile,unstageFile:le.unstageFile,discardFile:le.discardFile,stageAll:le.stageAll,unstageAll:le.unstageAll,commitChanges:le.commitChanges,pushChanges:le.pushChanges,selectGitFile:Ae,refresh:Z,folderPickerOpen:oe.folderPickerOpen,folderPickerPath:oe.folderPickerPath,folderPickerEntries:oe.folderPickerEntries,folderPickerLoading:oe.folderPickerLoading,folderPickerSelected:oe.folderPickerSelected,getFolderIcon:U,openFolderPicker:oe.openFolderPicker,folderPickerNavigateUp:oe.folderPickerNavigateUp,folderPickerSelectItem:oe.folderPickerSelectItem,folderPickerEnter:oe.folderPickerEnter,confirmFolderPicker:ce}}}});function Dg(e){let t=Vue.ref(!1),s=Vue.ref(!1),n=Vue.ref(""),r=Vue.ref(""),i=Vue.ref(!1),o=Vue.ref(!1),a=Vue.ref(0),l=Vue.ref(-1),c=Vue.ref(null),d=Vue.ref(null),u=[],p=[],f=()=>{let q=e.value?.cmInstance;if(!q)return;let V=q.getWrapperElement().querySelector(".cm-find-scrollbar-annotations");V&&V.remove()},g=()=>{let q=e.value?.cmInstance;if(!q||p.length===0)return;f();let L=q.getWrapperElement();if(!L.querySelector(".CodeMirror-vscrollbar"))return;let $=q.lineCount();if($===0)return;let T=document.createElement("div");T.className="cm-find-scrollbar-annotations";for(let I of p){let R=I.from.line/$*100,D=document.createElement("div");D.className="cm-find-scrollbar-tick",D.style.top=R+"%",T.appendChild(D)}L.appendChild(T)},h=()=>{for(let q of u)try{q.clear()}catch{}u=[],p=[],a.value=0,l.value=-1,f()},m=q=>{let L=e.value?.cmInstance;if(!L||!p[q])return;for(let $=0;$<u.length;$++){if(!u[$])continue;let T=u[$].find();T&&(u[$].clear(),u[$]=L.markText(T.from,T.to,{className:"cm-find-highlight"}))}let V=p[q];if(u[q]){let $=u[q].find();$&&(u[q].clear(),u[q]=L.markText($.from,$.to,{className:"cm-find-highlight cm-find-current"}))}setTimeout(()=>{L.scrollIntoView({from:V.from,to:V.to},100)},0)},y=()=>{h();let q=e.value?.cmInstance;if(!q||!n.value)return;let L=n.value;if(L.length<3)return;let V=q.getValue(),$=i.value,T=o.value,I=[];try{if(T){let R=$?"g":"gi",D=new RegExp(L,R),E;for(;(E=D.exec(V))!==null;){if(E[0].length===0){D.lastIndex++;continue}let Y=q.posFromIndex(E.index),Q=q.posFromIndex(E.index+E[0].length);if(I.push({from:Y,to:Q}),I.length>1e4)break}}else{let R=$?L:L.toLowerCase(),D=$?V:V.toLowerCase(),E=0;for(;(E=D.indexOf(R,E))!==-1;){let Y=q.posFromIndex(E),Q=q.posFromIndex(E+L.length);if(I.push({from:Y,to:Q}),E+=L.length,I.length>1e4)break}}}catch{return}p=I,a.value=I.length;for(let R of I)u.push(q.markText(R.from,R.to,{className:"cm-find-highlight"}));if(I.length>0){let R=q.getCursor(),D=0;for(let E=0;E<I.length;E++){if(CodeMirror.cmpPos(I[E].from,R)>=0){D=E;break}E===I.length-1&&(D=0)}l.value=D,m(D)}g()};return{findBarVisible:t,replaceBarVisible:s,findQuery:n,replaceQuery:r,findCaseSensitive:i,findUseRegex:o,findMatchCount:a,findMatchIndex:l,findInputRef:c,replaceInputRef:d,clearFindMarkers:h,performFind:y,onFindInput:()=>{y()},findNext:()=>{if(p.length===0)return;let q=(l.value+1)%p.length;l.value=q,m(q)},findPrev:()=>{if(p.length===0)return;let q=(l.value-1+p.length)%p.length;l.value=q,m(q)},openFindBar:(q=!1)=>{t.value=!0,s.value=q;let L=e.value?.cmInstance;if(L){let V=L.getSelection();V&&(n.value=V)}Vue.nextTick(()=>{c.value?.focus(),c.value?.select(),n.value&&y()})},closeFindBar:()=>{h(),t.value=!1,s.value=!1;let q=e.value?.cmInstance;q&&q.focus()},toggleReplaceBar:()=>{s.value=!s.value,s.value&&Vue.nextTick(()=>d.value?.focus())},replaceOne:()=>{let q=e.value?.cmInstance;if(!q||p.length===0||l.value<0)return;let L=p[l.value];q.replaceRange(r.value,L.from,L.to),y()},replaceAll:()=>{let q=e.value?.cmInstance;!q||p.length===0||(q.operation(()=>{for(let L=p.length-1;L>=0;L--)q.replaceRange(r.value,p[L].from,p[L].to)}),y())}}}var Eg=F(()=>{});function Lg(e,t){let{getEffectiveWorkDir:s,treePath:n}=t,r=Vue.reactive(new Set),i=Vue.ref(-1),o=Vue.ref(!1),a=Vue.ref(null),l=null,c=null,d=Vue.ref(!1),u=Vue.ref(""),p=Vue.ref("file"),f=Vue.ref(null),g=Vue.ref(!1),h=Vue.ref(""),m=Vue.ref(null),y=Vue.reactive({visible:!1,x:0,y:0,entry:null}),v=Vue.ref(!1),k=Vue.ref(""),w=Vue.ref(null),b=null,C=Vue.reactive({dragging:null,dropTarget:null}),S=Vue.ref(!1),M=(B,G)=>{l&&clearTimeout(l),a.value={ok:B,message:G},l=setTimeout(()=>{a.value=null},4e3)},N=()=>{o.value=!0,c&&clearTimeout(c),c=setTimeout(()=>{o.value&&(o.value=!1,M(!1,"Operation timed out"))},15e3)},q=B=>{r.has(B)?r.delete(B):r.add(B)},L=()=>{r.clear(),i.value=-1},V=B=>{p.value=B,u.value="",d.value=!0,Vue.nextTick(()=>f.value?.focus())},$=()=>{let B=u.value.trim();if(!B)return;d.value=!1;let G=n.value||s();if(!G)return;let ie=G.includes("\\")?"\\":"/",ke=G.replace(/[/\\]$/,"")+ie+B;N(),e.sendWsMessage({type:"create_file",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,filePath:ke,isDirectory:p.value==="directory",workDir:s(),_clientId:e.clientId})},T=async(B,G)=>{let ie=B.path.split("/").pop();await Ee(G("files.deleteConfirm",{name:ie})+(B.type==="directory"?G("files.deleteDirHint"):""),{destructive:!0})&&(N(),e.sendWsMessage({type:"delete_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[B.path],workDir:s(),_clientId:e.clientId}))},I=async B=>{let G=r.size;G!==0&&await Ee(B("files.deleteSelectedConfirm",{count:G}),{destructive:!0})&&(N(),e.sendWsMessage({type:"delete_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[...r],workDir:s(),_clientId:e.clientId}))},R=()=>{h.value=n.value||s()||"",g.value=!0,Vue.nextTick(()=>m.value?.focus())},D=()=>{let B=h.value.trim();!B||r.size===0||(g.value=!1,N(),e.sendWsMessage({type:"move_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[...r],destination:B,workDir:s(),_clientId:e.clientId}))},E=(B,G)=>{let se=B.clientX,ae=B.clientY;se+180>window.innerWidth&&(se=window.innerWidth-180),ae+240>window.innerHeight&&(ae=window.innerHeight-240),y.entry=G,y.x=se,y.y=ae,y.visible=!0},Y=()=>{y.visible=!1};return{selectedPaths:r,lastClickedIndex:i,fileOperating:o,fileOpFeedback:a,newFileDialogVisible:d,newFileName:u,newFileType:p,newFileInput:f,moveDialogVisible:g,moveDestination:h,moveDestInput:m,contextMenu:y,renameDialogVisible:v,renameNewName:k,renameInput:w,dragState:C,externalDropActive:S,showFileOpFeedback:M,toggleSelection:q,clearSelection:L,showNewFileDialog:V,confirmNewFile:$,deleteSingleFile:T,deleteSelected:I,openMoveDialog:R,confirmMove:D,showContextMenu:E,hideContextMenu:Y,ctxRename:()=>{let B=y.entry;Y(),B&&(k.value=B.name,v.value=!0,Vue.nextTick(()=>{let G=w.value;if(G)if(G.focus(),B.type==="file"){let ie=B.name.lastIndexOf(".");ie>0?G.setSelectionRange(0,ie):G.select()}else G.select()}))},confirmRename:()=>{let B=y.entry,G=k.value.trim();if(!G||!B||G===B.name){v.value=!1;return}v.value=!1;let ie=B.path.replace(/\/$/,"").split("/");ie.pop();let ke=ie.join("/")||"/";N(),e.sendWsMessage({type:"move_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[B.path],destination:ke,newName:G,workDir:s(),_clientId:e.clientId})},ctxCopy:()=>{let B=y.entry;if(Y(),!B)return;let G=B.path.replace(/\/$/,"").split("/");G.pop();let ie=G.join("/")||"/";N(),e.sendWsMessage({type:"copy_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[B.path],destination:ie,workDir:s(),_clientId:e.clientId})},ctxMoveTo:()=>{let B=y.entry;Y(),B&&(r.clear(),r.add(B.path),R())},ctxDelete:B=>{let G=y.entry;Y(),G&&T(G,B)},ctxDownload:()=>{let B=y.entry;Y(),!(!B||B.type!=="file")&&(b=B.path,e.sendWsMessage({type:"read_file",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,filePath:B.path,workDir:s(),_clientId:e.clientId}))},onDragStart:(B,G)=>{C.dragging=G,B.dataTransfer.setData("text/plain",G.path),B.dataTransfer.effectAllowed="move"},onDragOver:(B,G)=>{if(!C.dragging&&B.dataTransfer.types.includes("Files")){G.type==="directory"&&(B.dataTransfer.dropEffect="copy",C.dropTarget=G.path);return}!C.dragging||G.type!=="directory"||G.path!==C.dragging.path&&(G.path.startsWith(C.dragging.path+"/")||(B.dataTransfer.dropEffect="move",C.dropTarget=G.path))},onDragLeave:B=>{let G=B.relatedTarget;G&&B.currentTarget.contains(G)||(C.dropTarget=null)},onDrop:(B,G,ie)=>{if(C.dropTarget=null,!C.dragging&&B.dataTransfer.files.length>0&&G.type==="directory"){ie(B.dataTransfer.files,G.path);return}if(!C.dragging||G.type!=="directory"){C.dragging=null;return}if(G.path===C.dragging.path){C.dragging=null;return}N(),e.sendWsMessage({type:"move_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[C.dragging.path],destination:G.path,workDir:s(),_clientId:e.clientId}),C.dragging=null},onTreeDragOver:B=>{C.dragging||B.dataTransfer.types.includes("Files")&&(B.dataTransfer.dropEffect="copy",S.value=!0)},onTreeDragLeave:B=>{let G=B.relatedTarget;G&&B.currentTarget.contains(G)||(S.value=!1)},onTreeDrop:(B,G,ie)=>{if(S.value=!1,!C.dragging&&B.dataTransfer.files.length>0){let ke=n.value||G||s();ie(B.dataTransfer.files,ke)}},handleExternalFileDrop:async(B,G)=>{if(!G)return;let ie=[],ke=[];for(let se of B)ke.push(new Promise(ae=>{let Se=new FileReader;Se.onload=()=>{let Me=btoa(new Uint8Array(Se.result).reduce((Ve,Ke)=>Ve+String.fromCharCode(Ke),""));ie.push({name:se.name,data:Me}),ae()},Se.onerror=()=>ae(),Se.readAsArrayBuffer(se)}));await Promise.all(ke),ie.length!==0&&(o.value=!0,c&&clearTimeout(c),c=setTimeout(()=>{o.value&&(o.value=!1,M(!1,"Upload timed out"))},3e4),e.sendWsMessage({type:"upload_to_dir",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,files:ie,dirPath:G,workDir:s(),_clientId:e.clientId}))},handleFileOpResult:(B,G,ie)=>{o.value=!1,c&&(clearTimeout(c),c=null),M(B.success,B.success?B.message:B.error||"Operation failed"),B.success&&(ie&&G(ie),(B.operation==="delete"||B.operation==="move")&&(r.clear(),i.value=-1))},getPendingDownload:()=>b,clearPendingDownload:()=>{b=null},cleanup:()=>{l&&clearTimeout(l),c&&clearTimeout(c)}}}var $g=F(()=>{ot()});function Vg(e,{getEffectiveWorkDir:t,normalizePath:s,selectedPaths:n,lastClickedIndex:r,openFileInTab:i,clearSelection:o}){let a=Vue.ref(""),l=Vue.ref(""),c=Vue.reactive({}),d=Vue.ref(!1),u=Vue.ref(null),p=Vue.computed(()=>{if(!l.value)return"EXPLORER";let V=l.value.replace(/[\\/]+$/,"").split(/[\\/]/);return(V[V.length-1]||l.value).toUpperCase()}),f=Vue.computed(()=>l.value?!!c[l.value]?.expanded:!1),g=()=>{if(!l.value)return;let V=c[l.value];V&&(V.expanded=!V.expanded)},h=()=>{for(let V of Object.keys(c))c[V]&&(c[V].expanded=!1)},m=()=>{d.value=!0,Vue.nextTick(()=>u.value?.focus())},y=()=>{d.value=!1,b()},v=()=>{d.value=!1},k=Vue.computed(()=>{let V=[],$=(T,I)=>{let R=c[T];if(!(!R||!R.entries))for(let D of R.entries)V.push({...D,depth:I}),D.type==="directory"&&c[D.path]?.expanded&&$(D.path,I+1)};return l.value&&c[l.value]?.expanded&&$(l.value,0),V}),w=V=>{let $=s(V);c[$]?c[$].loading=!0:c[$]={entries:[],expanded:!0,loaded:!1,loading:!0},e.sendWsMessage({type:"list_directory",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,dirPath:V,workDir:t(),_clientId:e.clientId})},b=()=>{let V=a.value.trim();if(!V)return;let $=s(V);l.value=$,Object.keys(c).forEach(T=>delete c[T]),c[$]={entries:[],expanded:!0,loaded:!1,loading:!0},e.sendWsMessage({type:"list_directory",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,dirPath:V,workDir:t(),_clientId:e.clientId})},C=V=>{let $=s(V),T=c[$];T?T.loaded?T.expanded=!T.expanded:(T.expanded=!0,w(V)):(c[$]={entries:[],expanded:!0,loaded:!1,loading:!1},w(V))},S=(V,$)=>{let T=k.value,I=T.findIndex(R=>R.path===V.path);if($&&($.shiftKey||$.ctrlKey||$.metaKey)){if($.shiftKey&&r.value>=0&&I>=0){let R=Math.min(r.value,I),D=Math.max(r.value,I);!$.ctrlKey&&!$.metaKey&&n.clear();for(let E=R;E<=D;E++)n.add(T[E].path)}else n.has(V.path)?n.delete(V.path):n.add(V.path);r.value=I;return}n.size>0&&(n.clear(),r.value=-1),V.type==="directory"?C(V.path):i(V.path,V.name),r.value=I},M=V=>{let $=s(V.dirPath);if(V.error){c[$]&&(c[$].loading=!1);return}let T=(V.entries||[]).sort((D,E)=>D.type===E.type?D.name.localeCompare(E.name):D.type==="directory"?-1:1),I=$.replace(/\/$/,""),R=T.map(D=>({...D,path:I+"/"+D.name}));c[$]?(c[$].entries=R,c[$].loaded=!0,c[$].loading=!1):c[$]={entries:R,expanded:!0,loaded:!0,loading:!1},$===l.value&&(a.value=V.dirPath)},N=()=>{Object.keys(c).forEach(V=>delete c[V])};return{treePath:a,treeRootPath:l,treeNodes:c,flattenedTree:k,editingTreePath:d,treePathInputRef:u,rootFolderName:p,rootExpanded:f,toggleRootExpand:g,collapseAll:h,startTreePathEdit:m,confirmTreePath:y,cancelTreePathEdit:v,loadTreeDirectory:w,loadRootDirectory:b,toggleDirectory:C,onTreeItemClick:S,handleDirectoryListing:M,clearTreeNodes:N,initFileBrowser:()=>{let V=t();if(V){let $=s(V);a.value=V,l.value=$,N(),w(V)}},refresh:()=>{l.value&&w(l.value)}}}var Og=F(()=>{});function Rn(e){let t=e.lastIndexOf(".");if(t<0)return"text";let s=e.substring(t).toLowerCase();return bw.has(s)?"office":ww.has(s)?"pdf":kw.has(s)?"image":"text"}function Jt(e){let t=e.lastIndexOf(".");return t<0?!1:Sw.has(e.substring(t).toLowerCase())}function Iw(e){let t=e.split(".").pop()?.toLowerCase();return{js:"javascript",mjs:"javascript",jsx:"javascript",ts:{name:"javascript",typescript:!0},tsx:{name:"javascript",typescript:!0},json:{name:"javascript",json:!0},py:"python",html:"htmlmixed",htm:"htmlmixed",vue:"htmlmixed",xml:"xml",svg:"xml",css:"css",scss:"css",less:"css",sh:"shell",bash:"shell",zsh:"shell",c:"text/x-csrc",h:"text/x-csrc",cpp:"text/x-c++src",hpp:"text/x-c++src",cs:"text/x-csharp",java:"text/x-java",md:"markdown",markdown:"markdown"}[t]||"text/plain"}function Fg(e,{activeFile:t,editorContainer:s,fontSize:n,clearFindMarkers:r,openFindBar:i,saveFile:o}){let a=Vue.ref(""),l=Vue.reactive({}),c=()=>{},d=()=>{},u=({openQuickOpen:v,openGoToLine:k})=>{c=v,d=k},p=(v,k=0)=>{if(!s.value){k<20&&setTimeout(()=>p(v,k+1),100);return}if(!v)return;if(s.value.innerHTML="",typeof CodeMirror>"u"){let C=document.createElement("textarea");C.value=v.content||"",C.style.cssText="width:100%;height:100%;border:none;outline:none;resize:none;padding:12px;font-family:monospace;font-size:12px;background:var(--bg-main);color:var(--text-main);white-space:pre;tab-size:4;",C.spellcheck=!1,C.addEventListener("input",()=>{v.content=C.value,v.isDirty=C.value!==v.originalContent}),C.addEventListener("keydown",S=>{(S.ctrlKey||S.metaKey)&&S.key==="s"&&(S.preventDefault(),o())}),s.value.appendChild(C),a.value="";return}let b=document.documentElement.getAttribute("data-theme")==="dark"?"material-darker":"default";try{let C=CodeMirror(s.value,{value:v.content||"",mode:Iw(v.name),theme:b,lineNumbers:!0,tabSize:4,indentWithTabs:!1,lineWrapping:!1,readOnly:!1,extraKeys:{"Ctrl-S":()=>o(),"Cmd-S":()=>o(),"Ctrl-P":()=>c(),"Cmd-P":()=>c(),"Ctrl-G":()=>d(),"Cmd-G":()=>d(),"Ctrl-F":()=>i(!1),"Cmd-F":()=>i(!1),"Ctrl-R":()=>i(!0),"Cmd-R":()=>i(!0),"Ctrl-H":()=>i(!0),"Cmd-H":()=>i(!0)}});C.on("change",()=>{let M=C.getValue();v.content=M,v.isDirty=M!==v.originalContent}),v.cmInstance=C,C.getWrapperElement().style.fontSize=n.value+"px";let S=e.currentConversation;S&&l[S]?.[v.path]&&C.setHistory(l[S][v.path]),Vue.nextTick(()=>{C.refresh(),setTimeout(()=>C.refresh(),200)}),a.value=""}catch(C){a.value=`Editor error: ${C.message}`}};return{debugStatus:a,undoHistoryMap:l,createEditor:p,destroyEditor:()=>{r();let v=t.value;v?.cmInstance&&(v.cmInstance.toTextArea&&v.cmInstance.toTextArea(),v.cmInstance=null),s.value&&(s.value.innerHTML="")},setKeyBindings:u,saveCurrentUndoHistory:()=>{let v=e.currentConversation;if(!v)return;let k=t.value;k?.cmInstance&&(l[v]||(l[v]={}),l[v][k.path]=k.cmInstance.getHistory())},saveAllUndoHistory:v=>{if(!v)return;let k=t.value;k?.cmInstance&&(l[v]||(l[v]={}),l[v][k.path]=k.cmInstance.getHistory())},cleanupUndoHistory:(v,k)=>{v&&l[v]&&delete l[v][k]},deleteConversationHistory:v=>{delete l[v]}}}var bw,ww,kw,Sw,Fr=F(()=>{bw=new Set([".docx",".xlsx",".xls",".pptx",".ppt"]),ww=new Set([".pdf"]),kw=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico"]),Sw=new Set([".md",".markdown",".mdx"])});function Hg(e,{editorContainer:t,createEditor:s,t:n}){let r=Vue.ref(!0),i=Vue.ref(null),o=Vue.ref(null),a=Vue.computed(()=>{let f=e.value;return!!(f&&Jt(f.name))}),l=Vue.computed(()=>{let f=e.value;if(!f||!Jt(f.name)||f.content==null)return"";try{if(typeof marked<"u")return marked.parse(f.content)}catch{}return"<pre>"+(f.content||"")+"</pre>"});function c(){ht(i.value)}async function d(){await ht(i.value)}function u(){r.value=!1,Vue.nextTick(()=>{let f=e.value;f&&t.value&&s(f)})}return{mdPreviewMode:r,mdPreviewRef:i,officePreviewContainer:o,isActiveMarkdown:a,mdRenderedHtml:l,initMermaid:c,renderMermaidBlocks:d,switchToMdEdit:u,renderOfficeLocal:f=>{let g=o.value;if(!g||!f._arrayBuffer)return;g.innerHTML="";let h=("."+f.name.split(".").pop()).toLowerCase();if(h===".docx"&&window.docx)window.docx.renderAsync(f._arrayBuffer,g,null,{className:"docx-preview-content",inWrapper:!0,ignoreWidth:!1,ignoreHeight:!0}).catch(m=>{f.previewError=m.message});else if(h===".xlsx"||h===".xls")try{let m=XLSX.read(f._arrayBuffer,{type:"array"}),y=m.SheetNames[0],v=XLSX.utils.sheet_to_html(m.Sheets[y],{editable:!1});g.innerHTML='<div class="xlsx-sheet-tabs">'+m.SheetNames.map((k,w)=>`<button class="xlsx-sheet-tab${w===0?" active":""}" data-idx="${w}">${k}</button>`).join("")+'</div><div class="xlsx-table-wrap">'+v+"</div>",g.querySelectorAll(".xlsx-sheet-tab").forEach(k=>{k.addEventListener("click",()=>{let w=parseInt(k.dataset.idx),b=m.SheetNames[w],C=XLSX.utils.sheet_to_html(m.Sheets[b],{editable:!1});g.querySelector(".xlsx-table-wrap").innerHTML=C,g.querySelectorAll(".xlsx-sheet-tab").forEach(S=>S.classList.remove("active")),k.classList.add("active")})})}catch(m){f.previewError=m.message}else(h===".pptx"||h===".ppt")&&(g.innerHTML='<div class="preview-unsupported">'+(n?n("files.pptxNotSupported"):"PowerPoint preview not supported")+"</div>")}}}var qg=F(()=>{xr();Fr()});function Bg(e,{getEffectiveWorkDir:t,treePath:s,openFileInTab:n,normalizePath:r,treeRootPath:i,treeNodes:o,loadTreeDirectory:a}){let l=Vue.ref(""),c=Vue.ref([]),d=Vue.ref(!1),u=null,p=Vue.ref(!1),f=Vue.ref(""),g=Vue.ref([]),h=Vue.ref(0),m=Vue.ref(!1),y=Vue.ref(null),v=null,k=Vue.ref(!1),w=Vue.ref(""),b=Vue.ref(null),C=re=>{!e.currentAgent||!re.trim()||e.sendWsMessage({type:"file_search",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,query:re.trim(),dirPath:s.value||t()||"",_clientId:e.clientId})},S=()=>{if(u&&clearTimeout(u),!l.value.trim()){c.value=[],d.value=!1;return}d.value=!0,u=setTimeout(()=>{C(l.value)},300)},M=()=>{l.value="",c.value=[],d.value=!1},N=re=>{if(re.type==="directory"){let fe=r(re.fullPath);i.value=fe,s.value=re.fullPath,Object.keys(o).forEach(me=>delete o[me]),a(re.fullPath),M()}else n(re.fullPath,re.name),M()},q=()=>{p.value=!0,f.value="",g.value=[],h.value=0,m.value=!1,Vue.nextTick(()=>y.value?.focus())},L=()=>{p.value=!1,f.value="",g.value=[]},V=()=>{if(v&&clearTimeout(v),!f.value.trim()){g.value=[],m.value=!1;return}m.value=!0,h.value=0,v=setTimeout(()=>{C(f.value)},200)},$=()=>{g.value.length>0&&(h.value=(h.value+1)%g.value.length)},T=()=>{g.value.length>0&&(h.value=(h.value-1+g.value.length)%g.value.length)},I=re=>{re.type!=="directory"&&n(re.fullPath,re.name),L()},R=()=>{let re=g.value[h.value];re&&I(re)},D=()=>{k.value=!0,w.value="",Vue.nextTick(()=>b.value?.focus())},E=()=>{k.value=!1,w.value=""};return{searchQuery:l,searchResults:c,searchLoading:d,onSearchInput:S,clearSearch:M,onSearchResultClick:N,quickOpenVisible:p,quickOpenQuery:f,quickOpenResults:g,quickOpenSelectedIndex:h,quickOpenLoading:m,quickOpenInput:y,openQuickOpen:q,closeQuickOpen:L,onQuickOpenInput:V,quickOpenSelectNext:$,quickOpenSelectPrev:T,quickOpenConfirm:R,quickOpenOpenFile:I,goToLineVisible:k,goToLineValue:w,goToLineInput:b,openGoToLine:D,closeGoToLine:E,goToLineConfirm:re=>{let fe=parseInt(w.value);if(isNaN(fe)||fe<1)return;let me=re.value;if(me?.cmInstance){let le=me.cmInstance,W=Math.min(fe-1,le.lineCount()-1);le.setCursor({line:W,ch:0}),le.scrollIntoView({line:W,ch:0},100),le.focus()}E()},handleFileSearchResult:re=>{let fe=re.results||[];p.value?re.query&&re.query.trim()===f.value.trim()&&(g.value=fe,m.value=!1,h.value=0):re.query&&re.query.trim()===l.value.trim()&&(c.value=fe,d.value=!1)}}}var Ng=F(()=>{});function Wg(e,{getEffectiveWorkDir:t,treePath:s,treeRootPath:n,treeNodes:r,normalizePath:i,loadTreeDirectory:o}){let a=Vue.ref(!1),l=Vue.ref(""),c=Vue.ref([]),d=Vue.ref(!1),u=Vue.ref(""),p=()=>{a.value=!0,u.value="",d.value=!0;let k=s.value||t()||"";l.value=k,c.value=[],e.sendWsMessage({type:"list_directory",conversationId:"_folder_picker",agentId:e.currentAgent,dirPath:k,workDir:t(),_clientId:e.clientId})},f=k=>{d.value=!0,u.value="",e.sendWsMessage({type:"list_directory",conversationId:"_folder_picker",agentId:e.currentAgent,dirPath:k,workDir:t(),_clientId:e.clientId})};return{folderPickerOpen:a,folderPickerPath:l,folderPickerEntries:c,folderPickerLoading:d,folderPickerSelected:u,openFolderPicker:p,folderPickerNavigateUp:()=>{if(!l.value)return;let k=l.value.includes("\\"),w=k?"\\":"/",b=l.value.replace(/[/\\]$/,"").split(/[/\\]/);if(b.pop(),b.length===0)l.value="",f("");else if(k&&b.length===1&&/^[A-Za-z]:$/.test(b[0]))l.value=b[0]+"\\",f(b[0]+"\\");else{let C=b.join(w);l.value=C,f(C)}},folderPickerSelectItem:k=>{u.value=k.name},folderPickerEnter:k=>{let w;if(!l.value)w=k.name+(k.name.endsWith("\\")?"":"\\");else{let b=l.value.includes("\\")||/^[A-Z]:/.test(k.name)?"\\":"/";w=l.value.replace(/[/\\]$/,"")+b+k.name}l.value=w,f(w)},confirmFolderPicker:()=>{let k=l.value;if(!k)return;if(u.value){let b=k.includes("\\")?"\\":"/";k=k.replace(/[/\\]$/,"")+b+u.value}s.value=k,a.value=!1;let w=i(k);n.value=w,Object.keys(r).forEach(b=>delete r[b]),r[w]={entries:[],expanded:!0,loaded:!1,loading:!0},e.sendWsMessage({type:"list_directory",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,dirPath:k,workDir:t(),_clientId:e.clientId})},handleFolderPickerListing:k=>{d.value=!1,c.value=(k.entries||[]).filter(w=>w.type==="directory").sort((w,b)=>w.name.localeCompare(b.name)),k.dirPath!=null&&(l.value=k.dirPath)}}}var jg=F(()=>{});function Ug(e,{normalizePath:t,getEffectiveWorkDir:s,editorContainer:n,createEditor:r,destroyEditor:i,clearFindMarkers:o,saveCurrentUndoHistory:a,saveAllUndoHistory:l,cleanupUndoHistory:c,deleteConversationHistory:d,debugStatus:u,mdPreviewMode:p,renderOfficeLocal:f,performFind:g,findBarVisible:h,findQuery:m,t:y}){let v=Vue.reactive({}),k=Vue.ref([]),w=Vue.ref(-1),b=Vue.ref(!1),C=Vue.ref(!1),S=Vue.computed(()=>w.value>=0&&w.value<k.value.length?k.value[w.value]:null),M=null,N=()=>{M&&clearTimeout(M),M=setTimeout(()=>{e.sendWsMessage({type:"update_file_tabs",openFiles:k.value.map(D=>({path:D.path})),activeIndex:w.value})},500)},q=D=>{D&&(l(D),k.value.length>0?v[D]={files:k.value.map(E=>({path:E.path,name:E.name,content:E.content,originalContent:E.originalContent,isDirty:E.isDirty,fileType:E.fileType,agentId:E.agentId,conversationId:E.conversationId,workDir:E.workDir})),activeIndex:w.value}:delete v[D],N())},L=D=>{if(i(),!D||!v[D]){k.value=[],w.value=-1;return}let E=v[D];k.value=E.files.map(Y=>({...Y,isDirty:Y.isDirty||!1,originalContent:Y.originalContent||Y.content,cmInstance:null,fileType:Y.fileType||Rn(Y.name||""),blobUrl:null,previewUrl:null,previewLoading:!1,localPreviewReady:!1,previewError:null})),w.value=E.activeIndex,Vue.nextTick(()=>{let Y=S.value;Y&&(!Y.fileType||Y.fileType==="text")&&n.value&&r(Y)})};function V(D,E,Y={}){let Q=t(D),re=Y.agentId||e.currentAgent||null,fe=Y.conversationId||e.currentConversation||"_explorer",me=Y.workDir||s(),le=k.value.findIndex(ce=>ce.path===Q&&(!ce.agentId||ce.agentId===re)&&(!ce.conversationId||ce.conversationId===fe));if(le>=0){w.value!==le&&(o(),a(),w.value=le,Vue.nextTick(()=>{let ce=k.value[le];ce&&ce.content!=null&&(!ce.fileType||ce.fileType==="text")&&r(ce)})),q(e.currentConversation);return}a();let W=E||Q.split(/[/\\]/).pop(),ne=Rn(W);k.value.push({path:Q,name:W,agentId:re,conversationId:fe,workDir:me,content:null,originalContent:null,isDirty:!1,cmInstance:null,fileType:ne,blobUrl:null,previewUrl:null,previewLoading:ne!=="text",localPreviewReady:!1,previewError:null}),w.value=k.value.length-1,b.value=!0,ne==="text"&&i(),q(e.currentConversation),u.value=`Loading: ${D}`;let oe=Y.requestId||`file-${Date.now()}-${Math.random().toString(36).slice(2)}`,U=k.value[w.value];U&&(U.requestId=oe),e.sendWsMessage({type:"read_file",conversationId:fe,agentId:re,requestId:oe,filePath:D,workDir:me,_clientId:e.clientId})}let $=D=>{D!==w.value&&(o(),a(),w.value=D,q(e.currentConversation),Vue.nextTick(()=>{let E=k.value[D];E&&(!E.fileType||E.fileType==="text"?Jt(E.name)?p.value=!0:E.content!=null&&n.value&&(r(E),h.value&&m.value&&Vue.nextTick(()=>g())):E.fileType==="office"&&E.localPreviewReady&&Vue.nextTick(()=>f(E)))}))},T=async D=>{let E=k.value[D];if(E?.isDirty&&!await Ee(y("files.unsavedConfirm",{name:E.name}),{destructive:!0}))return;c(e.currentConversation,E.path),E.blobUrl&&URL.revokeObjectURL(E.blobUrl);let Y=D===w.value;k.value.splice(D,1),k.value.length===0?(w.value=-1,i()):w.value>=k.value.length?w.value=k.value.length-1:w.value>D?w.value--:Y&&w.value>=k.value.length&&(w.value=k.value.length-1),q(e.currentConversation),k.value.length>0&&Y&&Vue.nextTick(()=>{let Q=k.value[w.value];Q&&(!Q.fileType||Q.fileType==="text")&&Q.content!=null&&n.value&&r(Q)})};function I(){let D=S.value;if(!D||!D.isDirty||D.pendingSaveRequestId)return;C.value=!0;let E=`file-save-${Date.now()}-${Math.random().toString(36).slice(2)}`;D.pendingSaveRequestId=E,D.pendingSaveContent=D.content,e.sendWsMessage({type:"write_file",conversationId:D.conversationId||e.currentConversation||"_explorer",agentId:D.agentId||e.currentAgent,requestId:E,filePath:D.path,content:D.content,workDir:D.workDir||s(),_clientId:e.clientId})}return{fileTabsMap:v,openFiles:k,activeFileIndex:w,activeFile:S,fileLoading:b,fileSaving:C,saveTabsState:q,restoreTabsState:L,openFileInTab:V,switchToTab:$,closeFileTab:T,saveFile:I,handleConversationDeleted:D=>{let{conversationId:E}=D.detail;E&&(delete v[E],d(E))}}}var Kg=F(()=>{ot();Fr()});function zg({store:e,normalizePath:t,getEffectiveWorkDir:s,openFiles:n,activeFileIndex:r,activeFile:i,fileLoading:o,fileSaving:a,saveTabsState:l,createEditor:c,openFileInTab:d,tree:u,setTreeVisible:p,fp:f,qo:g,ops:h,mdPreviewMode:m,renderOfficeLocal:y,editorContainer:v,debugStatus:k,routeKey:w="",workspaceGeneration:b=""}){let C=new Map,S=(q,L)=>{if(!q||!Number.isFinite(L)||L<=0)return;let V=Math.max(0,Math.floor(L)-1),$=()=>{let T=q.cmInstance;return T?(T.setCursor({line:V,ch:0}),T.scrollIntoView({line:V,ch:0},80),T.focus(),!0):!1};Vue.nextTick(()=>{$()||setTimeout($,180)})};return{handleWorkbenchMessage:q=>{let L=q.detail;if(!L||!Tn(L,w,b))return;let V=Ot(L,w);switch(L.type){case"directory_listing":{if(V==="files-folder-picker"){f.handleFolderPickerListing(L);return}if(w&&V!=="main")return;u.handleDirectoryListing(L);break}case"file_content":{let $=t(L.requestedFilePath||L.filePath),T=n.value.find(R=>R.path===$&&(!R.agentId||!L.agentId||R.agentId===L.agentId)&&(!R.conversationId||!L.conversationId||R.conversationId===L.conversationId));if(!T||T.requestId&&L.requestId&&L.requestId!==T.requestId)return;if(o.value=!1,L.error){k.value=`Error: ${L.error}`,h.clearPendingDownload(),T.previewLoading=!1,T.previewError=L.error;return}if(h.getPendingDownload()&&t(h.getPendingDownload())===$){h.clearPendingDownload();try{if(L.binary){let R=`${location.protocol}//${location.host}/api/preview/${L.fileId}?token=${L.previewToken}`,D=document.createElement("a");D.href=R,D.download=$.split("/").pop()||"download",document.body.appendChild(D),D.click(),document.body.removeChild(D)}else{let R=new Blob([L.content||""],{type:"application/octet-stream"}),D=URL.createObjectURL(R),E=document.createElement("a");E.href=D,E.download=$.split("/").pop()||"download",document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(D)}}catch{}return}let I=n.value.indexOf(T);if(I>=0){let R=T;if(L.binary){R.previewLoading=!1;let D=`${location.protocol}//${location.host}/api/preview/${L.fileId}?token=${L.previewToken}`,E=R.fileType||Rn(R.name);R.fileType=E,E==="pdf"||E==="image"?fetch(D).then(Y=>Y.blob()).then(Y=>{R.blobUrl=URL.createObjectURL(Y)}).catch(Y=>{R.previewError=Y.message}):E==="office"&&((localStorage.getItem("officePreviewMode")||"local")==="online"?R.previewUrl="https://view.officeapps.live.com/op/embed.aspx?src="+encodeURIComponent(D):fetch(D).then(Q=>Q.arrayBuffer()).then(Q=>{R._arrayBuffer=Q,R.localPreviewReady=!0,I===r.value&&Vue.nextTick(()=>y(R))}).catch(Q=>{R.previewError=Q.message})),l(e.currentConversation);return}if(R.content=L.content||"",R.originalContent=L.content||"",R.isDirty=!1,l(e.currentConversation),I===r.value){Jt(R.name)&&m.value||Vue.nextTick(()=>{setTimeout(()=>c(R),100)});let D=C.get($);C.delete($),S(R,D)}}break}case"file_saved":{let $=t(L.requestedFilePath||L.filePath),T=n.value.find(R=>R.path===$&&(!R.agentId||!L.agentId||R.agentId===L.agentId)&&(!R.conversationId||!L.conversationId||R.conversationId===L.conversationId));if(!T?.pendingSaveRequestId||L.requestId&&L.requestId!==T.pendingSaveRequestId)return;a.value=!1;let I=T.pendingSaveContent;if(delete T.pendingSaveRequestId,delete T.pendingSaveContent,L.error)return;T.originalContent=I??T.content,T.isDirty=T.content!==T.originalContent,l(T.conversationId||e.currentConversation);break}case"file_search_result":{g.handleFileSearchResult(L);break}case"file_op_result":{h.handleFileOpResult(L,u.loadTreeDirectory,u.treeRootPath.value);break}case"file_tabs_restored":{if(L.openFiles?.length>0&&n.value.length===0){let $=L.activeIndex||0,T=L.openFiles.length;for(let I of L.openFiles){let R=t(I.path),D=R.split("/").pop(),E=Rn(D);n.value.push({path:R,name:D,content:null,originalContent:null,isDirty:!1,cmInstance:null,fileType:E,blobUrl:null,previewUrl:null,previewLoading:E!=="text",localPreviewReady:!1,previewError:null}),e.sendWsMessage({type:"read_file",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,filePath:I.path})}r.value=$>=0&&$<T?$:0}break}}},handleOpenFile:q=>{let{filePath:L,agentId:V=e.currentAgent,conversationId:$=e.currentConversation,workDir:T=s(),workbenchRouteKey:I=w,hideTree:R=!1,line:D=null}=q.detail||{},E=t(L);!E||!V||!$||w&&I!==w||(R&&typeof p=="function"&&p(!1),Number.isFinite(D)&&D>0&&C.set(E,D),d(E,E.split("/").pop(),{agentId:V,conversationId:$,workDir:T}),S(i.value,D))}}}var Yg=F(()=>{Fr();Mn()});var Gg,Qg=F(()=>{nc();Eg();$g();Og();Fr();qg();Ng();jg();Kg();Yg();Mn();Gg={name:"FilesTab",props:{treeInitiallyVisible:{type:Boolean,default:!0},routeKey:{type:String,required:!0},runtimeProvider:{type:String,required:!0},agentId:{type:String,required:!0},sessionId:{type:String,required:!0},conversationId:{type:String,required:!0},workDir:{type:String,default:""},workspaceGeneration:{type:String,required:!0}},template:`
|
|
2260
|
+
`,setup(e){let t=xn(Pinia.useChatStore(),e),s=Vue.inject("t"),n=_=>_.split(/[/\\]/).pop()||_,r=_=>{let P=_.split(/[/\\]/);return P.pop(),P.join("/")},i=_=>wo(n(_)),o=Vue.ref(null),a=Vue.reactive({staged:!1,modified:!1,untracked:!1}),l=_=>{a[_]=!a[_]},c=Vue.ref(!1),d=Vue.ref(""),u=Vue.ref(null),p=Vue.ref([]),f=Vue.computed(()=>t.effectiveWorkDir||""),g=Vue.ref(""),h=Vue.computed(()=>g.value.trim()||f.value),m=Vue.ref(null),y=Vue.ref(!1),v=Vue.ref(!1),k=Vue.ref(""),w=Vue.ref(null),b=Vue.ref([]),C=Vue.ref(null),S=Vue.ref(!0),M=Vue.ref(!1),N=Vue.ref(""),q=Vue.ref(null),L=Vue.ref(0),V=Vue.ref(0),$=_=>_==null||_===""?"":Sg(_,m.value||""),T=Vue.ref(parseInt(localStorage.getItem("gitDiffFontSize"))||12),I=_=>{T.value=Math.max(8,Math.min(24,_)),localStorage.setItem("gitDiffFontSize",T.value.toString())},R=()=>I(T.value+1),D=()=>I(T.value-1),E=_=>{_.deltaY<0?R():_.deltaY>0&&D()},Y=Vue.computed(()=>{let _=b.value;if(!_||_.length===0)return[];let P=_.length,j=[],K=0;for(;K<P;){let B=_[K];if(B.type==="addition"||B.type==="deletion"||B.type==="modification"){let G=B.type==="modification"?"modification":B.type,ie=K;for(;K<P&&(_[K].type===G||_[K].type==="modification"&&G!=="modification");)K++;let ke=K-ie;j.push({type:G,top:ie/P*100,height:Math.max(ke/P*100,.5)})}else K++}return j}),Q=_=>{let P=o.value;if(!P)return;let j=_.currentTarget.getBoundingClientRect(),K=(_.clientY-j.top)/j.height;P.scrollTop=K*(P.scrollHeight-P.clientHeight)},re=Vue.computed(()=>p.value.filter(_=>_.indexStatus!==" "&&_.indexStatus!=="?")),fe=Vue.computed(()=>p.value.filter(_=>_.workTreeStatus==="M"||_.workTreeStatus==="D")),me=Vue.computed(()=>p.value.filter(_=>_.indexStatus==="?"&&_.workTreeStatus==="?")),le=xg(t,{effectiveGitWorkDir:h,gitOperating:M,gitOpFeedback:q,commitMessage:N}),W=()=>le.loadGitStatus(c,d),ne=()=>{W()},oe=Mg(t,h),U=_=>ko(_),ce=()=>oe.confirmFolderPicker(g,W),Ae=(_,P)=>{m.value=_.path,y.value=P,v.value=!0,k.value="",w.value=null,b.value=[],C.value=null;let j=_.indexStatus==="?"&&_.workTreeStatus==="?";t.sendWsMessage({type:"git_diff",conversationId:t.currentConversation||"_explorer",agentId:t.currentAgent,workDir:h.value,filePath:_.path,staged:P,untracked:j,fullFile:S.value,_clientId:t.clientId})},Re=()=>{if(S.value=!S.value,m.value){let _=p.value.find(P=>P.path===m.value);_&&Ae(_,y.value)}},de=_=>{let P=_.detail;if(!(!P||!Tn(P,e.routeKey,e.workspaceGeneration)))switch(P.type){case"directory_listing":{Ot(P,e.routeKey)==="git-folder-picker"&&oe.handleDirectoryListing({...P,conversationId:"_git_folder_picker"});break}case"git_status_result":{if(e.routeKey&&Ot(P,e.routeKey)!=="main")return;if(c.value=!1,P.error){d.value=P.error,u.value=null,p.value=[];return}if(d.value="",u.value=P.branch||"HEAD",p.value=P.files||[],L.value=P.ahead||0,V.value=P.behind||0,m.value){let j=p.value.find(K=>K.path===m.value);if(j){let K=j.indexStatus!==" "&&j.indexStatus!=="?";y.value=K}else m.value=null,w.value=null,b.value=[],C.value=null}break}case"git_diff_result":{if(e.routeKey&&Ot(P,e.routeKey)!=="main")return;if(v.value=!1,P.error){k.value=P.error;return}k.value="";let j=Cg(P.diff,P.newFileContent,s);C.value=j.stats,b.value=j.lines,w.value=j.content;break}case"git_op_result":{if(e.routeKey&&Ot(P,e.routeKey)!=="main")return;le.handleGitOpResult(P,W);break}}};Vue.watch(()=>t.currentAgent,()=>{u.value=null,p.value=[],d.value="",m.value=null,w.value=null,t.currentAgent&&Vue.nextTick(()=>W())}),Vue.watch(()=>t.currentConversation,()=>{t.currentAgent&&(m.value=null,w.value=null,b.value=[],C.value=null,Vue.nextTick(()=>W()))});let Z=()=>W();return Vue.onMounted(()=>{window.addEventListener("workbench-message",de),t.currentAgent&&W()}),Vue.onUnmounted(()=>{window.removeEventListener("workbench-message",de),le.cleanup()}),{store:t,getFileName:n,getDirName:r,getFileIconHtml:i,hlLine:$,collapsedGroups:a,toggleGroup:l,gitLoading:c,gitError:d,gitBranch:u,gitFiles:p,gitWorkDir:g,defaultWorkDir:f,changeGitWorkDir:ne,stagedFiles:re,modifiedFiles:fe,untrackedFiles:me,selectedGitFile:m,selectedStaged:y,diffLoading:v,diffError:k,diffContent:w,diffLines:b,diffStats:C,diffFullFile:S,toggleDiffMode:Re,scrollMarkers:Y,diffScrollContainer:o,onMarkerClick:Q,fontSize:T,zoomIn:R,zoomOut:D,onWheel:E,gitOperating:M,commitMessage:N,gitOpFeedback:q,gitAhead:L,gitBehind:V,stageFile:le.stageFile,unstageFile:le.unstageFile,discardFile:le.discardFile,stageAll:le.stageAll,unstageAll:le.unstageAll,commitChanges:le.commitChanges,pushChanges:le.pushChanges,selectGitFile:Ae,refresh:Z,folderPickerOpen:oe.folderPickerOpen,folderPickerPath:oe.folderPickerPath,folderPickerEntries:oe.folderPickerEntries,folderPickerLoading:oe.folderPickerLoading,folderPickerSelected:oe.folderPickerSelected,getFolderIcon:U,openFolderPicker:oe.openFolderPicker,folderPickerNavigateUp:oe.folderPickerNavigateUp,folderPickerSelectItem:oe.folderPickerSelectItem,folderPickerEnter:oe.folderPickerEnter,confirmFolderPicker:ce}}}});function Dg(e){let t=Vue.ref(!1),s=Vue.ref(!1),n=Vue.ref(""),r=Vue.ref(""),i=Vue.ref(!1),o=Vue.ref(!1),a=Vue.ref(0),l=Vue.ref(-1),c=Vue.ref(null),d=Vue.ref(null),u=[],p=[],f=()=>{let q=e.value?.cmInstance;if(!q)return;let V=q.getWrapperElement().querySelector(".cm-find-scrollbar-annotations");V&&V.remove()},g=()=>{let q=e.value?.cmInstance;if(!q||p.length===0)return;f();let L=q.getWrapperElement();if(!L.querySelector(".CodeMirror-vscrollbar"))return;let $=q.lineCount();if($===0)return;let T=document.createElement("div");T.className="cm-find-scrollbar-annotations";for(let I of p){let R=I.from.line/$*100,D=document.createElement("div");D.className="cm-find-scrollbar-tick",D.style.top=R+"%",T.appendChild(D)}L.appendChild(T)},h=()=>{for(let q of u)try{q.clear()}catch{}u=[],p=[],a.value=0,l.value=-1,f()},m=q=>{let L=e.value?.cmInstance;if(!L||!p[q])return;for(let $=0;$<u.length;$++){if(!u[$])continue;let T=u[$].find();T&&(u[$].clear(),u[$]=L.markText(T.from,T.to,{className:"cm-find-highlight"}))}let V=p[q];if(u[q]){let $=u[q].find();$&&(u[q].clear(),u[q]=L.markText($.from,$.to,{className:"cm-find-highlight cm-find-current"}))}setTimeout(()=>{L.scrollIntoView({from:V.from,to:V.to},100)},0)},y=()=>{h();let q=e.value?.cmInstance;if(!q||!n.value)return;let L=n.value;if(L.length<3)return;let V=q.getValue(),$=i.value,T=o.value,I=[];try{if(T){let R=$?"g":"gi",D=new RegExp(L,R),E;for(;(E=D.exec(V))!==null;){if(E[0].length===0){D.lastIndex++;continue}let Y=q.posFromIndex(E.index),Q=q.posFromIndex(E.index+E[0].length);if(I.push({from:Y,to:Q}),I.length>1e4)break}}else{let R=$?L:L.toLowerCase(),D=$?V:V.toLowerCase(),E=0;for(;(E=D.indexOf(R,E))!==-1;){let Y=q.posFromIndex(E),Q=q.posFromIndex(E+L.length);if(I.push({from:Y,to:Q}),E+=L.length,I.length>1e4)break}}}catch{return}p=I,a.value=I.length;for(let R of I)u.push(q.markText(R.from,R.to,{className:"cm-find-highlight"}));if(I.length>0){let R=q.getCursor(),D=0;for(let E=0;E<I.length;E++){if(CodeMirror.cmpPos(I[E].from,R)>=0){D=E;break}E===I.length-1&&(D=0)}l.value=D,m(D)}g()};return{findBarVisible:t,replaceBarVisible:s,findQuery:n,replaceQuery:r,findCaseSensitive:i,findUseRegex:o,findMatchCount:a,findMatchIndex:l,findInputRef:c,replaceInputRef:d,clearFindMarkers:h,performFind:y,onFindInput:()=>{y()},findNext:()=>{if(p.length===0)return;let q=(l.value+1)%p.length;l.value=q,m(q)},findPrev:()=>{if(p.length===0)return;let q=(l.value-1+p.length)%p.length;l.value=q,m(q)},openFindBar:(q=!1)=>{t.value=!0,s.value=q;let L=e.value?.cmInstance;if(L){let V=L.getSelection();V&&(n.value=V)}Vue.nextTick(()=>{c.value?.focus(),c.value?.select(),n.value&&y()})},closeFindBar:()=>{h(),t.value=!1,s.value=!1;let q=e.value?.cmInstance;q&&q.focus()},toggleReplaceBar:()=>{s.value=!s.value,s.value&&Vue.nextTick(()=>d.value?.focus())},replaceOne:()=>{let q=e.value?.cmInstance;if(!q||p.length===0||l.value<0)return;let L=p[l.value];q.replaceRange(r.value,L.from,L.to),y()},replaceAll:()=>{let q=e.value?.cmInstance;!q||p.length===0||(q.operation(()=>{for(let L=p.length-1;L>=0;L--)q.replaceRange(r.value,p[L].from,p[L].to)}),y())}}}var Eg=F(()=>{});function Lg(e,t){let{getEffectiveWorkDir:s,treePath:n}=t,r=Vue.reactive(new Set),i=Vue.ref(-1),o=Vue.ref(!1),a=Vue.ref(null),l=null,c=null,d=Vue.ref(!1),u=Vue.ref(""),p=Vue.ref("file"),f=Vue.ref(null),g=Vue.ref(!1),h=Vue.ref(""),m=Vue.ref(null),y=Vue.reactive({visible:!1,x:0,y:0,entry:null}),v=Vue.ref(!1),k=Vue.ref(""),w=Vue.ref(null),b=null,C=Vue.reactive({dragging:null,dropTarget:null}),S=Vue.ref(!1),M=(B,G)=>{l&&clearTimeout(l),a.value={ok:B,message:G},l=setTimeout(()=>{a.value=null},4e3)},N=()=>{o.value=!0,c&&clearTimeout(c),c=setTimeout(()=>{o.value&&(o.value=!1,M(!1,"Operation timed out"))},15e3)},q=B=>{r.has(B)?r.delete(B):r.add(B)},L=()=>{r.clear(),i.value=-1},V=B=>{p.value=B,u.value="",d.value=!0,Vue.nextTick(()=>f.value?.focus())},$=()=>{let B=u.value.trim();if(!B)return;d.value=!1;let G=n.value||s();if(!G)return;let ie=G.includes("\\")?"\\":"/",ke=G.replace(/[/\\]$/,"")+ie+B;N(),e.sendWsMessage({type:"create_file",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,filePath:ke,isDirectory:p.value==="directory",workDir:s(),_clientId:e.clientId})},T=async(B,G)=>{let ie=B.path.split("/").pop();await De(G("files.deleteConfirm",{name:ie})+(B.type==="directory"?G("files.deleteDirHint"):""),{destructive:!0})&&(N(),e.sendWsMessage({type:"delete_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[B.path],workDir:s(),_clientId:e.clientId}))},I=async B=>{let G=r.size;G!==0&&await De(B("files.deleteSelectedConfirm",{count:G}),{destructive:!0})&&(N(),e.sendWsMessage({type:"delete_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[...r],workDir:s(),_clientId:e.clientId}))},R=()=>{h.value=n.value||s()||"",g.value=!0,Vue.nextTick(()=>m.value?.focus())},D=()=>{let B=h.value.trim();!B||r.size===0||(g.value=!1,N(),e.sendWsMessage({type:"move_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[...r],destination:B,workDir:s(),_clientId:e.clientId}))},E=(B,G)=>{let se=B.clientX,ae=B.clientY;se+180>window.innerWidth&&(se=window.innerWidth-180),ae+240>window.innerHeight&&(ae=window.innerHeight-240),y.entry=G,y.x=se,y.y=ae,y.visible=!0},Y=()=>{y.visible=!1};return{selectedPaths:r,lastClickedIndex:i,fileOperating:o,fileOpFeedback:a,newFileDialogVisible:d,newFileName:u,newFileType:p,newFileInput:f,moveDialogVisible:g,moveDestination:h,moveDestInput:m,contextMenu:y,renameDialogVisible:v,renameNewName:k,renameInput:w,dragState:C,externalDropActive:S,showFileOpFeedback:M,toggleSelection:q,clearSelection:L,showNewFileDialog:V,confirmNewFile:$,deleteSingleFile:T,deleteSelected:I,openMoveDialog:R,confirmMove:D,showContextMenu:E,hideContextMenu:Y,ctxRename:()=>{let B=y.entry;Y(),B&&(k.value=B.name,v.value=!0,Vue.nextTick(()=>{let G=w.value;if(G)if(G.focus(),B.type==="file"){let ie=B.name.lastIndexOf(".");ie>0?G.setSelectionRange(0,ie):G.select()}else G.select()}))},confirmRename:()=>{let B=y.entry,G=k.value.trim();if(!G||!B||G===B.name){v.value=!1;return}v.value=!1;let ie=B.path.replace(/\/$/,"").split("/");ie.pop();let ke=ie.join("/")||"/";N(),e.sendWsMessage({type:"move_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[B.path],destination:ke,newName:G,workDir:s(),_clientId:e.clientId})},ctxCopy:()=>{let B=y.entry;if(Y(),!B)return;let G=B.path.replace(/\/$/,"").split("/");G.pop();let ie=G.join("/")||"/";N(),e.sendWsMessage({type:"copy_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[B.path],destination:ie,workDir:s(),_clientId:e.clientId})},ctxMoveTo:()=>{let B=y.entry;Y(),B&&(r.clear(),r.add(B.path),R())},ctxDelete:B=>{let G=y.entry;Y(),G&&T(G,B)},ctxDownload:()=>{let B=y.entry;Y(),!(!B||B.type!=="file")&&(b=B.path,e.sendWsMessage({type:"read_file",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,filePath:B.path,workDir:s(),_clientId:e.clientId}))},onDragStart:(B,G)=>{C.dragging=G,B.dataTransfer.setData("text/plain",G.path),B.dataTransfer.effectAllowed="move"},onDragOver:(B,G)=>{if(!C.dragging&&B.dataTransfer.types.includes("Files")){G.type==="directory"&&(B.dataTransfer.dropEffect="copy",C.dropTarget=G.path);return}!C.dragging||G.type!=="directory"||G.path!==C.dragging.path&&(G.path.startsWith(C.dragging.path+"/")||(B.dataTransfer.dropEffect="move",C.dropTarget=G.path))},onDragLeave:B=>{let G=B.relatedTarget;G&&B.currentTarget.contains(G)||(C.dropTarget=null)},onDrop:(B,G,ie)=>{if(C.dropTarget=null,!C.dragging&&B.dataTransfer.files.length>0&&G.type==="directory"){ie(B.dataTransfer.files,G.path);return}if(!C.dragging||G.type!=="directory"){C.dragging=null;return}if(G.path===C.dragging.path){C.dragging=null;return}N(),e.sendWsMessage({type:"move_files",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,paths:[C.dragging.path],destination:G.path,workDir:s(),_clientId:e.clientId}),C.dragging=null},onTreeDragOver:B=>{C.dragging||B.dataTransfer.types.includes("Files")&&(B.dataTransfer.dropEffect="copy",S.value=!0)},onTreeDragLeave:B=>{let G=B.relatedTarget;G&&B.currentTarget.contains(G)||(S.value=!1)},onTreeDrop:(B,G,ie)=>{if(S.value=!1,!C.dragging&&B.dataTransfer.files.length>0){let ke=n.value||G||s();ie(B.dataTransfer.files,ke)}},handleExternalFileDrop:async(B,G)=>{if(!G)return;let ie=[],ke=[];for(let se of B)ke.push(new Promise(ae=>{let Se=new FileReader;Se.onload=()=>{let Me=btoa(new Uint8Array(Se.result).reduce((Ve,Ke)=>Ve+String.fromCharCode(Ke),""));ie.push({name:se.name,data:Me}),ae()},Se.onerror=()=>ae(),Se.readAsArrayBuffer(se)}));await Promise.all(ke),ie.length!==0&&(o.value=!0,c&&clearTimeout(c),c=setTimeout(()=>{o.value&&(o.value=!1,M(!1,"Upload timed out"))},3e4),e.sendWsMessage({type:"upload_to_dir",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,files:ie,dirPath:G,workDir:s(),_clientId:e.clientId}))},handleFileOpResult:(B,G,ie)=>{o.value=!1,c&&(clearTimeout(c),c=null),M(B.success,B.success?B.message:B.error||"Operation failed"),B.success&&(ie&&G(ie),(B.operation==="delete"||B.operation==="move")&&(r.clear(),i.value=-1))},getPendingDownload:()=>b,clearPendingDownload:()=>{b=null},cleanup:()=>{l&&clearTimeout(l),c&&clearTimeout(c)}}}var $g=F(()=>{ot()});function Vg(e,{getEffectiveWorkDir:t,normalizePath:s,selectedPaths:n,lastClickedIndex:r,openFileInTab:i,clearSelection:o}){let a=Vue.ref(""),l=Vue.ref(""),c=Vue.reactive({}),d=Vue.ref(!1),u=Vue.ref(null),p=Vue.computed(()=>{if(!l.value)return"EXPLORER";let V=l.value.replace(/[\\/]+$/,"").split(/[\\/]/);return(V[V.length-1]||l.value).toUpperCase()}),f=Vue.computed(()=>l.value?!!c[l.value]?.expanded:!1),g=()=>{if(!l.value)return;let V=c[l.value];V&&(V.expanded=!V.expanded)},h=()=>{for(let V of Object.keys(c))c[V]&&(c[V].expanded=!1)},m=()=>{d.value=!0,Vue.nextTick(()=>u.value?.focus())},y=()=>{d.value=!1,b()},v=()=>{d.value=!1},k=Vue.computed(()=>{let V=[],$=(T,I)=>{let R=c[T];if(!(!R||!R.entries))for(let D of R.entries)V.push({...D,depth:I}),D.type==="directory"&&c[D.path]?.expanded&&$(D.path,I+1)};return l.value&&c[l.value]?.expanded&&$(l.value,0),V}),w=V=>{let $=s(V);c[$]?c[$].loading=!0:c[$]={entries:[],expanded:!0,loaded:!1,loading:!0},e.sendWsMessage({type:"list_directory",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,dirPath:V,workDir:t(),_clientId:e.clientId})},b=()=>{let V=a.value.trim();if(!V)return;let $=s(V);l.value=$,Object.keys(c).forEach(T=>delete c[T]),c[$]={entries:[],expanded:!0,loaded:!1,loading:!0},e.sendWsMessage({type:"list_directory",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,dirPath:V,workDir:t(),_clientId:e.clientId})},C=V=>{let $=s(V),T=c[$];T?T.loaded?T.expanded=!T.expanded:(T.expanded=!0,w(V)):(c[$]={entries:[],expanded:!0,loaded:!1,loading:!1},w(V))},S=(V,$)=>{let T=k.value,I=T.findIndex(R=>R.path===V.path);if($&&($.shiftKey||$.ctrlKey||$.metaKey)){if($.shiftKey&&r.value>=0&&I>=0){let R=Math.min(r.value,I),D=Math.max(r.value,I);!$.ctrlKey&&!$.metaKey&&n.clear();for(let E=R;E<=D;E++)n.add(T[E].path)}else n.has(V.path)?n.delete(V.path):n.add(V.path);r.value=I;return}n.size>0&&(n.clear(),r.value=-1),V.type==="directory"?C(V.path):i(V.path,V.name),r.value=I},M=V=>{let $=s(V.dirPath);if(V.error){c[$]&&(c[$].loading=!1);return}let T=(V.entries||[]).sort((D,E)=>D.type===E.type?D.name.localeCompare(E.name):D.type==="directory"?-1:1),I=$.replace(/\/$/,""),R=T.map(D=>({...D,path:I+"/"+D.name}));c[$]?(c[$].entries=R,c[$].loaded=!0,c[$].loading=!1):c[$]={entries:R,expanded:!0,loaded:!0,loading:!1},$===l.value&&(a.value=V.dirPath)},N=()=>{Object.keys(c).forEach(V=>delete c[V])};return{treePath:a,treeRootPath:l,treeNodes:c,flattenedTree:k,editingTreePath:d,treePathInputRef:u,rootFolderName:p,rootExpanded:f,toggleRootExpand:g,collapseAll:h,startTreePathEdit:m,confirmTreePath:y,cancelTreePathEdit:v,loadTreeDirectory:w,loadRootDirectory:b,toggleDirectory:C,onTreeItemClick:S,handleDirectoryListing:M,clearTreeNodes:N,initFileBrowser:()=>{let V=t();if(V){let $=s(V);a.value=V,l.value=$,N(),w(V)}},refresh:()=>{l.value&&w(l.value)}}}var Og=F(()=>{});function Rn(e){let t=e.lastIndexOf(".");if(t<0)return"text";let s=e.substring(t).toLowerCase();return bw.has(s)?"office":ww.has(s)?"pdf":kw.has(s)?"image":"text"}function Jt(e){let t=e.lastIndexOf(".");return t<0?!1:Sw.has(e.substring(t).toLowerCase())}function Iw(e){let t=e.split(".").pop()?.toLowerCase();return{js:"javascript",mjs:"javascript",jsx:"javascript",ts:{name:"javascript",typescript:!0},tsx:{name:"javascript",typescript:!0},json:{name:"javascript",json:!0},py:"python",html:"htmlmixed",htm:"htmlmixed",vue:"htmlmixed",xml:"xml",svg:"xml",css:"css",scss:"css",less:"css",sh:"shell",bash:"shell",zsh:"shell",c:"text/x-csrc",h:"text/x-csrc",cpp:"text/x-c++src",hpp:"text/x-c++src",cs:"text/x-csharp",java:"text/x-java",md:"markdown",markdown:"markdown"}[t]||"text/plain"}function Fg(e,{activeFile:t,editorContainer:s,fontSize:n,clearFindMarkers:r,openFindBar:i,saveFile:o}){let a=Vue.ref(""),l=Vue.reactive({}),c=()=>{},d=()=>{},u=({openQuickOpen:v,openGoToLine:k})=>{c=v,d=k},p=(v,k=0)=>{if(!s.value){k<20&&setTimeout(()=>p(v,k+1),100);return}if(!v)return;if(s.value.innerHTML="",typeof CodeMirror>"u"){let C=document.createElement("textarea");C.value=v.content||"",C.style.cssText="width:100%;height:100%;border:none;outline:none;resize:none;padding:12px;font-family:monospace;font-size:12px;background:var(--bg-main);color:var(--text-main);white-space:pre;tab-size:4;",C.spellcheck=!1,C.addEventListener("input",()=>{v.content=C.value,v.isDirty=C.value!==v.originalContent}),C.addEventListener("keydown",S=>{(S.ctrlKey||S.metaKey)&&S.key==="s"&&(S.preventDefault(),o())}),s.value.appendChild(C),a.value="";return}let b=document.documentElement.getAttribute("data-theme")==="dark"?"material-darker":"default";try{let C=CodeMirror(s.value,{value:v.content||"",mode:Iw(v.name),theme:b,lineNumbers:!0,tabSize:4,indentWithTabs:!1,lineWrapping:!1,readOnly:!1,extraKeys:{"Ctrl-S":()=>o(),"Cmd-S":()=>o(),"Ctrl-P":()=>c(),"Cmd-P":()=>c(),"Ctrl-G":()=>d(),"Cmd-G":()=>d(),"Ctrl-F":()=>i(!1),"Cmd-F":()=>i(!1),"Ctrl-R":()=>i(!0),"Cmd-R":()=>i(!0),"Ctrl-H":()=>i(!0),"Cmd-H":()=>i(!0)}});C.on("change",()=>{let M=C.getValue();v.content=M,v.isDirty=M!==v.originalContent}),v.cmInstance=C,C.getWrapperElement().style.fontSize=n.value+"px";let S=e.currentConversation;S&&l[S]?.[v.path]&&C.setHistory(l[S][v.path]),Vue.nextTick(()=>{C.refresh(),setTimeout(()=>C.refresh(),200)}),a.value=""}catch(C){a.value=`Editor error: ${C.message}`}};return{debugStatus:a,undoHistoryMap:l,createEditor:p,destroyEditor:()=>{r();let v=t.value;v?.cmInstance&&(v.cmInstance.toTextArea&&v.cmInstance.toTextArea(),v.cmInstance=null),s.value&&(s.value.innerHTML="")},setKeyBindings:u,saveCurrentUndoHistory:()=>{let v=e.currentConversation;if(!v)return;let k=t.value;k?.cmInstance&&(l[v]||(l[v]={}),l[v][k.path]=k.cmInstance.getHistory())},saveAllUndoHistory:v=>{if(!v)return;let k=t.value;k?.cmInstance&&(l[v]||(l[v]={}),l[v][k.path]=k.cmInstance.getHistory())},cleanupUndoHistory:(v,k)=>{v&&l[v]&&delete l[v][k]},deleteConversationHistory:v=>{delete l[v]}}}var bw,ww,kw,Sw,Fr=F(()=>{bw=new Set([".docx",".xlsx",".xls",".pptx",".ppt"]),ww=new Set([".pdf"]),kw=new Set([".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico"]),Sw=new Set([".md",".markdown",".mdx"])});function Hg(e,{editorContainer:t,createEditor:s,t:n}){let r=Vue.ref(!0),i=Vue.ref(null),o=Vue.ref(null),a=Vue.computed(()=>{let f=e.value;return!!(f&&Jt(f.name))}),l=Vue.computed(()=>{let f=e.value;if(!f||!Jt(f.name)||f.content==null)return"";try{if(typeof marked<"u")return marked.parse(f.content)}catch{}return"<pre>"+(f.content||"")+"</pre>"});function c(){ht(i.value)}async function d(){await ht(i.value)}function u(){r.value=!1,Vue.nextTick(()=>{let f=e.value;f&&t.value&&s(f)})}return{mdPreviewMode:r,mdPreviewRef:i,officePreviewContainer:o,isActiveMarkdown:a,mdRenderedHtml:l,initMermaid:c,renderMermaidBlocks:d,switchToMdEdit:u,renderOfficeLocal:f=>{let g=o.value;if(!g||!f._arrayBuffer)return;g.innerHTML="";let h=("."+f.name.split(".").pop()).toLowerCase();if(h===".docx"&&window.docx)window.docx.renderAsync(f._arrayBuffer,g,null,{className:"docx-preview-content",inWrapper:!0,ignoreWidth:!1,ignoreHeight:!0}).catch(m=>{f.previewError=m.message});else if(h===".xlsx"||h===".xls")try{let m=XLSX.read(f._arrayBuffer,{type:"array"}),y=m.SheetNames[0],v=XLSX.utils.sheet_to_html(m.Sheets[y],{editable:!1});g.innerHTML='<div class="xlsx-sheet-tabs">'+m.SheetNames.map((k,w)=>`<button class="xlsx-sheet-tab${w===0?" active":""}" data-idx="${w}">${k}</button>`).join("")+'</div><div class="xlsx-table-wrap">'+v+"</div>",g.querySelectorAll(".xlsx-sheet-tab").forEach(k=>{k.addEventListener("click",()=>{let w=parseInt(k.dataset.idx),b=m.SheetNames[w],C=XLSX.utils.sheet_to_html(m.Sheets[b],{editable:!1});g.querySelector(".xlsx-table-wrap").innerHTML=C,g.querySelectorAll(".xlsx-sheet-tab").forEach(S=>S.classList.remove("active")),k.classList.add("active")})})}catch(m){f.previewError=m.message}else(h===".pptx"||h===".ppt")&&(g.innerHTML='<div class="preview-unsupported">'+(n?n("files.pptxNotSupported"):"PowerPoint preview not supported")+"</div>")}}}var qg=F(()=>{xr();Fr()});function Bg(e,{getEffectiveWorkDir:t,treePath:s,openFileInTab:n,normalizePath:r,treeRootPath:i,treeNodes:o,loadTreeDirectory:a}){let l=Vue.ref(""),c=Vue.ref([]),d=Vue.ref(!1),u=null,p=Vue.ref(!1),f=Vue.ref(""),g=Vue.ref([]),h=Vue.ref(0),m=Vue.ref(!1),y=Vue.ref(null),v=null,k=Vue.ref(!1),w=Vue.ref(""),b=Vue.ref(null),C=re=>{!e.currentAgent||!re.trim()||e.sendWsMessage({type:"file_search",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,query:re.trim(),dirPath:s.value||t()||"",_clientId:e.clientId})},S=()=>{if(u&&clearTimeout(u),!l.value.trim()){c.value=[],d.value=!1;return}d.value=!0,u=setTimeout(()=>{C(l.value)},300)},M=()=>{l.value="",c.value=[],d.value=!1},N=re=>{if(re.type==="directory"){let fe=r(re.fullPath);i.value=fe,s.value=re.fullPath,Object.keys(o).forEach(me=>delete o[me]),a(re.fullPath),M()}else n(re.fullPath,re.name),M()},q=()=>{p.value=!0,f.value="",g.value=[],h.value=0,m.value=!1,Vue.nextTick(()=>y.value?.focus())},L=()=>{p.value=!1,f.value="",g.value=[]},V=()=>{if(v&&clearTimeout(v),!f.value.trim()){g.value=[],m.value=!1;return}m.value=!0,h.value=0,v=setTimeout(()=>{C(f.value)},200)},$=()=>{g.value.length>0&&(h.value=(h.value+1)%g.value.length)},T=()=>{g.value.length>0&&(h.value=(h.value-1+g.value.length)%g.value.length)},I=re=>{re.type!=="directory"&&n(re.fullPath,re.name),L()},R=()=>{let re=g.value[h.value];re&&I(re)},D=()=>{k.value=!0,w.value="",Vue.nextTick(()=>b.value?.focus())},E=()=>{k.value=!1,w.value=""};return{searchQuery:l,searchResults:c,searchLoading:d,onSearchInput:S,clearSearch:M,onSearchResultClick:N,quickOpenVisible:p,quickOpenQuery:f,quickOpenResults:g,quickOpenSelectedIndex:h,quickOpenLoading:m,quickOpenInput:y,openQuickOpen:q,closeQuickOpen:L,onQuickOpenInput:V,quickOpenSelectNext:$,quickOpenSelectPrev:T,quickOpenConfirm:R,quickOpenOpenFile:I,goToLineVisible:k,goToLineValue:w,goToLineInput:b,openGoToLine:D,closeGoToLine:E,goToLineConfirm:re=>{let fe=parseInt(w.value);if(isNaN(fe)||fe<1)return;let me=re.value;if(me?.cmInstance){let le=me.cmInstance,W=Math.min(fe-1,le.lineCount()-1);le.setCursor({line:W,ch:0}),le.scrollIntoView({line:W,ch:0},100),le.focus()}E()},handleFileSearchResult:re=>{let fe=re.results||[];p.value?re.query&&re.query.trim()===f.value.trim()&&(g.value=fe,m.value=!1,h.value=0):re.query&&re.query.trim()===l.value.trim()&&(c.value=fe,d.value=!1)}}}var Ng=F(()=>{});function Wg(e,{getEffectiveWorkDir:t,treePath:s,treeRootPath:n,treeNodes:r,normalizePath:i,loadTreeDirectory:o}){let a=Vue.ref(!1),l=Vue.ref(""),c=Vue.ref([]),d=Vue.ref(!1),u=Vue.ref(""),p=()=>{a.value=!0,u.value="",d.value=!0;let k=s.value||t()||"";l.value=k,c.value=[],e.sendWsMessage({type:"list_directory",conversationId:"_folder_picker",agentId:e.currentAgent,dirPath:k,workDir:t(),_clientId:e.clientId})},f=k=>{d.value=!0,u.value="",e.sendWsMessage({type:"list_directory",conversationId:"_folder_picker",agentId:e.currentAgent,dirPath:k,workDir:t(),_clientId:e.clientId})};return{folderPickerOpen:a,folderPickerPath:l,folderPickerEntries:c,folderPickerLoading:d,folderPickerSelected:u,openFolderPicker:p,folderPickerNavigateUp:()=>{if(!l.value)return;let k=l.value.includes("\\"),w=k?"\\":"/",b=l.value.replace(/[/\\]$/,"").split(/[/\\]/);if(b.pop(),b.length===0)l.value="",f("");else if(k&&b.length===1&&/^[A-Za-z]:$/.test(b[0]))l.value=b[0]+"\\",f(b[0]+"\\");else{let C=b.join(w);l.value=C,f(C)}},folderPickerSelectItem:k=>{u.value=k.name},folderPickerEnter:k=>{let w;if(!l.value)w=k.name+(k.name.endsWith("\\")?"":"\\");else{let b=l.value.includes("\\")||/^[A-Z]:/.test(k.name)?"\\":"/";w=l.value.replace(/[/\\]$/,"")+b+k.name}l.value=w,f(w)},confirmFolderPicker:()=>{let k=l.value;if(!k)return;if(u.value){let b=k.includes("\\")?"\\":"/";k=k.replace(/[/\\]$/,"")+b+u.value}s.value=k,a.value=!1;let w=i(k);n.value=w,Object.keys(r).forEach(b=>delete r[b]),r[w]={entries:[],expanded:!0,loaded:!1,loading:!0},e.sendWsMessage({type:"list_directory",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,dirPath:k,workDir:t(),_clientId:e.clientId})},handleFolderPickerListing:k=>{d.value=!1,c.value=(k.entries||[]).filter(w=>w.type==="directory").sort((w,b)=>w.name.localeCompare(b.name)),k.dirPath!=null&&(l.value=k.dirPath)}}}var jg=F(()=>{});function Ug(e,{normalizePath:t,getEffectiveWorkDir:s,editorContainer:n,createEditor:r,destroyEditor:i,clearFindMarkers:o,saveCurrentUndoHistory:a,saveAllUndoHistory:l,cleanupUndoHistory:c,deleteConversationHistory:d,debugStatus:u,mdPreviewMode:p,renderOfficeLocal:f,performFind:g,findBarVisible:h,findQuery:m,t:y}){let v=Vue.reactive({}),k=Vue.ref([]),w=Vue.ref(-1),b=Vue.ref(!1),C=Vue.ref(!1),S=Vue.computed(()=>w.value>=0&&w.value<k.value.length?k.value[w.value]:null),M=null,N=()=>{M&&clearTimeout(M),M=setTimeout(()=>{e.sendWsMessage({type:"update_file_tabs",openFiles:k.value.map(D=>({path:D.path})),activeIndex:w.value})},500)},q=D=>{D&&(l(D),k.value.length>0?v[D]={files:k.value.map(E=>({path:E.path,name:E.name,content:E.content,originalContent:E.originalContent,isDirty:E.isDirty,fileType:E.fileType,agentId:E.agentId,conversationId:E.conversationId,workDir:E.workDir})),activeIndex:w.value}:delete v[D],N())},L=D=>{if(i(),!D||!v[D]){k.value=[],w.value=-1;return}let E=v[D];k.value=E.files.map(Y=>({...Y,isDirty:Y.isDirty||!1,originalContent:Y.originalContent||Y.content,cmInstance:null,fileType:Y.fileType||Rn(Y.name||""),blobUrl:null,previewUrl:null,previewLoading:!1,localPreviewReady:!1,previewError:null})),w.value=E.activeIndex,Vue.nextTick(()=>{let Y=S.value;Y&&(!Y.fileType||Y.fileType==="text")&&n.value&&r(Y)})};function V(D,E,Y={}){let Q=t(D),re=Y.agentId||e.currentAgent||null,fe=Y.conversationId||e.currentConversation||"_explorer",me=Y.workDir||s(),le=k.value.findIndex(ce=>ce.path===Q&&(!ce.agentId||ce.agentId===re)&&(!ce.conversationId||ce.conversationId===fe));if(le>=0){w.value!==le&&(o(),a(),w.value=le,Vue.nextTick(()=>{let ce=k.value[le];ce&&ce.content!=null&&(!ce.fileType||ce.fileType==="text")&&r(ce)})),q(e.currentConversation);return}a();let W=E||Q.split(/[/\\]/).pop(),ne=Rn(W);k.value.push({path:Q,name:W,agentId:re,conversationId:fe,workDir:me,content:null,originalContent:null,isDirty:!1,cmInstance:null,fileType:ne,blobUrl:null,previewUrl:null,previewLoading:ne!=="text",localPreviewReady:!1,previewError:null}),w.value=k.value.length-1,b.value=!0,ne==="text"&&i(),q(e.currentConversation),u.value=`Loading: ${D}`;let oe=Y.requestId||`file-${Date.now()}-${Math.random().toString(36).slice(2)}`,U=k.value[w.value];U&&(U.requestId=oe),e.sendWsMessage({type:"read_file",conversationId:fe,agentId:re,requestId:oe,filePath:D,workDir:me,_clientId:e.clientId})}let $=D=>{D!==w.value&&(o(),a(),w.value=D,q(e.currentConversation),Vue.nextTick(()=>{let E=k.value[D];E&&(!E.fileType||E.fileType==="text"?Jt(E.name)?p.value=!0:E.content!=null&&n.value&&(r(E),h.value&&m.value&&Vue.nextTick(()=>g())):E.fileType==="office"&&E.localPreviewReady&&Vue.nextTick(()=>f(E)))}))},T=async D=>{let E=k.value[D];if(E?.isDirty&&!await De(y("files.unsavedConfirm",{name:E.name}),{destructive:!0}))return;c(e.currentConversation,E.path),E.blobUrl&&URL.revokeObjectURL(E.blobUrl);let Y=D===w.value;k.value.splice(D,1),k.value.length===0?(w.value=-1,i()):w.value>=k.value.length?w.value=k.value.length-1:w.value>D?w.value--:Y&&w.value>=k.value.length&&(w.value=k.value.length-1),q(e.currentConversation),k.value.length>0&&Y&&Vue.nextTick(()=>{let Q=k.value[w.value];Q&&(!Q.fileType||Q.fileType==="text")&&Q.content!=null&&n.value&&r(Q)})};function I(){let D=S.value;if(!D||!D.isDirty||D.pendingSaveRequestId)return;C.value=!0;let E=`file-save-${Date.now()}-${Math.random().toString(36).slice(2)}`;D.pendingSaveRequestId=E,D.pendingSaveContent=D.content,e.sendWsMessage({type:"write_file",conversationId:D.conversationId||e.currentConversation||"_explorer",agentId:D.agentId||e.currentAgent,requestId:E,filePath:D.path,content:D.content,workDir:D.workDir||s(),_clientId:e.clientId})}return{fileTabsMap:v,openFiles:k,activeFileIndex:w,activeFile:S,fileLoading:b,fileSaving:C,saveTabsState:q,restoreTabsState:L,openFileInTab:V,switchToTab:$,closeFileTab:T,saveFile:I,handleConversationDeleted:D=>{let{conversationId:E}=D.detail;E&&(delete v[E],d(E))}}}var Kg=F(()=>{ot();Fr()});function zg({store:e,normalizePath:t,getEffectiveWorkDir:s,openFiles:n,activeFileIndex:r,activeFile:i,fileLoading:o,fileSaving:a,saveTabsState:l,createEditor:c,openFileInTab:d,tree:u,setTreeVisible:p,fp:f,qo:g,ops:h,mdPreviewMode:m,renderOfficeLocal:y,editorContainer:v,debugStatus:k,routeKey:w="",workspaceGeneration:b=""}){let C=new Map,S=(q,L)=>{if(!q||!Number.isFinite(L)||L<=0)return;let V=Math.max(0,Math.floor(L)-1),$=()=>{let T=q.cmInstance;return T?(T.setCursor({line:V,ch:0}),T.scrollIntoView({line:V,ch:0},80),T.focus(),!0):!1};Vue.nextTick(()=>{$()||setTimeout($,180)})};return{handleWorkbenchMessage:q=>{let L=q.detail;if(!L||!Tn(L,w,b))return;let V=Ot(L,w);switch(L.type){case"directory_listing":{if(V==="files-folder-picker"){f.handleFolderPickerListing(L);return}if(w&&V!=="main")return;u.handleDirectoryListing(L);break}case"file_content":{let $=t(L.requestedFilePath||L.filePath),T=n.value.find(R=>R.path===$&&(!R.agentId||!L.agentId||R.agentId===L.agentId)&&(!R.conversationId||!L.conversationId||R.conversationId===L.conversationId));if(!T||T.requestId&&L.requestId&&L.requestId!==T.requestId)return;if(o.value=!1,L.error){k.value=`Error: ${L.error}`,h.clearPendingDownload(),T.previewLoading=!1,T.previewError=L.error;return}if(h.getPendingDownload()&&t(h.getPendingDownload())===$){h.clearPendingDownload();try{if(L.binary){let R=`${location.protocol}//${location.host}/api/preview/${L.fileId}?token=${L.previewToken}`,D=document.createElement("a");D.href=R,D.download=$.split("/").pop()||"download",document.body.appendChild(D),D.click(),document.body.removeChild(D)}else{let R=new Blob([L.content||""],{type:"application/octet-stream"}),D=URL.createObjectURL(R),E=document.createElement("a");E.href=D,E.download=$.split("/").pop()||"download",document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(D)}}catch{}return}let I=n.value.indexOf(T);if(I>=0){let R=T;if(L.binary){R.previewLoading=!1;let D=`${location.protocol}//${location.host}/api/preview/${L.fileId}?token=${L.previewToken}`,E=R.fileType||Rn(R.name);R.fileType=E,E==="pdf"||E==="image"?fetch(D).then(Y=>Y.blob()).then(Y=>{R.blobUrl=URL.createObjectURL(Y)}).catch(Y=>{R.previewError=Y.message}):E==="office"&&((localStorage.getItem("officePreviewMode")||"local")==="online"?R.previewUrl="https://view.officeapps.live.com/op/embed.aspx?src="+encodeURIComponent(D):fetch(D).then(Q=>Q.arrayBuffer()).then(Q=>{R._arrayBuffer=Q,R.localPreviewReady=!0,I===r.value&&Vue.nextTick(()=>y(R))}).catch(Q=>{R.previewError=Q.message})),l(e.currentConversation);return}if(R.content=L.content||"",R.originalContent=L.content||"",R.isDirty=!1,l(e.currentConversation),I===r.value){Jt(R.name)&&m.value||Vue.nextTick(()=>{setTimeout(()=>c(R),100)});let D=C.get($);C.delete($),S(R,D)}}break}case"file_saved":{let $=t(L.requestedFilePath||L.filePath),T=n.value.find(R=>R.path===$&&(!R.agentId||!L.agentId||R.agentId===L.agentId)&&(!R.conversationId||!L.conversationId||R.conversationId===L.conversationId));if(!T?.pendingSaveRequestId||L.requestId&&L.requestId!==T.pendingSaveRequestId)return;a.value=!1;let I=T.pendingSaveContent;if(delete T.pendingSaveRequestId,delete T.pendingSaveContent,L.error)return;T.originalContent=I??T.content,T.isDirty=T.content!==T.originalContent,l(T.conversationId||e.currentConversation);break}case"file_search_result":{g.handleFileSearchResult(L);break}case"file_op_result":{h.handleFileOpResult(L,u.loadTreeDirectory,u.treeRootPath.value);break}case"file_tabs_restored":{if(L.openFiles?.length>0&&n.value.length===0){let $=L.activeIndex||0,T=L.openFiles.length;for(let I of L.openFiles){let R=t(I.path),D=R.split("/").pop(),E=Rn(D);n.value.push({path:R,name:D,content:null,originalContent:null,isDirty:!1,cmInstance:null,fileType:E,blobUrl:null,previewUrl:null,previewLoading:E!=="text",localPreviewReady:!1,previewError:null}),e.sendWsMessage({type:"read_file",conversationId:e.currentConversation||"_explorer",agentId:e.currentAgent,filePath:I.path})}r.value=$>=0&&$<T?$:0}break}}},handleOpenFile:q=>{let{filePath:L,agentId:V=e.currentAgent,conversationId:$=e.currentConversation,workDir:T=s(),workbenchRouteKey:I=w,hideTree:R=!1,line:D=null}=q.detail||{},E=t(L);!E||!V||!$||w&&I!==w||(R&&typeof p=="function"&&p(!1),Number.isFinite(D)&&D>0&&C.set(E,D),d(E,E.split("/").pop(),{agentId:V,conversationId:$,workDir:T}),S(i.value,D))}}}var Yg=F(()=>{Fr();Mn()});var Gg,Qg=F(()=>{nc();Eg();$g();Og();Fr();qg();Ng();jg();Kg();Yg();Mn();Gg={name:"FilesTab",props:{treeInitiallyVisible:{type:Boolean,default:!0},routeKey:{type:String,required:!0},runtimeProvider:{type:String,required:!0},agentId:{type:String,required:!0},sessionId:{type:String,required:!0},conversationId:{type:String,required:!0},workDir:{type:String,default:""},workspaceGeneration:{type:String,required:!0}},template:`
|
|
2261
2261
|
<div class="files-tab file-two-col" :class="{ 'mobile-editor-view': isMobile && mobileView === 'editor', 'tree-collapsed': !treeVisible }" ref="rootEl">
|
|
2262
2262
|
<div class="file-tree-collapsed-rail" v-if="!treeVisible">
|
|
2263
2263
|
<button
|
|
@@ -3539,7 +3539,7 @@ ${String(e||"").trim()}
|
|
|
3539
3539
|
</div>
|
|
3540
3540
|
</form>
|
|
3541
3541
|
</div>
|
|
3542
|
-
`,data(){return{view:"list",editing:null,busy:!1,idStatus:"idle",idErrorKey:"",formError:"",form:this.blankForm(),detail:null,detailLoading:!1,detailError:""}},computed:{vpStore(){return $t()},vpList(){return this.vpStore.vpList},vpDomainSections(){return Ns(this.vpList)},canSubmit(){return this.busy?!1:this.editing?!0:this.idStatus==="ok"}},methods:{blankForm(){return{vpId:"",displayName:"",displayNameZh:"",description:"",descriptionZh:"",role:"",roleZh:"",traitsRaw:"",modelHint:"",persona:""}},populateFormFrom(e){this.form={vpId:e.vpId,displayName:e.displayName||"",displayNameZh:e.displayNameZh||"",description:e.description||"",descriptionZh:e.descriptionZh||"",role:e.role||"",roleZh:e.roleZh||"",traitsRaw:Array.isArray(e.traits)?e.traits.join(", "):"",modelHint:e.modelHint||"",persona:typeof e.persona=="string"?e.persona:""}},returnToList(e){this.view="list",this.editing=null,this.form=this.blankForm(),this.idStatus="idle",this.idErrorKey="",this.formError=typeof e=="string"?e:"",this.detail=null,this.detailError="",this.detailLoading=!1},startCreate(){this.editing=null,this.form=this.blankForm(),this.idStatus="idle",this.idErrorKey="",this.formError="",this.view="form",this.$nextTick(()=>{let e=this.$refs.vpIdInput;e&&typeof e.focus=="function"&&e.focus()})},async startEdit(e){if(!this.busy&&!(!e||!e.vpId)&&!e.isStock){this.busy=!0,this.formError="";try{let t=await this.chatStore().vpCrudRequest("read",e.vpId);if(!(t&&t.ok&&t.vp)){let n=t&&t.error&&t.error.code||"unknown",r=Dn(n),i=this.$t(r);this.formError=i&&i!==r?i:t&&t.error&&t.error.message||n;return}let s=t.vp;this.editing={vpId:s.vpId},this.populateFormFrom(s),this.idStatus="ok",this.idErrorKey="",this.view="form"}finally{this.busy=!1}}},openInitialEdit(){let e=this.initialEditVpId;if(!e)return;let t=this.vpStore&&this.vpStore.vps&&this.vpStore.vps[e]||(this.vpList||[]).find(s=>s&&s.vpId===e)||{vpId:e};t.isStock||this.startEdit(t)},async startView(e){if(!(this.busy||!e||!e.vpId)){this.busy=!0,this.detailLoading=!0,this.detailError="",this.detail=null,this.view="detail";try{let t=await this.chatStore().vpCrudRequest("read",e.vpId);if(t&&t.ok&&t.vp)this.detail={vpId:t.vp.vpId,displayName:t.vp.displayName||"",displayNameZh:t.vp.displayNameZh||"",description:t.vp.description||"",descriptionZh:t.vp.descriptionZh||"",role:t.vp.role||"",roleZh:t.vp.roleZh||"",traits:Array.isArray(t.vp.traits)?t.vp.traits:[],modelHint:t.vp.modelHint||"",persona:typeof t.vp.persona=="string"?t.vp.persona:"",isStock:!!(t.vp.isStock!=null?t.vp.isStock:e.isStock)};else{let s=t&&t.error&&t.error.code||"unknown",n=Dn(s),r=this.$t(n);this.detailError=r&&r!==n?r:t&&t.error&&t.error.message||s}}catch(t){this.detailError=t&&t.message||this.$t("yeaft.vp.idError.unknown")}finally{this.detailLoading=!1,this.busy=!1}}},editFromDetail(){if(!this.detail||this.detail.isStock)return;let e=this.detail;this.editing={vpId:e.vpId},this.populateFormFrom(e),this.idStatus="ok",this.idErrorKey="",this.formError="",this.view="form"},async confirmDelete(e){if(this.busy||e&&e.isStock)return;let t=e.displayName||e.vpId,s=this.$t("yeaft.vp.crud.deleteConfirm").replace("{name}",t);if(await
|
|
3542
|
+
`,data(){return{view:"list",editing:null,busy:!1,idStatus:"idle",idErrorKey:"",formError:"",form:this.blankForm(),detail:null,detailLoading:!1,detailError:""}},computed:{vpStore(){return $t()},vpList(){return this.vpStore.vpList},vpDomainSections(){return Ns(this.vpList)},canSubmit(){return this.busy?!1:this.editing?!0:this.idStatus==="ok"}},methods:{blankForm(){return{vpId:"",displayName:"",displayNameZh:"",description:"",descriptionZh:"",role:"",roleZh:"",traitsRaw:"",modelHint:"",persona:""}},populateFormFrom(e){this.form={vpId:e.vpId,displayName:e.displayName||"",displayNameZh:e.displayNameZh||"",description:e.description||"",descriptionZh:e.descriptionZh||"",role:e.role||"",roleZh:e.roleZh||"",traitsRaw:Array.isArray(e.traits)?e.traits.join(", "):"",modelHint:e.modelHint||"",persona:typeof e.persona=="string"?e.persona:""}},returnToList(e){this.view="list",this.editing=null,this.form=this.blankForm(),this.idStatus="idle",this.idErrorKey="",this.formError=typeof e=="string"?e:"",this.detail=null,this.detailError="",this.detailLoading=!1},startCreate(){this.editing=null,this.form=this.blankForm(),this.idStatus="idle",this.idErrorKey="",this.formError="",this.view="form",this.$nextTick(()=>{let e=this.$refs.vpIdInput;e&&typeof e.focus=="function"&&e.focus()})},async startEdit(e){if(!this.busy&&!(!e||!e.vpId)&&!e.isStock){this.busy=!0,this.formError="";try{let t=await this.chatStore().vpCrudRequest("read",e.vpId);if(!(t&&t.ok&&t.vp)){let n=t&&t.error&&t.error.code||"unknown",r=Dn(n),i=this.$t(r);this.formError=i&&i!==r?i:t&&t.error&&t.error.message||n;return}let s=t.vp;this.editing={vpId:s.vpId},this.populateFormFrom(s),this.idStatus="ok",this.idErrorKey="",this.view="form"}finally{this.busy=!1}}},openInitialEdit(){let e=this.initialEditVpId;if(!e)return;let t=this.vpStore&&this.vpStore.vps&&this.vpStore.vps[e]||(this.vpList||[]).find(s=>s&&s.vpId===e)||{vpId:e};t.isStock||this.startEdit(t)},async startView(e){if(!(this.busy||!e||!e.vpId)){this.busy=!0,this.detailLoading=!0,this.detailError="",this.detail=null,this.view="detail";try{let t=await this.chatStore().vpCrudRequest("read",e.vpId);if(t&&t.ok&&t.vp)this.detail={vpId:t.vp.vpId,displayName:t.vp.displayName||"",displayNameZh:t.vp.displayNameZh||"",description:t.vp.description||"",descriptionZh:t.vp.descriptionZh||"",role:t.vp.role||"",roleZh:t.vp.roleZh||"",traits:Array.isArray(t.vp.traits)?t.vp.traits:[],modelHint:t.vp.modelHint||"",persona:typeof t.vp.persona=="string"?t.vp.persona:"",isStock:!!(t.vp.isStock!=null?t.vp.isStock:e.isStock)};else{let s=t&&t.error&&t.error.code||"unknown",n=Dn(s),r=this.$t(n);this.detailError=r&&r!==n?r:t&&t.error&&t.error.message||s}}catch(t){this.detailError=t&&t.message||this.$t("yeaft.vp.idError.unknown")}finally{this.detailLoading=!1,this.busy=!1}}},editFromDetail(){if(!this.detail||this.detail.isStock)return;let e=this.detail;this.editing={vpId:e.vpId},this.populateFormFrom(e),this.idStatus="ok",this.idErrorKey="",this.formError="",this.view="form"},async confirmDelete(e){if(this.busy||e&&e.isStock)return;let t=e.displayName||e.vpId,s=this.$t("yeaft.vp.crud.deleteConfirm").replace("{name}",t);if(await De(s,{destructive:!0})){this.busy=!0;try{let n=await this.chatStore().vpCrudRequest("delete",e.vpId);if(!n.ok){let r=n.error&&n.error.code||"unknown",i=Dn(r),o=this.$t(i);this.formError=this.$t("yeaft.vp.crud.deleteFailed").replace("{error}",o&&o!==i?o:n.error&&n.error.message||r)}}finally{this.busy=!1}}},onVpIdInput(){this.idStatus==="error"&&(this.idStatus="idle",this.idErrorKey="")},onVpIdBlur(){if(this.editing)return;let e=nh(this.form.vpId);e.ok?(this.idStatus="ok",this.idErrorKey=""):(this.idStatus="error",this.idErrorKey=Dn(e.reason))},vpLabelFor(e){let t=this.vpStore?.vpLabel;return typeof t=="function"?t(e):e},vpDescriptionFor(e){let t=this.vpStore?.vpDescription;return typeof t=="function"?t(e):""},parseTraits(e){return e?String(e).split(",").map(t=>t.trim()).filter(Boolean):[]},chatStore(){return window.Pinia&&window.Pinia.useChatStore&&window.Pinia.useChatStore()||typeof Pinia<"u"&&Pinia.useChatStore&&Pinia.useChatStore()},async onSubmit(){if(!this.canSubmit)return;this.busy=!0,this.formError="";let e={vpId:this.form.vpId,displayName:this.form.displayName||this.form.vpId,displayNameZh:this.form.displayNameZh,description:this.form.description,descriptionZh:this.form.descriptionZh,role:this.form.role,roleZh:this.form.roleZh,traits:this.parseTraits(this.form.traitsRaw),modelHint:this.form.modelHint||null,persona:this.form.persona},t=this.editing?"update":"create";try{let s=await this.chatStore().vpCrudRequest(t,e);if(s.ok)this.view="list",this.editing=null,this.form=this.blankForm();else{let n=s.error&&s.error.code||"unknown",r=Dn(n),i=this.$t(r);this.formError=this.$t("yeaft.vp.crud.saveFailed").replace("{error}",i&&i!==r?i:s.error&&s.error.message||n),this.editing==null&&rh(n)&&(this.idStatus="error",this.idErrorKey=r)}}finally{this.busy=!1}}},mounted(){this.openInitialEdit()},watch:{initialEditVpId(){this.openInitialEdit()},"vpStore.vps":{deep:!0,handler(e){let t=this.detail?.vpId||this.editing?.vpId;t&&(e&&e[t]||(this.view==="detail"||this.view==="form")&&this.returnToList(this.$t("yeaft.vp.crud.view.removed")))}}}}});var lh,ch=F(()=>{lh={name:"SearchSettingsTab",emits:["message"],template:`
|
|
3543
3543
|
<div class="search-settings-tab">
|
|
3544
3544
|
<div class="settings-section">
|
|
3545
3545
|
<h3 class="settings-section-title">{{ $t('search.settings.backendTitle') }}</h3>
|
|
@@ -3738,7 +3738,7 @@ ${String(e||"").trim()}
|
|
|
3738
3738
|
</div>
|
|
3739
3739
|
</div>
|
|
3740
3740
|
</div>
|
|
3741
|
-
`,setup(e,{emit:t}){let s=Pinia.useChatStore(),n=Vue.getCurrentInstance(),r=k=>n?.proxy?.$t?.(k)??k,i=Vue.computed(()=>s.yeaftMcpServers||[]),o=Vue.computed(()=>s.yeaftMcpRuntime||{connected:!1,toolCount:0,perServer:[]}),a=Vue.computed(()=>!!s.yeaftMcpLoading),l=Vue.computed(()=>{let k=new Map((o.value.perServer||[]).map(w=>[w.name,w]));return i.value.map(w=>{let b=k.get(w.name);return{...w,ready:!!(b&&b.ready),toolCount:b?b.toolCount:0}})}),c=Vue.reactive({name:"",command:"",argsRaw:"",envRaw:""}),d=Vue.ref("");function u(){c.name="",c.command="",c.argsRaw="",c.envRaw="",d.value=""}function p(k){if(!k)return[];let w=[],b=/"([^"]*)"|'([^']*)'|(\S+)/g,C;for(;(C=b.exec(k))!==null;)w.push(C[1]??C[2]??C[3]);return w}function f(k){if(!k)return{};let w={},b=k.split(/\r?\n/);for(let C of b){let S=C.trim();if(!S||S.startsWith("#"))continue;let M=S.indexOf("=");if(M<0)continue;let N=S.slice(0,M).trim(),q=S.slice(M+1);N&&(w[N]=q)}return w}function g(){d.value="";let k=(c.name||"").trim(),w=(c.command||"").trim();if(!k)return d.value=r("settings.mcp.errors.nameRequired"),null;if(!/^[a-z0-9_-]+$/.test(k))return d.value=r("settings.mcp.errors.nameFormat"),null;if(!w)return d.value=r("settings.mcp.errors.commandRequired"),null;let b=[],C={};try{b=p(c.argsRaw)}catch{return d.value=r("settings.mcp.errors.argsParse"),null}try{C=f(c.envRaw)}catch{return d.value=r("settings.mcp.errors.envParse"),null}return{name:k,command:w,args:b,env:C}}async function h(){let k=g();if(!k)return;let w=await s.addYeaftMcpServer(k);if(w?.error){t("message",w.error,!0);return}w?.connectError?t("message",r("settings.mcp.connectFailed")+": "+w.connectError,!0):t("message",r("settings.mcp.addSuccess"),!1),u()}async function m(k){if(!k||!await
|
|
3741
|
+
`,setup(e,{emit:t}){let s=Pinia.useChatStore(),n=Vue.getCurrentInstance(),r=k=>n?.proxy?.$t?.(k)??k,i=Vue.computed(()=>s.yeaftMcpServers||[]),o=Vue.computed(()=>s.yeaftMcpRuntime||{connected:!1,toolCount:0,perServer:[]}),a=Vue.computed(()=>!!s.yeaftMcpLoading),l=Vue.computed(()=>{let k=new Map((o.value.perServer||[]).map(w=>[w.name,w]));return i.value.map(w=>{let b=k.get(w.name);return{...w,ready:!!(b&&b.ready),toolCount:b?b.toolCount:0}})}),c=Vue.reactive({name:"",command:"",argsRaw:"",envRaw:""}),d=Vue.ref("");function u(){c.name="",c.command="",c.argsRaw="",c.envRaw="",d.value=""}function p(k){if(!k)return[];let w=[],b=/"([^"]*)"|'([^']*)'|(\S+)/g,C;for(;(C=b.exec(k))!==null;)w.push(C[1]??C[2]??C[3]);return w}function f(k){if(!k)return{};let w={},b=k.split(/\r?\n/);for(let C of b){let S=C.trim();if(!S||S.startsWith("#"))continue;let M=S.indexOf("=");if(M<0)continue;let N=S.slice(0,M).trim(),q=S.slice(M+1);N&&(w[N]=q)}return w}function g(){d.value="";let k=(c.name||"").trim(),w=(c.command||"").trim();if(!k)return d.value=r("settings.mcp.errors.nameRequired"),null;if(!/^[a-z0-9_-]+$/.test(k))return d.value=r("settings.mcp.errors.nameFormat"),null;if(!w)return d.value=r("settings.mcp.errors.commandRequired"),null;let b=[],C={};try{b=p(c.argsRaw)}catch{return d.value=r("settings.mcp.errors.argsParse"),null}try{C=f(c.envRaw)}catch{return d.value=r("settings.mcp.errors.envParse"),null}return{name:k,command:w,args:b,env:C}}async function h(){let k=g();if(!k)return;let w=await s.addYeaftMcpServer(k);if(w?.error){t("message",w.error,!0);return}w?.connectError?t("message",r("settings.mcp.connectFailed")+": "+w.connectError,!0):t("message",r("settings.mcp.addSuccess"),!1),u()}async function m(k){if(!k||!await De(r("settings.mcp.confirmRemove").replace("{name}",k),{destructive:!0}))return;let w=await s.removeYeaftMcpServer(k);w?.error?t("message",w.error,!0):t("message",r("settings.mcp.removeSuccess"),!1)}async function y(k){let w=await s.reloadYeaftMcpServer(k);w?.error?t("message",w.error,!0):t("message",r("settings.mcp.reloadSuccess"),!1)}async function v(){let k=await s.reloadYeaftMcpServer(null);k?.error?t("message",k.error,!0):t("message",r("settings.mcp.reloadSuccess"),!1)}return Vue.onMounted(()=>{s.loadYeaftMcpServers()}),{servers:i,runtime:o,loading:a,serversWithStatus:l,form:c,formError:d,resetForm:u,addServer:h,removeOne:m,reloadOne:y,reloadAll:v}}}});async function ph(e){try{return await e.json()}catch{throw new Error("SANDBOX_LOAD_FAILED")}}async function fh({headers:e={},fetchImpl:t=globalThis.fetch}={}){let s=await t("/api/sandbox/capability",{headers:e});if(!s.ok)throw new Error("SANDBOX_LOAD_FAILED");let n=await ph(s);if(!n||typeof n!="object")throw new Error("SANDBOX_LOAD_FAILED");if(n.available!==!0)return{capability:n,sandbox:null};let r=await t("/api/sandbox",{headers:e});if(!r.ok)throw new Error("SANDBOX_LOAD_FAILED");let i=await ph(r);return{capability:n,sandbox:i?.sandbox||null}}var gh=F(()=>{});var Io,oc=F(()=>{wt();Il();Rl();_n();sh();ah();ch();uh();gh();ot();Io={name:"SettingsPanel",components:{DashboardTab:th,VpCrudPanel:oh,SearchSettingsTab:lh,McpTab:dh},props:{visible:Boolean,initialTab:{type:String,default:""},initialSubTab:{type:String,default:""},initialEditVpId:{type:String,default:""}},emits:["close"],template:`
|
|
3742
3742
|
<div
|
|
3743
3743
|
class="settings-overlay"
|
|
3744
3744
|
v-if="visible"
|
|
@@ -4240,7 +4240,7 @@ ${String(e||"").trim()}
|
|
|
4240
4240
|
</div>
|
|
4241
4241
|
</div>
|
|
4242
4242
|
</div>
|
|
4243
|
-
`,directives:{"click-outside":{mounted(e,t){e._clickOutside=s=>{e.contains(s.target)||t.value()},document.addEventListener("click",e._clickOutside)},unmounted(e){document.removeEventListener("click",e._clickOutside)}}},data(){let e=Pinia.useChatStore();return{activeTab:"general",yeaftSubTab:"vp",profile:null,agentSecret:null,showSecret:!1,resettingSecret:!1,resetConfirm:!1,currentPassword:"",newPassword:"",confirmPassword:"",changingPassword:!1,deletePassword:"",deleteConfirm:!1,deleteConfirmText:"",deletingAccount:!1,invitations:[],inviteRole:"pro",creatingInvite:!1,message:"",isError:!1,selectedLocale:e.locale,openDropdown:null,officePreviewMode:localStorage.getItem("officePreviewMode")||"local",telemetryDraft:{enabled:!0,retentionDays:3,flushIntervalMs:1e3,maxQueueSize:5e3,rawExchangeMaxBytes:524288,traceTextMaxBytes:262144},telemetrySaving:!1,ssoBoundMessage:"",ssoConflictMessage:"",qrDataUrl:"",sandboxLoading:!1,sandboxSubmitting:!1,sandboxLoadError:!1,sandboxCapability:{available:!1,reasonCode:"SANDBOX_DISABLED",catalog:[]},sandboxSnapshot:null,sandboxAgentName:"",sandboxSizeId:"normal",sandboxIdempotencyKeys:{}}},computed:{authStore(){return $e()},chatStore(){return Pinia.useChatStore()},roleLabel(){return{admin:this.$t("settings.account.roleAdmin"),pro:this.$t("settings.account.rolePro")}[this.profile?.role]||this.$t("settings.account.rolePro")},accountDisplayName(){let e=this.profile;return e?e.displayName&&e.displayName!==e.username?e.displayName:e.username||"-":"-"},visibleTabs(){let e=[{key:"general",label:this.$t("settings.tabs.general")},{key:"account",label:this.$t("settings.tabs.account")},{key:"security",label:this.$t("settings.tabs.security")},{key:"sandbox",label:this.$t("settings.tabs.sandbox")}];return(this.authStore.role==="admin"||this.authStore.role==="pro")&&e.push({key:"yeaft",label:this.$t("settings.tabs.yeaft")}),this.authStore.role==="admin"&&(e.push({key:"invitations",label:this.$t("settings.tabs.invitations")}),e.push({key:"dashboard",label:this.$t("settings.tabs.dashboard")})),e},currentTabLabel(){return this.visibleTabs.find(t=>t.key===this.activeTab)?.label||""},telemetrySettings(){return this.chatStore.telemetrySettings},telemetryEnabled(){return this.telemetryDraft.enabled!==!1},themeOptions(){return[{value:"light",label:this.$t("settings.general.lightTheme")},{value:"dark",label:this.$t("settings.general.darkTheme")}]},yeaftSubTabs(){return[{key:"vp",label:this.$t("settings.yeaft.tabs.vp")},{key:"search",label:this.$t("settings.yeaft.tabs.search")},{key:"mcp",label:this.$t("settings.yeaft.tabs.mcp")}]},languageOptions(){return[{value:"zh-CN",label:"\u4E2D\u6587"},{value:"en",label:"English"}]},officePreviewOptions(){return[{value:"local",label:this.$t("files.localRender")},{value:"online",label:this.$t("files.officeOnline")}]},roleOptions(){return[{value:"pro",label:this.$t("settings.invite.proUser")}]},agentSecretActionLabel(){return this.agentSecret?this.$t("settings.security.resetKey"):this.$t("settings.security.generateKey")},agentName(){return zi(this.profile)},agentInstanceId(){return this.agentName},serverWsUrl(){return yn(location)},agentInstallCommand(){return Ui()},agentServiceCommand(){return Yi({profile:this.profile,agentSecret:this.agentSecret,serverWsUrl:this.serverWsUrl})},agentContainerCommand(){return Xp({profile:this.profile,agentSecret:this.agentSecret,serverWsUrl:this.serverWsUrl})},agentLlmCommand(){return Ki()},ssoProviderRows(){let e=this.authStore,t=new Map((e.linkedIdentities||[]).map(n=>[n.provider,n]));return[{key:"alipay",label:this.$t("login.alipay"),enabled:!!e.ssoProviders.alipay},{key:"microsoft",label:this.$t("login.microsoft"),enabled:!!e.aadEnabled},{key:"github",label:this.$t("login.github"),enabled:!!e.ssoProviders.github},{key:"google",label:this.$t("login.google"),enabled:!!e.ssoProviders.google},{key:"wechat",label:this.$t("login.wechat"),enabled:!!e.ssoProviders.wechat}].filter(n=>n.enabled||t.has(n.key)).map(n=>({...n,linked:t.has(n.key),identity:t.get(n.key)||null}))},sandboxUnavailableText(){let e=this.sandboxCapability.reasonCode||"SANDBOX_CAPACITY_UNAVAILABLE",t={SANDBOX_DISABLED:"disabled",SANDBOX_DOCKER_UNAVAILABLE:"dockerUnavailable",SANDBOX_NOT_ENTITLED:"notEntitled",SANDBOX_CAPACITY_UNAVAILABLE:"capacityUnavailable"};return this.$t("settings.sandbox.unavailable."+(t[e]||"capacityUnavailable"))},qrModalTitle(){let e=this.authStore.qrPanel?.provider;return e==="alipay"?this.$t("login.qr.titleAlipay"):e==="wechat"?this.$t("login.qr.titleWechat"):this.$t("login.qr.title")}},mounted(){if(this.visible)return this.applyInitialEntryPoint(),this.loadTelemetry(),this.loadData()},beforeUnmount(){this.invalidateSandboxLoads(),this.stopSandboxPolling()},watch:{visible(e){e?(this.applyInitialEntryPoint(),this.loadTelemetry(),this.loadData(),this.activeTab==="sandbox"&&this.loadSandbox()):(this.invalidateSandboxLoads(),this.stopSandboxPolling(),this.authStore.qrPanel&&this.cancelQrBind())},activeTab(e){e==="invitations"&&this.authStore.role==="admin"&&this.loadInvitations(),e==="sandbox"?this.loadSandbox():(this.invalidateSandboxLoads(),this.stopSandboxPolling())},"authStore.qrPanel.status"(e){if(e==="bound"){let t=this.authStore.qrPanel?.provider;this.authStore.cancelSsoQr(),this.qrDataUrl="",this.authStore.loadIdentities(),this.ssoBoundMessage=this.$t("settings.account.ssoBoundMsg",{provider:t?this.$t("login."+t):""})}},"authStore.qrPanel.authorizeUrl"(e){e&&this.authStore.qrPanel?.intent==="bind"&&this.renderQrCode()}},methods:{sandboxNeedsPolling(e=this.sandboxSnapshot){return e?.operation?.status==="pending"||e?.operation?.status==="running"},syncSandboxPolling(){if(!this.visible||this.activeTab!=="sandbox"||!this.sandboxNeedsPolling()){this.stopSandboxPolling();return}this._sandboxPollTimer||(this._sandboxPollTimer=setTimeout(async()=>{this._sandboxPollTimer=null,await this.loadSandbox({background:!0})},2e3))},stopSandboxPolling(){this._sandboxPollTimer&&(clearTimeout(this._sandboxPollTimer),this._sandboxPollTimer=null)},invalidateSandboxLoads(){this._sandboxLoadGeneration=(this._sandboxLoadGeneration||0)+1,this.sandboxLoading=!1},async loadSandbox({background:e=!1}={}){let t=(this._sandboxLoadGeneration||0)+1;this._sandboxLoadGeneration=t,e||(this.sandboxLoading=!0),e||(this.sandboxLoadError=!1);try{let s=await fh({headers:this.getHeaders()});if(t!==this._sandboxLoadGeneration)return;this.sandboxCapability=s.capability,this.sandboxSnapshot=s.sandbox}catch{if(t!==this._sandboxLoadGeneration)return;this.sandboxLoadError=!0,this.sandboxCapability={available:!1,reasonCode:"SANDBOX_CAPACITY_UNAVAILABLE",catalog:[]},e&&this.stopSandboxPolling()}finally{if(t!==this._sandboxLoadGeneration)return;e||(this.sandboxLoading=!1),this.syncSandboxPolling()}},sandboxIdempotencyKey(e){return this.sandboxIdempotencyKeys[e]||(this.sandboxIdempotencyKeys[e]=crypto.randomUUID()),this.sandboxIdempotencyKeys[e]},clearSandboxIdempotencyKey(e){delete this.sandboxIdempotencyKeys[e]},async createSandbox(){if(!(!this.sandboxCapability.available||this.sandboxSubmitting)){this.sandboxSubmitting=!0;try{let e=await fetch("/api/sandbox",{method:"POST",headers:{...this.getHeaders(),"Content-Type":"application/json","Idempotency-Key":this.sandboxIdempotencyKey("create")},body:JSON.stringify({})}),t=await e.json();if(!e.ok){this.clearSandboxIdempotencyKey("create");let s=t.code==="SANDBOX_OWNER_INACTIVE"?"SANDBOX_ACTION_FAILED":t.code||"SANDBOX_CREATE_FAILED";throw new Error(s)}this.clearSandboxIdempotencyKey("create"),this.sandboxSnapshot=t.snapshot,this.syncSandboxPolling()}catch(e){this.message=this.$t("settings.sandbox.error."+(e.message||"SANDBOX_CREATE_FAILED")),this.isError=!0}finally{this.sandboxSubmitting=!1}}},async confirmRemoveSandbox(){await Ee(this.$t("settings.sandbox.removeConfirm"),{destructive:!0})&&this.requestSandboxAction("remove")},async requestSandboxAction(e){if(!this.sandboxSubmitting){this.sandboxSubmitting=!0;try{let t=await fetch("/api/sandbox/"+e,{method:"POST",headers:{...this.getHeaders(),"Idempotency-Key":this.sandboxIdempotencyKey(e)}}),s=await t.json();if(!t.ok){this.clearSandboxIdempotencyKey(e);let n=s.code==="SANDBOX_OWNER_INACTIVE"?"SANDBOX_ACTION_FAILED":s.code||"SANDBOX_ACTION_FAILED";throw new Error(n)}this.clearSandboxIdempotencyKey(e),this.sandboxSnapshot=s.snapshot,this.syncSandboxPolling()}catch(t){this.message=this.$t("settings.sandbox.error."+(t.message||"SANDBOX_ACTION_FAILED")),this.isError=!0}finally{this.sandboxSubmitting=!1}}},trackOverlayPointerDown:Ft,trackOverlayPointerUp:Ht,clearOverlayPointerGesture:qt,async loadTelemetry(){let e=await this.chatStore.loadTelemetrySettings();e&&!e.error&&(this.telemetryDraft={...this.telemetryDraft,...e})},async saveTelemetry(){this.telemetrySaving=!0;try{let e=await this.chatStore.updateTelemetrySettings(this.telemetryDraft);e&&!e.error&&(this.telemetryDraft={...this.telemetryDraft,...e})}finally{this.telemetrySaving=!1}},async toggleTelemetry(){this.telemetryDraft={...this.telemetryDraft,enabled:!this.telemetryEnabled},await this.saveTelemetry()},formatBytes(e){let t=Number(e);return!Number.isFinite(t)||t<1024?`${Math.max(0,t||0)} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`},onSettingsOverlayClick(e){es(e)&&this.$emit("close")},onQrOverlayClick(e){es(e)&&this.cancelQrBind()},changeLanguage(){this.chatStore.changeLocale(this.selectedLocale)},selectLanguage(e){this.selectedLocale=e,this.chatStore.changeLocale(e)},toggleDropdown(e){this.openDropdown=this.openDropdown===e?null:e},closeDropdown(e){this.openDropdown===e&&(this.openDropdown=null)},setTheme(e){this.chatStore.theme!==e&&this.chatStore.toggleTheme()},setOfficePreviewMode(e){this.officePreviewMode=e,localStorage.setItem("officePreviewMode",e)},applyInitialEntryPoint(){this.initialTab&&this.visibleTabs.some(e=>e.key===this.initialTab)&&(this.activeTab=this.initialTab),this.initialSubTab&&this.activeTab==="yeaft"&&(this.yeaftSubTab=this.yeaftSubTabs.some(e=>e.key===this.initialSubTab)?this.initialSubTab:"vp"),this.initialEditVpId&&this.activeTab==="yeaft"&&(this.yeaftSubTab="vp")},async loadData(){this.message="",this._consumeSsoQueryFlags();try{let e=this.getHeaders(),[t,s]=await Promise.all([fetch("/api/user/profile",{headers:e}),fetch("/api/user/agent-secret",{headers:e})]);if(t.ok)this.profile=await t.json();else{let n=await t.json().catch(()=>({}));this.showMessage(n.error||this.$t("settings.account.profileLoadFailed"),!0)}if(s.ok){let n=await s.json();this.applyAgentSecretResponse(n)}this.authStore.role==="admin"&&this.activeTab==="invitations"&&await this.loadInvitations();try{await this.authStore.loadIdentities()}catch{}}catch{}},_consumeSsoQueryFlags(){let e=window.location.hash||"",t=e.indexOf("?");if(t<0)return;let s=new URLSearchParams(e.slice(t+1)),n=s.get("ssoBound"),r=s.get("ssoError"),i=s.get("provider");if(n&&(this.ssoBoundMessage=this.$t("settings.account.ssoBoundMsg",{provider:n}),this.activeTab="account"),r==="conflict"&&(this.ssoConflictMessage=this.$t("settings.account.ssoConflictMsg",{provider:i||""}),this.activeTab="account"),n||r)try{history.replaceState(null,"",window.location.pathname+window.location.search)}catch{}},bindSso(e){if(this.ssoBoundMessage="",this.ssoConflictMessage="",e==="alipay"&&Ni()){this.authStore.bindSso(e);return}if(e==="alipay"&&vn()){this.authStore.loginWithAlipayMobile({intent:"bind"});return}if(e==="wechat"&&(vn()||Bi())){this.ssoConflictMessage=this.$t("login.wechat.mobileUnsupported");return}e==="alipay"||e==="wechat"?this.startQrBind(e):this.authStore.bindSso(e)},async startQrBind(e){if(this.qrDataUrl="",!await this.authStore.startSsoQr(e,{intent:"bind"})){this.ssoConflictMessage=this.authStore.error||this.$t("settings.account.bindFailed");return}this.renderQrCode()},cancelQrBind(){this.authStore.cancelSsoQr(),this.qrDataUrl=""},relaunchAlipayMobile(){let e=this.authStore.qrPanel;if(!e||!e.authorizeUrl)return;let t=`alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(e.authorizeUrl)}`;window.location.href=t},renderQrCode(){let e=this.authStore.qrPanel;if(!(!e||!e.authorizeUrl)&&typeof qrcode=="function")try{let t=qrcode(0,"M");t.addData(e.authorizeUrl,"Byte"),t.make(),this.qrDataUrl=t.createDataURL(6,4)}catch{}},async unbindSso(e){this.ssoBoundMessage="",this.ssoConflictMessage="",await this.authStore.unbindIdentity(e)||(this.ssoConflictMessage=this.authStore.identitiesError||this.$t("settings.account.unbindFailed"))},canUnbind(e){let t=this.authStore.linkedIdentities||[];return t.some(n=>n.provider===e)?this.authStore.hasPassword?!0:t.length>1:!1},async loadInvitations(){try{let e=await fetch("/api/invitations",{headers:this.getHeaders()});if(e.ok){let t=await e.json();this.invitations=t.invitations.map(s=>({...s,code:s.id,expiresAt:s.expires_at,usedByUsername:s.used_by_username||null}))}}catch{}},getHeaders(){let e={"Content-Type":"application/json"},t=this.authStore.getActiveToken?.()||this.authStore.token;return t&&(e.Authorization=`Bearer ${t}`),e},applyAgentSecretResponse(e){let t=e?.agentSecret||e?.agent_secret||null;this.agentSecret=t&&String(t).trim()?String(t):null},async copySecret(){this.agentSecret&&await this.copyText(this.agentSecret)},async copyText(e){try{await navigator.clipboard.writeText(e),this.showMessage(this.$t("settings.msg.copiedClipboard"))}catch{this.showMessage(this.$t("settings.msg.copyFailed"),!0)}},async resetSecret(){if(this.agentSecret&&!this.resetConfirm){this.resetConfirm=!0;return}this.resettingSecret=!0;try{let e=await fetch("/api/user/agent-secret/reset",{method:"POST",headers:this.getHeaders()});if(e.ok){let t=await e.json();this.applyAgentSecretResponse(t),this.showSecret=!0,this.showMessage(this.$t("settings.msg.keyReset"))}else{let t=await e.json();this.showMessage(t.error||this.$t("settings.msg.resetFailed"),!0)}}catch(e){this.showMessage(this.$t("settings.msg.resetFailed")+": "+e.message,!0)}finally{this.resettingSecret=!1,this.resetConfirm=!1}},async changePassword(){let e=this.profile&&this.profile.hasPassword===!1;if(!e&&!this.currentPassword){this.showMessage(this.$t("settings.security.enterCurrentPwd"),!0);return}if(!this.newPassword||this.newPassword.length<6){this.showMessage(this.$t("settings.security.newPwdMin"),!0);return}if(this.newPassword!==this.confirmPassword){this.showMessage(this.$t("settings.security.pwdMismatch"),!0);return}this.changingPassword=!0;try{let t={newPassword:this.newPassword};e||(t.currentPassword=this.currentPassword);let s=await fetch("/api/user/profile",{method:"PUT",headers:this.getHeaders(),body:JSON.stringify(t)}),n=await s.json();if(s.ok&&n.success){this.showMessage(e?this.$t("settings.security.pwdSet"):this.$t("settings.security.pwdChanged")),this.currentPassword="",this.newPassword="",this.confirmPassword="";try{let r=await fetch("/api/user/profile",{headers:this.getHeaders()});r.ok&&(this.profile=await r.json())}catch{}}else this.showMessage(n.error||this.$t("settings.msg.changeFailed"),!0)}catch(t){this.showMessage(this.$t("settings.msg.changeFailed")+": "+t.message,!0)}finally{this.changingPassword=!1}},cancelDeleteAccount(){this.deleteConfirm=!1,this.deletePassword="",this.deleteConfirmText=""},async deleteAccount(){if(!this.deleteConfirm){this.deleteConfirm=!0;return}let e=this.profile&&this.profile.hasPassword!==!1;if(e&&!this.deletePassword){this.showMessage(this.$t("settings.security.enterCurrentPwd"),!0);return}if(!e&&this.deleteConfirmText!=="DELETE"){this.showMessage(this.$t("settings.security.deleteConfirmRequired"),!0);return}this.deletingAccount=!0;try{let t=await this.authStore.deleteAccount(e?{currentPassword:this.deletePassword}:{confirm:"DELETE"});if(!t.success){this.showMessage(t.error||this.$t("settings.security.deleteFailed"),!0);return}window.location.reload()}finally{this.deletingAccount=!1}},async createInvitation(){this.creatingInvite=!0;try{let e=await fetch("/api/invitations",{method:"POST",headers:this.getHeaders(),body:JSON.stringify({role:this.inviteRole})});if(e.ok)await this.loadInvitations(),this.showMessage(this.$t("settings.msg.inviteCreated"));else{let t=await e.json();this.showMessage(t.error||this.$t("settings.msg.createFailed"),!0)}}catch(e){this.showMessage(this.$t("settings.msg.createFailed")+": "+e.message,!0)}finally{this.creatingInvite=!1}},async copyInviteCode(e){try{await navigator.clipboard.writeText(e),this.showMessage(this.$t("settings.msg.inviteCopied"))}catch{this.showMessage(this.$t("settings.msg.copyFailed"),!0)}},async deleteInvitation(e){try{let t=await fetch(`/api/invitations/${e}`,{method:"DELETE",headers:this.getHeaders()});if(t.ok)await this.loadInvitations(),this.showMessage(this.$t("settings.msg.inviteDeleted"));else{let s=await t.json();this.showMessage(s.error||this.$t("settings.msg.deleteFailed"),!0)}}catch(t){this.showMessage(this.$t("settings.msg.deleteFailed")+": "+t.message,!0)}},inviteStatusClass(e){return e.used_by?"used":e.expiresAt<Date.now()?"expired":""},inviteStatusText(e){return e.used_by?this.$t("settings.invite.used"):e.expiresAt<Date.now()?this.$t("settings.invite.expired"):this.$t("settings.invite.available")},formatTime(e){return new Date(e).toLocaleString()},async doLogout(){await this.authStore.logout(),window.location.reload()},showMessage(e,t=!1){this.message=e,this.isError=t,setTimeout(()=>{this.message=""},3e3)},onLlmMessage(e,t){this.showMessage(e,t)}}}});var ac,hh=F(()=>{ac={anthropic:["claude-opus-4-8","claude-opus-4.8","claude-sonnet-4-20250514","claude-opus-4-20250514","claude-haiku-3-20250414"],openai:["gpt-5","gpt-4.1","gpt-4.1-mini","o3","o4-mini"],"openai-responses":["gpt-5","gpt-5-mini","gpt-5-nano","gpt-5-pro"]}});function $w(e){if(typeof e!="string"||!e)return null;let t=e.toLowerCase();return t.startsWith("claude")||t.includes("/claude")||t.includes(".claude")?"anthropic":/^(gpt-|o1|o3|o4|chatgpt-|codex-|omni-)/.test(t)?"openai-responses":null}var mh,vh=F(()=>{_n();mh={name:"ProviderPresetPicker",emits:["close","pick"],template:`
|
|
4243
|
+
`,directives:{"click-outside":{mounted(e,t){e._clickOutside=s=>{e.contains(s.target)||t.value()},document.addEventListener("click",e._clickOutside)},unmounted(e){document.removeEventListener("click",e._clickOutside)}}},data(){let e=Pinia.useChatStore();return{activeTab:"general",yeaftSubTab:"vp",profile:null,agentSecret:null,showSecret:!1,resettingSecret:!1,resetConfirm:!1,currentPassword:"",newPassword:"",confirmPassword:"",changingPassword:!1,deletePassword:"",deleteConfirm:!1,deleteConfirmText:"",deletingAccount:!1,invitations:[],inviteRole:"pro",creatingInvite:!1,message:"",isError:!1,selectedLocale:e.locale,openDropdown:null,officePreviewMode:localStorage.getItem("officePreviewMode")||"local",telemetryDraft:{enabled:!0,retentionDays:3,flushIntervalMs:1e3,maxQueueSize:5e3,rawExchangeMaxBytes:524288,traceTextMaxBytes:262144},telemetrySaving:!1,ssoBoundMessage:"",ssoConflictMessage:"",qrDataUrl:"",sandboxLoading:!1,sandboxSubmitting:!1,sandboxLoadError:!1,sandboxCapability:{available:!1,reasonCode:"SANDBOX_DISABLED",catalog:[]},sandboxSnapshot:null,sandboxAgentName:"",sandboxSizeId:"normal",sandboxIdempotencyKeys:{}}},computed:{authStore(){return $e()},chatStore(){return Pinia.useChatStore()},roleLabel(){return{admin:this.$t("settings.account.roleAdmin"),pro:this.$t("settings.account.rolePro")}[this.profile?.role]||this.$t("settings.account.rolePro")},accountDisplayName(){let e=this.profile;return e?e.displayName&&e.displayName!==e.username?e.displayName:e.username||"-":"-"},visibleTabs(){let e=[{key:"general",label:this.$t("settings.tabs.general")},{key:"account",label:this.$t("settings.tabs.account")},{key:"security",label:this.$t("settings.tabs.security")},{key:"sandbox",label:this.$t("settings.tabs.sandbox")}];return(this.authStore.role==="admin"||this.authStore.role==="pro")&&e.push({key:"yeaft",label:this.$t("settings.tabs.yeaft")}),this.authStore.role==="admin"&&(e.push({key:"invitations",label:this.$t("settings.tabs.invitations")}),e.push({key:"dashboard",label:this.$t("settings.tabs.dashboard")})),e},currentTabLabel(){return this.visibleTabs.find(t=>t.key===this.activeTab)?.label||""},telemetrySettings(){return this.chatStore.telemetrySettings},telemetryEnabled(){return this.telemetryDraft.enabled!==!1},themeOptions(){return[{value:"light",label:this.$t("settings.general.lightTheme")},{value:"dark",label:this.$t("settings.general.darkTheme")}]},yeaftSubTabs(){return[{key:"vp",label:this.$t("settings.yeaft.tabs.vp")},{key:"search",label:this.$t("settings.yeaft.tabs.search")},{key:"mcp",label:this.$t("settings.yeaft.tabs.mcp")}]},languageOptions(){return[{value:"zh-CN",label:"\u4E2D\u6587"},{value:"en",label:"English"}]},officePreviewOptions(){return[{value:"local",label:this.$t("files.localRender")},{value:"online",label:this.$t("files.officeOnline")}]},roleOptions(){return[{value:"pro",label:this.$t("settings.invite.proUser")}]},agentSecretActionLabel(){return this.agentSecret?this.$t("settings.security.resetKey"):this.$t("settings.security.generateKey")},agentName(){return zi(this.profile)},agentInstanceId(){return this.agentName},serverWsUrl(){return yn(location)},agentInstallCommand(){return Ui()},agentServiceCommand(){return Yi({profile:this.profile,agentSecret:this.agentSecret,serverWsUrl:this.serverWsUrl})},agentContainerCommand(){return Xp({profile:this.profile,agentSecret:this.agentSecret,serverWsUrl:this.serverWsUrl})},agentLlmCommand(){return Ki()},ssoProviderRows(){let e=this.authStore,t=new Map((e.linkedIdentities||[]).map(n=>[n.provider,n]));return[{key:"alipay",label:this.$t("login.alipay"),enabled:!!e.ssoProviders.alipay},{key:"microsoft",label:this.$t("login.microsoft"),enabled:!!e.aadEnabled},{key:"github",label:this.$t("login.github"),enabled:!!e.ssoProviders.github},{key:"google",label:this.$t("login.google"),enabled:!!e.ssoProviders.google},{key:"wechat",label:this.$t("login.wechat"),enabled:!!e.ssoProviders.wechat}].filter(n=>n.enabled||t.has(n.key)).map(n=>({...n,linked:t.has(n.key),identity:t.get(n.key)||null}))},sandboxUnavailableText(){let e=this.sandboxCapability.reasonCode||"SANDBOX_CAPACITY_UNAVAILABLE",t={SANDBOX_DISABLED:"disabled",SANDBOX_DOCKER_UNAVAILABLE:"dockerUnavailable",SANDBOX_NOT_ENTITLED:"notEntitled",SANDBOX_CAPACITY_UNAVAILABLE:"capacityUnavailable"};return this.$t("settings.sandbox.unavailable."+(t[e]||"capacityUnavailable"))},qrModalTitle(){let e=this.authStore.qrPanel?.provider;return e==="alipay"?this.$t("login.qr.titleAlipay"):e==="wechat"?this.$t("login.qr.titleWechat"):this.$t("login.qr.title")}},mounted(){if(this.visible)return this.applyInitialEntryPoint(),this.loadTelemetry(),this.loadData()},beforeUnmount(){this.invalidateSandboxLoads(),this.stopSandboxPolling()},watch:{visible(e){e?(this.applyInitialEntryPoint(),this.loadTelemetry(),this.loadData(),this.activeTab==="sandbox"&&this.loadSandbox()):(this.invalidateSandboxLoads(),this.stopSandboxPolling(),this.authStore.qrPanel&&this.cancelQrBind())},activeTab(e){e==="invitations"&&this.authStore.role==="admin"&&this.loadInvitations(),e==="sandbox"?this.loadSandbox():(this.invalidateSandboxLoads(),this.stopSandboxPolling())},"authStore.qrPanel.status"(e){if(e==="bound"){let t=this.authStore.qrPanel?.provider;this.authStore.cancelSsoQr(),this.qrDataUrl="",this.authStore.loadIdentities(),this.ssoBoundMessage=this.$t("settings.account.ssoBoundMsg",{provider:t?this.$t("login."+t):""})}},"authStore.qrPanel.authorizeUrl"(e){e&&this.authStore.qrPanel?.intent==="bind"&&this.renderQrCode()}},methods:{sandboxNeedsPolling(e=this.sandboxSnapshot){return e?.operation?.status==="pending"||e?.operation?.status==="running"},syncSandboxPolling(){if(!this.visible||this.activeTab!=="sandbox"||!this.sandboxNeedsPolling()){this.stopSandboxPolling();return}this._sandboxPollTimer||(this._sandboxPollTimer=setTimeout(async()=>{this._sandboxPollTimer=null,await this.loadSandbox({background:!0})},2e3))},stopSandboxPolling(){this._sandboxPollTimer&&(clearTimeout(this._sandboxPollTimer),this._sandboxPollTimer=null)},invalidateSandboxLoads(){this._sandboxLoadGeneration=(this._sandboxLoadGeneration||0)+1,this.sandboxLoading=!1},async loadSandbox({background:e=!1}={}){let t=(this._sandboxLoadGeneration||0)+1;this._sandboxLoadGeneration=t,e||(this.sandboxLoading=!0),e||(this.sandboxLoadError=!1);try{let s=await fh({headers:this.getHeaders()});if(t!==this._sandboxLoadGeneration)return;this.sandboxCapability=s.capability,this.sandboxSnapshot=s.sandbox}catch{if(t!==this._sandboxLoadGeneration)return;this.sandboxLoadError=!0,this.sandboxCapability={available:!1,reasonCode:"SANDBOX_CAPACITY_UNAVAILABLE",catalog:[]},e&&this.stopSandboxPolling()}finally{if(t!==this._sandboxLoadGeneration)return;e||(this.sandboxLoading=!1),this.syncSandboxPolling()}},sandboxIdempotencyKey(e){return this.sandboxIdempotencyKeys[e]||(this.sandboxIdempotencyKeys[e]=crypto.randomUUID()),this.sandboxIdempotencyKeys[e]},clearSandboxIdempotencyKey(e){delete this.sandboxIdempotencyKeys[e]},async createSandbox(){if(!(!this.sandboxCapability.available||this.sandboxSubmitting)){this.sandboxSubmitting=!0;try{let e=await fetch("/api/sandbox",{method:"POST",headers:{...this.getHeaders(),"Content-Type":"application/json","Idempotency-Key":this.sandboxIdempotencyKey("create")},body:JSON.stringify({})}),t=await e.json();if(!e.ok){this.clearSandboxIdempotencyKey("create");let s=t.code==="SANDBOX_OWNER_INACTIVE"?"SANDBOX_ACTION_FAILED":t.code||"SANDBOX_CREATE_FAILED";throw new Error(s)}this.clearSandboxIdempotencyKey("create"),this.sandboxSnapshot=t.snapshot,this.syncSandboxPolling()}catch(e){this.message=this.$t("settings.sandbox.error."+(e.message||"SANDBOX_CREATE_FAILED")),this.isError=!0}finally{this.sandboxSubmitting=!1}}},async confirmRemoveSandbox(){await De(this.$t("settings.sandbox.removeConfirm"),{destructive:!0})&&this.requestSandboxAction("remove")},async requestSandboxAction(e){if(!this.sandboxSubmitting){this.sandboxSubmitting=!0;try{let t=await fetch("/api/sandbox/"+e,{method:"POST",headers:{...this.getHeaders(),"Idempotency-Key":this.sandboxIdempotencyKey(e)}}),s=await t.json();if(!t.ok){this.clearSandboxIdempotencyKey(e);let n=s.code==="SANDBOX_OWNER_INACTIVE"?"SANDBOX_ACTION_FAILED":s.code||"SANDBOX_ACTION_FAILED";throw new Error(n)}this.clearSandboxIdempotencyKey(e),this.sandboxSnapshot=s.snapshot,this.syncSandboxPolling()}catch(t){this.message=this.$t("settings.sandbox.error."+(t.message||"SANDBOX_ACTION_FAILED")),this.isError=!0}finally{this.sandboxSubmitting=!1}}},trackOverlayPointerDown:Ft,trackOverlayPointerUp:Ht,clearOverlayPointerGesture:qt,async loadTelemetry(){let e=await this.chatStore.loadTelemetrySettings();e&&!e.error&&(this.telemetryDraft={...this.telemetryDraft,...e})},async saveTelemetry(){this.telemetrySaving=!0;try{let e=await this.chatStore.updateTelemetrySettings(this.telemetryDraft);e&&!e.error&&(this.telemetryDraft={...this.telemetryDraft,...e})}finally{this.telemetrySaving=!1}},async toggleTelemetry(){this.telemetryDraft={...this.telemetryDraft,enabled:!this.telemetryEnabled},await this.saveTelemetry()},formatBytes(e){let t=Number(e);return!Number.isFinite(t)||t<1024?`${Math.max(0,t||0)} B`:t<1024*1024?`${Math.round(t/1024)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`},onSettingsOverlayClick(e){es(e)&&this.$emit("close")},onQrOverlayClick(e){es(e)&&this.cancelQrBind()},changeLanguage(){this.chatStore.changeLocale(this.selectedLocale)},selectLanguage(e){this.selectedLocale=e,this.chatStore.changeLocale(e)},toggleDropdown(e){this.openDropdown=this.openDropdown===e?null:e},closeDropdown(e){this.openDropdown===e&&(this.openDropdown=null)},setTheme(e){this.chatStore.theme!==e&&this.chatStore.toggleTheme()},setOfficePreviewMode(e){this.officePreviewMode=e,localStorage.setItem("officePreviewMode",e)},applyInitialEntryPoint(){this.initialTab&&this.visibleTabs.some(e=>e.key===this.initialTab)&&(this.activeTab=this.initialTab),this.initialSubTab&&this.activeTab==="yeaft"&&(this.yeaftSubTab=this.yeaftSubTabs.some(e=>e.key===this.initialSubTab)?this.initialSubTab:"vp"),this.initialEditVpId&&this.activeTab==="yeaft"&&(this.yeaftSubTab="vp")},async loadData(){this.message="",this._consumeSsoQueryFlags();try{let e=this.getHeaders(),[t,s]=await Promise.all([fetch("/api/user/profile",{headers:e}),fetch("/api/user/agent-secret",{headers:e})]);if(t.ok)this.profile=await t.json();else{let n=await t.json().catch(()=>({}));this.showMessage(n.error||this.$t("settings.account.profileLoadFailed"),!0)}if(s.ok){let n=await s.json();this.applyAgentSecretResponse(n)}this.authStore.role==="admin"&&this.activeTab==="invitations"&&await this.loadInvitations();try{await this.authStore.loadIdentities()}catch{}}catch{}},_consumeSsoQueryFlags(){let e=window.location.hash||"",t=e.indexOf("?");if(t<0)return;let s=new URLSearchParams(e.slice(t+1)),n=s.get("ssoBound"),r=s.get("ssoError"),i=s.get("provider");if(n&&(this.ssoBoundMessage=this.$t("settings.account.ssoBoundMsg",{provider:n}),this.activeTab="account"),r==="conflict"&&(this.ssoConflictMessage=this.$t("settings.account.ssoConflictMsg",{provider:i||""}),this.activeTab="account"),n||r)try{history.replaceState(null,"",window.location.pathname+window.location.search)}catch{}},bindSso(e){if(this.ssoBoundMessage="",this.ssoConflictMessage="",e==="alipay"&&Ni()){this.authStore.bindSso(e);return}if(e==="alipay"&&vn()){this.authStore.loginWithAlipayMobile({intent:"bind"});return}if(e==="wechat"&&(vn()||Bi())){this.ssoConflictMessage=this.$t("login.wechat.mobileUnsupported");return}e==="alipay"||e==="wechat"?this.startQrBind(e):this.authStore.bindSso(e)},async startQrBind(e){if(this.qrDataUrl="",!await this.authStore.startSsoQr(e,{intent:"bind"})){this.ssoConflictMessage=this.authStore.error||this.$t("settings.account.bindFailed");return}this.renderQrCode()},cancelQrBind(){this.authStore.cancelSsoQr(),this.qrDataUrl=""},relaunchAlipayMobile(){let e=this.authStore.qrPanel;if(!e||!e.authorizeUrl)return;let t=`alipays://platformapi/startapp?appId=20000067&url=${encodeURIComponent(e.authorizeUrl)}`;window.location.href=t},renderQrCode(){let e=this.authStore.qrPanel;if(!(!e||!e.authorizeUrl)&&typeof qrcode=="function")try{let t=qrcode(0,"M");t.addData(e.authorizeUrl,"Byte"),t.make(),this.qrDataUrl=t.createDataURL(6,4)}catch{}},async unbindSso(e){this.ssoBoundMessage="",this.ssoConflictMessage="",await this.authStore.unbindIdentity(e)||(this.ssoConflictMessage=this.authStore.identitiesError||this.$t("settings.account.unbindFailed"))},canUnbind(e){let t=this.authStore.linkedIdentities||[];return t.some(n=>n.provider===e)?this.authStore.hasPassword?!0:t.length>1:!1},async loadInvitations(){try{let e=await fetch("/api/invitations",{headers:this.getHeaders()});if(e.ok){let t=await e.json();this.invitations=t.invitations.map(s=>({...s,code:s.id,expiresAt:s.expires_at,usedByUsername:s.used_by_username||null}))}}catch{}},getHeaders(){let e={"Content-Type":"application/json"},t=this.authStore.getActiveToken?.()||this.authStore.token;return t&&(e.Authorization=`Bearer ${t}`),e},applyAgentSecretResponse(e){let t=e?.agentSecret||e?.agent_secret||null;this.agentSecret=t&&String(t).trim()?String(t):null},async copySecret(){this.agentSecret&&await this.copyText(this.agentSecret)},async copyText(e){try{await navigator.clipboard.writeText(e),this.showMessage(this.$t("settings.msg.copiedClipboard"))}catch{this.showMessage(this.$t("settings.msg.copyFailed"),!0)}},async resetSecret(){if(this.agentSecret&&!this.resetConfirm){this.resetConfirm=!0;return}this.resettingSecret=!0;try{let e=await fetch("/api/user/agent-secret/reset",{method:"POST",headers:this.getHeaders()});if(e.ok){let t=await e.json();this.applyAgentSecretResponse(t),this.showSecret=!0,this.showMessage(this.$t("settings.msg.keyReset"))}else{let t=await e.json();this.showMessage(t.error||this.$t("settings.msg.resetFailed"),!0)}}catch(e){this.showMessage(this.$t("settings.msg.resetFailed")+": "+e.message,!0)}finally{this.resettingSecret=!1,this.resetConfirm=!1}},async changePassword(){let e=this.profile&&this.profile.hasPassword===!1;if(!e&&!this.currentPassword){this.showMessage(this.$t("settings.security.enterCurrentPwd"),!0);return}if(!this.newPassword||this.newPassword.length<6){this.showMessage(this.$t("settings.security.newPwdMin"),!0);return}if(this.newPassword!==this.confirmPassword){this.showMessage(this.$t("settings.security.pwdMismatch"),!0);return}this.changingPassword=!0;try{let t={newPassword:this.newPassword};e||(t.currentPassword=this.currentPassword);let s=await fetch("/api/user/profile",{method:"PUT",headers:this.getHeaders(),body:JSON.stringify(t)}),n=await s.json();if(s.ok&&n.success){this.showMessage(e?this.$t("settings.security.pwdSet"):this.$t("settings.security.pwdChanged")),this.currentPassword="",this.newPassword="",this.confirmPassword="";try{let r=await fetch("/api/user/profile",{headers:this.getHeaders()});r.ok&&(this.profile=await r.json())}catch{}}else this.showMessage(n.error||this.$t("settings.msg.changeFailed"),!0)}catch(t){this.showMessage(this.$t("settings.msg.changeFailed")+": "+t.message,!0)}finally{this.changingPassword=!1}},cancelDeleteAccount(){this.deleteConfirm=!1,this.deletePassword="",this.deleteConfirmText=""},async deleteAccount(){if(!this.deleteConfirm){this.deleteConfirm=!0;return}let e=this.profile&&this.profile.hasPassword!==!1;if(e&&!this.deletePassword){this.showMessage(this.$t("settings.security.enterCurrentPwd"),!0);return}if(!e&&this.deleteConfirmText!=="DELETE"){this.showMessage(this.$t("settings.security.deleteConfirmRequired"),!0);return}this.deletingAccount=!0;try{let t=await this.authStore.deleteAccount(e?{currentPassword:this.deletePassword}:{confirm:"DELETE"});if(!t.success){this.showMessage(t.error||this.$t("settings.security.deleteFailed"),!0);return}window.location.reload()}finally{this.deletingAccount=!1}},async createInvitation(){this.creatingInvite=!0;try{let e=await fetch("/api/invitations",{method:"POST",headers:this.getHeaders(),body:JSON.stringify({role:this.inviteRole})});if(e.ok)await this.loadInvitations(),this.showMessage(this.$t("settings.msg.inviteCreated"));else{let t=await e.json();this.showMessage(t.error||this.$t("settings.msg.createFailed"),!0)}}catch(e){this.showMessage(this.$t("settings.msg.createFailed")+": "+e.message,!0)}finally{this.creatingInvite=!1}},async copyInviteCode(e){try{await navigator.clipboard.writeText(e),this.showMessage(this.$t("settings.msg.inviteCopied"))}catch{this.showMessage(this.$t("settings.msg.copyFailed"),!0)}},async deleteInvitation(e){try{let t=await fetch(`/api/invitations/${e}`,{method:"DELETE",headers:this.getHeaders()});if(t.ok)await this.loadInvitations(),this.showMessage(this.$t("settings.msg.inviteDeleted"));else{let s=await t.json();this.showMessage(s.error||this.$t("settings.msg.deleteFailed"),!0)}}catch(t){this.showMessage(this.$t("settings.msg.deleteFailed")+": "+t.message,!0)}},inviteStatusClass(e){return e.used_by?"used":e.expiresAt<Date.now()?"expired":""},inviteStatusText(e){return e.used_by?this.$t("settings.invite.used"):e.expiresAt<Date.now()?this.$t("settings.invite.expired"):this.$t("settings.invite.available")},formatTime(e){return new Date(e).toLocaleString()},async doLogout(){await this.authStore.logout(),window.location.reload()},showMessage(e,t=!1){this.message=e,this.isError=t,setTimeout(()=>{this.message=""},3e3)},onLlmMessage(e,t){this.showMessage(e,t)}}}});var ac,hh=F(()=>{ac={anthropic:["claude-opus-4-8","claude-opus-4.8","claude-sonnet-4-20250514","claude-opus-4-20250514","claude-haiku-3-20250414"],openai:["gpt-5","gpt-4.1","gpt-4.1-mini","o3","o4-mini"],"openai-responses":["gpt-5","gpt-5-mini","gpt-5-nano","gpt-5-pro"]}});function $w(e){if(typeof e!="string"||!e)return null;let t=e.toLowerCase();return t.startsWith("claude")||t.includes("/claude")||t.includes(".claude")?"anthropic":/^(gpt-|o1|o3|o4|chatgpt-|codex-|omni-)/.test(t)?"openai-responses":null}var mh,vh=F(()=>{_n();mh={name:"ProviderPresetPicker",emits:["close","pick"],template:`
|
|
4244
4244
|
<div
|
|
4245
4245
|
class="llm-preset-modal-backdrop"
|
|
4246
4246
|
@pointerdown="trackOverlayPointerDown"
|
|
@@ -4755,7 +4755,7 @@ ${String(e||"").trim()}
|
|
|
4755
4755
|
</div>
|
|
4756
4756
|
</section>
|
|
4757
4757
|
</div>
|
|
4758
|
-
`,data(){return{activeCategory:["operations","trace","llm"].includes(this.initialCategory)?this.initialCategory:"operations",selectedAgentId:null,telemetryDraft:{...Co},telemetryLoading:!1,telemetrySaving:!1,telemetryMessage:"",telemetryError:!1,telemetryGeneration:0,llmMessage:"",llmMessageError:!1}},computed:{store(){return Pinia.useChatStore()},agents(){return this.store.agents||[]},agentOptions(){return this.agents.map(e=>({value:e.id,label:e.name||e.id,badge:e.online?this.$t("agentSettings.online"):this.$t("agentSettings.offline")}))},selectedAgent(){return this.agents.find(e=>e.id===this.selectedAgentId)||null},operations(){return this.store.agentOperations?.[this.selectedAgentId]||{}},restarting(){return this.operations.restart?.pending===!0},upgrading(){return this.operations.upgrade?.pending===!0},dreamState(){return this.store.agentDreamState?.[this.selectedAgentId]||{}},busy(){return this.restarting||this.upgrading}},watch:{agents:{immediate:!0,deep:!0,handler(e){e.some(t=>t.id===this.selectedAgentId)||this.selectAgent(e.find(t=>t.id===this.initialAgentId)?.id||e.find(t=>t.id===this.store.currentAgent)?.id||e[0]?.id||null)}}},methods:{selectAgent(e){this.selectedAgentId!==e&&(this.selectedAgentId=e),this.telemetryGeneration+=1,this.telemetryLoading=!1,this.telemetrySaving=!1,this.telemetryDraft={...Co},this.telemetryMessage="",this.telemetryError=!1,this.llmMessage="",this.llmMessageError=!1,e&&this.agents.find(t=>t.id===e)?.online&&this.loadTelemetry()},onLlmMessage(e,t=!1){this.llmMessage=e,this.llmMessageError=t},async loadTelemetry(){let e=this.selectedAgentId;if(!e)return;let t=++this.telemetryGeneration;this.telemetryLoading=!0,this.telemetryMessage="";try{let s=await this.store.loadTelemetrySettings(e);if(t!==this.telemetryGeneration||e!==this.selectedAgentId)return;if(s?.error)throw new Error(s.error);this.telemetryDraft={...Co,...s}}catch(s){if(t!==this.telemetryGeneration||e!==this.selectedAgentId)return;this.telemetryError=!0,this.telemetryMessage=s?.message||this.$t("agentSettings.telemetry.loadFailed")}finally{t===this.telemetryGeneration&&e===this.selectedAgentId&&(this.telemetryLoading=!1)}},async saveTelemetry(){let e=this.selectedAgentId;if(!e)return;let t=++this.telemetryGeneration;this.telemetrySaving=!0,this.telemetryMessage="";try{let s=await this.store.updateTelemetrySettings(this.telemetryDraft,e);if(t!==this.telemetryGeneration||e!==this.selectedAgentId)return;if(s?.error)throw new Error(s.error);this.telemetryDraft={...Co,...s},this.telemetryError=!1,this.telemetryMessage=this.$t("agentSettings.telemetry.saved")}catch(s){if(t!==this.telemetryGeneration||e!==this.selectedAgentId)return;this.telemetryError=!0,this.telemetryMessage=s?.message||this.$t("agentSettings.telemetry.saveFailed")}finally{t===this.telemetryGeneration&&e===this.selectedAgentId&&(this.telemetrySaving=!1)}},setDreamEnabled(e){this.selectedAgentId&&this.store.setDreamEnabled(this.selectedAgentId,e)},async restartAgent(){let e=this.selectedAgent;!e||!await
|
|
4758
|
+
`,data(){return{activeCategory:["operations","trace","llm"].includes(this.initialCategory)?this.initialCategory:"operations",selectedAgentId:null,telemetryDraft:{...Co},telemetryLoading:!1,telemetrySaving:!1,telemetryMessage:"",telemetryError:!1,telemetryGeneration:0,llmMessage:"",llmMessageError:!1}},computed:{store(){return Pinia.useChatStore()},agents(){return this.store.agents||[]},agentOptions(){return this.agents.map(e=>({value:e.id,label:e.name||e.id,badge:e.online?this.$t("agentSettings.online"):this.$t("agentSettings.offline")}))},selectedAgent(){return this.agents.find(e=>e.id===this.selectedAgentId)||null},operations(){return this.store.agentOperations?.[this.selectedAgentId]||{}},restarting(){return this.operations.restart?.pending===!0},upgrading(){return this.operations.upgrade?.pending===!0},dreamState(){return this.store.agentDreamState?.[this.selectedAgentId]||{}},busy(){return this.restarting||this.upgrading}},watch:{agents:{immediate:!0,deep:!0,handler(e){e.some(t=>t.id===this.selectedAgentId)||this.selectAgent(e.find(t=>t.id===this.initialAgentId)?.id||e.find(t=>t.id===this.store.currentAgent)?.id||e[0]?.id||null)}}},methods:{selectAgent(e){this.selectedAgentId!==e&&(this.selectedAgentId=e),this.telemetryGeneration+=1,this.telemetryLoading=!1,this.telemetrySaving=!1,this.telemetryDraft={...Co},this.telemetryMessage="",this.telemetryError=!1,this.llmMessage="",this.llmMessageError=!1,e&&this.agents.find(t=>t.id===e)?.online&&this.loadTelemetry()},onLlmMessage(e,t=!1){this.llmMessage=e,this.llmMessageError=t},async loadTelemetry(){let e=this.selectedAgentId;if(!e)return;let t=++this.telemetryGeneration;this.telemetryLoading=!0,this.telemetryMessage="";try{let s=await this.store.loadTelemetrySettings(e);if(t!==this.telemetryGeneration||e!==this.selectedAgentId)return;if(s?.error)throw new Error(s.error);this.telemetryDraft={...Co,...s}}catch(s){if(t!==this.telemetryGeneration||e!==this.selectedAgentId)return;this.telemetryError=!0,this.telemetryMessage=s?.message||this.$t("agentSettings.telemetry.loadFailed")}finally{t===this.telemetryGeneration&&e===this.selectedAgentId&&(this.telemetryLoading=!1)}},async saveTelemetry(){let e=this.selectedAgentId;if(!e)return;let t=++this.telemetryGeneration;this.telemetrySaving=!0,this.telemetryMessage="";try{let s=await this.store.updateTelemetrySettings(this.telemetryDraft,e);if(t!==this.telemetryGeneration||e!==this.selectedAgentId)return;if(s?.error)throw new Error(s.error);this.telemetryDraft={...Co,...s},this.telemetryError=!1,this.telemetryMessage=this.$t("agentSettings.telemetry.saved")}catch(s){if(t!==this.telemetryGeneration||e!==this.selectedAgentId)return;this.telemetryError=!0,this.telemetryMessage=s?.message||this.$t("agentSettings.telemetry.saveFailed")}finally{t===this.telemetryGeneration&&e===this.selectedAgentId&&(this.telemetrySaving=!1)}},setDreamEnabled(e){this.selectedAgentId&&this.store.setDreamEnabled(this.selectedAgentId,e)},async restartAgent(){let e=this.selectedAgent;!e||!await De(this.$t("chat.agent.restartConfirm",{name:e.name||e.id}))||this.store.restartAgent(e.id)},async upgradeAgent(){let e=this.selectedAgent;!e||!await De(this.$t("chat.agent.upgradeConfirm",{name:e.name||e.id}))||this.store.upgradeAgent(e.id)}}}});var wh,kh=F(()=>{wh={name:"ExpertRoleEditor",template:`
|
|
4759
4759
|
<div class="expert-editor-overlay" @click.self="$emit('close')">
|
|
4760
4760
|
<div class="expert-editor-modal">
|
|
4761
4761
|
<div class="expert-editor-header">
|
|
@@ -5394,7 +5394,7 @@ ${String(e||"").trim()}
|
|
|
5394
5394
|
<span class="mode-toggle-thumb"></span>
|
|
5395
5395
|
</span>
|
|
5396
5396
|
</button>
|
|
5397
|
-
`}});var Po,pc=F(()=>{Po={name:"SidebarAgentHeader",props:{onlineAgents:{type:Array,required:!0},onlineAgentCount:{type:Number,required:!0},restartingAgents:{type:Object,default:()=>({})},upgradingAgents:{type:Object,default:()=>({})},showAgentActions:{type:Boolean,default:!1}},emits:["open-agent-settings","upgrade-agent"],data(){return{open:!1}},created(){this._onDocClick=e=>{!this.open||e.target?.closest?.(".agent-header-controls")||(this.open=!1)},typeof document<"u"&&document.addEventListener("click",this._onDocClick,!0)},beforeUnmount(){this._onDocClick&&typeof document<"u"&&document.removeEventListener("click",this._onDocClick,!0)},methods:{tr(e,t,s){try{let n=this.$t?this.$t(e,s):e;return n&&n!==e?n:t||e}catch{return t||e}}},template:`
|
|
5397
|
+
`}});var Po,pc=F(()=>{Po={name:"SidebarAgentHeader",props:{onlineAgents:{type:Array,required:!0},onlineAgentCount:{type:Number,required:!0},restartingAgents:{type:Object,default:()=>({})},upgradingAgents:{type:Object,default:()=>({})},showAgentActions:{type:Boolean,default:!1}},emits:["open-agent-settings","restart-agent","upgrade-agent"],data(){return{open:!1}},created(){this._onDocClick=e=>{!this.open||e.target?.closest?.(".agent-header-controls")||(this.open=!1)},typeof document<"u"&&document.addEventListener("click",this._onDocClick,!0)},beforeUnmount(){this._onDocClick&&typeof document<"u"&&document.removeEventListener("click",this._onDocClick,!0)},methods:{tr(e,t,s){try{let n=this.$t?this.$t(e,s):e;return n&&n!==e?n:t||e}catch{return t||e}}},template:`
|
|
5398
5398
|
<div class="agent-header-controls">
|
|
5399
5399
|
<button
|
|
5400
5400
|
type="button"
|
|
@@ -5418,18 +5418,30 @@ ${String(e||"").trim()}
|
|
|
5418
5418
|
<span class="agent-dropdown-status" v-else-if="upgradingAgents[agent.id]">{{ tr('chat.agent.upgrading', 'Upgrading\u2026') }}</span>
|
|
5419
5419
|
<span class="agent-dropdown-version" v-else-if="agent.version">v{{ agent.version }}</span>
|
|
5420
5420
|
</span>
|
|
5421
|
-
<
|
|
5422
|
-
|
|
5423
|
-
|
|
5424
|
-
|
|
5425
|
-
|
|
5426
|
-
|
|
5427
|
-
|
|
5428
|
-
|
|
5429
|
-
|
|
5430
|
-
|
|
5431
|
-
|
|
5432
|
-
|
|
5421
|
+
<template v-if="showAgentActions">
|
|
5422
|
+
<button
|
|
5423
|
+
type="button"
|
|
5424
|
+
class="agent-dropdown-action-btn agent-dropdown-upgrade-btn"
|
|
5425
|
+
@click.stop="$emit('upgrade-agent', agent.id)"
|
|
5426
|
+
:disabled="!agent.online || restartingAgents[agent.id] || upgradingAgents[agent.id]"
|
|
5427
|
+
:title="tr('chat.agent.upgrade', 'Upgrade')"
|
|
5428
|
+
:aria-label="tr('chat.agent.upgrade', 'Upgrade')"
|
|
5429
|
+
>
|
|
5430
|
+
<span v-if="upgradingAgents[agent.id]" class="spinner-mini"></span>
|
|
5431
|
+
<svg v-else viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8-8 8z"/></svg>
|
|
5432
|
+
</button>
|
|
5433
|
+
<button
|
|
5434
|
+
type="button"
|
|
5435
|
+
class="agent-dropdown-action-btn agent-dropdown-restart-btn"
|
|
5436
|
+
@click.stop="$emit('restart-agent', agent.id)"
|
|
5437
|
+
:disabled="!agent.online || restartingAgents[agent.id] || upgradingAgents[agent.id]"
|
|
5438
|
+
:title="tr('chat.agent.restart', 'Restart')"
|
|
5439
|
+
:aria-label="tr('chat.agent.restart', 'Restart')"
|
|
5440
|
+
>
|
|
5441
|
+
<span v-if="restartingAgents[agent.id]" class="spinner-mini"></span>
|
|
5442
|
+
<svg v-else viewBox="0 0 24 24" width="16" height="16" aria-hidden="true"><path fill="currentColor" d="M17.65 6.35A7.958 7.958 0 0012 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0112 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>
|
|
5443
|
+
</button>
|
|
5444
|
+
</template>
|
|
5433
5445
|
</div>
|
|
5434
5446
|
<div v-if="onlineAgents.length === 0" class="agent-dropdown-empty">{{ tr('chat.agent.none', 'No agents online') }}</div>
|
|
5435
5447
|
</div>
|
|
@@ -5481,7 +5493,7 @@ ${String(e||"").trim()}
|
|
|
5481
5493
|
<slot name="collapsed"></slot>
|
|
5482
5494
|
<slot></slot>
|
|
5483
5495
|
</aside>
|
|
5484
|
-
`}});function Ah(e){let t=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(t)?t:0}function Th(e){if(e.length===0)return!1;let t=e.map(s=>s?.sortRank);return t.every(Number.isFinite)&&new Set(t).size===e.length}function hc(e,t=Th(e)){return[...e].sort((s,n)=>{if(!!s.pinned!=!!n.pinned)return s.pinned?-1:1;if(t){let i=Number.isFinite(s.sortRank)?s.sortRank:Number.MAX_SAFE_INTEGER,o=Number.isFinite(n.sortRank)?n.sortRank:Number.MAX_SAFE_INTEGER;if(i!==o)return i-o}let r=Ah(n.metadataUpdatedAt||n.createdAt)-Ah(s.metadataUpdatedAt||s.createdAt);return r!==0?r:String(s.catalogKey||"").localeCompare(String(n.catalogKey||""))})}function qe(e){return e?.id||""}function Ow(){try{if(typeof localStorage>"u")return{projects:!1,recents:!1};let e=JSON.parse(localStorage.getItem(Mh)||"{}");return{projects:e?.projects===!0,recents:e?.recents===!0}}catch{return{projects:!1,recents:!1}}}function xh(e){try{typeof localStorage<"u"&&localStorage.setItem(Mh,JSON.stringify({projects:e?.projects===!0,recents:e?.recents===!0}))}catch{}}function Fw(e,t,s,n="before"){let r=Array.isArray(e)?[...e]:[],i=r.findIndex(l=>qe(l)===t);if(i<0)return null;let[o]=r.splice(i,1),a=r.findIndex(l=>qe(l)===s);return a<0?null:(r.splice(a+(n==="after"?1:0),0,o),r)}function Hw(e,t){return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!0:e.some((s,n)=>s?.catalogKey!==t[n]?.catalogKey)}function qw(e,t,s=null,n="before"){let r=Array.isArray(e)?[...e]:[],i=r.findIndex(l=>l?.catalogKey===t);if(i<0)return null;let[o]=r.splice(i,1);if(n==="append")return r.push(o),r;let a=r.findIndex(l=>l?.catalogKey===s);return a<0?null:(r.splice(a+(n==="after"?1:0),0,o),r)}function Bw(e,t,s={}){let i=Math.max(0,Number(s.width)||0),o=Math.max(0,Number(s.height)||0),a=Math.min(Math.max(160,Number(t?.width)||0),Math.max(0,i-16)),l=Math.max(0,Number(t?.height)||0),c=Math.max(0,o-e.bottom-4-8),d=Math.max(0,e.top-4-8),u=c<l&&d>c,p=Math.min(l,u?d:c),f=Math.min(Math.max(8,e.right-a),Math.max(8,i-8-a)),g=u?e.top-4-p:e.bottom+4;return{top:Math.min(Math.max(8,g),Math.max(8,o-8-p)),left:f,width:a,maxHeight:p,placement:u?"above":"below"}}function Nw(e,t,s={}){let i=Math.max(0,Number(s.width)||0),o=Math.max(0,Number(s.height)||0),a=Math.min(Math.max(160,Number(t?.width)||0),Math.max(0,i-16)),l=Math.max(0,Number(t?.height)||0),c=Math.min(l,Math.max(0,o-16)),d=Math.max(0,i-e.right-4-8),u=Math.max(0,e.left-4-8),p=d<a&&u>d,f=p?e.left-4-a:e.right+4,g=Math.min(Math.max(8,f),Math.max(8,i-8-a));return{top:Math.min(Math.max(8,e.top),Math.max(8,o-8-c)),left:g,width:a,maxHeight:c,placement:p?"left":"right"}}var Mh,Do,mc=F(()=>{ot();Mh="yeaft-sidebar-section-collapse";Do={name:"UnifiedSessionList",emits:["select","create","create-in-project","action","project-action","close-work-center"],props:{sessions:{type:Array,default:()=>[]},projectStore:{type:Object,default:null},projects:{type:Array,default:()=>[]},activeRoute:{type:Object,default:null},isSessionUnread:{type:Function,default:null},processingConversations:{type:Object,default:()=>({})},isYeaftSessionProcessing:{type:Function,default:null},agents:{type:Array,default:()=>[]},workCenterOpen:{type:Boolean,default:!1}},data(){return{collapsedProjects:{},collapsedSections:Ow(),openMenuKey:null,openProjectMenuKey:null,suppressedActionsKey:null,draggedRow:null,dragTargetProjectId:null,dragTargetRowKey:null,dragTargetPosition:null,draggedProjectId:null,dragTargetProjectRowId:null,dragTargetProjectPosition:null,dragOperationPending:!1,projectCreateOpen:!1,projectCreateName:"",projectCreateSubmitting:!1,projectInstructionOpen:!1,projectInstructionProject:null,projectInstructionDraft:"",projectInstructionSubmitting:!1,floatingMenu:null,floatingMenuStyle:{},floatingMenuTrigger:null,projectSubmenuOpen:!1,projectSubmenuStyle:{}}},mounted(){document.addEventListener("pointerdown",this.closeMenusFromDocument,!0),document.addEventListener("keydown",this.closeMenusFromKeyboard),window.addEventListener("resize",this.positionFloatingMenu),window.addEventListener("scroll",this.positionFloatingMenu,!0)},beforeUnmount(){document.removeEventListener("pointerdown",this.closeMenusFromDocument,!0),document.removeEventListener("keydown",this.closeMenusFromKeyboard),window.removeEventListener("resize",this.positionFloatingMenu),window.removeEventListener("scroll",this.positionFloatingMenu,!0)},computed:{resolvedProjectStore(){if(this.projectStore)return this.projectStore;try{return window.Pinia?.useChatStore?.()||null}catch{return null}},hasCompleteCatalogOrder(){return Th(this.sessions)},projectRows(){return[...this.projects.length>0?this.projects:this.resolvedProjectStore?.sessionProjects||[]].sort((t,s)=>(t.sortOrder??Number.MAX_SAFE_INTEGER)-(s.sortOrder??Number.MAX_SAFE_INTEGER))},projectBySessionKey(){let e=new Map;for(let t of this.projectRows){let s=Array.isArray(t.members)?t.members:t.agentId?(t.sessionIds||[]).map(n=>({agentId:t.agentId,sessionId:n})):[];for(let n of s)n?.agentId&&n?.sessionId&&e.set(`${n.agentId}${n.sessionId}`,t)}return e},projectSessionRows(){let e=new Map(this.projectRows.map(t=>[qe(t),[]]));for(let t of this.sessions){if(t.runtimeProvider!=="yeaft")continue;let s=this.projectBySessionKey.get(`${t.routeRef?.agentId}${t.routeRef?.sessionId}`),n=qe(s);s&&e.has(n)&&e.get(n).push(t)}return e},rowsByProject(){let e=new Map;for(let[t,s]of this.projectSessionRows)e.set(t,hc(s.filter(n=>this.isRowOnline(n)),this.hasCompleteCatalogOrder));return e},recentRows(){return hc(this.sessions.filter(e=>{if(!this.isRowOnline(e))return!1;if(e.runtimeProvider==="yeaft"){let t=`${e.routeRef?.agentId}${e.routeRef?.sessionId}`;if(this.projectBySessionKey.has(t))return!1}return!0}),this.hasCompleteCatalogOrder)}},methods:{closeMenus(){this.openMenuKey=null,this.openProjectMenuKey=null,this.floatingMenu=null,this.floatingMenuStyle={},this.floatingMenuTrigger=null,this.projectSubmenuOpen=!1,this.projectSubmenuStyle={}},closeMenusFromDocument(e){e?.target?.closest?.(".session-menu, .session-submenu, .session-dots-btn")||this.closeMenus()},closeMenusFromKeyboard(e){e?.key==="Escape"&&(this.closeMenus(),this.cancelProjectCreate(),this.projectInstructionOpen&&this.closeProjectInstruction())},restoreRowActions(e){this.suppressedActionsKey===e?.catalogKey&&(this.suppressedActionsKey=null)},toggleProjectMenu(e,t){let s=qe(e);if(this.openProjectMenuKey===s){this.closeMenus();return}this.openMenuKey=null,this.openProjectMenuKey=s,this.floatingMenu={kind:"project",project:e},this.floatingMenuTrigger=t?.currentTarget||null,this.$nextTick(this.positionFloatingMenu)},toggleSessionMenu(e,t,s){if(this.openMenuKey===e.catalogKey){this.closeMenus();return}this.openProjectMenuKey=null,this.openMenuKey=e.catalogKey,this.floatingMenu={kind:"session",row:e,inProject:t===!0,currentProject:this.projectBySessionKey.get(`${e.routeRef?.agentId}${e.routeRef?.sessionId}`)||null},this.floatingMenuTrigger=s?.currentTarget||null,this.$nextTick(this.positionFloatingMenu)},positionFloatingMenu(){let e=this.floatingMenuTrigger,t=this.$refs.floatingMenu;if(!this.floatingMenu||!e?.isConnected||!t){this.floatingMenu&&e&&!e.isConnected&&this.closeMenus();return}let s=Bw(e.getBoundingClientRect(),{width:t.scrollWidth||t.offsetWidth||160,height:t.scrollHeight||t.offsetHeight||0},{width:document.documentElement.clientWidth||window.innerWidth,height:document.documentElement.clientHeight||window.innerHeight});this.floatingMenuStyle={top:`${s.top}px`,left:`${s.left}px`,width:`${s.width}px`,maxHeight:`${s.maxHeight}px`},this.projectSubmenuOpen&&this.$nextTick(this.positionProjectSubmenu)},isActive(e){let t=e?.routeRef,s=this.activeRoute;return!!t&&!!s&&t.runtimeProvider===s.runtimeProvider&&t.agentId===s.agentId&&t.sessionId===s.sessionId},isProcessing(e){return e?.runtimeProvider==="yeaft"?typeof this.isYeaftSessionProcessing=="function"?!!this.isYeaftSessionProcessing(e.routeRef.sessionId,e.routeRef.agentId):!1:!!this.processingConversations?.[e?.routeRef?.sessionId]},isUnread(e){return typeof this.isSessionUnread=="function"?!!this.isSessionUnread(e):!1},isProjectUnread(e){return(this.projectSessionRows.get(qe(e))||[]).some(s=>this.isUnread(s))},projectKey(e){return qe(e)},isAgentOnline(e){return!!e&&this.agents.some(t=>t.id===e&&t.online)},isRowOnline(e){return e?.availability!=="online"?!1:this.isAgentOnline(e?.routeRef?.agentId)},canEditProject(e){return e?.id?!e.legacyAgentId||this.isAgentOnline(e.legacyAgentId):!1},canEditRow(e){return!e?.routeRef?.agentId||e.availability!=="online"?!1:this.isAgentOnline(e.routeRef.agentId)},canMoveRowToProject(e,t=null){return this.canEditRow(e)?t?this.canEditProject(t)?!t.legacyAgentId||t.legacyAgentId===e.routeRef.agentId:!1:!0:!1},projectMoveTargets(e,t=null){let s=qe(t);return this.projectRows.filter(n=>qe(n)!==s&&this.canMoveRowToProject(e,n))},openProjectMoveList(){!this.floatingMenu||this.floatingMenu.kind!=="session"||(this.projectSubmenuOpen=!0,this.$nextTick(this.positionProjectSubmenu))},closeProjectMoveList(){this.projectSubmenuOpen=!1,this.projectSubmenuStyle={}},positionProjectSubmenu(){let e=this.$refs.floatingMenu,t=this.$refs.projectSubmenu;if(!this.projectSubmenuOpen||!e||!t)return;let s=Nw(e.getBoundingClientRect(),{width:t.scrollWidth||t.offsetWidth||160,height:t.scrollHeight||t.offsetHeight||0},{width:document.documentElement.clientWidth||window.innerWidth,height:document.documentElement.clientHeight||window.innerHeight});this.projectSubmenuStyle={top:`${s.top}px`,left:`${s.left}px`,width:`${s.width}px`,maxHeight:`${s.maxHeight}px`}},isSectionCollapsed(e){return this.collapsedSections?.[e]===!0},toggleSection(e){e!=="projects"&&e!=="recents"||(this.collapsedSections={...this.collapsedSections,[e]:!this.isSectionCollapsed(e)},xh(this.collapsedSections),this.closeMenus())},isProjectCollapsed(e){return this.collapsedProjects[qe(e)]===!0},toggleProject(e){let t=qe(e);this.collapsedProjects={...this.collapsedProjects,[t]:!this.collapsedProjects[t]},this.closeMenus()},providerLabel(e){return e.runtimeProvider==="yeaft"?"Yeaft":e.runtimeProvider==="copilot"?"Copilot":"Claude"},agentLabel(e){let t=this.agents.find(s=>s.id===e?.routeRef?.agentId);return e?.agentName||t?.name||e?.routeRef?.agentId||""},createSession(){this.workCenterOpen&&this.$emit("close-work-center"),this.$emit("create")},createSessionInProject(e){this.canEditProject(e)&&(this.closeMenus(),this.workCenterOpen&&this.$emit("close-work-center"),this.$emit("create-in-project",{project:e}))},selectRow(e,t,s={}){s.suppressActions===!0&&(this.suppressedActionsKey=e?.catalogKey||null,t?.currentTarget?.blur?.()),this.closeMenus(),this.workCenterOpen&&this.$emit("close-work-center"),this.$emit("select",e)},selectRowFromKeyboard(e,t){t?.target===t?.currentTarget&&(t.preventDefault(),this.selectRow(e,t))},async runAction(e,t){if(this.closeMenus(),!this.canEditRow(t))return;if(e==="rename"){let n=await Ml(this.$t("yeaft.session.renamePrompt",{name:t.title}),t.title);if(!n?.trim()||n.trim()===t.title)return;this.$emit("action",{action:e,row:t,title:n.trim()});return}let s=e==="delete"?"remove":e;this.$emit("action",{action:s,row:t})},dispatchSessionAction(e){return e?.action==="reorder"&&this.resolvedProjectStore?.reorderCatalogSessions?this.resolvedProjectStore.reorderCatalogSessions(e.sessions):(this.$emit("action",e),!0)},dispatchProjectAction(e){if(e?.action==="move-session"&&!this.canMoveRowToProject(e?.row,e?.project||null))return!1;this.$emit("project-action",e);let t=this.resolvedProjectStore;if(!t?.mutateProject)return!0;let{action:s,project:n,row:r,name:i,catalogOrder:o,agentId:a}=e,l=a||r?.routeRef?.agentId||null;if(s==="create")return t.mutateProject("create",{name:i},l);let c=n?.legacyProjectId||n?.id;return s==="rename"?t.mutateProject("rename",{projectId:c,name:i},n?.legacyAgentId||l):s==="update-instruction"?t.mutateProject("update_instruction",{projectId:c,instruction:e.instruction||""},n?.legacyAgentId||l):s==="delete"?t.mutateProject("delete",{projectId:c},n?.legacyAgentId||l):s==="reorder-projects"?t.mutateProject("reorder",{projectIds:(e.projects||[]).map(d=>d.id)}):s==="move-session"&&r?.routeRef?.sessionId?t.mutateProject("move_session",{sessionId:r.routeRef.sessionId,projectId:n?.legacyProjectId||n?.id||null,...Array.isArray(o)?{catalogOrder:o.map(d=>({catalogKey:d.catalogKey,routeRef:d.routeRef}))}:{}},l):!1},createProject(){this.projectCreateSubmitting||(this.isSectionCollapsed("projects")&&(this.collapsedSections={...this.collapsedSections,projects:!1},xh(this.collapsedSections)),this.projectCreateOpen=!0,this.projectCreateName="",this.$nextTick(()=>this.$refs.projectCreateInput?.focus?.()))},cancelProjectCreate(){this.projectCreateSubmitting||(this.projectCreateOpen=!1,this.projectCreateName="")},async submitProjectCreate(){let e=this.projectCreateName.trim();if(!(!e||this.projectCreateSubmitting)){this.projectCreateSubmitting=!0;try{(await this.dispatchProjectAction({action:"create",name:e}))?.ok!==!1&&(this.projectCreateOpen=!1,this.projectCreateName="")}finally{this.projectCreateSubmitting=!1}}},async renameProject(e){if(!this.canEditProject(e))return;let t=await Ml(this.$t("sidebar.projects.renamePrompt"),e.name);this.closeMenus(),t?.trim()&&t.trim()!==e.name&&this.dispatchProjectAction({action:"rename",project:e,name:t.trim()})},async deleteProject(e){this.canEditProject(e)&&(this.closeMenus(),await Ee(this.$t("sidebar.projects.deleteConfirm",{name:e.name}),{destructive:!0})&&this.dispatchProjectAction({action:"delete",project:e}))},editProjectInstruction(e){this.canEditProject(e)&&(this.closeMenus(),this.projectInstructionProject=e,this.projectInstructionDraft=typeof e.instruction=="string"?e.instruction:"",this.projectInstructionOpen=!0,this.$nextTick(()=>this.$refs.projectInstructionInput?.focus?.()))},closeProjectInstruction(){this.projectInstructionSubmitting||(this.projectInstructionOpen=!1,this.projectInstructionProject=null,this.projectInstructionDraft="")},async saveProjectInstruction(){let e=this.projectInstructionProject;if(!(!e||this.projectInstructionSubmitting)){this.projectInstructionSubmitting=!0;try{(await this.dispatchProjectAction({action:"update-instruction",project:e,instruction:this.projectInstructionDraft}))?.ok!==!1&&(this.projectInstructionOpen=!1,this.projectInstructionProject=null,this.projectInstructionDraft="")}finally{this.projectInstructionSubmitting=!1}}},moveRow(e,t=null,s=null){return this.closeMenus(),this.canMoveRowToProject(e,t)?this.dispatchProjectAction({action:"move-session",row:e,project:t,catalogOrder:s}):!1},projectForRow(e){if(e?.runtimeProvider!=="yeaft")return null;let t=`${e.routeRef?.agentId}${e.routeRef?.sessionId}`;return this.projectBySessionKey.get(t)||null},canDragProject(e){return!!e?.id&&!e.legacyProjectId&&this.projectRows.length>1&&this.projectRows.every(t=>t?.id&&!t.legacyProjectId)&&!this.dragOperationPending},startProjectDrag(e,t){this.canDragProject(e)&&(this.closeMenus(),this.finishDrag(),this.draggedProjectId=qe(e),t?.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",`project:${this.draggedProjectId}`)))},dragOverProjectRow(e,t){let s=qe(e);!this.draggedProjectId||s===this.draggedProjectId||!this.canDragProject(e)||(t?.preventDefault?.(),t?.stopPropagation?.(),t?.dataTransfer&&(t.dataTransfer.dropEffect="move"),this.dragTargetProjectRowId=s,this.dragTargetProjectPosition=this.dragPositionForEvent(t))},dragLeaveProjectRow(e,t){if(this.dragTargetProjectRowId!==qe(e))return;let s=t?.relatedTarget;s&&t?.currentTarget?.contains?.(s)||(this.dragTargetProjectRowId=null,this.dragTargetProjectPosition=null)},async dropProjectRow(e,t){t?.preventDefault?.(),t?.stopPropagation?.();let s=this.draggedProjectId,n=qe(e),r=this.dragTargetProjectRowId===n?this.dragTargetProjectPosition:this.dragPositionForEvent(t);if(this.finishProjectDrag(),!s||!n||s===n||!r)return!1;let i=Fw(this.projectRows,s,n,r);if(!i)return!1;this.dragOperationPending=!0;try{let o=await this.dispatchProjectAction({action:"reorder-projects",projects:i});return o!==!1&&o?.ok!==!1}finally{this.dragOperationPending=!1}},finishProjectDrag(){this.draggedProjectId=null,this.dragTargetProjectRowId=null,this.dragTargetProjectPosition=null},canDragRow(e,t=null){return this.dragOperationPending||!this.canEditRow(e)?!1:t?e?.runtimeProvider!=="yeaft"?!1:qe(this.projectForRow(e))===qe(t)||this.canMoveRowToProject(e,t):!0},canDropRow(e,t=null){return!e||this.dragOperationPending||!this.canEditRow(e)?!1:t?e.runtimeProvider!=="yeaft"?!1:qe(this.projectForRow(e))===qe(t)?this.canEditRow(e):this.canMoveRowToProject(e,t):e.runtimeProvider==="yeaft"||!this.projectForRow(e)},startDrag(e,t){this.canDragRow(e,this.projectForRow(e))&&(this.closeMenus(),this.finishProjectDrag(),this.draggedRow=e,this.dragTargetProjectId=null,this.dragTargetRowKey=null,this.dragTargetPosition=null,t?.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e.catalogKey)))},dragPositionForEvent(e){let t=e?.currentTarget?.getBoundingClientRect?.();return!t||!Number.isFinite(e?.clientY)?"before":e.clientY>t.top+t.height/2?"after":"before"},dragOverRow(e,t,s){let n=this.draggedRow;!this.canDropRow(n,t)||n.catalogKey===e?.catalogKey||!!n.pinned!=!!e?.pinned||(s?.preventDefault?.(),s?.stopPropagation?.(),s?.dataTransfer&&(s.dataTransfer.dropEffect="move"),this.dragTargetProjectId=null,this.dragTargetRowKey=e.catalogKey,this.dragTargetPosition=this.dragPositionForEvent(s))},dragLeaveRow(e,t){if(this.dragTargetRowKey!==e?.catalogKey)return;let s=t?.relatedTarget;s&&t?.currentTarget?.contains?.(s)||(this.dragTargetRowKey=null,this.dragTargetPosition=null)},async dropOnRow(e,t,s){s?.preventDefault?.(),s?.stopPropagation?.();let n=this.draggedRow,r=this.dragTargetRowKey===e?.catalogKey?this.dragTargetPosition:this.dragPositionForEvent(s);return this.finishDrag(),!this.canDropRow(n,t)||!r?!1:this.applySessionDrop(n,t,e,r)},dragOverProjectHeader(e,t){if(this.draggedProjectId){this.dragOverProjectRow(e,t);return}this.dragOverProject(e,t)},clearProjectHeaderDragTarget(e,t){if(this.draggedProjectId){this.dragLeaveProjectRow(e,t);return}this.clearGroupDragTarget(qe(e),t)},dropOnProjectHeader(e,t){return this.draggedProjectId?this.dropProjectRow(e,t):this.dropOnProject(e,t)},dragOverProject(e,t){if(!this.canDropRow(this.draggedRow,e)){this.clearDragTarget();return}t?.preventDefault?.(),t?.dataTransfer&&(t.dataTransfer.dropEffect="move"),this.dragTargetProjectId=qe(e),this.dragTargetRowKey=null,this.dragTargetPosition=null},async dropOnProject(e,t){t?.preventDefault?.();let s=this.draggedRow;return this.finishDrag(),this.canDropRow(s,e)?this.applySessionDropAtEnd(s,e):!1},dragOverRecents(e){if(!this.canDropRow(this.draggedRow,null)){this.clearDragTarget();return}e?.preventDefault?.(),e?.dataTransfer&&(e.dataTransfer.dropEffect="move"),this.dragTargetProjectId="__recents__",this.dragTargetRowKey=null,this.dragTargetPosition=null},async dropOnRecents(e){e?.preventDefault?.();let t=this.draggedRow;return this.finishDrag(),this.canDropRow(t,null)?this.applySessionDropAtEnd(t,null):!1},clearGroupDragTarget(e,t){if(this.dragTargetProjectId!==e)return;let s=t?.relatedTarget;s&&t?.currentTarget?.contains?.(s)||(this.dragTargetProjectId=null)},clearDragTarget(){this.dragTargetProjectId=null,this.dragTargetRowKey=null,this.dragTargetPosition=null},finishDrag(){this.draggedRow=null,this.clearDragTarget()},finishAllDrag(){this.finishDrag(),this.finishProjectDrag()},rowsForProject(e=null){return e?this.rowsByProject.get(qe(e))||[]:this.recentRows},async applySessionDropAtEnd(e,t=null){let n=this.rowsForProject(t).filter(r=>r.catalogKey!==e?.catalogKey).at(-1)||null;return this.applySessionDrop(e,t,n,n?"after":"append")},async applySessionDrop(e,t,s,n){if(!e?.catalogKey||!this.canDropRow(e,t))return!1;let r=hc(this.sessions),i=qw(r,e.catalogKey,s?.catalogKey||null,n);if(!i)return!1;let o=this.projectForRow(e),a=qe(o)!==qe(t),l=Hw(r,i);if(!a&&!l)return!1;this.dragOperationPending=!0;try{if(a){let c=await this.moveRow(e,t,i);return c!==!1&&c?.ok!==!1}return l?await this.dispatchSessionAction({action:"reorder",row:e,sessions:i})!==!1:!0}finally{this.dragOperationPending=!1}}},template:`
|
|
5496
|
+
`}});function Ah(e){let t=typeof e=="number"?e:Date.parse(e||"");return Number.isFinite(t)?t:0}function Th(e){if(e.length===0)return!1;let t=e.map(s=>s?.sortRank);return t.every(Number.isFinite)&&new Set(t).size===e.length}function hc(e,t=Th(e)){return[...e].sort((s,n)=>{if(!!s.pinned!=!!n.pinned)return s.pinned?-1:1;if(t){let i=Number.isFinite(s.sortRank)?s.sortRank:Number.MAX_SAFE_INTEGER,o=Number.isFinite(n.sortRank)?n.sortRank:Number.MAX_SAFE_INTEGER;if(i!==o)return i-o}let r=Ah(n.metadataUpdatedAt||n.createdAt)-Ah(s.metadataUpdatedAt||s.createdAt);return r!==0?r:String(s.catalogKey||"").localeCompare(String(n.catalogKey||""))})}function qe(e){return e?.id||""}function Ow(){try{if(typeof localStorage>"u")return{projects:!1,recents:!1};let e=JSON.parse(localStorage.getItem(Mh)||"{}");return{projects:e?.projects===!0,recents:e?.recents===!0}}catch{return{projects:!1,recents:!1}}}function xh(e){try{typeof localStorage<"u"&&localStorage.setItem(Mh,JSON.stringify({projects:e?.projects===!0,recents:e?.recents===!0}))}catch{}}function Fw(e,t,s,n="before"){let r=Array.isArray(e)?[...e]:[],i=r.findIndex(l=>qe(l)===t);if(i<0)return null;let[o]=r.splice(i,1),a=r.findIndex(l=>qe(l)===s);return a<0?null:(r.splice(a+(n==="after"?1:0),0,o),r)}function Hw(e,t){return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!0:e.some((s,n)=>s?.catalogKey!==t[n]?.catalogKey)}function qw(e,t,s=null,n="before"){let r=Array.isArray(e)?[...e]:[],i=r.findIndex(l=>l?.catalogKey===t);if(i<0)return null;let[o]=r.splice(i,1);if(n==="append")return r.push(o),r;let a=r.findIndex(l=>l?.catalogKey===s);return a<0?null:(r.splice(a+(n==="after"?1:0),0,o),r)}function Bw(e,t,s={}){let i=Math.max(0,Number(s.width)||0),o=Math.max(0,Number(s.height)||0),a=Math.min(Math.max(160,Number(t?.width)||0),Math.max(0,i-16)),l=Math.max(0,Number(t?.height)||0),c=Math.max(0,o-e.bottom-4-8),d=Math.max(0,e.top-4-8),u=c<l&&d>c,p=Math.min(l,u?d:c),f=Math.min(Math.max(8,e.right-a),Math.max(8,i-8-a)),g=u?e.top-4-p:e.bottom+4;return{top:Math.min(Math.max(8,g),Math.max(8,o-8-p)),left:f,width:a,maxHeight:p,placement:u?"above":"below"}}function Nw(e,t,s={}){let i=Math.max(0,Number(s.width)||0),o=Math.max(0,Number(s.height)||0),a=Math.min(Math.max(160,Number(t?.width)||0),Math.max(0,i-16)),l=Math.max(0,Number(t?.height)||0),c=Math.min(l,Math.max(0,o-16)),d=Math.max(0,i-e.right-4-8),u=Math.max(0,e.left-4-8),p=d<a&&u>d,f=p?e.left-4-a:e.right+4,g=Math.min(Math.max(8,f),Math.max(8,i-8-a));return{top:Math.min(Math.max(8,e.top),Math.max(8,o-8-c)),left:g,width:a,maxHeight:c,placement:p?"left":"right"}}var Mh,Do,mc=F(()=>{ot();Mh="yeaft-sidebar-section-collapse";Do={name:"UnifiedSessionList",emits:["select","create","create-in-project","action","project-action","close-work-center"],props:{sessions:{type:Array,default:()=>[]},projectStore:{type:Object,default:null},projects:{type:Array,default:()=>[]},activeRoute:{type:Object,default:null},isSessionUnread:{type:Function,default:null},processingConversations:{type:Object,default:()=>({})},isYeaftSessionProcessing:{type:Function,default:null},agents:{type:Array,default:()=>[]},workCenterOpen:{type:Boolean,default:!1}},data(){return{collapsedProjects:{},collapsedSections:Ow(),openMenuKey:null,openProjectMenuKey:null,suppressedActionsKey:null,draggedRow:null,dragTargetProjectId:null,dragTargetRowKey:null,dragTargetPosition:null,draggedProjectId:null,dragTargetProjectRowId:null,dragTargetProjectPosition:null,dragOperationPending:!1,projectCreateOpen:!1,projectCreateName:"",projectCreateSubmitting:!1,projectInstructionOpen:!1,projectInstructionProject:null,projectInstructionDraft:"",projectInstructionSubmitting:!1,floatingMenu:null,floatingMenuStyle:{},floatingMenuTrigger:null,projectSubmenuOpen:!1,projectSubmenuStyle:{}}},mounted(){document.addEventListener("pointerdown",this.closeMenusFromDocument,!0),document.addEventListener("keydown",this.closeMenusFromKeyboard),window.addEventListener("resize",this.positionFloatingMenu),window.addEventListener("scroll",this.positionFloatingMenu,!0)},beforeUnmount(){document.removeEventListener("pointerdown",this.closeMenusFromDocument,!0),document.removeEventListener("keydown",this.closeMenusFromKeyboard),window.removeEventListener("resize",this.positionFloatingMenu),window.removeEventListener("scroll",this.positionFloatingMenu,!0)},computed:{resolvedProjectStore(){if(this.projectStore)return this.projectStore;try{return window.Pinia?.useChatStore?.()||null}catch{return null}},hasCompleteCatalogOrder(){return Th(this.sessions)},projectRows(){return[...this.projects.length>0?this.projects:this.resolvedProjectStore?.sessionProjects||[]].sort((t,s)=>(t.sortOrder??Number.MAX_SAFE_INTEGER)-(s.sortOrder??Number.MAX_SAFE_INTEGER))},projectBySessionKey(){let e=new Map;for(let t of this.projectRows){let s=Array.isArray(t.members)?t.members:t.agentId?(t.sessionIds||[]).map(n=>({agentId:t.agentId,sessionId:n})):[];for(let n of s)n?.agentId&&n?.sessionId&&e.set(`${n.agentId}${n.sessionId}`,t)}return e},projectSessionRows(){let e=new Map(this.projectRows.map(t=>[qe(t),[]]));for(let t of this.sessions){if(t.runtimeProvider!=="yeaft")continue;let s=this.projectBySessionKey.get(`${t.routeRef?.agentId}${t.routeRef?.sessionId}`),n=qe(s);s&&e.has(n)&&e.get(n).push(t)}return e},rowsByProject(){let e=new Map;for(let[t,s]of this.projectSessionRows)e.set(t,hc(s.filter(n=>this.isRowOnline(n)),this.hasCompleteCatalogOrder));return e},recentRows(){return hc(this.sessions.filter(e=>{if(!this.isRowOnline(e))return!1;if(e.runtimeProvider==="yeaft"){let t=`${e.routeRef?.agentId}${e.routeRef?.sessionId}`;if(this.projectBySessionKey.has(t))return!1}return!0}),this.hasCompleteCatalogOrder)}},methods:{closeMenus(){this.openMenuKey=null,this.openProjectMenuKey=null,this.floatingMenu=null,this.floatingMenuStyle={},this.floatingMenuTrigger=null,this.projectSubmenuOpen=!1,this.projectSubmenuStyle={}},closeMenusFromDocument(e){e?.target?.closest?.(".session-menu, .session-submenu, .session-dots-btn")||this.closeMenus()},closeMenusFromKeyboard(e){e?.key==="Escape"&&(this.closeMenus(),this.cancelProjectCreate(),this.projectInstructionOpen&&this.closeProjectInstruction())},restoreRowActions(e){this.suppressedActionsKey===e?.catalogKey&&(this.suppressedActionsKey=null)},toggleProjectMenu(e,t){let s=qe(e);if(this.openProjectMenuKey===s){this.closeMenus();return}this.openMenuKey=null,this.openProjectMenuKey=s,this.floatingMenu={kind:"project",project:e},this.floatingMenuTrigger=t?.currentTarget||null,this.$nextTick(this.positionFloatingMenu)},toggleSessionMenu(e,t,s){if(this.openMenuKey===e.catalogKey){this.closeMenus();return}this.openProjectMenuKey=null,this.openMenuKey=e.catalogKey,this.floatingMenu={kind:"session",row:e,inProject:t===!0,currentProject:this.projectBySessionKey.get(`${e.routeRef?.agentId}${e.routeRef?.sessionId}`)||null},this.floatingMenuTrigger=s?.currentTarget||null,this.$nextTick(this.positionFloatingMenu)},positionFloatingMenu(){let e=this.floatingMenuTrigger,t=this.$refs.floatingMenu;if(!this.floatingMenu||!e?.isConnected||!t){this.floatingMenu&&e&&!e.isConnected&&this.closeMenus();return}let s=Bw(e.getBoundingClientRect(),{width:t.scrollWidth||t.offsetWidth||160,height:t.scrollHeight||t.offsetHeight||0},{width:document.documentElement.clientWidth||window.innerWidth,height:document.documentElement.clientHeight||window.innerHeight});this.floatingMenuStyle={top:`${s.top}px`,left:`${s.left}px`,width:`${s.width}px`,maxHeight:`${s.maxHeight}px`},this.projectSubmenuOpen&&this.$nextTick(this.positionProjectSubmenu)},isActive(e){let t=e?.routeRef,s=this.activeRoute;return!!t&&!!s&&t.runtimeProvider===s.runtimeProvider&&t.agentId===s.agentId&&t.sessionId===s.sessionId},isProcessing(e){return e?.runtimeProvider==="yeaft"?typeof this.isYeaftSessionProcessing=="function"?!!this.isYeaftSessionProcessing(e.routeRef.sessionId,e.routeRef.agentId):!1:!!this.processingConversations?.[e?.routeRef?.sessionId]},isUnread(e){return typeof this.isSessionUnread=="function"?!!this.isSessionUnread(e):!1},isProjectUnread(e){return(this.projectSessionRows.get(qe(e))||[]).some(s=>this.isUnread(s))},projectKey(e){return qe(e)},isAgentOnline(e){return!!e&&this.agents.some(t=>t.id===e&&t.online)},isRowOnline(e){return e?.availability!=="online"?!1:this.isAgentOnline(e?.routeRef?.agentId)},canEditProject(e){return e?.id?!e.legacyAgentId||this.isAgentOnline(e.legacyAgentId):!1},canEditRow(e){return!e?.routeRef?.agentId||e.availability!=="online"?!1:this.isAgentOnline(e.routeRef.agentId)},canMoveRowToProject(e,t=null){return this.canEditRow(e)?t?this.canEditProject(t)?!t.legacyAgentId||t.legacyAgentId===e.routeRef.agentId:!1:!0:!1},projectMoveTargets(e,t=null){let s=qe(t);return this.projectRows.filter(n=>qe(n)!==s&&this.canMoveRowToProject(e,n))},openProjectMoveList(){!this.floatingMenu||this.floatingMenu.kind!=="session"||(this.projectSubmenuOpen=!0,this.$nextTick(this.positionProjectSubmenu))},closeProjectMoveList(){this.projectSubmenuOpen=!1,this.projectSubmenuStyle={}},positionProjectSubmenu(){let e=this.$refs.floatingMenu,t=this.$refs.projectSubmenu;if(!this.projectSubmenuOpen||!e||!t)return;let s=Nw(e.getBoundingClientRect(),{width:t.scrollWidth||t.offsetWidth||160,height:t.scrollHeight||t.offsetHeight||0},{width:document.documentElement.clientWidth||window.innerWidth,height:document.documentElement.clientHeight||window.innerHeight});this.projectSubmenuStyle={top:`${s.top}px`,left:`${s.left}px`,width:`${s.width}px`,maxHeight:`${s.maxHeight}px`}},isSectionCollapsed(e){return this.collapsedSections?.[e]===!0},toggleSection(e){e!=="projects"&&e!=="recents"||(this.collapsedSections={...this.collapsedSections,[e]:!this.isSectionCollapsed(e)},xh(this.collapsedSections),this.closeMenus())},isProjectCollapsed(e){return this.collapsedProjects[qe(e)]===!0},toggleProject(e){let t=qe(e);this.collapsedProjects={...this.collapsedProjects,[t]:!this.collapsedProjects[t]},this.closeMenus()},providerLabel(e){return e.runtimeProvider==="yeaft"?"Yeaft":e.runtimeProvider==="copilot"?"Copilot":"Claude"},agentLabel(e){let t=this.agents.find(s=>s.id===e?.routeRef?.agentId);return e?.agentName||t?.name||e?.routeRef?.agentId||""},createSession(){this.workCenterOpen&&this.$emit("close-work-center"),this.$emit("create")},createSessionInProject(e){this.canEditProject(e)&&(this.closeMenus(),this.workCenterOpen&&this.$emit("close-work-center"),this.$emit("create-in-project",{project:e}))},selectRow(e,t,s={}){s.suppressActions===!0&&(this.suppressedActionsKey=e?.catalogKey||null,t?.currentTarget?.blur?.()),this.closeMenus(),this.workCenterOpen&&this.$emit("close-work-center"),this.$emit("select",e)},selectRowFromKeyboard(e,t){t?.target===t?.currentTarget&&(t.preventDefault(),this.selectRow(e,t))},async runAction(e,t){if(this.closeMenus(),!this.canEditRow(t))return;if(e==="rename"){let n=await Ml(this.$t("yeaft.session.renamePrompt",{name:t.title}),t.title);if(!n?.trim()||n.trim()===t.title)return;this.$emit("action",{action:e,row:t,title:n.trim()});return}let s=e==="delete"?"remove":e;this.$emit("action",{action:s,row:t})},dispatchSessionAction(e){return e?.action==="reorder"&&this.resolvedProjectStore?.reorderCatalogSessions?this.resolvedProjectStore.reorderCatalogSessions(e.sessions):(this.$emit("action",e),!0)},dispatchProjectAction(e){if(e?.action==="move-session"&&!this.canMoveRowToProject(e?.row,e?.project||null))return!1;this.$emit("project-action",e);let t=this.resolvedProjectStore;if(!t?.mutateProject)return!0;let{action:s,project:n,row:r,name:i,catalogOrder:o,agentId:a}=e,l=a||r?.routeRef?.agentId||null;if(s==="create")return t.mutateProject("create",{name:i},l);let c=n?.legacyProjectId||n?.id;return s==="rename"?t.mutateProject("rename",{projectId:c,name:i},n?.legacyAgentId||l):s==="update-instruction"?t.mutateProject("update_instruction",{projectId:c,instruction:e.instruction||""},n?.legacyAgentId||l):s==="delete"?t.mutateProject("delete",{projectId:c},n?.legacyAgentId||l):s==="reorder-projects"?t.mutateProject("reorder",{projectIds:(e.projects||[]).map(d=>d.id)}):s==="move-session"&&r?.routeRef?.sessionId?t.mutateProject("move_session",{sessionId:r.routeRef.sessionId,projectId:n?.legacyProjectId||n?.id||null,...Array.isArray(o)?{catalogOrder:o.map(d=>({catalogKey:d.catalogKey,routeRef:d.routeRef}))}:{}},l):!1},createProject(){this.projectCreateSubmitting||(this.isSectionCollapsed("projects")&&(this.collapsedSections={...this.collapsedSections,projects:!1},xh(this.collapsedSections)),this.projectCreateOpen=!0,this.projectCreateName="",this.$nextTick(()=>this.$refs.projectCreateInput?.focus?.()))},cancelProjectCreate(){this.projectCreateSubmitting||(this.projectCreateOpen=!1,this.projectCreateName="")},async submitProjectCreate(){let e=this.projectCreateName.trim();if(!(!e||this.projectCreateSubmitting)){this.projectCreateSubmitting=!0;try{(await this.dispatchProjectAction({action:"create",name:e}))?.ok!==!1&&(this.projectCreateOpen=!1,this.projectCreateName="")}finally{this.projectCreateSubmitting=!1}}},async renameProject(e){if(!this.canEditProject(e))return;let t=await Ml(this.$t("sidebar.projects.renamePrompt"),e.name);this.closeMenus(),t?.trim()&&t.trim()!==e.name&&this.dispatchProjectAction({action:"rename",project:e,name:t.trim()})},async deleteProject(e){this.canEditProject(e)&&(this.closeMenus(),await De(this.$t("sidebar.projects.deleteConfirm",{name:e.name}),{destructive:!0})&&this.dispatchProjectAction({action:"delete",project:e}))},editProjectInstruction(e){this.canEditProject(e)&&(this.closeMenus(),this.projectInstructionProject=e,this.projectInstructionDraft=typeof e.instruction=="string"?e.instruction:"",this.projectInstructionOpen=!0,this.$nextTick(()=>this.$refs.projectInstructionInput?.focus?.()))},closeProjectInstruction(){this.projectInstructionSubmitting||(this.projectInstructionOpen=!1,this.projectInstructionProject=null,this.projectInstructionDraft="")},async saveProjectInstruction(){let e=this.projectInstructionProject;if(!(!e||this.projectInstructionSubmitting)){this.projectInstructionSubmitting=!0;try{(await this.dispatchProjectAction({action:"update-instruction",project:e,instruction:this.projectInstructionDraft}))?.ok!==!1&&(this.projectInstructionOpen=!1,this.projectInstructionProject=null,this.projectInstructionDraft="")}finally{this.projectInstructionSubmitting=!1}}},moveRow(e,t=null,s=null){return this.closeMenus(),this.canMoveRowToProject(e,t)?this.dispatchProjectAction({action:"move-session",row:e,project:t,catalogOrder:s}):!1},projectForRow(e){if(e?.runtimeProvider!=="yeaft")return null;let t=`${e.routeRef?.agentId}${e.routeRef?.sessionId}`;return this.projectBySessionKey.get(t)||null},canDragProject(e){return!!e?.id&&!e.legacyProjectId&&this.projectRows.length>1&&this.projectRows.every(t=>t?.id&&!t.legacyProjectId)&&!this.dragOperationPending},startProjectDrag(e,t){this.canDragProject(e)&&(this.closeMenus(),this.finishDrag(),this.draggedProjectId=qe(e),t?.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",`project:${this.draggedProjectId}`)))},dragOverProjectRow(e,t){let s=qe(e);!this.draggedProjectId||s===this.draggedProjectId||!this.canDragProject(e)||(t?.preventDefault?.(),t?.stopPropagation?.(),t?.dataTransfer&&(t.dataTransfer.dropEffect="move"),this.dragTargetProjectRowId=s,this.dragTargetProjectPosition=this.dragPositionForEvent(t))},dragLeaveProjectRow(e,t){if(this.dragTargetProjectRowId!==qe(e))return;let s=t?.relatedTarget;s&&t?.currentTarget?.contains?.(s)||(this.dragTargetProjectRowId=null,this.dragTargetProjectPosition=null)},async dropProjectRow(e,t){t?.preventDefault?.(),t?.stopPropagation?.();let s=this.draggedProjectId,n=qe(e),r=this.dragTargetProjectRowId===n?this.dragTargetProjectPosition:this.dragPositionForEvent(t);if(this.finishProjectDrag(),!s||!n||s===n||!r)return!1;let i=Fw(this.projectRows,s,n,r);if(!i)return!1;this.dragOperationPending=!0;try{let o=await this.dispatchProjectAction({action:"reorder-projects",projects:i});return o!==!1&&o?.ok!==!1}finally{this.dragOperationPending=!1}},finishProjectDrag(){this.draggedProjectId=null,this.dragTargetProjectRowId=null,this.dragTargetProjectPosition=null},canDragRow(e,t=null){return this.dragOperationPending||!this.canEditRow(e)?!1:t?e?.runtimeProvider!=="yeaft"?!1:qe(this.projectForRow(e))===qe(t)||this.canMoveRowToProject(e,t):!0},canDropRow(e,t=null){return!e||this.dragOperationPending||!this.canEditRow(e)?!1:t?e.runtimeProvider!=="yeaft"?!1:qe(this.projectForRow(e))===qe(t)?this.canEditRow(e):this.canMoveRowToProject(e,t):e.runtimeProvider==="yeaft"||!this.projectForRow(e)},startDrag(e,t){this.canDragRow(e,this.projectForRow(e))&&(this.closeMenus(),this.finishProjectDrag(),this.draggedRow=e,this.dragTargetProjectId=null,this.dragTargetRowKey=null,this.dragTargetPosition=null,t?.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",e.catalogKey)))},dragPositionForEvent(e){let t=e?.currentTarget?.getBoundingClientRect?.();return!t||!Number.isFinite(e?.clientY)?"before":e.clientY>t.top+t.height/2?"after":"before"},dragOverRow(e,t,s){let n=this.draggedRow;!this.canDropRow(n,t)||n.catalogKey===e?.catalogKey||!!n.pinned!=!!e?.pinned||(s?.preventDefault?.(),s?.stopPropagation?.(),s?.dataTransfer&&(s.dataTransfer.dropEffect="move"),this.dragTargetProjectId=null,this.dragTargetRowKey=e.catalogKey,this.dragTargetPosition=this.dragPositionForEvent(s))},dragLeaveRow(e,t){if(this.dragTargetRowKey!==e?.catalogKey)return;let s=t?.relatedTarget;s&&t?.currentTarget?.contains?.(s)||(this.dragTargetRowKey=null,this.dragTargetPosition=null)},async dropOnRow(e,t,s){s?.preventDefault?.(),s?.stopPropagation?.();let n=this.draggedRow,r=this.dragTargetRowKey===e?.catalogKey?this.dragTargetPosition:this.dragPositionForEvent(s);return this.finishDrag(),!this.canDropRow(n,t)||!r?!1:this.applySessionDrop(n,t,e,r)},dragOverProjectHeader(e,t){if(this.draggedProjectId){this.dragOverProjectRow(e,t);return}this.dragOverProject(e,t)},clearProjectHeaderDragTarget(e,t){if(this.draggedProjectId){this.dragLeaveProjectRow(e,t);return}this.clearGroupDragTarget(qe(e),t)},dropOnProjectHeader(e,t){return this.draggedProjectId?this.dropProjectRow(e,t):this.dropOnProject(e,t)},dragOverProject(e,t){if(!this.canDropRow(this.draggedRow,e)){this.clearDragTarget();return}t?.preventDefault?.(),t?.dataTransfer&&(t.dataTransfer.dropEffect="move"),this.dragTargetProjectId=qe(e),this.dragTargetRowKey=null,this.dragTargetPosition=null},async dropOnProject(e,t){t?.preventDefault?.();let s=this.draggedRow;return this.finishDrag(),this.canDropRow(s,e)?this.applySessionDropAtEnd(s,e):!1},dragOverRecents(e){if(!this.canDropRow(this.draggedRow,null)){this.clearDragTarget();return}e?.preventDefault?.(),e?.dataTransfer&&(e.dataTransfer.dropEffect="move"),this.dragTargetProjectId="__recents__",this.dragTargetRowKey=null,this.dragTargetPosition=null},async dropOnRecents(e){e?.preventDefault?.();let t=this.draggedRow;return this.finishDrag(),this.canDropRow(t,null)?this.applySessionDropAtEnd(t,null):!1},clearGroupDragTarget(e,t){if(this.dragTargetProjectId!==e)return;let s=t?.relatedTarget;s&&t?.currentTarget?.contains?.(s)||(this.dragTargetProjectId=null)},clearDragTarget(){this.dragTargetProjectId=null,this.dragTargetRowKey=null,this.dragTargetPosition=null},finishDrag(){this.draggedRow=null,this.clearDragTarget()},finishAllDrag(){this.finishDrag(),this.finishProjectDrag()},rowsForProject(e=null){return e?this.rowsByProject.get(qe(e))||[]:this.recentRows},async applySessionDropAtEnd(e,t=null){let n=this.rowsForProject(t).filter(r=>r.catalogKey!==e?.catalogKey).at(-1)||null;return this.applySessionDrop(e,t,n,n?"after":"append")},async applySessionDrop(e,t,s,n){if(!e?.catalogKey||!this.canDropRow(e,t))return!1;let r=hc(this.sessions),i=qw(r,e.catalogKey,s?.catalogKey||null,n);if(!i)return!1;let o=this.projectForRow(e),a=qe(o)!==qe(t),l=Hw(r,i);if(!a&&!l)return!1;this.dragOperationPending=!0;try{if(a){let c=await this.moveRow(e,t,i);return c!==!1&&c?.ok!==!1}return l?await this.dispatchSessionAction({action:"reorder",row:e,sessions:i})!==!1:!0}finally{this.dragOperationPending=!1}}},template:`
|
|
5485
5497
|
<nav class="sidebar-navigation" :aria-label="$t('sidebar.surface.sessions')">
|
|
5486
5498
|
<div class="sidebar-primary-actions">
|
|
5487
5499
|
<button type="button" class="sidebar-primary-action" @click="createSession" :title="$t('sidebar.sessions.newChat')" :aria-label="$t('sidebar.sessions.newChat')">
|
|
@@ -6287,7 +6299,7 @@ ${String(e||"").trim()}
|
|
|
6287
6299
|
</Teleport>
|
|
6288
6300
|
`}});function Fo(e){let t=(Number(e?.workCenterUrlRestoreGeneration)||0)+1;return e&&(e.workCenterUrlRestoreGeneration=t),t}var Ho,Ic=F(()=>{ot();Vh();Fh();Jl();no();so();Ao();qr();wc();ps();Gi();Qa();Ho={name:"WorkCenterPage",components:{MessageComposer:mo,UserTurnBlock:In,VpTurnBlock:Sn,WorkCenterActionDetail:$h,WorkCenterSettingsModal:Oh,AgentSettingsPanel:En,ModernSelect:ws},mixins:[Dh],data(){return{selectedId:null,selectedActionId:null,narrowPane:"items",contentPanelOpen:!1,contentStack:[{type:"action-list"}],staleComposerTarget:null,composerTargetValue:"coordinator",actionInputRequestGeneration:0,workCenterUrlRestoreGeneration:0,workItemMessage:"",workItemMessageQuote:null,workItemMessageAttachments:[],workItemMessageAttachmentsUploading:!1,workItemMessageSending:!1,workItemMessageError:"",workItemComposerGeneration:0,preserveComposerOnEnvelopeClear:!1,detailLoading:!1,detailError:"",createOpen:!1,settingsOpen:!1,saving:!1,createGeneration:0,llmConfigOpen:!1,search:"",boardVpId:"",boardWorkItemType:"",boardUpdatedRange:"week",mobileBoardLane:"active",deletingWorkItemIds:{},deleteWorkItemError:"",boardQueryTimer:null,workDirTouched:!1,startTouched:!1,createAttachments:[],attachmentsUploading:!1,previewingAttachmentId:null,attachmentPreviewError:"",attachmentPreviewGeneration:0,form:{requirement:"",workDir:"",deliveryTarget:"",reuseMemory:!0,start:!0}}},computed:{store(){return Pinia.useChatStore()},chat(){return this.store},agentId(){return this.store.workCenterAgentId||this.store.currentAgent},agents(){return this.store.agents||[]},onlineAgents(){return this.agents.filter(e=>e?.online&&Array.isArray(e.capabilities)&&e.capabilities.includes("work_center"))},workCenterAgentOptions(){return this.onlineAgents.map(e=>({value:e.id,label:e.name||e.id}))},watcher(){return this.store.workCenterWatcherByAgent[this.agentId]||null},boardNextCursor(){return this.store.workCenterListPageByAgent[this.agentId]?.nextCursor||null},boardLoadingMore(){return!!this.store.workCenterListMoreLoadingByAgent[this.agentId]},settings(){return this.store.workCenterSettingsByAgent[this.agentId]||null},runtime(){return this.store.workCenterRuntimeByAgent[this.agentId]||null},workItemTypes(){return Array.isArray(this.runtime?.workItemTypes)?this.runtime.workItemTypes:[]},workItemAttachmentsSupported(){return this.runtime?.workItemAttachments===!0},canonicalMessageWireSupported(){return this.agents.find(e=>e?.id===this.agentId)?.capabilities?.includes("work_center_message_v2")===!0},createDefaultWorkDir(){return this.settings?.defaultWorkDir||this.runtime?.defaultWorkDir||""},createDefaultStart(){return this.settings?.startImmediately!==!1},folderPickerAgentId(){return this.agentId||""},defaultWorkDir(){return this.createDefaultWorkDir},items(){return this.store.workCenterItemsByAgent[this.agentId]||[]},loading(){return!!this.store.workCenterLoadingByAgent[this.agentId]},loaded(){return!!this.store.workCenterLoadedByAgent[this.agentId]},error(){return this.store.workCenterErrorByAgent[this.agentId]||null},detail(){return this.store.workCenterDetailByAgent[this.agentId]||null},selected(){return this.detail?.id===this.selectedId?this.detail:this.items.find(e=>e.id===this.selectedId)||null},selectedAction(){return(Array.isArray(this.selected?.actions)?this.selected.actions:[]).find(t=>t.id===this.selectedActionId)||null},contentRef(){return this.contentStack[this.contentStack.length-1]||{type:"action-list"}},contentIsActionList(){return this.contentRef.type==="action-list"},composerTargetIsCoordinator(){return this.composerTargetValue==="coordinator"},composerTargetAction(){if(!this.composerTargetValue.startsWith("action:"))return null;let[,e,t]=this.composerTargetValue.split(":"),s=Number(t);return(Array.isArray(this.selected?.actions)?this.selected.actions:[]).find(r=>r.id===e&&Number(r.generation)===s)||null},composerTargetIsStale(){return this.composerTargetValue!=="coordinator"&&!this.composerTargetAction},composerTargetOptions(){let e=Array.isArray(this.selected?.actions)?this.selected.actions:[],t=this.tr("workCenter.coordinator","Coordinator"),s=[{value:"coordinator",label:this.$t("workCenter.sendToTarget",{target:t}),sublabel:this.tr("workCenter.coordinatorTargetHint","Work Item planning and coordination"),disabled:!1},...e.map(n=>{let r=this.$t("workCenter.actionNumber",{number:this.actionSequence(n)});return{value:`action:${n.id}:${n.generation}`,label:this.$t("workCenter.sendToTarget",{target:r}),sublabel:n.brief?.objective||this.actionLabel(n.type),badge:this.statusLabel(n.status),disabled:!this.canMessageAction(n)}})];return this.composerTargetIsStale?[{value:this.composerTargetValue,label:this.tr("workCenter.targetUnavailable","Selected Action is no longer available"),sublabel:this.tr("workCenter.targetUnavailableHelp","Choose another target before sending. This draft was not redirected."),disabled:!0},...s]:s},composerTargetLabel(){return this.composerTargetAction?this.composerTargetAction.brief?.objective||this.actionLabel(this.composerTargetAction.type):this.tr("workCenter.coordinator","Coordinator")},composerPlaceholder(){return this.composerTargetAction?this.$t("workCenter.actionChatPlaceholder",{name:this.composerTargetLabel}):this.tr("workCenter.conversationPlaceholder","Message about this work item")},composerTargetUnavailable(){return this.coordinatorReadOnly?!0:this.composerTargetIsCoordinator?this.coordinatorThinking:this.composerTargetAction?!this.canMessageAction(this.composerTargetAction):!0},composerCanSend(){return!this.workItemMessageSending&&!this.workItemMessageAttachmentsUploading&&!this.composerTargetUnavailable&&(!!this.workItemMessage.trim()||this.workItemMessageAttachments.length>0)},pendingMessageEnvelope(){return this.selected?.id?this.store.loadWorkCenterMessageEnvelope(this.agentId,this.selected.id):null},composerDraftLocked(){return!!this.pendingMessageEnvelope&&!this.composerTargetIsStale},pendingEnvelopeHasAttachments(){return Array.isArray(this.pendingMessageEnvelope?.attachments)&&this.pendingMessageEnvelope.attachments.length>0},pendingEnvelopeAttachmentRecovery(){return this.composerDraftLocked&&this.pendingEnvelopeHasAttachments},actionMessageKey(){return this.selected?.id&&this.selectedAction?.id?fn(this.agentId,this.selected.id,this.selectedAction.id,this.selectedAction.generation):""},workItemComposerScope(){return this.selected?.id?`${this.agentId}:${this.selected.id}:${this.workItemComposerGeneration}`:""},conversationBlocks(){return(Array.isArray(this.selected?.messages)?this.selected.messages:[]).map(e=>{let t=Number(e?.updatedAt||e?.createdAt)||0;if(e?.role==="user")return{key:e.id,kind:"user",message:{id:e.id,messageId:e.id,type:"user",content:e.text||"",attachments:Array.isArray(e.attachments)?e.attachments:[],quote:rt(e.quote),timestamp:t}};if(e?.role==="assistant"){let s=e.speaker||{},n=this.workItemMessageSpeaker(e),r=s.id||`work-center-coordinator:${this.selected?.id||"unknown"}`,i=e.status==="thinking"?this.tr("workCenter.conversationThinking","Working\u2026"):e.error||"",o=e.decision?.kind&&e.decision.kind!=="answer"?this.tr(`workCenter.coordinatorDecision.${e.decision.kind}`,e.decision.kind):"",a=[e.text,i,o].filter(Boolean);return{key:e.id,kind:"assistant",speakerName:n,turn:{id:e.id,messageId:e.id,atMessageId:e.id,turnId:e.turnId||e.id,textContent:a.join(`
|
|
6289
6301
|
|
|
6290
|
-
`),textSegments:a.map((l,c)=>({key:`${e.id}:${c}`,content:l,kind:e.status==="thinking"?"progress":"result",isStreaming:e.status==="thinking"})),isStreaming:e.status==="thinking",speakerVpId:r,speakerTimestamp:t,showSpeakerHeader:!0,timestamp:t,createdAt:t,todoMsg:null,toolMsgs:[],toolSummaryCount:0,imageMsgs:[],askMsg:null,attachments:Array.isArray(e.attachments)?e.attachments:[]}}}return{key:e.id,kind:"system",message:e}})},coordinatorThinking(){return(this.selected?.messages||[]).some(e=>e?.role==="assistant"&&e.status==="thinking")},coordinatorReadOnly(){return["done","cancelled"].includes(this.selected?.status)},actionMessages(){let e=Array.isArray(this.selectedAction?.messages)?this.selectedAction.messages:[],t=(Array.isArray(this.selectedAction?.thread)?this.selectedAction.thread:[]).flatMap(o=>Array.isArray(o?.messages)?o.messages:[]),s=this.store.workCenterActionMessages[this.actionMessageKey]?.messages||[],n=mr(t,s,e),r=this.selectedAction?.liveMessage,i=r&&n.some(o=>o.role==="assistant"&&o.runId!=null&&o.runId===r.runId&&(r.status==="running"?o.text===r.text:o.status!=="running"));return mr(n,i?null:r)},actionMessagesNextCursor(){let e=this.store.workCenterActionMessages[this.actionMessageKey];return e?e.nextCursor:this.selectedAction?.messageCursor},actionMessagesLoading(){return!!this.store.workCenterActionMessagesLoading[this.actionMessageKey]},actionMessagesError(){return this.store.workCenterActionMessagesError[this.actionMessageKey]||""},orderedActions(){let e=Array.isArray(this.selected?.actions)?this.selected.actions:[],t={running:0,waiting:1,failed:2,ready:3,completed:4,done:4,closed:5,superseded:6,cancelled:7};return e.map((s,n)=>({action:s,index:n})).sort((s,n)=>{let r=t[s.action?.status]??7,i=t[n.action?.status]??7;if(r!==i)return r-i;let o=Number(s.action?.sequence),a=Number(n.action?.sequence);return Number.isFinite(o)&&Number.isFinite(a)&&o!==a?o-a:s.index-n.index}).map(s=>s.action)},boardLanes(){return[{id:"active",title:this.tr("workCenter.board.active","Active")},{id:"needs_attention",title:this.tr("workCenter.board.needsAttention","Needs attention")},{id:"closed",title:this.tr("workCenter.board.closed","Closed")}].map(e=>({...e,items:this.items.filter(t=>t.boardLane===e.id)}))},boardExecutorOptions(){let e=new Map;for(let t of this.items)for(let s of Array.isArray(t.executors)?t.executors:[])s?.id&&e.set(s.id,s.name||s.id);return[...e.entries()].map(([t,s])=>({id:t,name:s}))},boardTypeOptions(){return[...new Set(this.items.map(e=>e.workItemType).filter(Boolean))].sort()},emptyState(){return{title:this.search.trim()?this.tr("workCenter.noMatchesTitle","No matching work items"):this.tr("workCenter.emptyTitle","No work items yet"),body:this.search.trim()?this.tr("workCenter.noMatchesBody","Try a different search or filter."):this.tr("workCenter.emptyBody","Create a persistent task when work must continue beyond one conversation turn."),canCreate:!this.search.trim()}}},watch:{agentId:{immediate:!0,handler(e,t){Fo(this),this.createGeneration=(Number(this.createGeneration)||0)+1,this.saving=!1,this.selectedId=null,this.selectedActionId=null,this.contentPanelOpen=!1,this.resetWorkItemComposer?.(),this.resetContentStack?.(),this.composerTargetValue="coordinator",this.narrowPane="items",this.previewingAttachmentId=null,this.attachmentPreviewError="",this.attachmentPreviewGeneration=(Number(this.attachmentPreviewGeneration)||0)+1,t&&e!==t&&(this.closeFolderPicker(),this.resetCreateExecutionContext(e)),e&&((typeof this.boardFilters=="function"?this.store.listWorkItems(e,this.boardFilters()):this.store.listWorkItems(e)).catch(()=>{}),this.store.loadWorkCenterSettings(e).catch(()=>{}))}},createDefaultWorkDir(){this.applyCreateDefaults()},createDefaultStart(){this.applyCreateDefaults()},search(){this.scheduleBoardQuery()},boardVpId(){this.scheduleBoardQuery()},boardWorkItemType(){this.scheduleBoardQuery()},boardUpdatedRange(){this.scheduleBoardQuery()},"detail.coordinatorRevision"(){this.$nextTick(()=>{let e=this.$el?.querySelector?.(".work-center-conversation-scroll");e&&(e.scrollTop=e.scrollHeight)})},pendingMessageEnvelope(e,t){if(!(!t||e||t.workItemId!==this.selectedId)){if(this.preserveComposerOnEnvelopeClear){this.preserveComposerOnEnvelopeClear=!1,this.workItemMessageError="",this.workItemMessageSending=!1;return}this.workItemMessage="",this.workItemMessageQuote=null,this.workItemMessageAttachments=[],this.workItemMessageError="",this.workItemMessageSending=!1}},detail:{deep:!0,handler(e){if(!e||e.id!==this.selectedId)return;let t=Array.isArray(e.actions)?e.actions:[];this.selectedActionId&&!t.some(s=>s.id===this.selectedActionId)&&(this.selectedActionId=null,this.contentPanelOpen=!1,this.resetContentStack(),this.syncWorkCenterUrl(!0),this.previewingAttachmentId=null,this.attachmentPreviewError="",this.attachmentPreviewGeneration=(Number(this.attachmentPreviewGeneration)||0)+1),this.composerTargetAction==null&&this.composerTargetValue!=="coordinator"?this.staleComposerTarget=this.composerTargetValue:this.staleComposerTarget=null}}},beforeUnmount(){Fo(this),this.boardQueryTimer&&clearTimeout(this.boardQueryTimer),window.removeEventListener("popstate",this.restoreWorkCenterUrl)},mounted(){window.addEventListener("popstate",this.restoreWorkCenterUrl),this.restoreWorkCenterUrl();let e=this.store.workCenterCreateDraft;e&&(this.form={requirement:e.requirement||e.goal||e.title||"",workDir:e.workDir||"",deliveryTarget:e.deliveryTarget||"",reuseMemory:!0,start:this.settings?.startImmediately!==!1},this.createOpen=!0,this.workDirTouched=!!String(e.workDir||"").trim(),this.startTouched=!1,this.applyCreateDefaults())},methods:{tr(e,t){let s=this.$t?this.$t(e):e;return s&&s!==e?s:t},selectWorkCenterAgent(e){!e||e===this.agentId||this.store.enterWorkCenter(e)},statusLabel(e){return this.tr(`workCenter.status.${e}`,String(e||"").replace("_"," "))},actionLabel(e){return this.tr(`workCenter.action.${e}`,e||"\u2014")},messageSpeakerRole(e,t){return e?this.$t("workCenter.messageSpeakerRole",{name:e,role:t}):t},workItemMessageSpeaker(e){if(e?.role==="user")return this.tr("workCenter.you","You");if(e?.role==="legacy_instruction")return this.tr("workCenter.originalRequest","Original request");let t=e?.speaker?.name||e?.speaker?.id||"";return this.messageSpeakerRole(t,this.tr("workCenter.coordinator","Coordinator"))},quoteWorkItemMessage(e){let t=rt(e);t&&(this.workItemMessageQuote=t,this.saveComposerDraft(),this.$nextTick(()=>this.$refs.workItemComposer?.getTextarea?.()?.focus?.()))},removeWorkItemMessageQuote(){this.workItemMessageQuote=null,this.saveComposerDraft()},editWorkItemMessageAsNew(e){this.workItemMessageQuote=null,this.workItemMessage=String(e||""),this.saveComposerDraft(),this.$nextTick(()=>{let t=this.$refs.workItemComposer?.getTextarea?.();t?.focus?.();let s=t?.value?.length||0;t?.setSelectionRange?.(s,s)})},openConversationAttachment(e){return this.previewAttachment(e?.attachment||e,e?.trigger||null)},actionSequence(e){let t=Number(e?.sequence);if(Number.isFinite(t)&&t>0)return t;let n=(Array.isArray(this.selected?.actions)?this.selected.actions:[]).findIndex(r=>r?.id===e?.id);return n>=0?n+1:1},actionBreadcrumbDescription(e){return String(e?.brief?.objective||e?.objective||this.actionContentSummary(e)||"").trim().replace(/\s+/g," ")||this.tr("workCenter.untitledAction","Untitled Action")},itemActionProgress(e){let t=Math.max(0,Number(e?.actionCount)||0),s=Math.min(t,Math.max(0,Number(e?.completedActionCount)||0));return this.$t("workCenter.actionProgress",{completed:s,total:t})},time(e){if(!e)return"";try{return new Date(Number(e)).toLocaleString()}catch{return""}},onWorkItemMessageInput(){this.saveComposerDraft()},onWorkItemMessageKeydown(e){e.key!=="Enter"||e.shiftKey||e.isComposing||(e.preventDefault(),this.sendSelectedWorkItemMessage())},boardFilters(){let e=Date.now(),t=this.boardUpdatedRange==="day"?e-1440*60*1e3:this.boardUpdatedRange==="week"?e-10080*60*1e3:this.boardUpdatedRange==="month"?e-720*60*60*1e3:null;return{keyword:this.search.trim(),vpId:this.boardVpId,workItemType:this.boardWorkItemType,updatedFrom:t,limit:200}},scheduleBoardQuery(){this.boardQueryTimer&&clearTimeout(this.boardQueryTimer),this.boardQueryTimer=setTimeout(()=>{this.boardQueryTimer=null,this.agentId&&this.refresh()},180)},refresh(){return this.store.listWorkItems(this.agentId,this.boardFilters()).catch(()=>{})},refreshWorkCenterRuntime(e){if(!(!e||e!==this.agentId))return this.store.refreshWorkCenterRuntime(e).catch(()=>{})},loadMoreBoardItems(){return this.store.loadMoreWorkItems(this.agentId).catch(()=>{})},boardAction(e){return e.attentionAction||e.activeAction||e.currentAction||null},boardActionCountLabel(e){let t=e.actionCounts||{},s=[];for(let n of["running","failed","waiting","ready"])Number(t[n])>0&&s.push(`${t[n]} ${this.statusLabel(n)}`);return s.join(" \xB7 ")||this.itemActionProgress(e)},boardExecutorLabel(e){let t=Array.isArray(e.executors)?e.executors:[];if(t.length>0)return t.map(n=>n.name||n.id).join(", ");let s=this.boardAction(e);return s?.assignedVp?.name||s?.assignedVp?.id||this.tr("workCenter.assignment.planned","Planned assignment")},sameContentRef(e,t){return e?.type===t?.type&&e?.actionId===t?.actionId&&e?.runId===t?.runId&&e?.resourceId===t?.resourceId},resetContentStack(e=[{type:"action-list"}]){let t=Array.isArray(e)?e:[e],s=t[0]?.type==="action-list"?t:[{type:"action-list"},...t];this.contentStack=s.length>0?s:[{type:"action-list"}];let n=[...this.contentStack].reverse().find(r=>r.type==="action");this.selectedActionId=this.contentRef.actionId||n?.actionId||null},openContentPanel({syncUrl:e=!0}={}){this.contentPanelOpen=!0,e&&this.syncWorkCenterUrl()},closeContentPanel({syncUrl:e=!0}={}){this.contentPanelOpen=!1,this.resetContentStack(),e&&this.syncWorkCenterUrl(),this.$nextTick(()=>this.$refs.actionsButton?.focus?.())},pushContentRef(e,{replace:t=!1,syncUrl:s=!0}={}){let n=this.contentRef;if(this.contentPanelOpen=!0,this.sameContentRef(n,e)){s&&this.syncWorkCenterUrl(t);return}this.contentStack=e.type==="action-list"?[{type:"action-list"}]:[...this.contentStack,e],this.selectedActionId=e.actionId||this.selectedActionId,s&&this.syncWorkCenterUrl(t)},popContentRef(){if(this.contentStack.length<=1)return;this.contentStack=this.contentStack.slice(0,-1);let e=[...this.contentStack].reverse().find(t=>t.type==="action");this.selectedActionId=e?.actionId||null,this.syncWorkCenterUrl()},contentRefParam(e){return e.type==="action"&&e.actionId?`action:${e.actionId}`:e.type==="run"&&e.actionId&&e.runId?`run:${e.actionId}:${e.runId}`:e.type==="attachment"&&e.resourceId?`attachment:${e.actionId||"-"}:${e.resourceId}`:"action-list"},contentStackParam(){return this.contentStack.map(e=>this.contentRefParam(e)).join("/")},parseContentRef(e){let t=String(e||"");if(t==="action-list")return{type:"action-list"};if(t.startsWith("action:"))return{type:"action",actionId:t.slice(7)};if(t.startsWith("run:")){let[,s,n]=t.split(":");return{type:"run",actionId:s,runId:n}}if(t.startsWith("attachment:")){let[,s,n]=t.split(":");return{type:"attachment",actionId:s==="-"?null:s,resourceId:n}}return{type:"action-list"}},parseContentStack(e){let s=[...String(e||"").split("/").filter(Boolean).map(n=>this.parseContentRef(n))].reverse().find(n=>n.actionId&&["action","run","attachment"].includes(n.type));return s?[{type:"action-list"},{type:"action",actionId:s.actionId}]:[{type:"action-list"}]},workCenterUrlRoute(){let e=new URLSearchParams(window.location.search);return{agentId:e.get("workAgentId"),itemId:e.get("workItemId"),content:e.has("workContent")?e.get("workContent"):null}},sameWorkCenterUrlRoute(e,t){return e?.agentId===t?.agentId&&e?.itemId===t?.itemId&&e?.content===t?.content},syncWorkCenterUrl(e=!1){Fo(this);let t=new URL(window.location.href);this.selectedId?(t.searchParams.set("workAgentId",this.agentId||""),t.searchParams.set("workItemId",this.selectedId),this.contentPanelOpen?t.searchParams.set("workContent",this.contentStackParam()):t.searchParams.delete("workContent")):(t.searchParams.delete("workAgentId"),t.searchParams.delete("workItemId"),t.searchParams.delete("workContent"));let s=`${t.pathname}${t.search}${t.hash}`;if(`${window.location.pathname}${window.location.search}${window.location.hash}`===s)return;let n={...window.history.state,workCenter:!!this.selectedId,workCenterContent:!!this.selectedId&&this.contentPanelOpen};window.history[e?"replaceState":"pushState"](n,"",s)},async restoreWorkCenterUrl(){let e=Fo(this),t=this.workCenterUrlRoute(),s=()=>e===this.workCenterUrlRestoreGeneration&&this.sameWorkCenterUrlRoute(t,this.workCenterUrlRoute()),n=t.agentId,r=t.itemId;if(!r||n&&n!==this.agentId){this.selectedId&&this.showItemsPane({syncUrl:!1});return}let i=t.content!=null,o=this.parseContentStack(t.content),a=o.at(-1);if(this.selectedId!==r||this.detail?.id!==r){this.openWorkItem(r,{syncUrl:!1,contentRefs:o,contentOpen:i}),this.detailLoading=!0;try{await this.store.getWorkItem(r,this.agentId)}catch(c){s()&&(this.detailError=c?.message||String(c))}finally{s()&&(this.detailLoading=!1)}}if(!s())return;let l=a.actionId||[...o].reverse().find(c=>c.type==="action")?.actionId;if(l&&!this.selected?.actions?.some(c=>c.id===l)){this.resetContentStack(),this.syncWorkCenterUrl(!0);return}this.resetContentStack(o),this.contentPanelOpen=i,this.narrowPane="work-item",i&&l&&this.loadLatestActionMessages(this.selectedAction),i&&t.content!==this.contentStackParam()&&this.syncWorkCenterUrl(!0)},resetWorkItemComposer(){this.workItemComposerGeneration+=1,this.workItemMessage="",this.workItemMessageQuote=null,this.workItemMessageAttachments=[],this.workItemMessageAttachmentsUploading=!1,this.workItemMessageError="",this.workItemMessageSending=!1},draftTarget(){let e=this.composerTargetAction;return e?{kind:"action",actionId:e.id,generation:Number(e.generation)}:this.composerTargetValue==="coordinator"?{kind:"coordinator"}:(()=>{let[,t="",s="0"]=this.composerTargetValue.split(":");return{kind:"action",actionId:t,generation:Number(s)||0}})()},targetValue(e){return typeof e=="string"&&e.startsWith("action:")?e:e?.kind==="action"?`action:${e.actionId}:${e.generation}`:"coordinator"},saveComposerDraft(){!this.selectedId||!this.agentId||this.store.saveWorkCenterComposerDraft(this.agentId,this.selectedId,{text:this.workItemMessage,quote:this.workItemMessageQuote,attachments:[...this.workItemMessageAttachments],target:this.draftTarget(),error:this.workItemMessageError})},restoreComposerDraft(e){let s=this.store.loadWorkCenterMessageEnvelope(this.agentId,e)||this.store.loadWorkCenterComposerDraft(this.agentId,e);this.workItemMessage=s?.text||"",this.workItemMessageQuote=rt(s?.quote),this.workItemMessageAttachments=[...s?.attachments||[]],this.composerTargetValue=this.targetValue(s?.target),this.workItemMessageError=s?.error||"",this.staleComposerTarget=null,this.workItemMessageSending=!1,this.workItemMessageAttachmentsUploading=!1,this.workItemComposerGeneration+=1},openWorkItem(e,{syncUrl:t=!0,contentRefs:s=[{type:"action-list"}],contentOpen:n=!1}={}){this.saveComposerDraft(),this.selectedId=e,this.narrowPane="work-item",this.contentPanelOpen=n,this.resetContentStack(s),this.restoreComposerDraft(e),this.detailError="",this.detailLoading=!1,this.previewingAttachmentId=null,this.attachmentPreviewError="",this.attachmentPreviewGeneration=(Number(this.attachmentPreviewGeneration)||0)+1,t&&this.syncWorkCenterUrl()},async selectItem(e){this.openWorkItem(e.id),this.detailLoading=!0;try{await this.store.getWorkItem(e.id,this.agentId)}catch(t){this.selectedId===e.id&&(this.detailError=t?.message||String(t))}finally{this.selectedId===e.id&&(this.detailLoading=!1)}},selectAction(e){this.selectedActionId!==e.id&&(this.previewingAttachmentId=null,this.attachmentPreviewError="",this.attachmentPreviewGeneration=(Number(this.attachmentPreviewGeneration)||0)+1),this.pushContentRef({type:"action",actionId:e.id}),this.loadLatestActionMessages(e)},loadLatestActionMessages(e=this.selectedAction){if(!this.selected?.id||!e?.id||Array.isArray(e.messages))return null;let t=fn(this.agentId,this.selected.id,e.id,e.generation);return this.store.workCenterActionMessages[t]?null:this.store.loadWorkItemActionMessages(this.selected.id,e.id,e.generation,null,this.agentId).catch(()=>null)},showItemsPane({syncUrl:e=!0}={}){this.saveComposerDraft(),this.narrowPane="items",this.selectedId=null,this.contentPanelOpen=!1,this.resetContentStack(),this.composerTargetValue="coordinator",this.resetWorkItemComposer(),e&&this.syncWorkCenterUrl()},showActionsPane(){this.contentPanelOpen=!0,this.contentIsActionList?this.syncWorkCenterUrl():this.popContentRef()},canMessageAction(e){return!e||["done","cancelled"].includes(this.selected?.status)?!1:["idle","ready","running","paused","waiting","failed","completed","stopped"].includes(e.status)&&e.admissionStatus!=="blocked"},clearPendingMessageEnvelope({preserveAttachments:e=!1}={}){return!this.selectedId||!this.pendingMessageEnvelope?!1:(this.actionInputRequestGeneration=(Number(this.actionInputRequestGeneration)||0)+1,this.preserveComposerOnEnvelopeClear=!0,this.store.discardWorkCenterMessageEnvelope(this.agentId,this.selectedId)?(e||(this.workItemMessageAttachments=[]),this.workItemMessageError="",this.workItemMessageSending=!1,!0):(this.preserveComposerOnEnvelopeClear=!1,!1))},chooseCoordinatorTarget(){this.pendingMessageEnvelope&&!this.clearPendingMessageEnvelope({preserveAttachments:!0})||(this.composerTargetValue="coordinator",this.staleComposerTarget=null,this.saveComposerDraft())},onComposerTargetChange(){this.pendingMessageEnvelope&&!this.clearPendingMessageEnvelope({preserveAttachments:!0})||(this.staleComposerTarget=this.composerTargetAction==null&&this.composerTargetValue!=="coordinator"?this.composerTargetValue:null,this.saveComposerDraft())},loadEarlierActionMessages(){return!this.selected?.id||!this.selectedAction?.id||this.actionMessagesNextCursor==null?null:this.store.loadWorkItemActionMessages(this.selected.id,this.selectedAction.id,this.selectedAction.generation,this.actionMessagesNextCursor,this.agentId).catch(()=>null)},actionExecutor(e){return e?.assignedVp?.name||e?.assignedVp?.id||e?.requiredRole||e?.assignmentPolicy?.fixedVpId||e?.assignmentPolicy?.capability||this.tr("workCenter.assignment.auto","Auto")},actionContentSummary(e){return String(e?.contentSummary||e?.response||e?.brief?.objective||"").trim()},executionStats(e){return e?.executionStats||{}},formatCount(e){return new Intl.NumberFormat().format(Math.max(0,Number(e)||0))},formatTokens(e){let t=Math.max(0,Number(e)||0);return t>=1e6?`${(t/1e6).toFixed(1)}m`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)},resetCreateExecutionContext(e){let t=this.workDirTouched||this.startTouched,s=this.store.workCenterCreateDraft;s&&(this.store.workCenterCreateDraft={sourceAgentId:e||null,requirement:s.requirement||s.goal||s.title||"",workDir:"",deliveryTarget:s.deliveryTarget||"",origin:null,linkedSessionIds:[]}),this.form.workDir="",this.form.start=!0,this.workDirTouched=!1,this.startTouched=!1,t&&(this.createOpen=!1),this.applyCreateDefaults()},applyCreateDefaults(){this.createOpen&&(!this.workDirTouched&&!this.form.workDir.trim()&&(this.form.workDir=this.createDefaultWorkDir),this.startTouched||(this.form.start=this.createDefaultStart))},folderPickerInitialDir(){return this.form.workDir.trim()||this.createDefaultWorkDir},folderPickerSetWorkDir(e){this.form.workDir=e,this.workDirTouched=!0},onCreateWorkDirInput(){this.workDirTouched=!0},onCreateStartInput(){this.startTouched=!0},async onCreateAttachmentInput(e){if(!this.workItemAttachmentsSupported)throw e.target.value="",new Error(this.tr("workCenter.attachmentsUnsupported","The selected Agent does not support Work Item attachments."));let t=Array.from(e.target.files||[]);if(e.target.value="",t.length===0)return;let s=Math.max(0,10-this.createAttachments.length),n=t.slice(0,s);if(n.length!==0){this.attachmentsUploading=!0;try{let r=new FormData;for(let d of n)r.append("files",d,d.name||"attachment");let i=Pinia.useAuthStore(),o=i.getActiveToken?.()||i.token||null,a=o?{Authorization:`Bearer ${o}`}:{},l=await fetch("/api/upload",{method:"POST",headers:a,body:r});if(!l.ok)throw new Error(this.tr("workCenter.attachmentsUploadFailed","Attachment upload failed"));let c=await l.json();this.createAttachments=[...this.createAttachments,...Array.isArray(c.files)?c.files:[]].slice(0,10)}finally{this.attachmentsUploading=!1}}},removeCreateAttachment(e){this.createAttachments=this.createAttachments.filter((t,s)=>s!==e)},discardPendingMessageEnvelope(){this.clearPendingMessageEnvelope()&&this.saveComposerDraft()},async onWorkItemMessageAttachmentInput(e){if(!this.workItemAttachmentsSupported){e.target.value="",this.workItemMessageError=this.tr("workCenter.attachmentsUnsupported","The selected Agent does not support Work Item attachments.");return}let t=Array.from(e.target.files||[]);if(e.target.value="",t.length===0)return;let s=this.workItemComposerScope;if(!s)return;let n=this.pendingEnvelopeAttachmentRecovery,r=Array.isArray(this.selected?.attachments)?this.selected.attachments.length:0,i=Math.max(0,10-r-(n?0:this.workItemMessageAttachments.length)),o=t.slice(0,i);if(o.length!==0){this.workItemMessageAttachmentsUploading=!0,this.workItemMessageError="";try{let a=new FormData;for(let g of o)a.append("files",g,g.name||"attachment");let l=Pinia.useAuthStore(),c=l.getActiveToken?.()||l.token||null,d=c?{Authorization:`Bearer ${c}`}:{},u=await fetch("/api/upload",{method:"POST",headers:d,body:a});if(!u.ok)throw new Error(this.tr("workCenter.attachmentsUploadFailed","Attachment upload failed"));let p=await u.json();if(this.workItemComposerScope!==s)return;let f=(Array.isArray(p.files)?p.files:[]).slice(0,Math.max(0,10-r));if(n){let g=this.store.replaceWorkCenterMessageEnvelopeAttachments(this.agentId,this.selectedId,f);if(!g)throw new Error(this.tr("workCenter.pendingEnvelopeChanged","The pending request changed; reopen this Work Item and try again."));this.workItemMessageAttachments=[...g.attachments],this.workItemMessageError=""}else this.workItemMessageAttachments=[...this.workItemMessageAttachments,...f].slice(0,Math.max(0,10-r)),this.saveComposerDraft()}catch(a){this.workItemComposerScope===s&&(this.workItemMessageError=a?.message||String(a))}finally{this.workItemComposerScope===s&&(this.workItemMessageAttachmentsUploading=!1)}}},removeWorkItemMessageAttachment(e){this.workItemMessageAttachments=this.workItemMessageAttachments.filter((t,s)=>s!==e),this.saveComposerDraft()},async previewAttachment(e,t=null){if(!this.selected?.id||!e?.id||this.previewingAttachmentId)return;let s=this.agentId,n=this.selected.id,r=this.selectedActionId||"",i=`${s}:${n}:${r}`,o=(Number(this.attachmentPreviewGeneration)||0)+1;this.attachmentPreviewGeneration=o;let a=()=>this.attachmentPreviewGeneration===o&&`${this.agentId}:${this.selected?.id||""}:${this.selectedActionId||""}`===i,l=e.isImage?null:window.open("","_blank");if(!e.isImage&&!l){this.attachmentPreviewError=this.tr("workCenter.attachmentOpenBlocked","The browser blocked the attachment window. Allow pop-ups and try again.");return}l&&(l.opener=null),this.previewingAttachmentId=e.id,this.attachmentPreviewError="";try{let c=await this.store.previewWorkItemAttachment(n,e.id,s);if(!a()){l?.close();return}c?.preview&&c.attachment?.isImage?bn(c.preview,{alt:e.name||this.tr("workCenter.previewAttachment","Open attachment"),closeLabel:this.tr("common.close","Close"),trigger:t}):c?.preview&&l?l.location.replace(c.preview):l?.close()}catch(c){l?.close(),a()&&(this.attachmentPreviewError=c?.message||this.tr("workCenter.attachmentPreviewFailed","Could not open the attachment. Try again."))}finally{a()&&(this.previewingAttachmentId=null)}},isExternalOutput(e){return["link","pr"].includes(e?.kind)&&/^https?:\/\//i.test(String(e?.ref||""))},formatAttachmentSize(e){let t=Math.max(0,Number(e)||0);return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`},openCreate(){this.createOpen=!0,this.workDirTouched=!1,this.startTouched=!1,this.applyCreateDefaults()},closeCreate(){this.saving||(this.closeFolderPicker(),this.createOpen=!1,this.store.workCenterCreateDraft=null)},async submitCreate(){let e=String(this.form.requirement||this.form.goal||this.form.title||"").trim();if(!e||!this.form.workDir.trim())return;let t=this.agentId,s=(Number(this.createGeneration)||0)+1;this.createGeneration=s,this.saving=!0;try{let n=this.store.workCenterCreateDraft,r=n?.sourceAgentId===t,i=await this.store.createWorkItem({requirement:e,title:e,goal:e,acceptanceCriteria:[],workItemType:"auto",workDir:this.form.workDir.trim(),deliveryTarget:this.form.deliveryTarget||null,origin:r&&n.origin||null,linkedSessionIds:r?n.linkedSessionIds||[]:[],attachments:this.workItemAttachmentsSupported?(this.createAttachments||[]).map(o=>({fileId:o.fileId,name:o.name,mimeType:o.mimeType,size:o.size})):[],reuseMemory:this.form.reuseMemory,start:this.form.start},t);if(this.agentId!==t||this.createGeneration!==s)return;this.openWorkItem(i.id),this.form={requirement:"",workDir:"",deliveryTarget:"",reuseMemory:!0,start:this.settings?.startImmediately!==!1},this.store.workCenterCreateDraft=null,this.createAttachments=[],this.workDirTouched=!1,this.startTouched=!1,this.createOpen=!1}finally{this.agentId===t&&this.createGeneration===s&&(this.saving=!1)}},async startSelected(){this.selected&&await this.store.startWorkItem(this.selected.id,this.agentId)},async sendSelectedWorkItemMessage(){if(!this.selected||!this.composerCanSend)return;let e=this.workItemComposerScope,t=this.composerTargetValue,s=this.composerTargetAction;if(!this.composerTargetIsCoordinator&&!s)return;let n=this.selected.id,r=this.selected.revision,i=this.workItemMessage.trim(),o=rt(this.workItemMessageQuote),a=this.workItemMessageAttachments.map(c=>({fileId:c.fileId,name:c.name,mimeType:c.mimeType,size:c.size})),l=(Number(this.actionInputRequestGeneration)||0)+1;this.actionInputRequestGeneration=l,this.workItemMessageSending=!0,this.workItemMessageError="",this.saveComposerDraft();try{let c={planRevision:this.selected.planRevision,ledgerRevision:this.selected.ledgerRevision,coordinatorRevision:this.selected.coordinatorRevision};this.canonicalMessageWireSupported?await this.store.postWorkItemMessage(n,i,s?{kind:"action",actionId:s.id,generation:s.generation}:{kind:"coordinator"},r,a,this.agentId,c,o):s?await this.store.sendWorkItemActionInput(n,i,s.id,r,s.generation,a,this.agentId,o):await this.store.sendWorkItemMessage(n,i,r,a,this.agentId,c,o),this.workItemComposerScope===e&&this.actionInputRequestGeneration===l&&this.composerTargetValue===t&&this.workItemMessage.trim()===i&&!this.store.loadWorkCenterMessageEnvelope(this.agentId,n)&&(this.workItemMessage="",this.workItemMessageQuote=null,this.workItemMessageAttachments=[],this.store.removeWorkCenterComposerDraft(this.agentId,n))}catch(c){this.workItemComposerScope===e&&this.actionInputRequestGeneration===l&&(this.workItemMessageError=c?.message||String(c),this.saveComposerDraft())}finally{this.workItemComposerScope===e&&this.actionInputRequestGeneration===l&&(this.workItemMessageSending=!1)}},workItemCanDelete(e){return["done","cancelled","draft","needs_attention"].includes(e?.status)},workItemDeleting(e){return!!this.deletingWorkItemIds[e?.id]},async deleteWorkItem(e){if(!e||this.workItemDeleting(e))return;let t=this.tr("workCenter.deleteConfirm","Permanently delete this Work Item, its execution history, and attachments?");if(await Ee(t,{destructive:!0})){this.deleteWorkItemError="",this.deletingWorkItemIds={...this.deletingWorkItemIds,[e.id]:!0};try{let s=await this.store.deleteWorkItem(e.id,e.revision,this.agentId);s?.cleanupWarning&&(this.deleteWorkItemError=s.cleanupWarning),this.selectedId===e.id&&this.showItemsPane()}catch(s){this.deleteWorkItemError=s?.message||String(s)}finally{let s={...this.deletingWorkItemIds};delete s[e.id],this.deletingWorkItemIds=s}}},async cancelSelected(){if(!this.selected||["done","cancelled"].includes(this.selected.status))return;let e=this.tr("workCenter.cancelConfirm","Stop this work item and its unfinished Actions?");await Ee(e,{destructive:!0})&&await this.store.cancelWorkItem(this.selected.id,this.agentId)},async resumeSelected(){!this.selected||this.selected.status!=="cancelled"||await this.store.resumeWorkItem(this.selected.id,this.selected.revision,this.agentId)}},template:`
|
|
6302
|
+
`),textSegments:a.map((l,c)=>({key:`${e.id}:${c}`,content:l,kind:e.status==="thinking"?"progress":"result",isStreaming:e.status==="thinking"})),isStreaming:e.status==="thinking",speakerVpId:r,speakerTimestamp:t,showSpeakerHeader:!0,timestamp:t,createdAt:t,todoMsg:null,toolMsgs:[],toolSummaryCount:0,imageMsgs:[],askMsg:null,attachments:Array.isArray(e.attachments)?e.attachments:[]}}}return{key:e.id,kind:"system",message:e}})},coordinatorThinking(){return(this.selected?.messages||[]).some(e=>e?.role==="assistant"&&e.status==="thinking")},coordinatorReadOnly(){return["done","cancelled"].includes(this.selected?.status)},actionMessages(){let e=Array.isArray(this.selectedAction?.messages)?this.selectedAction.messages:[],t=(Array.isArray(this.selectedAction?.thread)?this.selectedAction.thread:[]).flatMap(o=>Array.isArray(o?.messages)?o.messages:[]),s=this.store.workCenterActionMessages[this.actionMessageKey]?.messages||[],n=mr(t,s,e),r=this.selectedAction?.liveMessage,i=r&&n.some(o=>o.role==="assistant"&&o.runId!=null&&o.runId===r.runId&&(r.status==="running"?o.text===r.text:o.status!=="running"));return mr(n,i?null:r)},actionMessagesNextCursor(){let e=this.store.workCenterActionMessages[this.actionMessageKey];return e?e.nextCursor:this.selectedAction?.messageCursor},actionMessagesLoading(){return!!this.store.workCenterActionMessagesLoading[this.actionMessageKey]},actionMessagesError(){return this.store.workCenterActionMessagesError[this.actionMessageKey]||""},orderedActions(){let e=Array.isArray(this.selected?.actions)?this.selected.actions:[],t={running:0,waiting:1,failed:2,ready:3,completed:4,done:4,closed:5,superseded:6,cancelled:7};return e.map((s,n)=>({action:s,index:n})).sort((s,n)=>{let r=t[s.action?.status]??7,i=t[n.action?.status]??7;if(r!==i)return r-i;let o=Number(s.action?.sequence),a=Number(n.action?.sequence);return Number.isFinite(o)&&Number.isFinite(a)&&o!==a?o-a:s.index-n.index}).map(s=>s.action)},boardLanes(){return[{id:"active",title:this.tr("workCenter.board.active","Active")},{id:"needs_attention",title:this.tr("workCenter.board.needsAttention","Needs attention")},{id:"closed",title:this.tr("workCenter.board.closed","Closed")}].map(e=>({...e,items:this.items.filter(t=>t.boardLane===e.id)}))},boardExecutorOptions(){let e=new Map;for(let t of this.items)for(let s of Array.isArray(t.executors)?t.executors:[])s?.id&&e.set(s.id,s.name||s.id);return[...e.entries()].map(([t,s])=>({id:t,name:s}))},boardTypeOptions(){return[...new Set(this.items.map(e=>e.workItemType).filter(Boolean))].sort()},emptyState(){return{title:this.search.trim()?this.tr("workCenter.noMatchesTitle","No matching work items"):this.tr("workCenter.emptyTitle","No work items yet"),body:this.search.trim()?this.tr("workCenter.noMatchesBody","Try a different search or filter."):this.tr("workCenter.emptyBody","Create a persistent task when work must continue beyond one conversation turn."),canCreate:!this.search.trim()}}},watch:{agentId:{immediate:!0,handler(e,t){Fo(this),this.createGeneration=(Number(this.createGeneration)||0)+1,this.saving=!1,this.selectedId=null,this.selectedActionId=null,this.contentPanelOpen=!1,this.resetWorkItemComposer?.(),this.resetContentStack?.(),this.composerTargetValue="coordinator",this.narrowPane="items",this.previewingAttachmentId=null,this.attachmentPreviewError="",this.attachmentPreviewGeneration=(Number(this.attachmentPreviewGeneration)||0)+1,t&&e!==t&&(this.closeFolderPicker(),this.resetCreateExecutionContext(e)),e&&((typeof this.boardFilters=="function"?this.store.listWorkItems(e,this.boardFilters()):this.store.listWorkItems(e)).catch(()=>{}),this.store.loadWorkCenterSettings(e).catch(()=>{}))}},createDefaultWorkDir(){this.applyCreateDefaults()},createDefaultStart(){this.applyCreateDefaults()},search(){this.scheduleBoardQuery()},boardVpId(){this.scheduleBoardQuery()},boardWorkItemType(){this.scheduleBoardQuery()},boardUpdatedRange(){this.scheduleBoardQuery()},"detail.coordinatorRevision"(){this.$nextTick(()=>{let e=this.$el?.querySelector?.(".work-center-conversation-scroll");e&&(e.scrollTop=e.scrollHeight)})},pendingMessageEnvelope(e,t){if(!(!t||e||t.workItemId!==this.selectedId)){if(this.preserveComposerOnEnvelopeClear){this.preserveComposerOnEnvelopeClear=!1,this.workItemMessageError="",this.workItemMessageSending=!1;return}this.workItemMessage="",this.workItemMessageQuote=null,this.workItemMessageAttachments=[],this.workItemMessageError="",this.workItemMessageSending=!1}},detail:{deep:!0,handler(e){if(!e||e.id!==this.selectedId)return;let t=Array.isArray(e.actions)?e.actions:[];this.selectedActionId&&!t.some(s=>s.id===this.selectedActionId)&&(this.selectedActionId=null,this.contentPanelOpen=!1,this.resetContentStack(),this.syncWorkCenterUrl(!0),this.previewingAttachmentId=null,this.attachmentPreviewError="",this.attachmentPreviewGeneration=(Number(this.attachmentPreviewGeneration)||0)+1),this.composerTargetAction==null&&this.composerTargetValue!=="coordinator"?this.staleComposerTarget=this.composerTargetValue:this.staleComposerTarget=null}}},beforeUnmount(){Fo(this),this.boardQueryTimer&&clearTimeout(this.boardQueryTimer),window.removeEventListener("popstate",this.restoreWorkCenterUrl)},mounted(){window.addEventListener("popstate",this.restoreWorkCenterUrl),this.restoreWorkCenterUrl();let e=this.store.workCenterCreateDraft;e&&(this.form={requirement:e.requirement||e.goal||e.title||"",workDir:e.workDir||"",deliveryTarget:e.deliveryTarget||"",reuseMemory:!0,start:this.settings?.startImmediately!==!1},this.createOpen=!0,this.workDirTouched=!!String(e.workDir||"").trim(),this.startTouched=!1,this.applyCreateDefaults())},methods:{tr(e,t){let s=this.$t?this.$t(e):e;return s&&s!==e?s:t},selectWorkCenterAgent(e){!e||e===this.agentId||this.store.enterWorkCenter(e)},statusLabel(e){return this.tr(`workCenter.status.${e}`,String(e||"").replace("_"," "))},actionLabel(e){return this.tr(`workCenter.action.${e}`,e||"\u2014")},messageSpeakerRole(e,t){return e?this.$t("workCenter.messageSpeakerRole",{name:e,role:t}):t},workItemMessageSpeaker(e){if(e?.role==="user")return this.tr("workCenter.you","You");if(e?.role==="legacy_instruction")return this.tr("workCenter.originalRequest","Original request");let t=e?.speaker?.name||e?.speaker?.id||"";return this.messageSpeakerRole(t,this.tr("workCenter.coordinator","Coordinator"))},quoteWorkItemMessage(e){let t=rt(e);t&&(this.workItemMessageQuote=t,this.saveComposerDraft(),this.$nextTick(()=>this.$refs.workItemComposer?.getTextarea?.()?.focus?.()))},removeWorkItemMessageQuote(){this.workItemMessageQuote=null,this.saveComposerDraft()},editWorkItemMessageAsNew(e){this.workItemMessageQuote=null,this.workItemMessage=String(e||""),this.saveComposerDraft(),this.$nextTick(()=>{let t=this.$refs.workItemComposer?.getTextarea?.();t?.focus?.();let s=t?.value?.length||0;t?.setSelectionRange?.(s,s)})},openConversationAttachment(e){return this.previewAttachment(e?.attachment||e,e?.trigger||null)},actionSequence(e){let t=Number(e?.sequence);if(Number.isFinite(t)&&t>0)return t;let n=(Array.isArray(this.selected?.actions)?this.selected.actions:[]).findIndex(r=>r?.id===e?.id);return n>=0?n+1:1},actionBreadcrumbDescription(e){return String(e?.brief?.objective||e?.objective||this.actionContentSummary(e)||"").trim().replace(/\s+/g," ")||this.tr("workCenter.untitledAction","Untitled Action")},itemActionProgress(e){let t=Math.max(0,Number(e?.actionCount)||0),s=Math.min(t,Math.max(0,Number(e?.completedActionCount)||0));return this.$t("workCenter.actionProgress",{completed:s,total:t})},time(e){if(!e)return"";try{return new Date(Number(e)).toLocaleString()}catch{return""}},onWorkItemMessageInput(){this.saveComposerDraft()},onWorkItemMessageKeydown(e){e.key!=="Enter"||e.shiftKey||e.isComposing||(e.preventDefault(),this.sendSelectedWorkItemMessage())},boardFilters(){let e=Date.now(),t=this.boardUpdatedRange==="day"?e-1440*60*1e3:this.boardUpdatedRange==="week"?e-10080*60*1e3:this.boardUpdatedRange==="month"?e-720*60*60*1e3:null;return{keyword:this.search.trim(),vpId:this.boardVpId,workItemType:this.boardWorkItemType,updatedFrom:t,limit:200}},scheduleBoardQuery(){this.boardQueryTimer&&clearTimeout(this.boardQueryTimer),this.boardQueryTimer=setTimeout(()=>{this.boardQueryTimer=null,this.agentId&&this.refresh()},180)},refresh(){return this.store.listWorkItems(this.agentId,this.boardFilters()).catch(()=>{})},refreshWorkCenterRuntime(e){if(!(!e||e!==this.agentId))return this.store.refreshWorkCenterRuntime(e).catch(()=>{})},loadMoreBoardItems(){return this.store.loadMoreWorkItems(this.agentId).catch(()=>{})},boardAction(e){return e.attentionAction||e.activeAction||e.currentAction||null},boardActionCountLabel(e){let t=e.actionCounts||{},s=[];for(let n of["running","failed","waiting","ready"])Number(t[n])>0&&s.push(`${t[n]} ${this.statusLabel(n)}`);return s.join(" \xB7 ")||this.itemActionProgress(e)},boardExecutorLabel(e){let t=Array.isArray(e.executors)?e.executors:[];if(t.length>0)return t.map(n=>n.name||n.id).join(", ");let s=this.boardAction(e);return s?.assignedVp?.name||s?.assignedVp?.id||this.tr("workCenter.assignment.planned","Planned assignment")},sameContentRef(e,t){return e?.type===t?.type&&e?.actionId===t?.actionId&&e?.runId===t?.runId&&e?.resourceId===t?.resourceId},resetContentStack(e=[{type:"action-list"}]){let t=Array.isArray(e)?e:[e],s=t[0]?.type==="action-list"?t:[{type:"action-list"},...t];this.contentStack=s.length>0?s:[{type:"action-list"}];let n=[...this.contentStack].reverse().find(r=>r.type==="action");this.selectedActionId=this.contentRef.actionId||n?.actionId||null},openContentPanel({syncUrl:e=!0}={}){this.contentPanelOpen=!0,e&&this.syncWorkCenterUrl()},closeContentPanel({syncUrl:e=!0}={}){this.contentPanelOpen=!1,this.resetContentStack(),e&&this.syncWorkCenterUrl(),this.$nextTick(()=>this.$refs.actionsButton?.focus?.())},pushContentRef(e,{replace:t=!1,syncUrl:s=!0}={}){let n=this.contentRef;if(this.contentPanelOpen=!0,this.sameContentRef(n,e)){s&&this.syncWorkCenterUrl(t);return}this.contentStack=e.type==="action-list"?[{type:"action-list"}]:[...this.contentStack,e],this.selectedActionId=e.actionId||this.selectedActionId,s&&this.syncWorkCenterUrl(t)},popContentRef(){if(this.contentStack.length<=1)return;this.contentStack=this.contentStack.slice(0,-1);let e=[...this.contentStack].reverse().find(t=>t.type==="action");this.selectedActionId=e?.actionId||null,this.syncWorkCenterUrl()},contentRefParam(e){return e.type==="action"&&e.actionId?`action:${e.actionId}`:e.type==="run"&&e.actionId&&e.runId?`run:${e.actionId}:${e.runId}`:e.type==="attachment"&&e.resourceId?`attachment:${e.actionId||"-"}:${e.resourceId}`:"action-list"},contentStackParam(){return this.contentStack.map(e=>this.contentRefParam(e)).join("/")},parseContentRef(e){let t=String(e||"");if(t==="action-list")return{type:"action-list"};if(t.startsWith("action:"))return{type:"action",actionId:t.slice(7)};if(t.startsWith("run:")){let[,s,n]=t.split(":");return{type:"run",actionId:s,runId:n}}if(t.startsWith("attachment:")){let[,s,n]=t.split(":");return{type:"attachment",actionId:s==="-"?null:s,resourceId:n}}return{type:"action-list"}},parseContentStack(e){let s=[...String(e||"").split("/").filter(Boolean).map(n=>this.parseContentRef(n))].reverse().find(n=>n.actionId&&["action","run","attachment"].includes(n.type));return s?[{type:"action-list"},{type:"action",actionId:s.actionId}]:[{type:"action-list"}]},workCenterUrlRoute(){let e=new URLSearchParams(window.location.search);return{agentId:e.get("workAgentId"),itemId:e.get("workItemId"),content:e.has("workContent")?e.get("workContent"):null}},sameWorkCenterUrlRoute(e,t){return e?.agentId===t?.agentId&&e?.itemId===t?.itemId&&e?.content===t?.content},syncWorkCenterUrl(e=!1){Fo(this);let t=new URL(window.location.href);this.selectedId?(t.searchParams.set("workAgentId",this.agentId||""),t.searchParams.set("workItemId",this.selectedId),this.contentPanelOpen?t.searchParams.set("workContent",this.contentStackParam()):t.searchParams.delete("workContent")):(t.searchParams.delete("workAgentId"),t.searchParams.delete("workItemId"),t.searchParams.delete("workContent"));let s=`${t.pathname}${t.search}${t.hash}`;if(`${window.location.pathname}${window.location.search}${window.location.hash}`===s)return;let n={...window.history.state,workCenter:!!this.selectedId,workCenterContent:!!this.selectedId&&this.contentPanelOpen};window.history[e?"replaceState":"pushState"](n,"",s)},async restoreWorkCenterUrl(){let e=Fo(this),t=this.workCenterUrlRoute(),s=()=>e===this.workCenterUrlRestoreGeneration&&this.sameWorkCenterUrlRoute(t,this.workCenterUrlRoute()),n=t.agentId,r=t.itemId;if(!r||n&&n!==this.agentId){this.selectedId&&this.showItemsPane({syncUrl:!1});return}let i=t.content!=null,o=this.parseContentStack(t.content),a=o.at(-1);if(this.selectedId!==r||this.detail?.id!==r){this.openWorkItem(r,{syncUrl:!1,contentRefs:o,contentOpen:i}),this.detailLoading=!0;try{await this.store.getWorkItem(r,this.agentId)}catch(c){s()&&(this.detailError=c?.message||String(c))}finally{s()&&(this.detailLoading=!1)}}if(!s())return;let l=a.actionId||[...o].reverse().find(c=>c.type==="action")?.actionId;if(l&&!this.selected?.actions?.some(c=>c.id===l)){this.resetContentStack(),this.syncWorkCenterUrl(!0);return}this.resetContentStack(o),this.contentPanelOpen=i,this.narrowPane="work-item",i&&l&&this.loadLatestActionMessages(this.selectedAction),i&&t.content!==this.contentStackParam()&&this.syncWorkCenterUrl(!0)},resetWorkItemComposer(){this.workItemComposerGeneration+=1,this.workItemMessage="",this.workItemMessageQuote=null,this.workItemMessageAttachments=[],this.workItemMessageAttachmentsUploading=!1,this.workItemMessageError="",this.workItemMessageSending=!1},draftTarget(){let e=this.composerTargetAction;return e?{kind:"action",actionId:e.id,generation:Number(e.generation)}:this.composerTargetValue==="coordinator"?{kind:"coordinator"}:(()=>{let[,t="",s="0"]=this.composerTargetValue.split(":");return{kind:"action",actionId:t,generation:Number(s)||0}})()},targetValue(e){return typeof e=="string"&&e.startsWith("action:")?e:e?.kind==="action"?`action:${e.actionId}:${e.generation}`:"coordinator"},saveComposerDraft(){!this.selectedId||!this.agentId||this.store.saveWorkCenterComposerDraft(this.agentId,this.selectedId,{text:this.workItemMessage,quote:this.workItemMessageQuote,attachments:[...this.workItemMessageAttachments],target:this.draftTarget(),error:this.workItemMessageError})},restoreComposerDraft(e){let s=this.store.loadWorkCenterMessageEnvelope(this.agentId,e)||this.store.loadWorkCenterComposerDraft(this.agentId,e);this.workItemMessage=s?.text||"",this.workItemMessageQuote=rt(s?.quote),this.workItemMessageAttachments=[...s?.attachments||[]],this.composerTargetValue=this.targetValue(s?.target),this.workItemMessageError=s?.error||"",this.staleComposerTarget=null,this.workItemMessageSending=!1,this.workItemMessageAttachmentsUploading=!1,this.workItemComposerGeneration+=1},openWorkItem(e,{syncUrl:t=!0,contentRefs:s=[{type:"action-list"}],contentOpen:n=!1}={}){this.saveComposerDraft(),this.selectedId=e,this.narrowPane="work-item",this.contentPanelOpen=n,this.resetContentStack(s),this.restoreComposerDraft(e),this.detailError="",this.detailLoading=!1,this.previewingAttachmentId=null,this.attachmentPreviewError="",this.attachmentPreviewGeneration=(Number(this.attachmentPreviewGeneration)||0)+1,t&&this.syncWorkCenterUrl()},async selectItem(e){this.openWorkItem(e.id),this.detailLoading=!0;try{await this.store.getWorkItem(e.id,this.agentId)}catch(t){this.selectedId===e.id&&(this.detailError=t?.message||String(t))}finally{this.selectedId===e.id&&(this.detailLoading=!1)}},selectAction(e){this.selectedActionId!==e.id&&(this.previewingAttachmentId=null,this.attachmentPreviewError="",this.attachmentPreviewGeneration=(Number(this.attachmentPreviewGeneration)||0)+1),this.pushContentRef({type:"action",actionId:e.id}),this.loadLatestActionMessages(e)},loadLatestActionMessages(e=this.selectedAction){if(!this.selected?.id||!e?.id||Array.isArray(e.messages))return null;let t=fn(this.agentId,this.selected.id,e.id,e.generation);return this.store.workCenterActionMessages[t]?null:this.store.loadWorkItemActionMessages(this.selected.id,e.id,e.generation,null,this.agentId).catch(()=>null)},showItemsPane({syncUrl:e=!0}={}){this.saveComposerDraft(),this.narrowPane="items",this.selectedId=null,this.contentPanelOpen=!1,this.resetContentStack(),this.composerTargetValue="coordinator",this.resetWorkItemComposer(),e&&this.syncWorkCenterUrl()},showActionsPane(){this.contentPanelOpen=!0,this.contentIsActionList?this.syncWorkCenterUrl():this.popContentRef()},canMessageAction(e){return!e||["done","cancelled"].includes(this.selected?.status)?!1:["idle","ready","running","paused","waiting","failed","completed","stopped"].includes(e.status)&&e.admissionStatus!=="blocked"},clearPendingMessageEnvelope({preserveAttachments:e=!1}={}){return!this.selectedId||!this.pendingMessageEnvelope?!1:(this.actionInputRequestGeneration=(Number(this.actionInputRequestGeneration)||0)+1,this.preserveComposerOnEnvelopeClear=!0,this.store.discardWorkCenterMessageEnvelope(this.agentId,this.selectedId)?(e||(this.workItemMessageAttachments=[]),this.workItemMessageError="",this.workItemMessageSending=!1,!0):(this.preserveComposerOnEnvelopeClear=!1,!1))},chooseCoordinatorTarget(){this.pendingMessageEnvelope&&!this.clearPendingMessageEnvelope({preserveAttachments:!0})||(this.composerTargetValue="coordinator",this.staleComposerTarget=null,this.saveComposerDraft())},onComposerTargetChange(){this.pendingMessageEnvelope&&!this.clearPendingMessageEnvelope({preserveAttachments:!0})||(this.staleComposerTarget=this.composerTargetAction==null&&this.composerTargetValue!=="coordinator"?this.composerTargetValue:null,this.saveComposerDraft())},loadEarlierActionMessages(){return!this.selected?.id||!this.selectedAction?.id||this.actionMessagesNextCursor==null?null:this.store.loadWorkItemActionMessages(this.selected.id,this.selectedAction.id,this.selectedAction.generation,this.actionMessagesNextCursor,this.agentId).catch(()=>null)},actionExecutor(e){return e?.assignedVp?.name||e?.assignedVp?.id||e?.requiredRole||e?.assignmentPolicy?.fixedVpId||e?.assignmentPolicy?.capability||this.tr("workCenter.assignment.auto","Auto")},actionContentSummary(e){return String(e?.contentSummary||e?.response||e?.brief?.objective||"").trim()},executionStats(e){return e?.executionStats||{}},formatCount(e){return new Intl.NumberFormat().format(Math.max(0,Number(e)||0))},formatTokens(e){let t=Math.max(0,Number(e)||0);return t>=1e6?`${(t/1e6).toFixed(1)}m`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)},resetCreateExecutionContext(e){let t=this.workDirTouched||this.startTouched,s=this.store.workCenterCreateDraft;s&&(this.store.workCenterCreateDraft={sourceAgentId:e||null,requirement:s.requirement||s.goal||s.title||"",workDir:"",deliveryTarget:s.deliveryTarget||"",origin:null,linkedSessionIds:[]}),this.form.workDir="",this.form.start=!0,this.workDirTouched=!1,this.startTouched=!1,t&&(this.createOpen=!1),this.applyCreateDefaults()},applyCreateDefaults(){this.createOpen&&(!this.workDirTouched&&!this.form.workDir.trim()&&(this.form.workDir=this.createDefaultWorkDir),this.startTouched||(this.form.start=this.createDefaultStart))},folderPickerInitialDir(){return this.form.workDir.trim()||this.createDefaultWorkDir},folderPickerSetWorkDir(e){this.form.workDir=e,this.workDirTouched=!0},onCreateWorkDirInput(){this.workDirTouched=!0},onCreateStartInput(){this.startTouched=!0},async onCreateAttachmentInput(e){if(!this.workItemAttachmentsSupported)throw e.target.value="",new Error(this.tr("workCenter.attachmentsUnsupported","The selected Agent does not support Work Item attachments."));let t=Array.from(e.target.files||[]);if(e.target.value="",t.length===0)return;let s=Math.max(0,10-this.createAttachments.length),n=t.slice(0,s);if(n.length!==0){this.attachmentsUploading=!0;try{let r=new FormData;for(let d of n)r.append("files",d,d.name||"attachment");let i=Pinia.useAuthStore(),o=i.getActiveToken?.()||i.token||null,a=o?{Authorization:`Bearer ${o}`}:{},l=await fetch("/api/upload",{method:"POST",headers:a,body:r});if(!l.ok)throw new Error(this.tr("workCenter.attachmentsUploadFailed","Attachment upload failed"));let c=await l.json();this.createAttachments=[...this.createAttachments,...Array.isArray(c.files)?c.files:[]].slice(0,10)}finally{this.attachmentsUploading=!1}}},removeCreateAttachment(e){this.createAttachments=this.createAttachments.filter((t,s)=>s!==e)},discardPendingMessageEnvelope(){this.clearPendingMessageEnvelope()&&this.saveComposerDraft()},async onWorkItemMessageAttachmentInput(e){if(!this.workItemAttachmentsSupported){e.target.value="",this.workItemMessageError=this.tr("workCenter.attachmentsUnsupported","The selected Agent does not support Work Item attachments.");return}let t=Array.from(e.target.files||[]);if(e.target.value="",t.length===0)return;let s=this.workItemComposerScope;if(!s)return;let n=this.pendingEnvelopeAttachmentRecovery,r=Array.isArray(this.selected?.attachments)?this.selected.attachments.length:0,i=Math.max(0,10-r-(n?0:this.workItemMessageAttachments.length)),o=t.slice(0,i);if(o.length!==0){this.workItemMessageAttachmentsUploading=!0,this.workItemMessageError="";try{let a=new FormData;for(let g of o)a.append("files",g,g.name||"attachment");let l=Pinia.useAuthStore(),c=l.getActiveToken?.()||l.token||null,d=c?{Authorization:`Bearer ${c}`}:{},u=await fetch("/api/upload",{method:"POST",headers:d,body:a});if(!u.ok)throw new Error(this.tr("workCenter.attachmentsUploadFailed","Attachment upload failed"));let p=await u.json();if(this.workItemComposerScope!==s)return;let f=(Array.isArray(p.files)?p.files:[]).slice(0,Math.max(0,10-r));if(n){let g=this.store.replaceWorkCenterMessageEnvelopeAttachments(this.agentId,this.selectedId,f);if(!g)throw new Error(this.tr("workCenter.pendingEnvelopeChanged","The pending request changed; reopen this Work Item and try again."));this.workItemMessageAttachments=[...g.attachments],this.workItemMessageError=""}else this.workItemMessageAttachments=[...this.workItemMessageAttachments,...f].slice(0,Math.max(0,10-r)),this.saveComposerDraft()}catch(a){this.workItemComposerScope===s&&(this.workItemMessageError=a?.message||String(a))}finally{this.workItemComposerScope===s&&(this.workItemMessageAttachmentsUploading=!1)}}},removeWorkItemMessageAttachment(e){this.workItemMessageAttachments=this.workItemMessageAttachments.filter((t,s)=>s!==e),this.saveComposerDraft()},async previewAttachment(e,t=null){if(!this.selected?.id||!e?.id||this.previewingAttachmentId)return;let s=this.agentId,n=this.selected.id,r=this.selectedActionId||"",i=`${s}:${n}:${r}`,o=(Number(this.attachmentPreviewGeneration)||0)+1;this.attachmentPreviewGeneration=o;let a=()=>this.attachmentPreviewGeneration===o&&`${this.agentId}:${this.selected?.id||""}:${this.selectedActionId||""}`===i,l=e.isImage?null:window.open("","_blank");if(!e.isImage&&!l){this.attachmentPreviewError=this.tr("workCenter.attachmentOpenBlocked","The browser blocked the attachment window. Allow pop-ups and try again.");return}l&&(l.opener=null),this.previewingAttachmentId=e.id,this.attachmentPreviewError="";try{let c=await this.store.previewWorkItemAttachment(n,e.id,s);if(!a()){l?.close();return}c?.preview&&c.attachment?.isImage?bn(c.preview,{alt:e.name||this.tr("workCenter.previewAttachment","Open attachment"),closeLabel:this.tr("common.close","Close"),trigger:t}):c?.preview&&l?l.location.replace(c.preview):l?.close()}catch(c){l?.close(),a()&&(this.attachmentPreviewError=c?.message||this.tr("workCenter.attachmentPreviewFailed","Could not open the attachment. Try again."))}finally{a()&&(this.previewingAttachmentId=null)}},isExternalOutput(e){return["link","pr"].includes(e?.kind)&&/^https?:\/\//i.test(String(e?.ref||""))},formatAttachmentSize(e){let t=Math.max(0,Number(e)||0);return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/1024/1024).toFixed(1)} MB`},openCreate(){this.createOpen=!0,this.workDirTouched=!1,this.startTouched=!1,this.applyCreateDefaults()},closeCreate(){this.saving||(this.closeFolderPicker(),this.createOpen=!1,this.store.workCenterCreateDraft=null)},async submitCreate(){let e=String(this.form.requirement||this.form.goal||this.form.title||"").trim();if(!e||!this.form.workDir.trim())return;let t=this.agentId,s=(Number(this.createGeneration)||0)+1;this.createGeneration=s,this.saving=!0;try{let n=this.store.workCenterCreateDraft,r=n?.sourceAgentId===t,i=await this.store.createWorkItem({requirement:e,title:e,goal:e,acceptanceCriteria:[],workItemType:"auto",workDir:this.form.workDir.trim(),deliveryTarget:this.form.deliveryTarget||null,origin:r&&n.origin||null,linkedSessionIds:r?n.linkedSessionIds||[]:[],attachments:this.workItemAttachmentsSupported?(this.createAttachments||[]).map(o=>({fileId:o.fileId,name:o.name,mimeType:o.mimeType,size:o.size})):[],reuseMemory:this.form.reuseMemory,start:this.form.start},t);if(this.agentId!==t||this.createGeneration!==s)return;this.openWorkItem(i.id),this.form={requirement:"",workDir:"",deliveryTarget:"",reuseMemory:!0,start:this.settings?.startImmediately!==!1},this.store.workCenterCreateDraft=null,this.createAttachments=[],this.workDirTouched=!1,this.startTouched=!1,this.createOpen=!1}finally{this.agentId===t&&this.createGeneration===s&&(this.saving=!1)}},async startSelected(){this.selected&&await this.store.startWorkItem(this.selected.id,this.agentId)},async sendSelectedWorkItemMessage(){if(!this.selected||!this.composerCanSend)return;let e=this.workItemComposerScope,t=this.composerTargetValue,s=this.composerTargetAction;if(!this.composerTargetIsCoordinator&&!s)return;let n=this.selected.id,r=this.selected.revision,i=this.workItemMessage.trim(),o=rt(this.workItemMessageQuote),a=this.workItemMessageAttachments.map(c=>({fileId:c.fileId,name:c.name,mimeType:c.mimeType,size:c.size})),l=(Number(this.actionInputRequestGeneration)||0)+1;this.actionInputRequestGeneration=l,this.workItemMessageSending=!0,this.workItemMessageError="",this.saveComposerDraft();try{let c={planRevision:this.selected.planRevision,ledgerRevision:this.selected.ledgerRevision,coordinatorRevision:this.selected.coordinatorRevision};this.canonicalMessageWireSupported?await this.store.postWorkItemMessage(n,i,s?{kind:"action",actionId:s.id,generation:s.generation}:{kind:"coordinator"},r,a,this.agentId,c,o):s?await this.store.sendWorkItemActionInput(n,i,s.id,r,s.generation,a,this.agentId,o):await this.store.sendWorkItemMessage(n,i,r,a,this.agentId,c,o),this.workItemComposerScope===e&&this.actionInputRequestGeneration===l&&this.composerTargetValue===t&&this.workItemMessage.trim()===i&&!this.store.loadWorkCenterMessageEnvelope(this.agentId,n)&&(this.workItemMessage="",this.workItemMessageQuote=null,this.workItemMessageAttachments=[],this.store.removeWorkCenterComposerDraft(this.agentId,n))}catch(c){this.workItemComposerScope===e&&this.actionInputRequestGeneration===l&&(this.workItemMessageError=c?.message||String(c),this.saveComposerDraft())}finally{this.workItemComposerScope===e&&this.actionInputRequestGeneration===l&&(this.workItemMessageSending=!1)}},workItemCanDelete(e){return["done","cancelled","draft","needs_attention"].includes(e?.status)},workItemDeleting(e){return!!this.deletingWorkItemIds[e?.id]},async deleteWorkItem(e){if(!e||this.workItemDeleting(e))return;let t=this.tr("workCenter.deleteConfirm","Permanently delete this Work Item, its execution history, and attachments?");if(await De(t,{destructive:!0})){this.deleteWorkItemError="",this.deletingWorkItemIds={...this.deletingWorkItemIds,[e.id]:!0};try{let s=await this.store.deleteWorkItem(e.id,e.revision,this.agentId);s?.cleanupWarning&&(this.deleteWorkItemError=s.cleanupWarning),this.selectedId===e.id&&this.showItemsPane()}catch(s){this.deleteWorkItemError=s?.message||String(s)}finally{let s={...this.deletingWorkItemIds};delete s[e.id],this.deletingWorkItemIds=s}}},async cancelSelected(){if(!this.selected||["done","cancelled"].includes(this.selected.status))return;let e=this.tr("workCenter.cancelConfirm","Stop this work item and its unfinished Actions?");await De(e,{destructive:!0})&&await this.store.cancelWorkItem(this.selected.id,this.agentId)},async resumeSelected(){!this.selected||this.selected.status!=="cancelled"||await this.store.resumeWorkItem(this.selected.id,this.selected.revision,this.agentId)}},template:`
|
|
6291
6303
|
<main class="work-center-main" :class="{ 'workbench-maximized': store.workbenchMaximized && store.workbenchExpanded }">
|
|
6292
6304
|
<div class="work-center-shell" :class="{ 'showing-detail': narrowPane !== 'items' }">
|
|
6293
6305
|
<header v-if="narrowPane === 'items'" class="work-center-header">
|
|
@@ -6878,6 +6890,7 @@ ${String(e||"").trim()}
|
|
|
6878
6890
|
:upgrading-agents="upgradingAgents"
|
|
6879
6891
|
:show-agent-actions="true"
|
|
6880
6892
|
@open-agent-settings="openAgentSettings(store.currentAgent || null)"
|
|
6893
|
+
@restart-agent="restartAgent"
|
|
6881
6894
|
@upgrade-agent="upgradeAgent"
|
|
6882
6895
|
/>
|
|
6883
6896
|
<div class="sidebar-header-actions">
|
|
@@ -7296,7 +7309,7 @@ ${String(e||"").trim()}
|
|
|
7296
7309
|
</div>
|
|
7297
7310
|
</div>
|
|
7298
7311
|
</div>
|
|
7299
|
-
`,data(){return{showAgentDropdown:!1,showSettingsPanel:!1,showAgentSettings:!1,agentSettingsAgentId:null,showConversationModal:!1,unifiedSessionCreateOpen:!1,unifiedSessionCreateProvider:"yeaft",unifiedSessionCreateProject:null,convModalAgent:"",convModalWorkDir:"",convModalProvider:"claude-code",selectedResumeSession:null,historyLoaded:!1,windowWidth:window.innerWidth,folderPickerOpen:!1,folderPickerPath:"",folderPickerEntries:[],folderPickerLoading:!1,folderPickerSelected:"",folderPickerTarget:"",_folderPickerRequestId:null,_folderPickerRequestAgentId:null,serverVersion:"",chatGroupCollapsed:!1,sidebarTab:"chat",editingChatId:null,editingChatName:"",activeSessionMenu:null}},computed:{store(){return Pinia.useChatStore()},restartingAgents(){return Object.fromEntries(Object.entries(this.store.agentOperations||{}).filter(([,e])=>e.restart?.pending))},upgradingAgents(){return Object.fromEntries(Object.entries(this.store.agentOperations||{}).filter(([,e])=>e.upgrade?.pending))},providerOptions(){return[{value:"claude-code",label:this.$t("provider.claudeCode")},{value:"copilot",label:this.$t("provider.copilot")}]},agentOptions(){return this.store.agents.filter(e=>e.online).map(e=>({value:e.id,label:`${e.name}${e.latency?` (${e.latency}ms)`:""}`}))},canUseWorkbench(){let e=$e().role;return e==="admin"||e==="pro"},selectedConvModalAgentWorkDir(){return this.convModalAgent&&this.store.agents.find(t=>t.id===this.convModalAgent)?.workDir||""},onlineAgents(){return this.store.agents.filter(e=>e.online)},onlineAgentCount(){return this.onlineAgents.length},workCenterAgents(){return this.onlineAgents.filter(e=>Array.isArray(e.capabilities)&&e.capabilities.includes("work_center"))},isMobileView(){return this.windowWidth<=768},effectiveSidebarCollapsed(){return this.isMobileView?!this.store.sessionSidebarOpen:this.store.sidebarCollapsed},normalConversations(){return this.sortByActivity(this.store.conversations.filter(e=>e.agentOnline!==!1&&!this.isConversationHidden(e)))},pinnedChatConversations(){let e=this.store.conversations.filter(t=>t.agentOnline!==!1&&!this.isConversationHidden(t)&&this.store.isSessionPinned(t.id));return this.sortByActivity(e)},unpinnedChatConversations(){return this.sortByActivity(this.store.conversations.filter(e=>e.agentOnline!==!1&&!this.isConversationHidden(e)&&!this.store.isSessionPinned(e.id)))},chatSessionCount(){return this.store.conversations.filter(e=>e.agentOnline!==!1&&!this.isConversationHidden(e)).length}},methods:{isConversationHidden(e){return e?.id?(this.store.hiddenSessionCatalog||[]).some(t=>t?.runtimeProvider===(e.provider||"claude-code")&&t?.routeRef?.sessionId===e.id&&t?.routeRef?.agentId===(e.agentId||this.store.currentAgent||null)):!1},onSidebarCollapse(){Hh({isMobileView:this.isMobileView,showMobileSidebar:this.store.sessionSidebarOpen,closeMobileSidebar:()=>this.store.closeSessionSidebar(),toggleSidebar:()=>this.store.toggleSidebar()})},onModeFlip(e){e==="yeaft"?this.store.enterYeaft():this.store.leaveYeaft()},sortByActivity(e){return Tp(e)},isCatalogSessionUnread(e){return e?.runtimeProvider!=="yeaft"?!1:this.store.isYeaftSessionUnread(e.routeRef?.sessionId,e.routeRef?.agentId)},onUnifiedCreate(e="yeaft"){this.unifiedSessionCreateProject=null,this.unifiedSessionCreateProvider=["yeaft","copilot","claude-code"].includes(e)?e:"yeaft",this.unifiedSessionCreateOpen=!0},onUnifiedCreateInProject({project:e}={}){e?.id&&(this.unifiedSessionCreateProject=e,this.unifiedSessionCreateProvider="yeaft",this.unifiedSessionCreateOpen=!0)},closeUnifiedSessionCreate(){this.unifiedSessionCreateOpen=!1,this.unifiedSessionCreateProject=null},async onUnifiedSessionCreated(e){let t=this.unifiedSessionCreateProject;if(this.closeUnifiedSessionCreate(),!t||!e?.id)return;let s=e.agentId||t.legacyAgentId||this.store.currentAgent||null,n=await this.store.mutateProject?.("move_session",{sessionId:e.id,projectId:t.legacyProjectId||t.id},s);if(!n?.ok){let r=n?.error?.message||n?.error?.code||"unknown";await it(this.$t("sidebar.projects.assignFailed",{name:t.name,message:r}))}},openWorkCenter(e=null){let t=this.workCenterAgents.find(s=>s.id===e)||this.workCenterAgents.find(s=>s.id===this.store.workCenterAgentId)||this.workCenterAgents[0];t&&this.store.enterWorkCenter(t.id)},onUnifiedSessionAction({action:e,row:t,title:s,sessions:n}={}){if(!t?.routeRef)return;let{runtimeProvider:r,agentId:i,sessionId:o}=t.routeRef;e==="rename"?this.store.renameCatalogSession({row:t,title:s}):e==="reorder"?this.store.reorderCatalogSessions(n):e==="pin"?this.store.toggleCatalogSessionPin(t):e==="remove"?this.store.hideCatalogSession(t):r==="yeaft"&&e==="settings"&&(this.store.pendingUnifiedSessionSettings={sessionId:o,agentId:i,section:"session"},this.store.openCatalogSession(t))},openConversationModal({preserveProvider:e=!1}={}){this.showConversationModal=!0,e||(this.convModalProvider="claude-code"),this.convModalAgent="",this.convModalWorkDir="",this.selectedResumeSession=null,this.historyLoaded=!1,this._foldersRetried=!1;let t=this.store.agents.filter(r=>r.online),n=t.find(r=>r.id===this.store.currentAgent)||t[0];n&&(this.convModalAgent=n.id,this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider).then(()=>{this.showConversationModal&&this.store.folders.length===0&&!this._foldersRetried&&(this._foldersRetried=!0,setTimeout(()=>{this.showConversationModal&&this.convModalAgent&&this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider)},1500))}))},openConversationModalResume(){this.openConversationModal()},closeConversationModal(){this.showConversationModal=!1,this.convModalAgent="",this.convModalWorkDir="",this.selectedResumeSession=null,this.historyLoaded=!1},onConvModalAgentChange(){this.convModalAgent&&(this.convModalWorkDir="",this.selectedResumeSession=null,this.historyLoaded=!1,this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider))},onConvModalProviderChange(){this.convModalWorkDir="",this.selectedResumeSession=null,this.historyLoaded=!1,this.convModalAgent&&this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider)},onConvModalWorkDirInput(){this.historyLoaded=!1,this.selectedResumeSession=null,this._workDirInputTimer&&clearTimeout(this._workDirInputTimer),this._workDirInputTimer=setTimeout(()=>{this.convModalWorkDir.trim()&&this.convModalAgent&&(this.store.listHistorySessionsForAgent(this.convModalAgent,this.convModalWorkDir.trim(),this.convModalProvider),this.historyLoaded=!0)},500)},selectConvModalFolder(e){this.convModalWorkDir=e,this.selectedResumeSession=null,this.convModalAgent&&(this.store.listHistorySessionsForAgent(this.convModalAgent,e,this.convModalProvider),this.historyLoaded=!0)},loadConvModalFolders(){this.convModalAgent&&this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider)},loadConvModalSessions(){this.convModalAgent&&this.convModalWorkDir.trim()&&(this.store.listHistorySessionsForAgent(this.convModalAgent,this.convModalWorkDir.trim(),this.convModalProvider),this.historyLoaded=!0)},toggleAgentDropdown(){this.showAgentDropdown=!this.showAgentDropdown,this.showAgentDropdown&&this.store.refreshAgents()},selectAgent(e){this.store.selectAgent(e),this.showAgentDropdown=!1},createNewConversation(){if(!this.convModalAgent)return;this.store.selectAgent(this.convModalAgent);let e=this.convModalWorkDir.trim()||this.selectedConvModalAgentWorkDir;this.store.createConversation(e,this.convModalAgent,null,this.buildConvOpts()),this.closeConversationModal()},buildConvOpts(){let e={provider:this.convModalProvider};return this.convModalProvider==="copilot"&&(e.providerOptions={allowAllTools:!0}),e},resumeSession(e){if(!this.convModalAgent)return;this.store.selectAgent(this.convModalAgent),this.store._pendingSessionTitle=e.title;let t=e.workDir||this.convModalWorkDir.trim()||this.selectedConvModalAgentWorkDir;this.store.resumeConversation(e.sessionId,t,this.convModalAgent,this.buildConvOpts()),this.closeConversationModal()},resumeSelectedSession(){if(!this.convModalAgent||!this.selectedResumeSession)return;this.store.selectAgent(this.convModalAgent),this.store._pendingSessionTitle=this.selectedResumeSession.title;let e=this.selectedResumeSession.workDir||this.convModalWorkDir.trim()||this.selectedConvModalAgentWorkDir;this.store.resumeConversation(this.selectedResumeSession.sessionId,e,this.convModalAgent,this.buildConvOpts()),this.closeConversationModal()},formatDate(e){return Eo(e,this.$t.bind(this))},selectConversation(e,t){this.store.leaveWorkCenter(),this.store.selectConversation(e,t,{refresh:!0}),this.store.closeSessionSidebar()},onSessionClick(e){if(e.agentOnline===!1){this.store.addMessage({type:"system",content:this.$t("chat.session.agentOffline")});return}if(this.store.isSplitMode&&this.store.activePanelId){this.store.leaveWorkCenter(),this.store.setPanelConversation(this.store.activePanelId,e.id,{refresh:!0}),this.store.closeSessionSidebar();return}this.selectConversation(e.id,e.agentId)},hideSessionFromSidebar(e){if(!e?.id)return;let t=e.provider||"claude-code";this.store.hideCatalogSession({catalogKey:`chat:${e.id}`,runtimeProvider:t,routeRef:{runtimeProvider:t,agentId:e.agentId||this.store.currentAgent||null,sessionId:e.id},title:this.getConversationTitle(e),workDir:e.workDir||"",agentName:e.agentName||"",availability:e.agentOnline===!1?"offline":"online",pinned:this.store.isSessionPinned(e.id)})},closeSession(e,t){this.store.closeSession(e,t)},async deleteConversation(e,t){await Ee(this.$t("chat.delete.confirm"),{destructive:!0})&&this.store.deleteConversation(e,t)},getConversationTitle(e){let t=this.store.getConversationTitle(e.id);return t?t.length>30?t.slice(0,30)+"...":t:e.claudeSessionId?e.claudeSessionId.slice(0,8)+"...":e.id.slice(0,8)+"..."},getConversationFullTitle(e){let t=this.store.getConversationTitle(e.id);if(t&&t.length>30)return t},startChatRename(e){this.editingChatId=e.id,this.editingChatName=this.store.customConversationTitles[e.id]||this.store.conversationTitles[e.id]||"",this.$nextTick(()=>{let t=this.$refs.chatRenameInput;if(t){let s=Array.isArray(t)?t[0]:t;s.focus(),s.select()}})},commitChatRename(){if(!this.editingChatId)return;let e=this.editingChatId,t=this.editingChatName.trim();this.editingChatId=null,this.editingChatName="",this.store.renameChatSession(e,t)},cancelChatRename(){this.editingChatId=null,this.editingChatName=""},toggleSessionMenu(e){this.activeSessionMenu=this.activeSessionMenu===e?null:e},closeSessionMenu(){this.activeSessionMenu=null},getConversationTime(e){let s=this.store.executionStatusMap[e.id]?.lastActivity||e.createdAt;if(!s)return"";let n=new Date(s),r=new Date,i=r-n;return i<6e4?this.$t("chat.time.justNow"):i<36e5?this.$t("chat.time.minutesAgo",{count:Math.floor(i/6e4)}):n.toDateString()===r.toDateString()?n.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):n.toLocaleDateString(void 0,{month:"numeric",day:"numeric"})},providerLabel(e){return e==="copilot"?this.$t("provider.copilot"):e==="claude-code"?this.$t("provider.claudeCode"):e||""},shortenPath(e){return qo(e)},formatTime(e){return e?new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""},getLastPathSegment(e){return Br(e)},getParentPath(e){if(!e)return"";let t=e.split(/[/\\]/);return t.length<=2?"":t.slice(0,-1).join("/")},handleResize(){this.windowWidth=window.innerWidth},openAgentSettings(e){this.agentSettingsAgentId=e||null,this.showAgentSettings=!0},async upgradeAgent(e){let s=this.store.agents.find(n=>n.id===e)?.name||e;await Ee(this.$t("chat.agent.upgradeConfirm",{name:s}))&&this.store.upgradeAgent(e)},closeFolderPicker(){this.folderPickerOpen=!1,this._folderPickerRequestId=null,this._folderPickerRequestAgentId=null,this._folderPickerTimer&&(clearTimeout(this._folderPickerTimer),this._folderPickerTimer=null)},openFolderPicker(e){let t=this.convModalAgent;if(!t)return;this.folderPickerTarget=e,this.folderPickerOpen=!0,this.folderPickerSelected="",this.folderPickerLoading=!0;let s=this.convModalWorkDir,n=this.store.agents.find(a=>a.id===t),r=s||n?.workDir||"";this.folderPickerPath=r,this.folderPickerEntries=[];let i=`folder-picker-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this._folderPickerRequestId=i,this._folderPickerRequestAgentId=t;let o=()=>{this.store.sendWsMessage({type:"list_directory",conversationId:"_workdir_picker",directoryPickerScope:"agent",requestId:i,agentId:t,dirPath:r})};o(),this._folderPickerTimer&&clearTimeout(this._folderPickerTimer),this._folderPickerTimer=setTimeout(()=>{this.folderPickerLoading&&this.folderPickerOpen&&o()},5e3)},loadFolderPickerDir(e){let t=this.convModalAgent;if(!t)return;this.folderPickerLoading=!0,this.folderPickerSelected="",this.folderPickerEntries=[];let s=`folder-picker-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this._folderPickerRequestId=s,this._folderPickerRequestAgentId=t;let n=()=>{this.store.sendWsMessage({type:"list_directory",conversationId:"_workdir_picker",directoryPickerScope:"agent",requestId:s,agentId:t,dirPath:e})};n(),this._folderPickerTimer&&clearTimeout(this._folderPickerTimer),this._folderPickerTimer=setTimeout(()=>{this.folderPickerLoading&&this.folderPickerOpen&&n()},5e3)},folderPickerNavigateUp(){if(!this.folderPickerPath)return;let e=this.folderPickerPath.includes("\\"),t=e?"\\":"/",s=this.folderPickerPath.replace(/[/\\]$/,"").split(/[/\\]/);if(s.pop(),s.length===0)this.folderPickerPath="",this.loadFolderPickerDir("");else if(e&&s.length===1&&/^[A-Za-z]:$/.test(s[0]))this.folderPickerPath=s[0]+"\\",this.loadFolderPickerDir(s[0]+"\\");else{let n=s.join(t);this.folderPickerPath=n,this.loadFolderPickerDir(n)}},folderPickerSelectItem(e){this.folderPickerSelected=e.name},folderPickerEnter(e){let s=this.folderPickerPath.includes("\\")||/^[A-Z]:/.test(e.name)?"\\":"/",n;this.folderPickerPath?n=this.folderPickerPath.replace(/[/\\]$/,"")+s+e.name:/^[A-Z]:$/.test(e.name)?n=e.name+"\\":n="/"+e.name,this.folderPickerPath=n,this.loadFolderPickerDir(n)},confirmFolderPicker(){let e=this.folderPickerPath;if(e){if(this.folderPickerSelected){let t=e.includes("\\")?"\\":"/";e=e.replace(/[/\\]$/,"")+t+this.folderPickerSelected}this.convModalWorkDir=e,this.selectedResumeSession=null,this.convModalAgent&&(this.store.listHistorySessionsForAgent(this.convModalAgent,e,this.convModalProvider),this.historyLoaded=!0),this.closeFolderPicker()}},handleFolderPickerMessage(e){let t=e.detail;!t||t.type!=="directory_listing"||t.conversationId!=="_workdir_picker"||!this.folderPickerOpen||!this._folderPickerRequestId||t.requestId!==this._folderPickerRequestId||this.convModalAgent!==this._folderPickerRequestAgentId||(this._folderPickerTimer&&(clearTimeout(this._folderPickerTimer),this._folderPickerTimer=null),this._folderPickerRequestId=null,this._folderPickerRequestAgentId=null,this.folderPickerLoading=!1,this.folderPickerEntries=(t.entries||[]).filter(s=>s.type==="directory").sort((s,n)=>s.name.localeCompare(n.name)),t.dirPath!=null&&(this.folderPickerPath=t.dirPath))}},mounted(){if(this.store.openUnifiedChatCreate){let e=this.store.openUnifiedChatCreate;this.store.openUnifiedChatCreate=!1,this.convModalProvider=e==="copilot"?"copilot":"claude-code",this.openConversationModal({preserveProvider:!0})}this._clickOutsideHandler=e=>{e.target.closest(".agent-selector")||(this.showAgentDropdown=!1),!e.target.closest(".session-dots-btn")&&!e.target.closest(".session-menu")&&(this.activeSessionMenu=null)},document.addEventListener("click",this._clickOutsideHandler),window.addEventListener("resize",this.handleResize),window.addEventListener("workbench-message",this.handleFolderPickerMessage),fetch("/api/version").then(e=>e.json()).then(e=>{this.serverVersion=e.version}).catch(()=>{}),this._agentUpgradeAckHandler=e=>{let{success:t,error:s,alreadyLatest:n,version:r,reason:i,currentNode:o,requiredNode:a}=e.detail||{};t?n&&it(this.$t("chat.agent.alreadyLatest",{version:r||""})):i==="node_incompatible"?it(this.$t("chat.agent.nodeIncompatible",{current:o||"?",required:a||"?",version:r||""})):i==="container_image_upgrade_required"?it(this.$t("chat.agent.containerImageUpgradeRequired",{version:r||"?"})):i==="manual_upgrade_required"?it(this.$t("chat.agent.manualUpgradeRequired",{version:r||"?"})):it(`Agent upgrade failed: ${s||"Unknown error"}`)},window.addEventListener("agent-upgrade-ack",this._agentUpgradeAckHandler)},beforeUnmount(){document.removeEventListener("click",this._clickOutsideHandler),window.removeEventListener("resize",this.handleResize),window.removeEventListener("workbench-message",this.handleFolderPickerMessage),window.removeEventListener("agent-upgrade-ack",this._agentUpgradeAckHandler),this._folderPickerTimer&&clearTimeout(this._folderPickerTimer)}}});function Wh(e={}){let{sessions:t,activeSessionId:s,activeSessionKey:n,pinnedSessionIds:r,onlineAgentIds:i}=e,o=s||null,a=n||null,l=Object.prototype.hasOwnProperty.call(e,"activeSessionKey"),c=Array.isArray(r)?r:[],d=Array.isArray(i)?new Set(i.filter(Boolean)):null,u=new Map;c.forEach((f,g)=>{typeof f=="string"&&f&&!u.has(f)&&u.set(f,g)});let p=[];for(let f of Array.isArray(t)?t:[]){if(!f||!f.id||d&&f.agentId&&!d.has(f.agentId))continue;let g=String(f.id),h=f.agentId?`${f.agentId}${g}`:g;p.push({kind:"session",id:g,raw:f,pinned:!!f.pinned||!f.agentId&&u.has(g),active:l?h===a:g===o,processing:!!f.running||!!f.active||!!f.isRunning||!!f.isActive,_manualOrder:Number.isFinite(f.sortOrder)?f.sortOrder:Number.MAX_SAFE_INTEGER,_activityTime:Li(f)})}return p.sort((f,g)=>{if(f.pinned!==g.pinned)return f.pinned?-1:1;if(f._manualOrder!==g._manualOrder)return f._manualOrder-g._manualOrder;if(f._activityTime!==g._activityTime)return g._activityTime-f._activityTime;let h=u.has(f.id)?u.get(f.id):Number.MAX_SAFE_INTEGER,m=u.has(g.id)?u.get(g.id):Number.MAX_SAFE_INTEGER;return h!==m?h-m:f.id.localeCompare(g.id)}),p.map(({_manualOrder:f,_activityTime:g,...h})=>h)}var jh=F(()=>{$i()});var Gw,Lx,Uh,Kh=F(()=>{ot();Lo();uc();pc();fc();gc();mc();Cc();jh();Gw=3600*1e3,Lx=24*Gw,Uh={name:"YeaftSidebar",components:{SessionCreateModal:Ln,SidebarModeToggle:Mo,SidebarAgentHeader:Po,SidebarWorkCenter:Ro,SessionSidebarShell:_o,UnifiedSessionList:Do},emits:["select-group","select-chat","toggle-sidebar","back","open-settings","open-agent-settings","open-group-settings"],template:`
|
|
7312
|
+
`,data(){return{showAgentDropdown:!1,showSettingsPanel:!1,showAgentSettings:!1,agentSettingsAgentId:null,showConversationModal:!1,unifiedSessionCreateOpen:!1,unifiedSessionCreateProvider:"yeaft",unifiedSessionCreateProject:null,convModalAgent:"",convModalWorkDir:"",convModalProvider:"claude-code",selectedResumeSession:null,historyLoaded:!1,windowWidth:window.innerWidth,folderPickerOpen:!1,folderPickerPath:"",folderPickerEntries:[],folderPickerLoading:!1,folderPickerSelected:"",folderPickerTarget:"",_folderPickerRequestId:null,_folderPickerRequestAgentId:null,serverVersion:"",chatGroupCollapsed:!1,sidebarTab:"chat",editingChatId:null,editingChatName:"",activeSessionMenu:null}},computed:{store(){return Pinia.useChatStore()},restartingAgents(){return Object.fromEntries(Object.entries(this.store.agentOperations||{}).filter(([,e])=>e.restart?.pending))},upgradingAgents(){return Object.fromEntries(Object.entries(this.store.agentOperations||{}).filter(([,e])=>e.upgrade?.pending))},providerOptions(){return[{value:"claude-code",label:this.$t("provider.claudeCode")},{value:"copilot",label:this.$t("provider.copilot")}]},agentOptions(){return this.store.agents.filter(e=>e.online).map(e=>({value:e.id,label:`${e.name}${e.latency?` (${e.latency}ms)`:""}`}))},canUseWorkbench(){let e=$e().role;return e==="admin"||e==="pro"},selectedConvModalAgentWorkDir(){return this.convModalAgent&&this.store.agents.find(t=>t.id===this.convModalAgent)?.workDir||""},onlineAgents(){return this.store.agents.filter(e=>e.online)},onlineAgentCount(){return this.onlineAgents.length},workCenterAgents(){return this.onlineAgents.filter(e=>Array.isArray(e.capabilities)&&e.capabilities.includes("work_center"))},isMobileView(){return this.windowWidth<=768},effectiveSidebarCollapsed(){return this.isMobileView?!this.store.sessionSidebarOpen:this.store.sidebarCollapsed},normalConversations(){return this.sortByActivity(this.store.conversations.filter(e=>e.agentOnline!==!1&&!this.isConversationHidden(e)))},pinnedChatConversations(){let e=this.store.conversations.filter(t=>t.agentOnline!==!1&&!this.isConversationHidden(t)&&this.store.isSessionPinned(t.id));return this.sortByActivity(e)},unpinnedChatConversations(){return this.sortByActivity(this.store.conversations.filter(e=>e.agentOnline!==!1&&!this.isConversationHidden(e)&&!this.store.isSessionPinned(e.id)))},chatSessionCount(){return this.store.conversations.filter(e=>e.agentOnline!==!1&&!this.isConversationHidden(e)).length}},methods:{isConversationHidden(e){return e?.id?(this.store.hiddenSessionCatalog||[]).some(t=>t?.runtimeProvider===(e.provider||"claude-code")&&t?.routeRef?.sessionId===e.id&&t?.routeRef?.agentId===(e.agentId||this.store.currentAgent||null)):!1},onSidebarCollapse(){Hh({isMobileView:this.isMobileView,showMobileSidebar:this.store.sessionSidebarOpen,closeMobileSidebar:()=>this.store.closeSessionSidebar(),toggleSidebar:()=>this.store.toggleSidebar()})},onModeFlip(e){e==="yeaft"?this.store.enterYeaft():this.store.leaveYeaft()},sortByActivity(e){return Tp(e)},isCatalogSessionUnread(e){return e?.runtimeProvider!=="yeaft"?!1:this.store.isYeaftSessionUnread(e.routeRef?.sessionId,e.routeRef?.agentId)},onUnifiedCreate(e="yeaft"){this.unifiedSessionCreateProject=null,this.unifiedSessionCreateProvider=["yeaft","copilot","claude-code"].includes(e)?e:"yeaft",this.unifiedSessionCreateOpen=!0},onUnifiedCreateInProject({project:e}={}){e?.id&&(this.unifiedSessionCreateProject=e,this.unifiedSessionCreateProvider="yeaft",this.unifiedSessionCreateOpen=!0)},closeUnifiedSessionCreate(){this.unifiedSessionCreateOpen=!1,this.unifiedSessionCreateProject=null},async onUnifiedSessionCreated(e){let t=this.unifiedSessionCreateProject;if(this.closeUnifiedSessionCreate(),!t||!e?.id)return;let s=e.agentId||t.legacyAgentId||this.store.currentAgent||null,n=await this.store.mutateProject?.("move_session",{sessionId:e.id,projectId:t.legacyProjectId||t.id},s);if(!n?.ok){let r=n?.error?.message||n?.error?.code||"unknown";await it(this.$t("sidebar.projects.assignFailed",{name:t.name,message:r}))}},openWorkCenter(e=null){let t=this.workCenterAgents.find(s=>s.id===e)||this.workCenterAgents.find(s=>s.id===this.store.workCenterAgentId)||this.workCenterAgents[0];t&&this.store.enterWorkCenter(t.id)},onUnifiedSessionAction({action:e,row:t,title:s,sessions:n}={}){if(!t?.routeRef)return;let{runtimeProvider:r,agentId:i,sessionId:o}=t.routeRef;e==="rename"?this.store.renameCatalogSession({row:t,title:s}):e==="reorder"?this.store.reorderCatalogSessions(n):e==="pin"?this.store.toggleCatalogSessionPin(t):e==="remove"?this.store.hideCatalogSession(t):r==="yeaft"&&e==="settings"&&(this.store.pendingUnifiedSessionSettings={sessionId:o,agentId:i,section:"session"},this.store.openCatalogSession(t))},openConversationModal({preserveProvider:e=!1}={}){this.showConversationModal=!0,e||(this.convModalProvider="claude-code"),this.convModalAgent="",this.convModalWorkDir="",this.selectedResumeSession=null,this.historyLoaded=!1,this._foldersRetried=!1;let t=this.store.agents.filter(r=>r.online),n=t.find(r=>r.id===this.store.currentAgent)||t[0];n&&(this.convModalAgent=n.id,this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider).then(()=>{this.showConversationModal&&this.store.folders.length===0&&!this._foldersRetried&&(this._foldersRetried=!0,setTimeout(()=>{this.showConversationModal&&this.convModalAgent&&this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider)},1500))}))},openConversationModalResume(){this.openConversationModal()},closeConversationModal(){this.showConversationModal=!1,this.convModalAgent="",this.convModalWorkDir="",this.selectedResumeSession=null,this.historyLoaded=!1},onConvModalAgentChange(){this.convModalAgent&&(this.convModalWorkDir="",this.selectedResumeSession=null,this.historyLoaded=!1,this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider))},onConvModalProviderChange(){this.convModalWorkDir="",this.selectedResumeSession=null,this.historyLoaded=!1,this.convModalAgent&&this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider)},onConvModalWorkDirInput(){this.historyLoaded=!1,this.selectedResumeSession=null,this._workDirInputTimer&&clearTimeout(this._workDirInputTimer),this._workDirInputTimer=setTimeout(()=>{this.convModalWorkDir.trim()&&this.convModalAgent&&(this.store.listHistorySessionsForAgent(this.convModalAgent,this.convModalWorkDir.trim(),this.convModalProvider),this.historyLoaded=!0)},500)},selectConvModalFolder(e){this.convModalWorkDir=e,this.selectedResumeSession=null,this.convModalAgent&&(this.store.listHistorySessionsForAgent(this.convModalAgent,e,this.convModalProvider),this.historyLoaded=!0)},loadConvModalFolders(){this.convModalAgent&&this.store.listFoldersForAgent(this.convModalAgent,this.convModalProvider)},loadConvModalSessions(){this.convModalAgent&&this.convModalWorkDir.trim()&&(this.store.listHistorySessionsForAgent(this.convModalAgent,this.convModalWorkDir.trim(),this.convModalProvider),this.historyLoaded=!0)},toggleAgentDropdown(){this.showAgentDropdown=!this.showAgentDropdown,this.showAgentDropdown&&this.store.refreshAgents()},selectAgent(e){this.store.selectAgent(e),this.showAgentDropdown=!1},createNewConversation(){if(!this.convModalAgent)return;this.store.selectAgent(this.convModalAgent);let e=this.convModalWorkDir.trim()||this.selectedConvModalAgentWorkDir;this.store.createConversation(e,this.convModalAgent,null,this.buildConvOpts()),this.closeConversationModal()},buildConvOpts(){let e={provider:this.convModalProvider};return this.convModalProvider==="copilot"&&(e.providerOptions={allowAllTools:!0}),e},resumeSession(e){if(!this.convModalAgent)return;this.store.selectAgent(this.convModalAgent),this.store._pendingSessionTitle=e.title;let t=e.workDir||this.convModalWorkDir.trim()||this.selectedConvModalAgentWorkDir;this.store.resumeConversation(e.sessionId,t,this.convModalAgent,this.buildConvOpts()),this.closeConversationModal()},resumeSelectedSession(){if(!this.convModalAgent||!this.selectedResumeSession)return;this.store.selectAgent(this.convModalAgent),this.store._pendingSessionTitle=this.selectedResumeSession.title;let e=this.selectedResumeSession.workDir||this.convModalWorkDir.trim()||this.selectedConvModalAgentWorkDir;this.store.resumeConversation(this.selectedResumeSession.sessionId,e,this.convModalAgent,this.buildConvOpts()),this.closeConversationModal()},formatDate(e){return Eo(e,this.$t.bind(this))},selectConversation(e,t){this.store.leaveWorkCenter(),this.store.selectConversation(e,t,{refresh:!0}),this.store.closeSessionSidebar()},onSessionClick(e){if(e.agentOnline===!1){this.store.addMessage({type:"system",content:this.$t("chat.session.agentOffline")});return}if(this.store.isSplitMode&&this.store.activePanelId){this.store.leaveWorkCenter(),this.store.setPanelConversation(this.store.activePanelId,e.id,{refresh:!0}),this.store.closeSessionSidebar();return}this.selectConversation(e.id,e.agentId)},hideSessionFromSidebar(e){if(!e?.id)return;let t=e.provider||"claude-code";this.store.hideCatalogSession({catalogKey:`chat:${e.id}`,runtimeProvider:t,routeRef:{runtimeProvider:t,agentId:e.agentId||this.store.currentAgent||null,sessionId:e.id},title:this.getConversationTitle(e),workDir:e.workDir||"",agentName:e.agentName||"",availability:e.agentOnline===!1?"offline":"online",pinned:this.store.isSessionPinned(e.id)})},closeSession(e,t){this.store.closeSession(e,t)},async deleteConversation(e,t){await De(this.$t("chat.delete.confirm"),{destructive:!0})&&this.store.deleteConversation(e,t)},getConversationTitle(e){let t=this.store.getConversationTitle(e.id);return t?t.length>30?t.slice(0,30)+"...":t:e.claudeSessionId?e.claudeSessionId.slice(0,8)+"...":e.id.slice(0,8)+"..."},getConversationFullTitle(e){let t=this.store.getConversationTitle(e.id);if(t&&t.length>30)return t},startChatRename(e){this.editingChatId=e.id,this.editingChatName=this.store.customConversationTitles[e.id]||this.store.conversationTitles[e.id]||"",this.$nextTick(()=>{let t=this.$refs.chatRenameInput;if(t){let s=Array.isArray(t)?t[0]:t;s.focus(),s.select()}})},commitChatRename(){if(!this.editingChatId)return;let e=this.editingChatId,t=this.editingChatName.trim();this.editingChatId=null,this.editingChatName="",this.store.renameChatSession(e,t)},cancelChatRename(){this.editingChatId=null,this.editingChatName=""},toggleSessionMenu(e){this.activeSessionMenu=this.activeSessionMenu===e?null:e},closeSessionMenu(){this.activeSessionMenu=null},getConversationTime(e){let s=this.store.executionStatusMap[e.id]?.lastActivity||e.createdAt;if(!s)return"";let n=new Date(s),r=new Date,i=r-n;return i<6e4?this.$t("chat.time.justNow"):i<36e5?this.$t("chat.time.minutesAgo",{count:Math.floor(i/6e4)}):n.toDateString()===r.toDateString()?n.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):n.toLocaleDateString(void 0,{month:"numeric",day:"numeric"})},providerLabel(e){return e==="copilot"?this.$t("provider.copilot"):e==="claude-code"?this.$t("provider.claudeCode"):e||""},shortenPath(e){return qo(e)},formatTime(e){return e?new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"}):""},getLastPathSegment(e){return Br(e)},getParentPath(e){if(!e)return"";let t=e.split(/[/\\]/);return t.length<=2?"":t.slice(0,-1).join("/")},handleResize(){this.windowWidth=window.innerWidth},openAgentSettings(e){this.agentSettingsAgentId=e||null,this.showAgentSettings=!0},async restartAgent(e){let s=this.store.agents.find(n=>n.id===e)?.name||e;await De(this.$t("chat.agent.restartConfirm",{name:s}))&&this.store.restartAgent(e)},async upgradeAgent(e){let s=this.store.agents.find(n=>n.id===e)?.name||e;await De(this.$t("chat.agent.upgradeConfirm",{name:s}))&&this.store.upgradeAgent(e)},closeFolderPicker(){this.folderPickerOpen=!1,this._folderPickerRequestId=null,this._folderPickerRequestAgentId=null,this._folderPickerTimer&&(clearTimeout(this._folderPickerTimer),this._folderPickerTimer=null)},openFolderPicker(e){let t=this.convModalAgent;if(!t)return;this.folderPickerTarget=e,this.folderPickerOpen=!0,this.folderPickerSelected="",this.folderPickerLoading=!0;let s=this.convModalWorkDir,n=this.store.agents.find(a=>a.id===t),r=s||n?.workDir||"";this.folderPickerPath=r,this.folderPickerEntries=[];let i=`folder-picker-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this._folderPickerRequestId=i,this._folderPickerRequestAgentId=t;let o=()=>{this.store.sendWsMessage({type:"list_directory",conversationId:"_workdir_picker",directoryPickerScope:"agent",requestId:i,agentId:t,dirPath:r})};o(),this._folderPickerTimer&&clearTimeout(this._folderPickerTimer),this._folderPickerTimer=setTimeout(()=>{this.folderPickerLoading&&this.folderPickerOpen&&o()},5e3)},loadFolderPickerDir(e){let t=this.convModalAgent;if(!t)return;this.folderPickerLoading=!0,this.folderPickerSelected="",this.folderPickerEntries=[];let s=`folder-picker-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;this._folderPickerRequestId=s,this._folderPickerRequestAgentId=t;let n=()=>{this.store.sendWsMessage({type:"list_directory",conversationId:"_workdir_picker",directoryPickerScope:"agent",requestId:s,agentId:t,dirPath:e})};n(),this._folderPickerTimer&&clearTimeout(this._folderPickerTimer),this._folderPickerTimer=setTimeout(()=>{this.folderPickerLoading&&this.folderPickerOpen&&n()},5e3)},folderPickerNavigateUp(){if(!this.folderPickerPath)return;let e=this.folderPickerPath.includes("\\"),t=e?"\\":"/",s=this.folderPickerPath.replace(/[/\\]$/,"").split(/[/\\]/);if(s.pop(),s.length===0)this.folderPickerPath="",this.loadFolderPickerDir("");else if(e&&s.length===1&&/^[A-Za-z]:$/.test(s[0]))this.folderPickerPath=s[0]+"\\",this.loadFolderPickerDir(s[0]+"\\");else{let n=s.join(t);this.folderPickerPath=n,this.loadFolderPickerDir(n)}},folderPickerSelectItem(e){this.folderPickerSelected=e.name},folderPickerEnter(e){let s=this.folderPickerPath.includes("\\")||/^[A-Z]:/.test(e.name)?"\\":"/",n;this.folderPickerPath?n=this.folderPickerPath.replace(/[/\\]$/,"")+s+e.name:/^[A-Z]:$/.test(e.name)?n=e.name+"\\":n="/"+e.name,this.folderPickerPath=n,this.loadFolderPickerDir(n)},confirmFolderPicker(){let e=this.folderPickerPath;if(e){if(this.folderPickerSelected){let t=e.includes("\\")?"\\":"/";e=e.replace(/[/\\]$/,"")+t+this.folderPickerSelected}this.convModalWorkDir=e,this.selectedResumeSession=null,this.convModalAgent&&(this.store.listHistorySessionsForAgent(this.convModalAgent,e,this.convModalProvider),this.historyLoaded=!0),this.closeFolderPicker()}},handleFolderPickerMessage(e){let t=e.detail;!t||t.type!=="directory_listing"||t.conversationId!=="_workdir_picker"||!this.folderPickerOpen||!this._folderPickerRequestId||t.requestId!==this._folderPickerRequestId||this.convModalAgent!==this._folderPickerRequestAgentId||(this._folderPickerTimer&&(clearTimeout(this._folderPickerTimer),this._folderPickerTimer=null),this._folderPickerRequestId=null,this._folderPickerRequestAgentId=null,this.folderPickerLoading=!1,this.folderPickerEntries=(t.entries||[]).filter(s=>s.type==="directory").sort((s,n)=>s.name.localeCompare(n.name)),t.dirPath!=null&&(this.folderPickerPath=t.dirPath))}},mounted(){if(this.store.openUnifiedChatCreate){let e=this.store.openUnifiedChatCreate;this.store.openUnifiedChatCreate=!1,this.convModalProvider=e==="copilot"?"copilot":"claude-code",this.openConversationModal({preserveProvider:!0})}this._clickOutsideHandler=e=>{e.target.closest(".agent-selector")||(this.showAgentDropdown=!1),!e.target.closest(".session-dots-btn")&&!e.target.closest(".session-menu")&&(this.activeSessionMenu=null)},document.addEventListener("click",this._clickOutsideHandler),window.addEventListener("resize",this.handleResize),window.addEventListener("workbench-message",this.handleFolderPickerMessage),fetch("/api/version").then(e=>e.json()).then(e=>{this.serverVersion=e.version}).catch(()=>{}),this._agentUpgradeAckHandler=e=>{let{success:t,error:s,alreadyLatest:n,version:r,reason:i,currentNode:o,requiredNode:a}=e.detail||{};t?n&&it(this.$t("chat.agent.alreadyLatest",{version:r||""})):i==="node_incompatible"?it(this.$t("chat.agent.nodeIncompatible",{current:o||"?",required:a||"?",version:r||""})):i==="container_image_upgrade_required"?it(this.$t("chat.agent.containerImageUpgradeRequired",{version:r||"?"})):i==="manual_upgrade_required"?it(this.$t("chat.agent.manualUpgradeRequired",{version:r||"?"})):it(`Agent upgrade failed: ${s||"Unknown error"}`)},window.addEventListener("agent-upgrade-ack",this._agentUpgradeAckHandler)},beforeUnmount(){document.removeEventListener("click",this._clickOutsideHandler),window.removeEventListener("resize",this.handleResize),window.removeEventListener("workbench-message",this.handleFolderPickerMessage),window.removeEventListener("agent-upgrade-ack",this._agentUpgradeAckHandler),this._folderPickerTimer&&clearTimeout(this._folderPickerTimer)}}});function Wh(e={}){let{sessions:t,activeSessionId:s,activeSessionKey:n,pinnedSessionIds:r,onlineAgentIds:i}=e,o=s||null,a=n||null,l=Object.prototype.hasOwnProperty.call(e,"activeSessionKey"),c=Array.isArray(r)?r:[],d=Array.isArray(i)?new Set(i.filter(Boolean)):null,u=new Map;c.forEach((f,g)=>{typeof f=="string"&&f&&!u.has(f)&&u.set(f,g)});let p=[];for(let f of Array.isArray(t)?t:[]){if(!f||!f.id||d&&f.agentId&&!d.has(f.agentId))continue;let g=String(f.id),h=f.agentId?`${f.agentId}${g}`:g;p.push({kind:"session",id:g,raw:f,pinned:!!f.pinned||!f.agentId&&u.has(g),active:l?h===a:g===o,processing:!!f.running||!!f.active||!!f.isRunning||!!f.isActive,_manualOrder:Number.isFinite(f.sortOrder)?f.sortOrder:Number.MAX_SAFE_INTEGER,_activityTime:Li(f)})}return p.sort((f,g)=>{if(f.pinned!==g.pinned)return f.pinned?-1:1;if(f._manualOrder!==g._manualOrder)return f._manualOrder-g._manualOrder;if(f._activityTime!==g._activityTime)return g._activityTime-f._activityTime;let h=u.has(f.id)?u.get(f.id):Number.MAX_SAFE_INTEGER,m=u.has(g.id)?u.get(g.id):Number.MAX_SAFE_INTEGER;return h!==m?h-m:f.id.localeCompare(g.id)}),p.map(({_manualOrder:f,_activityTime:g,...h})=>h)}var jh=F(()=>{$i()});var Gw,Lx,Uh,Kh=F(()=>{ot();Lo();uc();pc();fc();gc();mc();Cc();jh();Gw=3600*1e3,Lx=24*Gw,Uh={name:"YeaftSidebar",components:{SessionCreateModal:Ln,SidebarModeToggle:Mo,SidebarAgentHeader:Po,SidebarWorkCenter:Ro,SessionSidebarShell:_o,UnifiedSessionList:Do},emits:["select-group","select-chat","toggle-sidebar","back","open-settings","open-agent-settings","open-group-settings"],template:`
|
|
7300
7313
|
<SessionSidebarShell class="yeaft-sidebar" :collapsed="collapsed">
|
|
7301
7314
|
<template #collapsed>
|
|
7302
7315
|
<!-- Collapsed Icon Bar \u2014 mirrors Chat's .sidebar-collapsed-bar so the
|
|
@@ -7327,6 +7340,7 @@ ${String(e||"").trim()}
|
|
|
7327
7340
|
:upgrading-agents="upgradingAgents"
|
|
7328
7341
|
:show-agent-actions="true"
|
|
7329
7342
|
@open-agent-settings="$emit('open-agent-settings')"
|
|
7343
|
+
@restart-agent="restartAgent"
|
|
7330
7344
|
@upgrade-agent="upgradeAgent"
|
|
7331
7345
|
/>
|
|
7332
7346
|
<div class="sidebar-header-actions">
|
|
@@ -7477,7 +7491,7 @@ ${String(e||"").trim()}
|
|
|
7477
7491
|
</button>
|
|
7478
7492
|
</div>
|
|
7479
7493
|
</SessionSidebarShell>
|
|
7480
|
-
`,props:{collapsed:{type:Boolean,default:!1}},data(){return{now:Date.now(),sessionCreateOpen:!1,sessionCreateProject:null,groupMenu:{open:!1,groupId:null},draggedSessionKey:null,dragOverSessionKey:null,serverVersion:""}},created(){try{typeof fetch=="function"&&fetch("/api/version").then(e=>e.json()).then(e=>{this.serverVersion=e&&e.version||""}).catch(()=>{})}catch{}},mounted(){if(this.chatStore?.openUnifiedSessionCreate&&(this.chatStore.openUnifiedSessionCreate=!1,this.sessionCreateOpen=!0),this.chatStore?.pendingUnifiedSessionSettings){let e=this.chatStore.pendingUnifiedSessionSettings;this.chatStore.pendingUnifiedSessionSettings=null,this.openGroupSettings({id:e.sessionId,agentId:e.agentId},e.section||"session")}this._agentUpgradeAckHandler=e=>{let{success:t,error:s,alreadyLatest:n,version:r,reason:i,currentNode:o,requiredNode:a}=e.detail||{};t?n&&it(this.$t("chat.agent.alreadyLatest",{version:r||""})):i==="node_incompatible"?it(this.$t("chat.agent.nodeIncompatible",{current:o||"?",required:a||"?",version:r||""})):i==="container_image_upgrade_required"?it(this.$t("chat.agent.containerImageUpgradeRequired",{version:r||"?"})):i==="manual_upgrade_required"?it(this.$t("chat.agent.manualUpgradeRequired",{version:r||"?"})):it(`Agent upgrade failed: ${s||"Unknown error"}`)},typeof window<"u"&&window.addEventListener("agent-upgrade-ack",this._agentUpgradeAckHandler)},beforeUnmount(){typeof window<"u"&&window.removeEventListener("agent-upgrade-ack",this._agentUpgradeAckHandler)},computed:{store(){try{if(typeof Pinia<"u"&&Pinia.useChatStore)return Pinia.useChatStore()}catch{}return null},sessionsStore(){try{if(typeof window<"u"&&window.Pinia?.useSessionsStore)return window.Pinia.useSessionsStore()}catch{}return null},activeSessionId(){return this.chatStore?.yeaftActiveSessionFilter||this.sessionsStore?.activeSessionId||null},activeSessionKey(){let e=this.sessionsStore?.activeSessionKey||null;return(e?this.sessionsStore?.sessions?.[e]:null)?.id===this.activeSessionId?e:null},sessionList(){let e=Wh({sessions:this.sessionsStore?.sessionList||[],activeSessionId:this.activeSessionId,activeSessionKey:this.activeSessionKey,pinnedSessionIds:this.chatStore?.pinnedSessions||[],onlineAgentIds:Array.isArray(this.onlineAgents)?this.onlineAgents.map(n=>n.id):void 0}),t=new Set((this.chatStore?.hiddenSessionCatalog||[]).filter(n=>n?.runtimeProvider==="yeaft").map(n=>`${n.routeRef?.agentId||""}${n.routeRef?.sessionId||""}`)),s=this.chatStore?.currentAgent||"";return e.filter(n=>!t.has(`${n.raw?.agentId||s}${n.id||""}`))},restartingAgents(){return Object.fromEntries(Object.entries(this.chatStore?.agentOperations||{}).filter(([,e])=>e.restart?.pending))},upgradingAgents(){return Object.fromEntries(Object.entries(this.chatStore?.agentOperations||{}).filter(([,e])=>e.upgrade?.pending))},chatStore(){if(this.store)return this.store;try{if(typeof window<"u"&&window.Pinia?.useChatStore)return window.Pinia.useChatStore()}catch{}return null},onlineAgents(){let e=this.chatStore||this.store;return!e||!Array.isArray(e.agents)?[]:e.agents.filter(t=>t&&t.online)},onlineAgentCount(){return this.onlineAgents.length},workCenterAgents(){return this.onlineAgents.filter(e=>Array.isArray(e.capabilities)&&e.capabilities.includes("work_center"))},currentAgentName(){let e=this.chatStore||this.store;if(!e||!Array.isArray(e.agents))return"";let t=e.currentAgent;if(t){let n=e.agents.find(r=>r&&r.id===t);if(n&&n.name)return String(n.name);if(n&&n.id)return String(n.id)}let s=e.agents.find(n=>n&&n.online);return s?String(s.name||s.id||""):"Agent"},currentAgentOnline(){let e=this.chatStore||this.store;if(!e||!Array.isArray(e.agents))return!1;let t=e.currentAgent;if(t){let s=e.agents.find(n=>n&&n.id===t);if(s)return!!s.online}return e.agents.some(s=>s&&s.online)},agentTitleText(){let e=this.chatStore||this.store;return!e||!e.currentAgent?"":String(e.currentAgent)}},methods:{tr(e,t){if(typeof this.$t=="function"){let s=this.$t(e);if(s&&s!==e)return s}return t},isSessionProcessing(e,t=null){let s=this.chatStore||this.store;return!s||!e?!1:typeof s.isYeaftSessionProcessing=="function"?s.isYeaftSessionProcessing(e,t):!1},isCatalogSessionUnread(e){if(e?.runtimeProvider!=="yeaft")return!1;let t=this.chatStore||this.store;return!t||typeof t.isYeaftSessionUnread!="function"?!1:t.isYeaftSessionUnread(e.routeRef?.sessionId,e.routeRef?.agentId)},onModeFlip(e){e==="chat"&&this.$emit("back")},onOpenWorkCenter(e=null){let t=this.chatStore||this.store,s=this.workCenterAgents.find(n=>n.id===e)||this.workCenterAgents.find(n=>n.id===t?.workCenterAgentId)||this.workCenterAgents[0];s&&t&&typeof t.enterWorkCenter=="function"&&t.enterWorkCenter(s.id)},onOpenPlugins(){let e=this.chatStore||this.store;e&&typeof e.openPluginCenter=="function"&&e.openPluginCenter()},async upgradeAgent(e){let t=this.chatStore||this.store;if(!t||typeof t.upgradeAgent!="function")return;let n=t.agents?.find(r=>r?.id===e)?.name||e;await Ee(this.$t("chat.agent.upgradeConfirm",{name:n}))&&t.upgradeAgent(e)},onGroupCreated(e){},onOpenSessionCreate(){this.sessionCreateProject=null,this.sessionCreateOpen=!0},onUnifiedCreate(){this.onOpenSessionCreate()},onUnifiedCreateInProject({project:e}={}){e?.id&&(this.sessionCreateProject=e,this.sessionCreateOpen=!0)},closeSessionCreate(){this.sessionCreateOpen=!1,this.sessionCreateProject=null},onUnifiedSessionAction({action:e,row:t,title:s,sessions:n}={}){if(!t?.routeRef)return;let r=this.chatStore||this.store,{runtimeProvider:i,agentId:o,sessionId:a}=t.routeRef;e==="rename"?r?.renameCatalogSession?.({row:t,title:s}):e==="reorder"?r?.reorderCatalogSessions?.(n):e==="pin"?r?.toggleCatalogSessionPin?.(t):i==="yeaft"&&e==="settings"?this.openGroupSettings({id:a,agentId:o},"session"):e==="remove"&&r?.hideCatalogSession?.(t)},async onSessionCreated(e){let t=this.sessionCreateProject;if(this.closeSessionCreate(),!t||!e?.id)return;let s=this.chatStore||this.store,n=e.agentId||t.legacyAgentId||s?.currentAgent||null,r=await s?.mutateProject?.("move_session",{sessionId:e.id,projectId:t.legacyProjectId||t.id},n);if(!r?.ok){let i=r?.error?.message||r?.error?.code||"unknown";await it(this.$t("sidebar.projects.assignFailed",{name:t.name,message:i}))}},onSelectGroup(e){if(!e||!e.id)return;let t=this.chatStore||this.store;t&&typeof t.leaveWorkCenter=="function"&&t.leaveWorkCenter(),e.agentId&&this.chatStore&&this.chatStore.currentAgent!==e.agentId&&(typeof this.chatStore.selectAgent=="function"?this.chatStore.selectAgent(e.agentId):this.chatStore.currentAgent=e.agentId),this.sessionsStore&&this.sessionsStore.setActive(e.id,e.agentId||null),this.$emit("select-group",e)},sessionDragKey(e){return!e||!e.id?"":e.agentId?`${e.agentId}${e.id}`:`legacy${e.id}`},onSessionDragStart(e,t){let s=this.sessionDragKey(e);s&&(this.groupMenu={open:!1,groupId:null},this.draggedSessionKey=s,this.dragOverSessionKey=null,t?.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",s)))},onSessionDragOver(e,t){let s=this.sessionDragKey(e);!s||!this.draggedSessionKey||s===this.draggedSessionKey||(this.dragOverSessionKey=s,t?.dataTransfer&&(t.dataTransfer.dropEffect="move"))},onSessionDragLeave(e,t){let s=this.sessionDragKey(e);if(!s||this.dragOverSessionKey!==s)return;let n=t?.relatedTarget;n&&t?.currentTarget?.contains&&t.currentTarget.contains(n)||(this.dragOverSessionKey=null)},onSessionDrop(e,t){let s=this.draggedSessionKey||t?.dataTransfer?.getData?.("text/plain")||null,n=this.sessionDragKey(e);this.draggedSessionKey=null,this.dragOverSessionKey=null,!(!s||!n||s===n)&&this.reorderSessionRows(s,n)},onSessionDragEnd(){this.draggedSessionKey=null,this.dragOverSessionKey=null},reorderSessionRows(e,t){let s=this.sessionList.map(l=>this.sessionDragKey(l.raw)).filter(Boolean),n=s.indexOf(e),r=s.indexOf(t);if(n<0||r<0||n===r)return;let[i]=s.splice(n,1);s.splice(r,0,i);let o=this.sessionsStore?.reorderSessionsGlobally?.(s)||[],a=this.chatStore?.sessionCrudRequest;typeof a=="function"&&a.call(this.chatStore,"reorder",{sessions:o})},sessionAgentName(e){if(!e||!e.agentId)return"";let t=this.chatStore||this.store;if(!t||!Array.isArray(t.agents))return String(e.agentName||e.agentId||"");let s=t.agents.find(n=>n&&n.id===e.agentId);return String(s?.name||e.agentName||e.agentId||"")},groupPath(e){return qo(e?.workDir)},openGroupSettings(e,t="members"){!e||!e.id||this.$emit("open-group-settings",{sessionId:e.id,agentId:e.agentId||null,section:t})},openGroupSettingsFromMenu(e,t){this.groupMenu={open:!1,groupId:null},this.openGroupSettings(e,t)},isSessionPinned(e){let t=e&&typeof e=="object"?e.id:e,s=!!(e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"pinned")),n=!!(s&&e.pinned);if(s&&e.agentId)return n;let r=this.chatStore&&this.chatStore.isSessionPinned;return n||(typeof r=="function"?!!r.call(this.chatStore,t):!1)},onTogglePin(e){if(this.groupMenu={open:!1,groupId:null},!e||!e.id)return;let t=this.chatStore&&this.chatStore.togglePin;typeof t=="function"&&t.call(this.chatStore,e.id,{sessionKind:"yeaft",agentId:e.agentId||this.store?.currentAgent||null,sessionName:e.name||e.title||e.id,workDir:e.workDir||"",pinned:!!e.pinned})},onRemoveFromList(e){if(this.groupMenu={open:!1,groupId:null},!e||!e.id)return;let t=e.agentId||this.chatStore?.currentAgent||null;if(!t||typeof this.chatStore?.hideCatalogSession!="function")return;let s=`yeaft:${t}:${e.id}`,n=this.chatStore.sessionCatalog?.find(r=>r.catalogKey===s)||{catalogKey:s,runtimeProvider:"yeaft",routeRef:{runtimeProvider:"yeaft",agentId:t,sessionId:e.id},title:e.name||e.id,workDir:e.workDir||"",agentName:this.sessionAgentName(e),availability:this.onlineAgents.some(r=>r.id===t)?"online":"offline",pinned:!!e.pinned};this.chatStore.hideCatalogSession(n)},groupDisplayName(e){return e?e.id==="grp_default"&&(e.name==="Default"||!e.name)?this.$t("yeaft.session.defaultName"):e.name||e.id||"":""},groupTime(e){let t=e&&e.createdAt?e.createdAt:null;if(!t)return"";let s=new Date(t),n=new Date,r=n-s;return r<6e4?this.$t("chat.time.justNow"):r<36e5?this.$t("chat.time.minutesAgo",{count:Math.floor(r/6e4)}):s.toDateString()===n.toDateString()?s.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):s.toLocaleDateString(void 0,{month:"numeric",day:"numeric"})},groupSubtitle(e){if(!e)return"";let t=Array.isArray(e.roster)?e.roster.length:0;if(t===0)return this.$t("yeaft.session.empty.title");let s=t===1?"yeaft.session.memberCount.one":"yeaft.session.memberCount.other";return this.$t(s,{count:t})},openGroupMenu(e,t){if(!e||!e.id)return;let s=this.sessionDragKey(e);if(!s)return;if(this.groupMenu.open&&this.groupMenu.groupId===s){this.groupMenu={open:!1,groupId:null};return}this.groupMenu={open:!0,groupId:s};let n=r=>{r&&r.target&&r.target.closest&&r.target.closest(".session-menu")||(this.groupMenu={open:!1,groupId:null},window.removeEventListener("click",n,!0))};setTimeout(()=>window.addEventListener("click",n,!0),0),t&&typeof t.stopPropagation=="function"&&t.stopPropagation()}}}});var zh,Yh=F(()=>{zh={name:"SessionInviteModal",emits:["open-library","dismiss"],props:{groupName:{type:String,default:""}},template:`
|
|
7494
|
+
`,props:{collapsed:{type:Boolean,default:!1}},data(){return{now:Date.now(),sessionCreateOpen:!1,sessionCreateProject:null,groupMenu:{open:!1,groupId:null},draggedSessionKey:null,dragOverSessionKey:null,serverVersion:""}},created(){try{typeof fetch=="function"&&fetch("/api/version").then(e=>e.json()).then(e=>{this.serverVersion=e&&e.version||""}).catch(()=>{})}catch{}},mounted(){if(this.chatStore?.openUnifiedSessionCreate&&(this.chatStore.openUnifiedSessionCreate=!1,this.sessionCreateOpen=!0),this.chatStore?.pendingUnifiedSessionSettings){let e=this.chatStore.pendingUnifiedSessionSettings;this.chatStore.pendingUnifiedSessionSettings=null,this.openGroupSettings({id:e.sessionId,agentId:e.agentId},e.section||"session")}this._agentUpgradeAckHandler=e=>{let{success:t,error:s,alreadyLatest:n,version:r,reason:i,currentNode:o,requiredNode:a}=e.detail||{};t?n&&it(this.$t("chat.agent.alreadyLatest",{version:r||""})):i==="node_incompatible"?it(this.$t("chat.agent.nodeIncompatible",{current:o||"?",required:a||"?",version:r||""})):i==="container_image_upgrade_required"?it(this.$t("chat.agent.containerImageUpgradeRequired",{version:r||"?"})):i==="manual_upgrade_required"?it(this.$t("chat.agent.manualUpgradeRequired",{version:r||"?"})):it(`Agent upgrade failed: ${s||"Unknown error"}`)},typeof window<"u"&&window.addEventListener("agent-upgrade-ack",this._agentUpgradeAckHandler)},beforeUnmount(){typeof window<"u"&&window.removeEventListener("agent-upgrade-ack",this._agentUpgradeAckHandler)},computed:{store(){try{if(typeof Pinia<"u"&&Pinia.useChatStore)return Pinia.useChatStore()}catch{}return null},sessionsStore(){try{if(typeof window<"u"&&window.Pinia?.useSessionsStore)return window.Pinia.useSessionsStore()}catch{}return null},activeSessionId(){return this.chatStore?.yeaftActiveSessionFilter||this.sessionsStore?.activeSessionId||null},activeSessionKey(){let e=this.sessionsStore?.activeSessionKey||null;return(e?this.sessionsStore?.sessions?.[e]:null)?.id===this.activeSessionId?e:null},sessionList(){let e=Wh({sessions:this.sessionsStore?.sessionList||[],activeSessionId:this.activeSessionId,activeSessionKey:this.activeSessionKey,pinnedSessionIds:this.chatStore?.pinnedSessions||[],onlineAgentIds:Array.isArray(this.onlineAgents)?this.onlineAgents.map(n=>n.id):void 0}),t=new Set((this.chatStore?.hiddenSessionCatalog||[]).filter(n=>n?.runtimeProvider==="yeaft").map(n=>`${n.routeRef?.agentId||""}${n.routeRef?.sessionId||""}`)),s=this.chatStore?.currentAgent||"";return e.filter(n=>!t.has(`${n.raw?.agentId||s}${n.id||""}`))},restartingAgents(){return Object.fromEntries(Object.entries(this.chatStore?.agentOperations||{}).filter(([,e])=>e.restart?.pending))},upgradingAgents(){return Object.fromEntries(Object.entries(this.chatStore?.agentOperations||{}).filter(([,e])=>e.upgrade?.pending))},chatStore(){if(this.store)return this.store;try{if(typeof window<"u"&&window.Pinia?.useChatStore)return window.Pinia.useChatStore()}catch{}return null},onlineAgents(){let e=this.chatStore||this.store;return!e||!Array.isArray(e.agents)?[]:e.agents.filter(t=>t&&t.online)},onlineAgentCount(){return this.onlineAgents.length},workCenterAgents(){return this.onlineAgents.filter(e=>Array.isArray(e.capabilities)&&e.capabilities.includes("work_center"))},currentAgentName(){let e=this.chatStore||this.store;if(!e||!Array.isArray(e.agents))return"";let t=e.currentAgent;if(t){let n=e.agents.find(r=>r&&r.id===t);if(n&&n.name)return String(n.name);if(n&&n.id)return String(n.id)}let s=e.agents.find(n=>n&&n.online);return s?String(s.name||s.id||""):"Agent"},currentAgentOnline(){let e=this.chatStore||this.store;if(!e||!Array.isArray(e.agents))return!1;let t=e.currentAgent;if(t){let s=e.agents.find(n=>n&&n.id===t);if(s)return!!s.online}return e.agents.some(s=>s&&s.online)},agentTitleText(){let e=this.chatStore||this.store;return!e||!e.currentAgent?"":String(e.currentAgent)}},methods:{tr(e,t){if(typeof this.$t=="function"){let s=this.$t(e);if(s&&s!==e)return s}return t},isSessionProcessing(e,t=null){let s=this.chatStore||this.store;return!s||!e?!1:typeof s.isYeaftSessionProcessing=="function"?s.isYeaftSessionProcessing(e,t):!1},isCatalogSessionUnread(e){if(e?.runtimeProvider!=="yeaft")return!1;let t=this.chatStore||this.store;return!t||typeof t.isYeaftSessionUnread!="function"?!1:t.isYeaftSessionUnread(e.routeRef?.sessionId,e.routeRef?.agentId)},onModeFlip(e){e==="chat"&&this.$emit("back")},onOpenWorkCenter(e=null){let t=this.chatStore||this.store,s=this.workCenterAgents.find(n=>n.id===e)||this.workCenterAgents.find(n=>n.id===t?.workCenterAgentId)||this.workCenterAgents[0];s&&t&&typeof t.enterWorkCenter=="function"&&t.enterWorkCenter(s.id)},onOpenPlugins(){let e=this.chatStore||this.store;e&&typeof e.openPluginCenter=="function"&&e.openPluginCenter()},async restartAgent(e){let t=this.chatStore||this.store;if(!t||typeof t.restartAgent!="function")return;let n=t.agents?.find(r=>r?.id===e)?.name||e;await De(this.$t("chat.agent.restartConfirm",{name:n}))&&t.restartAgent(e)},async upgradeAgent(e){let t=this.chatStore||this.store;if(!t||typeof t.upgradeAgent!="function")return;let n=t.agents?.find(r=>r?.id===e)?.name||e;await De(this.$t("chat.agent.upgradeConfirm",{name:n}))&&t.upgradeAgent(e)},onGroupCreated(e){},onOpenSessionCreate(){this.sessionCreateProject=null,this.sessionCreateOpen=!0},onUnifiedCreate(){this.onOpenSessionCreate()},onUnifiedCreateInProject({project:e}={}){e?.id&&(this.sessionCreateProject=e,this.sessionCreateOpen=!0)},closeSessionCreate(){this.sessionCreateOpen=!1,this.sessionCreateProject=null},onUnifiedSessionAction({action:e,row:t,title:s,sessions:n}={}){if(!t?.routeRef)return;let r=this.chatStore||this.store,{runtimeProvider:i,agentId:o,sessionId:a}=t.routeRef;e==="rename"?r?.renameCatalogSession?.({row:t,title:s}):e==="reorder"?r?.reorderCatalogSessions?.(n):e==="pin"?r?.toggleCatalogSessionPin?.(t):i==="yeaft"&&e==="settings"?this.openGroupSettings({id:a,agentId:o},"session"):e==="remove"&&r?.hideCatalogSession?.(t)},async onSessionCreated(e){let t=this.sessionCreateProject;if(this.closeSessionCreate(),!t||!e?.id)return;let s=this.chatStore||this.store,n=e.agentId||t.legacyAgentId||s?.currentAgent||null,r=await s?.mutateProject?.("move_session",{sessionId:e.id,projectId:t.legacyProjectId||t.id},n);if(!r?.ok){let i=r?.error?.message||r?.error?.code||"unknown";await it(this.$t("sidebar.projects.assignFailed",{name:t.name,message:i}))}},onSelectGroup(e){if(!e||!e.id)return;let t=this.chatStore||this.store;t&&typeof t.leaveWorkCenter=="function"&&t.leaveWorkCenter(),e.agentId&&this.chatStore&&this.chatStore.currentAgent!==e.agentId&&(typeof this.chatStore.selectAgent=="function"?this.chatStore.selectAgent(e.agentId):this.chatStore.currentAgent=e.agentId),this.sessionsStore&&this.sessionsStore.setActive(e.id,e.agentId||null),this.$emit("select-group",e)},sessionDragKey(e){return!e||!e.id?"":e.agentId?`${e.agentId}${e.id}`:`legacy${e.id}`},onSessionDragStart(e,t){let s=this.sessionDragKey(e);s&&(this.groupMenu={open:!1,groupId:null},this.draggedSessionKey=s,this.dragOverSessionKey=null,t?.dataTransfer&&(t.dataTransfer.effectAllowed="move",t.dataTransfer.setData("text/plain",s)))},onSessionDragOver(e,t){let s=this.sessionDragKey(e);!s||!this.draggedSessionKey||s===this.draggedSessionKey||(this.dragOverSessionKey=s,t?.dataTransfer&&(t.dataTransfer.dropEffect="move"))},onSessionDragLeave(e,t){let s=this.sessionDragKey(e);if(!s||this.dragOverSessionKey!==s)return;let n=t?.relatedTarget;n&&t?.currentTarget?.contains&&t.currentTarget.contains(n)||(this.dragOverSessionKey=null)},onSessionDrop(e,t){let s=this.draggedSessionKey||t?.dataTransfer?.getData?.("text/plain")||null,n=this.sessionDragKey(e);this.draggedSessionKey=null,this.dragOverSessionKey=null,!(!s||!n||s===n)&&this.reorderSessionRows(s,n)},onSessionDragEnd(){this.draggedSessionKey=null,this.dragOverSessionKey=null},reorderSessionRows(e,t){let s=this.sessionList.map(l=>this.sessionDragKey(l.raw)).filter(Boolean),n=s.indexOf(e),r=s.indexOf(t);if(n<0||r<0||n===r)return;let[i]=s.splice(n,1);s.splice(r,0,i);let o=this.sessionsStore?.reorderSessionsGlobally?.(s)||[],a=this.chatStore?.sessionCrudRequest;typeof a=="function"&&a.call(this.chatStore,"reorder",{sessions:o})},sessionAgentName(e){if(!e||!e.agentId)return"";let t=this.chatStore||this.store;if(!t||!Array.isArray(t.agents))return String(e.agentName||e.agentId||"");let s=t.agents.find(n=>n&&n.id===e.agentId);return String(s?.name||e.agentName||e.agentId||"")},groupPath(e){return qo(e?.workDir)},openGroupSettings(e,t="members"){!e||!e.id||this.$emit("open-group-settings",{sessionId:e.id,agentId:e.agentId||null,section:t})},openGroupSettingsFromMenu(e,t){this.groupMenu={open:!1,groupId:null},this.openGroupSettings(e,t)},isSessionPinned(e){let t=e&&typeof e=="object"?e.id:e,s=!!(e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"pinned")),n=!!(s&&e.pinned);if(s&&e.agentId)return n;let r=this.chatStore&&this.chatStore.isSessionPinned;return n||(typeof r=="function"?!!r.call(this.chatStore,t):!1)},onTogglePin(e){if(this.groupMenu={open:!1,groupId:null},!e||!e.id)return;let t=this.chatStore&&this.chatStore.togglePin;typeof t=="function"&&t.call(this.chatStore,e.id,{sessionKind:"yeaft",agentId:e.agentId||this.store?.currentAgent||null,sessionName:e.name||e.title||e.id,workDir:e.workDir||"",pinned:!!e.pinned})},onRemoveFromList(e){if(this.groupMenu={open:!1,groupId:null},!e||!e.id)return;let t=e.agentId||this.chatStore?.currentAgent||null;if(!t||typeof this.chatStore?.hideCatalogSession!="function")return;let s=`yeaft:${t}:${e.id}`,n=this.chatStore.sessionCatalog?.find(r=>r.catalogKey===s)||{catalogKey:s,runtimeProvider:"yeaft",routeRef:{runtimeProvider:"yeaft",agentId:t,sessionId:e.id},title:e.name||e.id,workDir:e.workDir||"",agentName:this.sessionAgentName(e),availability:this.onlineAgents.some(r=>r.id===t)?"online":"offline",pinned:!!e.pinned};this.chatStore.hideCatalogSession(n)},groupDisplayName(e){return e?e.id==="grp_default"&&(e.name==="Default"||!e.name)?this.$t("yeaft.session.defaultName"):e.name||e.id||"":""},groupTime(e){let t=e&&e.createdAt?e.createdAt:null;if(!t)return"";let s=new Date(t),n=new Date,r=n-s;return r<6e4?this.$t("chat.time.justNow"):r<36e5?this.$t("chat.time.minutesAgo",{count:Math.floor(r/6e4)}):s.toDateString()===n.toDateString()?s.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):s.toLocaleDateString(void 0,{month:"numeric",day:"numeric"})},groupSubtitle(e){if(!e)return"";let t=Array.isArray(e.roster)?e.roster.length:0;if(t===0)return this.$t("yeaft.session.empty.title");let s=t===1?"yeaft.session.memberCount.one":"yeaft.session.memberCount.other";return this.$t(s,{count:t})},openGroupMenu(e,t){if(!e||!e.id)return;let s=this.sessionDragKey(e);if(!s)return;if(this.groupMenu.open&&this.groupMenu.groupId===s){this.groupMenu={open:!1,groupId:null};return}this.groupMenu={open:!0,groupId:s};let n=r=>{r&&r.target&&r.target.closest&&r.target.closest(".session-menu")||(this.groupMenu={open:!1,groupId:null},window.removeEventListener("click",n,!0))};setTimeout(()=>window.addEventListener("click",n,!0),0),t&&typeof t.stopPropagation=="function"&&t.stopPropagation()}}}});var zh,Yh=F(()=>{zh={name:"SessionInviteModal",emits:["open-library","dismiss"],props:{groupName:{type:String,default:""}},template:`
|
|
7481
7495
|
<div class="group-invite-overlay" @click.self="onDismiss" role="dialog" aria-modal="true" :aria-label="$t('yeaft.session.invite.title')">
|
|
7482
7496
|
<div class="group-invite-modal">
|
|
7483
7497
|
<header class="group-invite-header">
|