pi-web-ui 0.65.0 → 0.66.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +42 -0
- package/README.zh-CN.md +466 -427
- package/dist/server/agent-service.js +45 -9
- package/dist/server/update-check.js +55 -16
- package/package.json +1 -1
- package/web/dist/assets/{TerminalPanel-B_ACe6Lp.js → TerminalPanel-Bu0PEPj5.js} +1 -1
- package/web/dist/assets/index-DiO-MN6k.css +10 -0
- package/web/dist/assets/{index-CaJbqnT7.js → index-DoOQgKox.js} +24 -24
- package/web/dist/index.html +2 -2
- package/web/dist/assets/index-Bq4P6EhG.css +0 -10
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-
|
|
2
|
-
import{R as tt,a as l,j as e,M as ki,b as ji,c as wi}from"./markdown-DRBrS2Nf.js";import{r as kn}from"./react-C9ovnpIm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))r(c);new MutationObserver(c=>{for(const i of c)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(c){const i={};return c.integrity&&(i.integrity=c.integrity),c.referrerPolicy&&(i.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?i.credentials="include":c.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(c){if(c.ep)return;c.ep=!0;const i=n(c);fetch(c.href,i)}})();var It={},Ds;function Ni(){if(Ds)return It;Ds=1;var t=kn();return It.createRoot=t.createRoot,It.hydrateRoot=t.hydrateRoot,It}var Ci=Ni();const Si="modulepreload",Ti=function(t){return"/"+t},As={},Ei=function(s,n,r){let c=Promise.resolve();if(n&&n.length>0){let a=function(m){return Promise.all(m.map(y=>Promise.resolve(y).then(x=>({status:"fulfilled",value:x}),x=>({status:"rejected",reason:x}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),u=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));c=a(n.map(m=>{if(m=Ti(m),m in As)return;As[m]=!0;const y=m.endsWith(".css"),x=y?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${x}`))return;const f=document.createElement("link");if(f.rel=y?"stylesheet":Si,y||(f.as="script"),f.crossOrigin="",f.href=m,u&&f.setAttribute("nonce",u),document.head.appendChild(f),y)return new Promise((b,T)=>{f.addEventListener("load",b),f.addEventListener("error",()=>T(new Error(`Unable to preload CSS for ${m}`)))})}))}function i(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return c.then(a=>{for(const o of a||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};var jn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},_s=tt.createContext&&tt.createContext(jn),Pi=["attr","size","title"];function Mi(t,s){if(t==null)return{};var n,r,c=Ii(t,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],s.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(c[n]=t[n])}return c}function Ii(t,s){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(s.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function Ft(){return Ft=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},Ft.apply(null,arguments)}function Bs(t,s){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);s&&(r=r.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),n.push.apply(n,r)}return n}function $t(t){for(var s=1;s<arguments.length;s++){var n=arguments[s]!=null?arguments[s]:{};s%2?Bs(Object(n),!0).forEach(function(r){Ri(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Bs(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Ri(t,s,n){return(s=Li(s))in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function Li(t){var s=Di(t,"string");return typeof s=="symbol"?s:s+""}function Di(t,s){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,s);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function wn(t){return t&&t.map((s,n)=>tt.createElement(s.tag,$t({key:n},s.attr),wn(s.child)))}function ne(t){return s=>tt.createElement(Ai,Ft({attr:$t({},t.attr)},s),wn(t.child))}function Ai(t){var s=n=>{var r=t.attr,c=t.size,i=t.title,a=Mi(t,Pi),o=c||n.size||"1em",u;return n.className&&(u=n.className),t.className&&(u=(u?u+" ":"")+t.className),tt.createElement("svg",Ft({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,a,{className:u,style:$t($t({color:t.color||n.color},n.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&tt.createElement("title",null,i),t.children)};return _s!==void 0?tt.createElement(_s.Consumer,null,n=>s(n)):s(jn)}function _i(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(t)}function Bi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"11",y1:"8",x2:"11",y2:"14"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(t)}function Dt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"},child:[]}]})(t)}function Re(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"18",y1:"6",x2:"6",y2:"18"},child:[]},{tag:"line",attr:{x1:"6",y1:"6",x2:"18",y2:"18"},child:[]}]})(t)}function Nn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"},child:[]},{tag:"path",attr:{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"},child:[]}]})(t)}function Fs(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"},child:[]},{tag:"circle",attr:{cx:"9",cy:"7",r:"4"},child:[]},{tag:"path",attr:{d:"M23 21v-2a4 4 0 0 0-3-3.87"},child:[]},{tag:"path",attr:{d:"M16 3.13a4 4 0 0 1 0 7.75"},child:[]}]})(t)}function Fi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"17 8 12 3 7 8"},child:[]},{tag:"line",attr:{x1:"12",y1:"3",x2:"12",y2:"15"},child:[]}]})(t)}function $i(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 9.9-1"},child:[]}]})(t)}function He(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(t)}function ot(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"4 17 10 11 4 5"},child:[]},{tag:"line",attr:{x1:"12",y1:"19",x2:"20",y2:"19"},child:[]}]})(t)}function $s(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"6"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"2"},child:[]}]})(t)}function Hs(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"},child:[]},{tag:"line",attr:{x1:"7",y1:"7",x2:"7.01",y2:"7"},child:[]}]})(t)}function Hi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"5"},child:[]},{tag:"line",attr:{x1:"12",y1:"1",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"23"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},child:[]},{tag:"line",attr:{x1:"1",y1:"12",x2:"3",y2:"12"},child:[]},{tag:"line",attr:{x1:"21",y1:"12",x2:"23",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},child:[]}]})(t)}function Ht(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]}]})(t)}function Oi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"4",y1:"21",x2:"4",y2:"14"},child:[]},{tag:"line",attr:{x1:"4",y1:"10",x2:"4",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"20",y1:"21",x2:"20",y2:"16"},child:[]},{tag:"line",attr:{x1:"20",y1:"12",x2:"20",y2:"3"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"7",y2:"14"},child:[]},{tag:"line",attr:{x1:"9",y1:"8",x2:"15",y2:"8"},child:[]},{tag:"line",attr:{x1:"17",y1:"16",x2:"23",y2:"16"},child:[]}]})(t)}function Ot(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]},{tag:"path",attr:{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"},child:[]}]})(t)}function Cn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"22",y1:"2",x2:"11",y2:"13"},child:[]},{tag:"polygon",attr:{points:"22 2 15 22 11 13 2 9 22 2"},child:[]}]})(t)}function Wt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]}]})(t)}function Wi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"},child:[]},{tag:"polyline",attr:{points:"17 21 17 13 7 13 7 21"},child:[]},{tag:"polyline",attr:{points:"7 3 7 8 15 8"},child:[]}]})(t)}function Sn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"1 4 1 10 7 10"},child:[]},{tag:"path",attr:{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"},child:[]}]})(t)}function rt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"polyline",attr:{points:"1 20 1 14 7 14"},child:[]},{tag:"path",attr:{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"},child:[]}]})(t)}function Ke(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(t)}function xo(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"5 3 19 12 5 21 5 3"},child:[]}]})(t)}function Ui(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"},child:[]}]})(t)}function Jt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"16.5",y1:"9.4",x2:"7.5",y2:"4.21"},child:[]},{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(t)}function Ki(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"19",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"5",cy:"12",r:"1"},child:[]}]})(t)}function qi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"},child:[]}]})(t)}function ct(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},child:[]}]})(t)}function zi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"3",y1:"12",x2:"21",y2:"12"},child:[]},{tag:"line",attr:{x1:"3",y1:"6",x2:"21",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"18",x2:"21",y2:"18"},child:[]}]})(t)}function Vi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"},child:[]}]})(t)}function Gi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 3 21 3 21 9"},child:[]},{tag:"polyline",attr:{points:"9 21 3 21 3 15"},child:[]},{tag:"line",attr:{x1:"21",y1:"3",x2:"14",y2:"10"},child:[]},{tag:"line",attr:{x1:"3",y1:"21",x2:"10",y2:"14"},child:[]}]})(t)}function Qi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 10 0v4"},child:[]}]})(t)}function ps(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"},child:[]},{tag:"path",attr:{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"},child:[]}]})(t)}function Ut(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"12 2 2 7 12 12 22 7 12 2"},child:[]},{tag:"polyline",attr:{points:"2 17 12 22 22 17"},child:[]},{tag:"polyline",attr:{points:"2 12 12 17 22 12"},child:[]}]})(t)}function Yi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12.01",y2:"8"},child:[]}]})(t)}function Ji(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]},{tag:"circle",attr:{cx:"8.5",cy:"8.5",r:"1.5"},child:[]},{tag:"polyline",attr:{points:"21 15 16 10 5 21"},child:[]}]})(t)}function Xi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"14",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"3",y:"14",width:"7",height:"7"},child:[]}]})(t)}function Zi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"path",attr:{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"},child:[]}]})(t)}function Os(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"},child:[]}]})(t)}function At(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"6",y1:"3",x2:"6",y2:"15"},child:[]},{tag:"circle",attr:{cx:"18",cy:"6",r:"3"},child:[]},{tag:"circle",attr:{cx:"6",cy:"18",r:"3"},child:[]},{tag:"path",attr:{d:"M18 9a9 9 0 0 1-9 9"},child:[]}]})(t)}function st(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"},child:[]}]})(t)}function ea(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"},child:[]},{tag:"polyline",attr:{points:"13 2 13 9 20 9"},child:[]}]})(t)}function Tn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"},child:[]},{tag:"polyline",attr:{points:"14 2 14 8 20 8"},child:[]},{tag:"line",attr:{x1:"16",y1:"13",x2:"8",y2:"13"},child:[]},{tag:"line",attr:{x1:"16",y1:"17",x2:"8",y2:"17"},child:[]},{tag:"polyline",attr:{points:"10 9 9 9 8 9"},child:[]}]})(t)}function ms(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]}]})(t)}function hs(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M12 20h9"},child:[]},{tag:"path",attr:{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"},child:[]}]})(t)}function Kt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"},child:[]}]})(t)}function zt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"7 10 12 15 17 10"},child:[]},{tag:"line",attr:{x1:"12",y1:"15",x2:"12",y2:"3"},child:[]}]})(t)}function wt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"4",y:"4",width:"16",height:"16",rx:"2",ry:"2"},child:[]},{tag:"rect",attr:{x:"9",y:"9",width:"6",height:"6"},child:[]},{tag:"line",attr:{x1:"9",y1:"1",x2:"9",y2:"4"},child:[]},{tag:"line",attr:{x1:"15",y1:"1",x2:"15",y2:"4"},child:[]},{tag:"line",attr:{x1:"9",y1:"20",x2:"9",y2:"23"},child:[]},{tag:"line",attr:{x1:"15",y1:"20",x2:"15",y2:"23"},child:[]},{tag:"line",attr:{x1:"20",y1:"9",x2:"23",y2:"9"},child:[]},{tag:"line",attr:{x1:"20",y1:"14",x2:"23",y2:"14"},child:[]},{tag:"line",attr:{x1:"1",y1:"9",x2:"4",y2:"9"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"4",y2:"14"},child:[]}]})(t)}function ta(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 10 4 15 9 20"},child:[]},{tag:"path",attr:{d:"M20 4v7a4 4 0 0 1-4 4H4"},child:[]}]})(t)}function En(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"},child:[]}]})(t)}function sa(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"16 18 22 12 16 6"},child:[]},{tag:"polyline",attr:{points:"8 6 2 12 8 18"},child:[]}]})(t)}function Ws(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"polyline",attr:{points:"12 6 12 12 16 14"},child:[]}]})(t)}function Pn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"13 17 18 12 13 7"},child:[]},{tag:"polyline",attr:{points:"6 17 11 12 6 7"},child:[]}]})(t)}function Mn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"11 17 6 12 11 7"},child:[]},{tag:"polyline",attr:{points:"18 17 13 12 18 7"},child:[]}]})(t)}function Tt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"18 15 12 9 6 15"},child:[]}]})(t)}function Vt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function Ze(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"6 9 12 15 18 9"},child:[]}]})(t)}function Et(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"20 6 9 17 4 12"},child:[]}]})(t)}function na(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"},child:[]},{tag:"polyline",attr:{points:"22 4 12 14.01 9 11.01"},child:[]}]})(t)}function Xt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(t)}function ia(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"},child:[]},{tag:"path",attr:{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"},child:[]}]})(t)}function aa(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"},child:[]},{tag:"path",attr:{d:"M13.73 21a2 2 0 0 1-3.46 0"},child:[]}]})(t)}function In(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"19",x2:"12",y2:"5"},child:[]},{tag:"polyline",attr:{points:"5 12 12 5 19 12"},child:[]}]})(t)}function Rn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"polyline",attr:{points:"19 12 12 19 5 12"},child:[]}]})(t)}function ra(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"21 8 21 21 3 21 3 8"},child:[]},{tag:"rect",attr:{x:"1",y:"3",width:"22",height:"5"},child:[]},{tag:"line",attr:{x1:"10",y1:"12",x2:"14",y2:"12"},child:[]}]})(t)}function la(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"},child:[]},{tag:"line",attr:{x1:"12",y1:"9",x2:"12",y2:"13"},child:[]},{tag:"line",attr:{x1:"12",y1:"17",x2:"12.01",y2:"17"},child:[]}]})(t)}function oa(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12.01",y2:"16"},child:[]}]})(t)}function ca(t){return t.map(s=>s.kind==="package"?`pi update npm:${s.name}`:`npm i -g ${s.name}@latest`).join("; ")}function Qe(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(n=>n.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Xe({trigger:t,open:s,onOpenChange:n,children:r,align:c="right",fit:i=!1,direction:a="down",menuClassName:o,menuRef:u,menuStyle:m}){const y=l.useRef(null);return l.useEffect(()=>{if(!s)return;const x=b=>{y.current&&!y.current.contains(b.target)&&n(!1)},f=b=>{b.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",x),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",x),document.removeEventListener("keydown",f)}},[s,n]),e.jsxs("div",{className:`dropdown ${c} ${i?"fit":""} ${a==="up"?"dd-up":""}`,ref:y,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!s),"aria-expanded":s,children:[t,e.jsx(Ze,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${o??""}`,ref:u,style:m,children:r})]})}function $e({active:t,disabled:s=!1,title:n,onClick:r,children:c}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:n,onClick:r,children:c})}const Ln="pi-web-ui:lang",Us={docTitle:"pi-web-ui — pi 编码智能体",cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",collapsePanel:"收起面板",expandPanel:"展开面板",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",engineBadge:"引擎",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",cwdGoUp:"上级目录",cwdPickCurrent:"选择当前目录",cwdChoose:"选择",cwdEnter:"进入",cwdEmpty:"(空目录)",cwdNewFolder:"新建文件夹",cwdNewName:"文件夹名称",cwdCreate:"创建",cwdCancel:"取消",cacheHit:"缓存命中",cacheHitTip:"缓存读取 {read} · 缓存写入 {write} · 未命中 {miss}(共 {input} 输入 token)",tps:"t/s",rateTip:"实时生成速率(估算)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",queueSteerTag:"插队",queueFollowTag:"排队",queueRemoveTip:"移除此排队消息",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",subagentBadge:"子代理",convErrorBadge:"子代理运行报错:{error}",subagentTitle:"子代理 · {title}",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",renameSession:"重命名该对话",renameSessionPlaceholder:"输入新名称…",renameSessionConfirm:"重命名",dismissConversation:"从运行列表移出(历史记录保留)",dismissConversationConfirm:"确认移出",collapseSection:"折叠",expandSection:"展开",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",computer:"此电脑",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",fileNotFoundShort:"文件不存在",pluginMountFailed:"插件 {name} 挂载失败",liveOutputOmitted:`…[前 {n} 字符已省略]…
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-Bu0PEPj5.js","assets/markdown-DRBrS2Nf.js","assets/xterm-D1D2FVe3.js","assets/react-C9ovnpIm.js","assets/TerminalPanel-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{R as tt,a as l,j as e,M as ki,b as ji,c as wi}from"./markdown-DRBrS2Nf.js";import{r as kn}from"./react-C9ovnpIm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))r(c);new MutationObserver(c=>{for(const i of c)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(c){const i={};return c.integrity&&(i.integrity=c.integrity),c.referrerPolicy&&(i.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?i.credentials="include":c.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(c){if(c.ep)return;c.ep=!0;const i=n(c);fetch(c.href,i)}})();var Rt={},As;function Ni(){if(As)return Rt;As=1;var t=kn();return Rt.createRoot=t.createRoot,Rt.hydrateRoot=t.hydrateRoot,Rt}var Ci=Ni();const Si="modulepreload",Ti=function(t){return"/"+t},_s={},Ei=function(s,n,r){let c=Promise.resolve();if(n&&n.length>0){let a=function(m){return Promise.all(m.map(f=>Promise.resolve(f).then(y=>({status:"fulfilled",value:y}),y=>({status:"rejected",reason:y}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),u=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));c=a(n.map(m=>{if(m=Ti(m),m in _s)return;_s[m]=!0;const f=m.endsWith(".css"),y=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${y}`))return;const x=document.createElement("link");if(x.rel=f?"stylesheet":Si,f||(x.as="script"),x.crossOrigin="",x.href=m,u&&x.setAttribute("nonce",u),document.head.appendChild(x),f)return new Promise((b,T)=>{x.addEventListener("load",b),x.addEventListener("error",()=>T(new Error(`Unable to preload CSS for ${m}`)))})}))}function i(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return c.then(a=>{for(const o of a||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};var jn={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Bs=tt.createContext&&tt.createContext(jn),Pi=["attr","size","title"];function Mi(t,s){if(t==null)return{};var n,r,c=Ii(t,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],s.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(c[n]=t[n])}return c}function Ii(t,s){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(s.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function $t(){return $t=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},$t.apply(null,arguments)}function Fs(t,s){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);s&&(r=r.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),n.push.apply(n,r)}return n}function Ht(t){for(var s=1;s<arguments.length;s++){var n=arguments[s]!=null?arguments[s]:{};s%2?Fs(Object(n),!0).forEach(function(r){Ri(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Fs(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function Ri(t,s,n){return(s=Li(s))in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function Li(t){var s=Di(t,"string");return typeof s=="symbol"?s:s+""}function Di(t,s){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,s);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function wn(t){return t&&t.map((s,n)=>tt.createElement(s.tag,Ht({key:n},s.attr),wn(s.child)))}function ne(t){return s=>tt.createElement(Ai,$t({attr:Ht({},t.attr)},s),wn(t.child))}function Ai(t){var s=n=>{var r=t.attr,c=t.size,i=t.title,a=Mi(t,Pi),o=c||n.size||"1em",u;return n.className&&(u=n.className),t.className&&(u=(u?u+" ":"")+t.className),tt.createElement("svg",$t({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,a,{className:u,style:Ht(Ht({color:t.color||n.color},n.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&tt.createElement("title",null,i),t.children)};return Bs!==void 0?tt.createElement(Bs.Consumer,null,n=>s(n)):s(jn)}function _i(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(t)}function Bi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"11",y1:"8",x2:"11",y2:"14"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(t)}function At(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"},child:[]}]})(t)}function Re(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"18",y1:"6",x2:"6",y2:"18"},child:[]},{tag:"line",attr:{x1:"6",y1:"6",x2:"18",y2:"18"},child:[]}]})(t)}function Nn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"},child:[]},{tag:"path",attr:{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"},child:[]}]})(t)}function $s(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"},child:[]},{tag:"circle",attr:{cx:"9",cy:"7",r:"4"},child:[]},{tag:"path",attr:{d:"M23 21v-2a4 4 0 0 0-3-3.87"},child:[]},{tag:"path",attr:{d:"M16 3.13a4 4 0 0 1 0 7.75"},child:[]}]})(t)}function Fi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"17 8 12 3 7 8"},child:[]},{tag:"line",attr:{x1:"12",y1:"3",x2:"12",y2:"15"},child:[]}]})(t)}function $i(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 9.9-1"},child:[]}]})(t)}function He(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(t)}function ct(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"4 17 10 11 4 5"},child:[]},{tag:"line",attr:{x1:"12",y1:"19",x2:"20",y2:"19"},child:[]}]})(t)}function Hs(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"6"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"2"},child:[]}]})(t)}function Os(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"},child:[]},{tag:"line",attr:{x1:"7",y1:"7",x2:"7.01",y2:"7"},child:[]}]})(t)}function Hi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"5"},child:[]},{tag:"line",attr:{x1:"12",y1:"1",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"23"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},child:[]},{tag:"line",attr:{x1:"1",y1:"12",x2:"3",y2:"12"},child:[]},{tag:"line",attr:{x1:"21",y1:"12",x2:"23",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},child:[]}]})(t)}function Ot(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]}]})(t)}function Oi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"4",y1:"21",x2:"4",y2:"14"},child:[]},{tag:"line",attr:{x1:"4",y1:"10",x2:"4",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"20",y1:"21",x2:"20",y2:"16"},child:[]},{tag:"line",attr:{x1:"20",y1:"12",x2:"20",y2:"3"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"7",y2:"14"},child:[]},{tag:"line",attr:{x1:"9",y1:"8",x2:"15",y2:"8"},child:[]},{tag:"line",attr:{x1:"17",y1:"16",x2:"23",y2:"16"},child:[]}]})(t)}function Wt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]},{tag:"path",attr:{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"},child:[]}]})(t)}function Cn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"22",y1:"2",x2:"11",y2:"13"},child:[]},{tag:"polygon",attr:{points:"22 2 15 22 11 13 2 9 22 2"},child:[]}]})(t)}function Ut(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]}]})(t)}function Wi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"},child:[]},{tag:"polyline",attr:{points:"17 21 17 13 7 13 7 21"},child:[]},{tag:"polyline",attr:{points:"7 3 7 8 15 8"},child:[]}]})(t)}function Sn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"1 4 1 10 7 10"},child:[]},{tag:"path",attr:{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"},child:[]}]})(t)}function lt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"polyline",attr:{points:"1 20 1 14 7 14"},child:[]},{tag:"path",attr:{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"},child:[]}]})(t)}function Ke(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(t)}function xo(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"5 3 19 12 5 21 5 3"},child:[]}]})(t)}function Ui(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"},child:[]}]})(t)}function Xt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"16.5",y1:"9.4",x2:"7.5",y2:"4.21"},child:[]},{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(t)}function Ki(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"19",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"5",cy:"12",r:"1"},child:[]}]})(t)}function qi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"},child:[]}]})(t)}function dt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},child:[]}]})(t)}function zi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"3",y1:"12",x2:"21",y2:"12"},child:[]},{tag:"line",attr:{x1:"3",y1:"6",x2:"21",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"18",x2:"21",y2:"18"},child:[]}]})(t)}function Vi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"},child:[]}]})(t)}function Gi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 3 21 3 21 9"},child:[]},{tag:"polyline",attr:{points:"9 21 3 21 3 15"},child:[]},{tag:"line",attr:{x1:"21",y1:"3",x2:"14",y2:"10"},child:[]},{tag:"line",attr:{x1:"3",y1:"21",x2:"10",y2:"14"},child:[]}]})(t)}function Qi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 10 0v4"},child:[]}]})(t)}function ms(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"},child:[]},{tag:"path",attr:{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"},child:[]}]})(t)}function Kt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"12 2 2 7 12 12 22 7 12 2"},child:[]},{tag:"polyline",attr:{points:"2 17 12 22 22 17"},child:[]},{tag:"polyline",attr:{points:"2 12 12 17 22 12"},child:[]}]})(t)}function Yi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12.01",y2:"8"},child:[]}]})(t)}function Ji(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]},{tag:"circle",attr:{cx:"8.5",cy:"8.5",r:"1.5"},child:[]},{tag:"polyline",attr:{points:"21 15 16 10 5 21"},child:[]}]})(t)}function Xi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"14",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"3",y:"14",width:"7",height:"7"},child:[]}]})(t)}function Zi(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"path",attr:{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"},child:[]}]})(t)}function Ws(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"},child:[]}]})(t)}function _t(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"6",y1:"3",x2:"6",y2:"15"},child:[]},{tag:"circle",attr:{cx:"18",cy:"6",r:"3"},child:[]},{tag:"circle",attr:{cx:"6",cy:"18",r:"3"},child:[]},{tag:"path",attr:{d:"M18 9a9 9 0 0 1-9 9"},child:[]}]})(t)}function st(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"},child:[]}]})(t)}function ea(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"},child:[]},{tag:"polyline",attr:{points:"13 2 13 9 20 9"},child:[]}]})(t)}function Tn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"},child:[]},{tag:"polyline",attr:{points:"14 2 14 8 20 8"},child:[]},{tag:"line",attr:{x1:"16",y1:"13",x2:"8",y2:"13"},child:[]},{tag:"line",attr:{x1:"16",y1:"17",x2:"8",y2:"17"},child:[]},{tag:"polyline",attr:{points:"10 9 9 9 8 9"},child:[]}]})(t)}function hs(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]}]})(t)}function gs(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M12 20h9"},child:[]},{tag:"path",attr:{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"},child:[]}]})(t)}function qt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"},child:[]}]})(t)}function Vt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"7 10 12 15 17 10"},child:[]},{tag:"line",attr:{x1:"12",y1:"15",x2:"12",y2:"3"},child:[]}]})(t)}function Nt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"4",y:"4",width:"16",height:"16",rx:"2",ry:"2"},child:[]},{tag:"rect",attr:{x:"9",y:"9",width:"6",height:"6"},child:[]},{tag:"line",attr:{x1:"9",y1:"1",x2:"9",y2:"4"},child:[]},{tag:"line",attr:{x1:"15",y1:"1",x2:"15",y2:"4"},child:[]},{tag:"line",attr:{x1:"9",y1:"20",x2:"9",y2:"23"},child:[]},{tag:"line",attr:{x1:"15",y1:"20",x2:"15",y2:"23"},child:[]},{tag:"line",attr:{x1:"20",y1:"9",x2:"23",y2:"9"},child:[]},{tag:"line",attr:{x1:"20",y1:"14",x2:"23",y2:"14"},child:[]},{tag:"line",attr:{x1:"1",y1:"9",x2:"4",y2:"9"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"4",y2:"14"},child:[]}]})(t)}function ta(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 10 4 15 9 20"},child:[]},{tag:"path",attr:{d:"M20 4v7a4 4 0 0 1-4 4H4"},child:[]}]})(t)}function En(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"},child:[]}]})(t)}function sa(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"16 18 22 12 16 6"},child:[]},{tag:"polyline",attr:{points:"8 6 2 12 8 18"},child:[]}]})(t)}function Us(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"polyline",attr:{points:"12 6 12 12 16 14"},child:[]}]})(t)}function Pn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"13 17 18 12 13 7"},child:[]},{tag:"polyline",attr:{points:"6 17 11 12 6 7"},child:[]}]})(t)}function Mn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"11 17 6 12 11 7"},child:[]},{tag:"polyline",attr:{points:"18 17 13 12 18 7"},child:[]}]})(t)}function Et(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"18 15 12 9 6 15"},child:[]}]})(t)}function Gt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function Ze(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"6 9 12 15 18 9"},child:[]}]})(t)}function Pt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"20 6 9 17 4 12"},child:[]}]})(t)}function na(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"},child:[]},{tag:"polyline",attr:{points:"22 4 12 14.01 9 11.01"},child:[]}]})(t)}function Zt(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(t)}function ia(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"},child:[]},{tag:"path",attr:{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"},child:[]}]})(t)}function aa(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"},child:[]},{tag:"path",attr:{d:"M13.73 21a2 2 0 0 1-3.46 0"},child:[]}]})(t)}function In(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"19",x2:"12",y2:"5"},child:[]},{tag:"polyline",attr:{points:"5 12 12 5 19 12"},child:[]}]})(t)}function Rn(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"polyline",attr:{points:"19 12 12 19 5 12"},child:[]}]})(t)}function ra(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"21 8 21 21 3 21 3 8"},child:[]},{tag:"rect",attr:{x:"1",y:"3",width:"22",height:"5"},child:[]},{tag:"line",attr:{x1:"10",y1:"12",x2:"14",y2:"12"},child:[]}]})(t)}function la(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"},child:[]},{tag:"line",attr:{x1:"12",y1:"9",x2:"12",y2:"13"},child:[]},{tag:"line",attr:{x1:"12",y1:"17",x2:"12.01",y2:"17"},child:[]}]})(t)}function oa(t){return ne({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12.01",y2:"16"},child:[]}]})(t)}function ca(t){return t.map(s=>s.kind==="package"?`pi update npm:${s.name}`:`npm i -g ${s.name}@latest`).join("; ")}function Qe(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(n=>n.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Xe({trigger:t,open:s,onOpenChange:n,children:r,align:c="right",fit:i=!1,direction:a="down",menuClassName:o,menuRef:u,menuStyle:m}){const f=l.useRef(null);return l.useEffect(()=>{if(!s)return;const y=b=>{f.current&&!f.current.contains(b.target)&&n(!1)},x=b=>{b.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",y),document.addEventListener("keydown",x),()=>{document.removeEventListener("mousedown",y),document.removeEventListener("keydown",x)}},[s,n]),e.jsxs("div",{className:`dropdown ${c} ${i?"fit":""} ${a==="up"?"dd-up":""}`,ref:f,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!s),"aria-expanded":s,children:[t,e.jsx(Ze,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${o??""}`,ref:u,style:m,children:r})]})}function $e({active:t,disabled:s=!1,title:n,onClick:r,children:c}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:n,onClick:r,children:c})}const Ln="pi-web-ui:lang",Ks={docTitle:"pi-web-ui — pi 编码智能体",cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",collapsePanel:"收起面板",expandPanel:"展开面板",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",engineBadge:"引擎",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",cwdGoUp:"上级目录",cwdPickCurrent:"选择当前目录",cwdChoose:"选择",cwdEnter:"进入",cwdEmpty:"(空目录)",cwdNewFolder:"新建文件夹",cwdNewName:"文件夹名称",cwdCreate:"创建",cwdCancel:"取消",cacheHit:"缓存命中",cacheHitTip:"缓存读取 {read} · 缓存写入 {write} · 未命中 {miss}(共 {input} 输入 token)",tps:"t/s",rateTip:"实时生成速率(估算)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",queueSteerTag:"插队",queueFollowTag:"排队",queueRemoveTip:"移除此排队消息",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",subagentBadge:"子代理",convErrorBadge:"子代理运行报错:{error}",subagentTitle:"子代理 · {title}",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",renameSession:"重命名该对话",renameSessionPlaceholder:"输入新名称…",renameSessionConfirm:"重命名",dismissConversation:"从运行列表移出(历史记录保留)",dismissConversationConfirm:"确认移出",collapseSection:"折叠",expandSection:"展开",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",computer:"此电脑",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",fileNotFoundShort:"文件不存在",pluginMountFailed:"插件 {name} 挂载失败",liveOutputOmitted:`…[前 {n} 字符已省略]…
|
|
3
3
|
`,uploadToFolder:"上传文件到此文件夹",uploadToCurrentDir:"上传文件到当前目录",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",modelQuestion:"模型提问",modelQuestionCustom:"补充回答(可选)",modelQuestionSubmit:"提交回答",noOptions:"(无选项)",inputPlaceholder:"输入内容",questionTimeout:"⏳ 剩余 {s} 秒,超时将自动取消",questionTimeoutExpired:"提问已超时,正在恢复对话…",modelNoVision:"当前模型 {name} 不支持图片,请切换到 DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH 引擎使用运行时内置技能(dsh-skill),暂不支持在设置面板启停",dshExtensionsNote:"DSH 引擎无 pi 扩展体系,能力由运行时内置(MCP/subagent/goal/plan/skill 等)",dshReviewPromptNote:"DSH 无独立审查会话:此指令将随目标轮次附加到系统提示词,供模型在目标轮次中遵守",dshVisionHiddenNote:"DSH 引擎直接支持图片输入(仅 DeepSeek V4 Flash Vision (exp) 模型),无需视觉桥转写",dshNoReviewModel:"DSH 无独立审查模型:目标由模型自判定完成/受阻,轮次上限即自动迭代次数",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量",notifyHeader:"桌面通知",notifyEnable:"启用桌面通知(PWA)",notifyEnableDesc:"会话完成或需要你输入时,即使切到其他应用也会提醒(需授权,仅页面前台无焦点时触发)。",notifyDenied:"通知权限已被拒绝 —— 请在浏览器/系统设置里为本站点开启通知。",notifyUnsupported:"此浏览器不支持通知。",notifyDoneTitle:"任务完成",notifyDoneBody:"会话已完成,等待你的输入。",notifyQuestionTitle:"需要你回答",notifyQuestionBody:"pi 正在等你回答一个问题。",notifyErrorTitle:"出错了",notifyErrorBody:"一个会话报告了错误。","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-web-ui 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",directory:"目录",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",modelUsedCount:"已用 {n} 次",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:搜索历史对话全文(含 AI 回复)、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","tpl.title":"提示词模板","tpl.hint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.clickCard":"点击填入输入框","tpl.editTpl":"编辑 / 删除模板","tpl.openPicker":"提示词模板(常用提示词,随时取用)","tpl.pickerTitle":"提示词模板","tpl.pickerHint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.add":"新建模板","tpl.addDesc":"把常用工作流存成模板","tpl.reset":"恢复默认模板","tpl.resetConfirm":"确认恢复默认?","tpl.builtin":"内置","tpl.custom":"自定义","tpl.newTitle":"新建提示词模板","tpl.editTitle":"编辑提示词模板","tpl.fieldIcon":"图标","tpl.fieldTitle":"标题","tpl.fieldTitlePh":"卡片上显示的短标题","tpl.fieldDesc":"说明","tpl.fieldDescPh":"一句话说明,显示在卡片上","tpl.fieldPrompt":"提示词","tpl.fieldPromptPh":"完整提示词 —— 发送给智能体的内容","tpl.required":"标题和提示词不能为空","tpl.save":"保存修改","tpl.fill":"填入输入框","tpl.fillTip":"填入输入框,可再编辑后发送","tpl.sendNow":"直接发送","tpl.sendTip":"立即作为新对话发送","tpl.delete":"删除","tpl.deleteTip":"删除这个自定义模板","tpl.remove":"移出模板库","tpl.removeTip":"把内置模板移出模板库,可在底部「恢复默认模板」找回","tpl.restore":"恢复默认","tpl.restoreTip":"撤掉你的修改,恢复内置默认","tpl.sk.setup":"仓库初始化","tpl.sk.setup.desc":"让仓库了解它的构建与约定","tpl.sk.setup.prompt":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
|
|
4
4
|
|
|
5
5
|
1. 项目类型、技术栈与目录结构
|
|
@@ -150,7 +150,7 @@ import{R as tt,a as l,j as e,M as ki,b as ji,c as wi}from"./markdown-DRBrS2Nf.js
|
|
|
150
150
|
2. 用最小实现让测试通过
|
|
151
151
|
3. 重构并保持测试通过
|
|
152
152
|
|
|
153
|
-
避免三种反模式:与实现耦合的测试、空洞断言(永远为真)、横向切片(只测表面)。每步汇报并运行测试。`,error:"出错",done:"完成",running:"执行中…",toolQueued:"排队中",copyArgs:"复制参数",errorOutput:"错误输出",output:"输出",waitingOutput:"等待输出…",toolDoneWaitingModel:"已结束 · 等模型",waitingModel:"等待模型响应…",thinkingNow:"思考中",thinkingPreview:"思考:{preview}",commands:"命令",newCommand:"新建命令",newTerminal:"新建终端",name:"名称",command:"命令",cwdHint:"(${pwd} = 当前工作目录)",noCommands:"还没有命令,点 + 添加一个",clickToRun:"点击运行",edit:"编辑",delete:"删除",confirmQ:"确认?",builtinTerminal:"内置终端",termEmptySub:"点击左侧命令运行,或点右侧 + 新建终端",noTerminal:"暂无终端",exited:"(已退出{code})",exitBanner:"[进程已退出,退出码 {code}]",closeTerminal:"关闭终端",renameTerminal:"重命名终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",aiBashGroup:"终端接管 bash",exampleName:"例如:启动开发服务器",exampleCommand:"例如:npm run dev",scmTab:"Git",scmTitle:"源代码管理",scmRefreshTip:"重新查询 Git 状态与差异",scmCurrentBranch:"当前分支",scmUpstreamGone:"上游已删除",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"分离 HEAD",scmSelectBranch:"选择分支…",scmRemoteBranches:"远程分支",scmStageTip:"暂存 {path}",scmUnstageTip:"取消暂存 {path}",scmSwitch:"切换",scmSwitchBranch:"切换分支",scmSwitchBranchTip:"在终端中执行 git checkout {branch}",scmPush:"推送",scmPushTip:"在终端中执行 git push",scmPull:"拉取",scmPullTip:"在终端中执行 git pull",scmCommit:"提交",scmCommitTip:'在终端中执行 git commit -m "…"(仅提交已暂存的更改)',scmCommitAll:"全部提交",scmCommitAllTip:'在终端中执行 git add -A && git commit -m "…"(暂存全部更改含未跟踪并提交)',scmCommitPlaceholder:"输入提交信息…",scmChanges:"更改",scmHistory:"提交树",scmCommitDetail:"提交详情",scmSelectCommitHint:"点击左侧提交查看详情",scmNoHistory:"暂无提交记录",scmNoChanges:"工作区干净,没有更改",scmNotGitRepo:"当前目录不是 Git 仓库",scmLoading:"查询中…",scmConnecting:"等待连接…",scmDiff:"差异",scmSelectFileHint:"点击左侧文件查看差异",scmNoDiff:"(无差异)",scmStaged:"已暂存",scmUnstaged:"未暂存",scmStagedUnstaged:"已暂存 + 未暂存",scmUntracked:"未跟踪",scmUntrackedNote:"未跟踪文件:需先用 + 暂存,或使用“全部提交”才会包含",scmQueryFailed:"Git 查询失败:{error}",scmQueryFailedShort:"查询失败",pluginCommandFallback:"插件命令",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"只需填入 API 密钥",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",cloneProvider:"添加密钥",cloning:"添加中",cloneProviderTitle:"为该供应商添加第二把密钥(自动复制 baseUrl 与模型列表,可改名后保存)",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",addKey:"添加密钥",addKeyPlaceholder:"粘贴密钥值…",keyNamePh:"名称(可留空,如 备用)",providerIdPlaceholder:"供应商 ID",baseUrlExamplePh:"baseUrl 链接,如 https://api.opencode.ai/zen/v1 或 http://127.0.0.1:4096",saveAllBatch:"一键保存全部({n})",netDisconnected:"网络连接已断开,请重连后重试",advancedEdit:"高级编辑",batchCreateProviders:"批量创建供应商({n}个接口)",secondKeyTitle:"为 {api} · {baseUrl} · {n} 个模型添加第二把密钥,只需指定新供应商名字和密钥即可。",noBaseUrlShort:"(无 baseUrl)",providerNameLabel:"供应商名字",providerNameHint:"(新 ID,如 opencode-2)",apiKeyLabel:"API 密钥",secondKeyPlaceholder:"sk-… 第二把 key",batchDesc:"该供应商含多种接口({apis}),已按接口拆分为 {n} 个自定义供应商,分别保存后才能让所有模型(如 muse-spark)都可用。统一填入第二把 API 密钥后一键保存。",batchKeyLabel:"统一 API 密钥(将应用到全部 {n} 个供应商)",modelsCountShort:"{n} 个模型:",noKeyYet:"尚无密钥,添加一把即可用",activateKey:"设为当前",removeKey:"移除",removeKeyConfirm:"确定移除该密钥?移除后需重新配置才能使用。",customProviders:"自定义服务商",customDesc:"用于 Ollama / vLLM / 兼容 OpenAI 的代理等,写入 pi 的 models.json,保存后热重载、立即生效。",noCustomProviders:"还没有自定义服务商",modelsCount:"{n} 个模型",addProvider:"新增服务商",providerId:"服务商 ID",providerIdHint:"(必填,如 ollama / my-proxy)",displayName:"显示名",displayNamePh:"我的代理",apiType:"API 类型",baseUrlHint:"(OpenAI 兼容端点)",apiKeyHint:"sk-…(可留空,用 auth.json 的密钥)",authHeader:"自动添加 Authorization 请求头",modelsTitle:"模型",modelIdReq:"模型 ID(必填)",text:"文本",textImage:"文本+图片",contextWindow:"上下文",maxOutput:"最大输出",removeModel:"移除模型",addModel:"添加模型",deleteProviderConfirm:"删除服务商 {id} 及其 {n} 个模型?",fetchModels:"自动获取模型列表",fetchModelsHint:"从 baseUrl 的 /models 接口自动拉取模型 ID(服务端请求,不受 CORS 限制)",fetchingModels:"获取中…",fetchModelsOk:"已获取 {n} 个模型",fetchModelsEmpty:"接口未返回任何模型",fetchModelsErr:"获取失败:{msg}",fetchModelsNeedBaseUrl:"请先填写 baseUrl 再获取",goalBarTitle:"目标",goalBarPlaceholder:"设定一个目标,agent 完成后自动审查…",goalBarSet:"开始",goalBarClear:"取消",goalBarLocked:"锁定:应用到后续所有回合",goalBarUnlocked:"仅本回合(改完自动清除)",goalBarReviewModel:"审查模型",goalBarUseMainModel:"使用主模型",goalBarMaxRounds:"最大轮数",goalBarMaxRoundsTip:"最大审查重改轮数;0 或不填 = 不限(持续改到通过)",goalBarUnlimitedShort:"不限",goalBarReviewing:"审查中…",goalBarRound:"第 {n} 轮",goalBarActive:"目标生效中",goalBarPassed:"已通过",goalBarFailed:"未通过",goalBarStatusPending:"等待生成…",goalWizardBtn:"AI 提炼",goalWizardTip:"让 AI 通过问卷调研细化需求,收敛为目标",goalWizardRunning:"目标调研中",goalWizardAnswer:"回答",goalWizardCard:"目标调研",settings:"设置",settingsTitle:"设置",settingsDesc:"修改立即生效:系统提示词、技能与插件开关会重建当前会话;审查提示词与审查技能只影响后续目标审查(回复进行中则主会话变更自动延迟)。",settingsSystemPrompt:"系统提示词",settingsPromptHistory:"输入历史",settingsPromptHistoryDesc:"用 ↑↓ 在输入框循环历史提问,全局跨对话共享(localStorage)",promptHistoryMax:"最大条数",promptHistoryMaxHint:"超过上限时最旧的自动丢弃,可设 1–500",promptHistoryCharLimit:"限制单条字数",promptHistoryCharLimitHint:"开启后超长输入截断后保存,避免大段粘贴占满存储",promptHistoryCharLimitPlaceholder:"最大字数(100–20000)",promptHistoryClear:"清空历史",promptHistoryClearConfirm:"确认清空?",promptHistoryCleared:"已清空输入历史",promptHistoryCount:"当前 {n} 条",promptHistoryEmpty:"暂无历史记录,上/下键暂无可循环内容",settingsPromptMode:"模式",promptModeAppend:"追加",promptModeReplace:"替换",promptAppendHint:"追加模式:自定义内容拼接到默认系统提示词末尾(推荐,保留默认行为约束)。",promptReplaceHint:"替换模式:完全用自定义内容替换系统提示词(项目上下文与技能段仍会自动附加)。切换后输入框会显示原本的默认提示词,可直接修改;不改动失焦则仍使用默认。",promptPlaceholder:"输入自定义系统提示词…(失焦后自动应用)",settingsViewPrompt:"查看当前完整提示词",settingsViewPromptHint:"当前会话实际生效的完整系统提示词(含自定义追加/替换内容、项目上下文、技能说明与工具引导),只读。",settingsViewPromptEmpty:"会话尚未就绪,暂无系统提示词。",settingsSkills:"技能",settingsReview:"目标审查",settingsReviewDesc:"为独立的目标审查会话配置额外提示词和技能;不会改变主会话设置。",settingsReviewSkills:"审查可用技能",reviewPromptPlaceholder:"输入审查自定义提示词…(失焦后自动应用)",reviewPromptHint:"这些内容会追加到审查任务中;审查仍会强制要求输出 pass/fail JSON。技能开关仅对审查生效。",settingsVisionBridge:"视觉桥",settingsVisionBridgeDesc:"当前模型不支持识图时,把图片交给已配置的视觉模型转写为文字证据,再让模型回答",visionBridgeEnabled:"启用视觉桥",visionBridgeModel:"转写模型",visionBridgeAuto:"自动选择(按顺序)",visionBridgeNoModels:"未找到已配置的视觉模型:在模型配置里添加任意支持图片的模型(如 qwen-vl、GLM-4V、Gemini)即可自动启用",visionBridgeOffHint:"已关闭:图片将原样发送,纯文本模型可能看不到图片内容",visionBridgeCurrent:"当前转写模型:{model}",visionBridgePromptMode:"转写提示词",settingsMarkers:"标记工具",settingsMarkersDesc:"让 AI 用 [[todo:...]] / [[svc:...]] / [[notify:...]] / [[conv:rename:...]] 内联标记在正文里改状态,无需工具往返。全局关闭则全部停用;分组开关可细粒度控制。",markersEnabled:"启用标记工具(全局)",markersEnabledDesc:"关闭后 AI 不再收到任何标记引导,解析也跳过(所有标记原文原样保留,不执行)。",markersOffHint:"已全局关闭:所有标记停用,AI 不会写标记,也不会触发任务/重命名等副作用。",markerGroupTodo:"任务标记 todo",markerGroupSvc:"后台服务标记 svc",markerGroupNotify:"提醒标记 notify",markerGroupRename:"重命名标记 conv/rename",markerRenameTip:"[[conv:rename:新标题]] 或 [[rename:set:标题]] 重命名当前对话(标题 ≤80 字)",settingsTerminalTools:"终端工具",terminalToolsEnabled:"启用持久终端工具",settingsTerminalToolsDesc:"让 AI 在交互式程序(REPL/vim)、长驻服务、需要持续观察输出或你要求在可见终端操作时,使用内置终端;普通命令仍走一次性 bash 工具",terminalToolsOffHint:"已关闭:AI 无法使用 terminal_* 工具,也不会收到相关使用引导",settingsMessageDisplay:"消息显示",thinkingWrap:"完整显示思考",thinkingWrapDesc:"开启:思考内容始终完整展开并自动换行(流式推理过程也实时可见);关闭:折叠成一行摘要,流式中一行实时显示最新文本",toolsWrap:"完整显示工具",toolsWrapDesc:"开启:工具调用始终完整展开显示参数和输出;关闭:默认折叠,点击展开",wideChat:"宽屏聊天列",wideChatDesc:"开启:中央列铺满宽度(超宽屏有用);关闭:保持 860px 上限",terminalBashTakeover:"终端接管 bash",terminalBashTakeoverDesc:"此开关决定 bash 是否覆盖为终端版:关 = 原生 SDK bash(纯进程、不开终端);开 = 跑进可见终端,且 persist 参数在本开关的基础上决定一次性(false,命令跑完进程退出、输出留档)还是持久(true,shell 状态跨调用保留、静默自动转后台并通知 AI)",terminalBashIdleMs:"静默转后台阈值(毫秒)",terminalBashIdleMsDesc:"持久终端模式下,命令连续无输出达到该时长即不再阻塞等待,转入后台继续运行并通知 AI;0 = 一直等到命令结束(默认 15000)",visionBridgePromptPlaceholder:"输入自定义转写提示词…(留空 = 使用内置默认提示词,失焦后自动应用)",visionBridgePromptAppendHint:"追加模式:自定义内容拼接到内置转写提示词末尾(推荐,保留默认的逐字转写约束)。",visionBridgePromptReplaceHint:"替换模式:完全用自定义内容替换内置转写提示词。切换后输入框会显示内置默认提示词,可直接修改;不改动失焦则仍使用默认。",uninstallExt:"卸载",uninstallConfirm:"确认卸载?",uninstallConfirmHint:"再次点击确认,将在终端执行 pi remove",uninstallHint:"通过可见终端执行 pi remove 卸载此包,完成后自动刷新列表",uninstallTitle:"卸载",pluginUpdate:"更新",pluginUpdateHint:"从安装来源重新拉取并覆盖安装(保留 config.json 配置),完成后自动重载插件列表",pluginMarket:"插件市场",pluginCatalogAdd:"添加插件",pluginCatalogAddHint:"把第三方插件填进可安装列表(owner/repo 或完整 GitHub 地址)",pluginCatalogSource:"来源 owner/repo 或 owner/repo/子目录(必填)",pluginCatalogId:"id(可选,默认取仓库/子目录名)",pluginCatalogName:"名称(可选)",pluginCatalogIcon:"图标 emoji(可选)",pluginCatalogDesc:"简介(可选)",pluginCatalogAddSubmit:"添加到列表",noPluginCatalog:"列表为空 —— 点「添加插件」把第三方插件填进列表",pluginInstalled:"已安装",pluginCatalogCustom:"自定义",pluginInstall:"安装",pluginInstallHint:"从来源直接安装到界面插件(在可见终端执行)",pluginCatalogRemoveHint:"从列表移除这条自定义插件",pluginUninstallHint:"在可见终端执行 pi-web-ui uninstall 卸载此插件(再次点击确认),完成后自动刷新列表",settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",dshPatches:"DSH 用户补丁",dshPatchesDesc:"启动时按文件名序加载的 Cordis patch(<dataDir>/dsh-patches/*.yml)。新增/修改后点「重扫」重启运行时生效;失败的文件会被跳过并打印到运行时 stderr。",dshPatchesRescan:"重扫",dshPatchesRescanHint:"重新扫描补丁目录并重启 DSH 运行时使新补丁生效",dshPatchesEmpty:"未放置补丁文件",dshPatchesPath:"补丁目录:",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsSubagentTemplates:"子代理模板",settingsSubagentTemplatesDesc:"配置子代理预设(角色系统提示词 + 技能/扩展白名单 + 可选模型)。AI 派生子代理时可选用模板(subagent_spawn 的 template 参数),也可不传按默认运行;停用的模板保留在面板但对 AI 不可见。",noSubagentTemplates:"还没有子代理模板。AI 派生子代理时可选用模板(角色提示词 + 技能/扩展白名单 + 可选模型),也可以不传 template 按默认配置运行。",subagentTemplateNew:"新建模板",subagentTemplateEdit:"编辑",subagentTemplateClosed:"已停用",tplDefaultBadge:"默认",subagentTemplateOffHint:"关闭的模板保留在面板、可随时重新启用,但 AI 工具查询不到、不能选择",subagentTemplateEnable:"启用",subagentTemplateDisable:"停用",subagentDefaultModelLabel:"子代理默认模型",subagentFollowMain:"跟随主对话当前模型",subagentDefaultModelHint:"所有子代理的兜底模型(模板里指定的模型和 subagent_spawn 的 model 参数优先级更高);不改主对话模型。",subagentNoModels:"暂无可用的模型(需要先配置服务商 API Key)——子代理将跟随主对话模型。",tplNamePlaceholder:"模板名(AI 用 subagent_spawn 的 template 参数引用)…",tplDescriptionPlaceholder:"简介(AI 据此判断适用场景)…",tplPromptModeLabel:"系统提示词模式",tplModelLabel:"模型(空 = 跟随主对话)",tplSystemPromptLabel:"系统提示词",tplSystemPromptPlaceholder:"模板角色系统提示词…(append 模式可留空)",tplWhitelistHint:"白名单:勾选 = 子代理只启用这些;全部不勾 = 跟随主会话设置",tplSkillsLabel:"技能白名单",tplExtensionsLabel:"扩展白名单",tplSave:"保存模板",tplCancel:"取消编辑",tplDelete:"删除模板",tplInherit:"跟随主会话",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},Ks={docTitle:"pi-web-ui — pi coding agent",cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",collapsePanel:"Collapse panel",expandPanel:"Expand panel",dragToResize:"Drag to resize · double-click to reset",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",githubRepo:"GitHub repository (xing-shuyin/pi-web-ui)",copy:"Copy",viewSwitch:"Switch view",chat:"Chat",terminal:"Terminal",selectModel:"Select model",availableModels:"Available models",allProviders:"All",providers:"Providers",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",engineBadge:"Engine",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",cwdGoUp:"Up one level",cwdPickCurrent:"Select this folder",cwdChoose:"Select",cwdEnter:"Enter",cwdEmpty:"(empty)",cwdNewFolder:"New folder",cwdNewName:"Folder name",cwdCreate:"Create",cwdCancel:"Cancel",cacheHit:"Cache hit",cacheHitTip:"read {read} · write {write} · miss {miss} (of {input} input tokens)",tps:"t/s",rateTip:"Live generation rate (estimated)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",placeholderStreaming:"The agent is working… press Enter to steer, or click Queue to send after the reply finishes",placeholderIdle:"Message pi — Enter to send, / for commands",placeholderConnecting:"Connecting to server…",stopAgent:"Stop agent",stop:"Stop",bgTasks:"Background tasks",bgTasksTip:"Servers the AI started in the background (npm run dev & etc.) — stop them individually or all at once; they survive the conversation",bgTasksEmpty:"No background tasks",bgTasksDesc:"Processes the AI started that are still listening (detected by port)",bgTaskPort:"Port",bgTaskPid:"PID",bgTaskSince:"Started",bgTaskStop:"Stop",bgTaskStopAll:"Stop all",bgTaskRefresh:"Refresh",bgTaskJustNow:"just now",bgTaskMinutes:"{n} min ago",bgTaskHours:"{n} hr ago",bgTaskDays:"{n} days ago",stopBash:"Stop",stopBashTip:"Stop the running bash command (conversation continues)",supplement:"Queue",supplementTip:"Add to queue: sent only after the whole run finishes (no interruption)",queueSteerTag:"Steer",queueFollowTag:"Queued",queueRemoveTip:"Remove this queued message",sendTip:"Send (Enter)",slashCommands:"Commands",slashMenuHint:"↑↓ select · Enter/Tab complete",slashHelpTitle:"pi commands",slashHelpHint:"Type / anytime to open the command list",slashLoading:"Loading commands… (available once connected)",slashBuiltin:"Builtin",slashExtension:"Extension",slashPrompt:"Template",slashSkill:"Skill",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",subagentBadge:"Subagent",convErrorBadge:"Subagent failed: {error}",subagentTitle:"Subagent · {title}",historySessions:"History",openHistory:"History",openFiles:"Files",streaming:"Streaming…",noHistory:"No previous chats",current:"Current",messageCount:"{n} messages",tuiTip:"Chat in the pi terminal (TUI)",deleteProject:"Remove from recent projects",deleteProjectConfirm:"Confirm remove",deleteSession:"Delete this chat transcript permanently",deleteSessionConfirm:"Confirm delete",renameSession:"Rename this chat",renameSessionPlaceholder:"Type a new name…",renameSessionConfirm:"Rename",dismissConversation:"Dismiss from running (keep in history)",dismissConversationConfirm:"Confirm dismiss",collapseSection:"Collapse",expandSection:"Expand",emptyChat:"Empty chat",editReask:"Edit & re-ask",editReaskTip:"Edit this question and re-ask from here (forks a new conversation; the original is kept)",reaskFromHere:"Re-ask from here",editPlaceholder:"Edit the question…",editHint:"⌘/Ctrl+Enter to submit · Esc to cancel",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-web-ui",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-web-ui",updateTerminalHint:"Clicking runs npm i -g pi-web-ui@latest in a visible terminal; restart the service afterwards to take effect (pi-web-ui server restart).",updatesAllTitle:"Component updates",updatesAllBadge:"{n} updates",updatesAllUpToDate:"All components up to date",kindWebUi:"Web UI",kindPiCore:"Core",kindPackage:"Package",updatesAllRefresh:"Re-check all",updateCheckFailed:"Check failed",updateBtn:"Update",updateAllBtn:"Update all",updatePkgTabTitle:"Update {name}",updateAllTabTitle:"Update all components",computer:"This PC",rootDir:"Root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",previewFile:"Preview",downloadFile:"Download file",downloadFailed:"Download failed: {error}",fileNotFoundShort:"File not found",pluginMountFailed:"Plugin {name} failed to mount",liveOutputOmitted:`…[{n} chars omitted above]…
|
|
153
|
+
避免三种反模式:与实现耦合的测试、空洞断言(永远为真)、横向切片(只测表面)。每步汇报并运行测试。`,error:"出错",done:"完成",running:"执行中…",toolQueued:"排队中",copyArgs:"复制参数",errorOutput:"错误输出",output:"输出",waitingOutput:"等待输出…",toolDoneWaitingModel:"已结束 · 等模型",waitingModel:"等待模型响应…",thinkingNow:"思考中",thinkingPreview:"思考:{preview}",commands:"命令",newCommand:"新建命令",newTerminal:"新建终端",name:"名称",command:"命令",cwdHint:"(${pwd} = 当前工作目录)",noCommands:"还没有命令,点 + 添加一个",clickToRun:"点击运行",edit:"编辑",delete:"删除",confirmQ:"确认?",builtinTerminal:"内置终端",termEmptySub:"点击左侧命令运行,或点右侧 + 新建终端",noTerminal:"暂无终端",exited:"(已退出{code})",exitBanner:"[进程已退出,退出码 {code}]",closeTerminal:"关闭终端",renameTerminal:"重命名终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",aiBashGroup:"终端接管 bash",exampleName:"例如:启动开发服务器",exampleCommand:"例如:npm run dev",scmTab:"Git",scmTitle:"源代码管理",scmRefreshTip:"重新查询 Git 状态与差异",scmCurrentBranch:"当前分支",scmUpstreamGone:"上游已删除",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"分离 HEAD",scmSelectBranch:"选择分支…",scmRemoteBranches:"远程分支",scmStageTip:"暂存 {path}",scmUnstageTip:"取消暂存 {path}",scmSwitch:"切换",scmSwitchBranch:"切换分支",scmSwitchBranchTip:"在终端中执行 git checkout {branch}",scmPush:"推送",scmPushTip:"在终端中执行 git push",scmPull:"拉取",scmPullTip:"在终端中执行 git pull",scmCommit:"提交",scmCommitTip:'在终端中执行 git commit -m "…"(仅提交已暂存的更改)',scmCommitAll:"全部提交",scmCommitAllTip:'在终端中执行 git add -A && git commit -m "…"(暂存全部更改含未跟踪并提交)',scmCommitPlaceholder:"输入提交信息…",scmChanges:"更改",scmHistory:"提交树",scmCommitDetail:"提交详情",scmSelectCommitHint:"点击左侧提交查看详情",scmNoHistory:"暂无提交记录",scmNoChanges:"工作区干净,没有更改",scmNotGitRepo:"当前目录不是 Git 仓库",scmLoading:"查询中…",scmConnecting:"等待连接…",scmDiff:"差异",scmSelectFileHint:"点击左侧文件查看差异",scmNoDiff:"(无差异)",scmStaged:"已暂存",scmUnstaged:"未暂存",scmStagedUnstaged:"已暂存 + 未暂存",scmUntracked:"未跟踪",scmUntrackedNote:"未跟踪文件:需先用 + 暂存,或使用“全部提交”才会包含",scmQueryFailed:"Git 查询失败:{error}",scmQueryFailedShort:"查询失败",pluginCommandFallback:"插件命令",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"只需填入 API 密钥",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",cloneProvider:"添加密钥",cloning:"添加中",cloneProviderTitle:"为该供应商添加第二把密钥(自动复制 baseUrl 与模型列表,可改名后保存)",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",addKey:"添加密钥",addKeyPlaceholder:"粘贴密钥值…",keyNamePh:"名称(可留空,如 备用)",providerIdPlaceholder:"供应商 ID",baseUrlExamplePh:"baseUrl 链接,如 https://api.opencode.ai/zen/v1 或 http://127.0.0.1:4096",saveAllBatch:"一键保存全部({n})",netDisconnected:"网络连接已断开,请重连后重试",advancedEdit:"高级编辑",batchCreateProviders:"批量创建供应商({n}个接口)",secondKeyTitle:"为 {api} · {baseUrl} · {n} 个模型添加第二把密钥,只需指定新供应商名字和密钥即可。",noBaseUrlShort:"(无 baseUrl)",providerNameLabel:"供应商名字",providerNameHint:"(新 ID,如 opencode-2)",apiKeyLabel:"API 密钥",secondKeyPlaceholder:"sk-… 第二把 key",batchDesc:"该供应商含多种接口({apis}),已按接口拆分为 {n} 个自定义供应商,分别保存后才能让所有模型(如 muse-spark)都可用。统一填入第二把 API 密钥后一键保存。",batchKeyLabel:"统一 API 密钥(将应用到全部 {n} 个供应商)",modelsCountShort:"{n} 个模型:",noKeyYet:"尚无密钥,添加一把即可用",activateKey:"设为当前",removeKey:"移除",removeKeyConfirm:"确定移除该密钥?移除后需重新配置才能使用。",customProviders:"自定义服务商",customDesc:"用于 Ollama / vLLM / 兼容 OpenAI 的代理等,写入 pi 的 models.json,保存后热重载、立即生效。",noCustomProviders:"还没有自定义服务商",modelsCount:"{n} 个模型",addProvider:"新增服务商",providerId:"服务商 ID",providerIdHint:"(必填,如 ollama / my-proxy)",displayName:"显示名",displayNamePh:"我的代理",apiType:"API 类型",baseUrlHint:"(OpenAI 兼容端点)",apiKeyHint:"sk-…(可留空,用 auth.json 的密钥)",authHeader:"自动添加 Authorization 请求头",modelsTitle:"模型",modelIdReq:"模型 ID(必填)",text:"文本",textImage:"文本+图片",contextWindow:"上下文",maxOutput:"最大输出",removeModel:"移除模型",addModel:"添加模型",deleteProviderConfirm:"删除服务商 {id} 及其 {n} 个模型?",fetchModels:"自动获取模型列表",fetchModelsHint:"从 baseUrl 的 /models 接口自动拉取模型 ID(服务端请求,不受 CORS 限制)",fetchingModels:"获取中…",fetchModelsOk:"已获取 {n} 个模型",fetchModelsEmpty:"接口未返回任何模型",fetchModelsErr:"获取失败:{msg}",fetchModelsNeedBaseUrl:"请先填写 baseUrl 再获取",goalBarTitle:"目标",goalBarPlaceholder:"设定一个目标,agent 完成后自动审查…",goalBarSet:"开始",goalBarClear:"取消",goalBarLocked:"锁定:应用到后续所有回合",goalBarUnlocked:"仅本回合(改完自动清除)",goalBarReviewModel:"审查模型",goalBarUseMainModel:"使用主模型",goalBarMaxRounds:"最大轮数",goalBarMaxRoundsTip:"最大审查重改轮数;0 或不填 = 不限(持续改到通过)",goalBarUnlimitedShort:"不限",goalBarReviewing:"审查中…",goalBarRound:"第 {n} 轮",goalBarActive:"目标生效中",goalBarPassed:"已通过",goalBarFailed:"未通过",goalBarStatusPending:"等待生成…",goalWizardBtn:"AI 提炼",goalWizardTip:"让 AI 通过问卷调研细化需求,收敛为目标",goalWizardRunning:"目标调研中",goalWizardAnswer:"回答",goalWizardCard:"目标调研",settings:"设置",settingsTitle:"设置",settingsDesc:"修改立即生效:系统提示词、技能与插件开关会重建当前会话;审查提示词与审查技能只影响后续目标审查(回复进行中则主会话变更自动延迟)。",settingsSystemPrompt:"系统提示词",settingsPromptHistory:"输入历史",settingsPromptHistoryDesc:"用 ↑↓ 在输入框循环历史提问,全局跨对话共享(localStorage)",promptHistoryMax:"最大条数",promptHistoryMaxHint:"超过上限时最旧的自动丢弃,可设 1–500",promptHistoryCharLimit:"限制单条字数",promptHistoryCharLimitHint:"开启后超长输入截断后保存,避免大段粘贴占满存储",promptHistoryCharLimitPlaceholder:"最大字数(100–20000)",promptHistoryClear:"清空历史",promptHistoryClearConfirm:"确认清空?",promptHistoryCleared:"已清空输入历史",promptHistoryCount:"当前 {n} 条",promptHistoryEmpty:"暂无历史记录,上/下键暂无可循环内容",settingsPromptMode:"模式",promptModeAppend:"追加",promptModeReplace:"替换",promptAppendHint:"追加模式:自定义内容拼接到默认系统提示词末尾(推荐,保留默认行为约束)。",promptReplaceHint:"替换模式:完全用自定义内容替换系统提示词(项目上下文与技能段仍会自动附加)。切换后输入框会显示原本的默认提示词,可直接修改;不改动失焦则仍使用默认。",promptPlaceholder:"输入自定义系统提示词…(失焦后自动应用)",settingsViewPrompt:"查看当前完整提示词",settingsViewPromptHint:"当前会话实际生效的完整系统提示词(含自定义追加/替换内容、项目上下文、技能说明与工具引导),只读。",settingsViewPromptEmpty:"会话尚未就绪,暂无系统提示词。",settingsSkills:"技能",settingsReview:"目标审查",settingsReviewDesc:"为独立的目标审查会话配置额外提示词和技能;不会改变主会话设置。",settingsReviewSkills:"审查可用技能",reviewPromptPlaceholder:"输入审查自定义提示词…(失焦后自动应用)",reviewPromptHint:"这些内容会追加到审查任务中;审查仍会强制要求输出 pass/fail JSON。技能开关仅对审查生效。",settingsVisionBridge:"视觉桥",settingsVisionBridgeDesc:"当前模型不支持识图时,把图片交给已配置的视觉模型转写为文字证据,再让模型回答",visionBridgeEnabled:"启用视觉桥",visionBridgeModel:"转写模型",visionBridgeAuto:"自动选择(按顺序)",visionBridgeNoModels:"未找到已配置的视觉模型:在模型配置里添加任意支持图片的模型(如 qwen-vl、GLM-4V、Gemini)即可自动启用",visionBridgeOffHint:"已关闭:图片将原样发送,纯文本模型可能看不到图片内容",visionBridgeCurrent:"当前转写模型:{model}",visionBridgePromptMode:"转写提示词",settingsMarkers:"标记工具",settingsMarkersDesc:"让 AI 用 [[todo:...]] / [[svc:...]] / [[notify:...]] / [[conv:rename:...]] 内联标记在正文里改状态,无需工具往返。全局关闭则全部停用;分组开关可细粒度控制。",markersEnabled:"启用标记工具(全局)",markersEnabledDesc:"关闭后 AI 不再收到任何标记引导,解析也跳过(所有标记原文原样保留,不执行)。",markersOffHint:"已全局关闭:所有标记停用,AI 不会写标记,也不会触发任务/重命名等副作用。",markerGroupTodo:"任务标记 todo",markerGroupSvc:"后台服务标记 svc",markerGroupNotify:"提醒标记 notify",markerGroupRename:"重命名标记 conv/rename",markerRenameTip:"[[conv:rename:新标题]] 或 [[rename:set:标题]] 重命名当前对话(标题 ≤80 字)",settingsTerminalTools:"终端工具",terminalToolsEnabled:"启用持久终端工具",settingsTerminalToolsDesc:"让 AI 在交互式程序(REPL/vim)、长驻服务、需要持续观察输出或你要求在可见终端操作时,使用内置终端;普通命令仍走一次性 bash 工具",terminalToolsOffHint:"已关闭:AI 无法使用 terminal_* 工具,也不会收到相关使用引导",settingsMessageDisplay:"消息显示",thinkingWrap:"完整显示思考",thinkingWrapDesc:"开启:思考内容始终完整展开并自动换行(流式推理过程也实时可见);关闭:折叠成一行摘要,流式中一行实时显示最新文本",toolsWrap:"完整显示工具",toolsWrapDesc:"开启:工具调用始终完整展开显示参数和输出;关闭:默认折叠,点击展开",wideChat:"宽屏聊天列",wideChatDesc:"开启:中央列铺满宽度(超宽屏有用);关闭:保持 860px 上限",terminalBashTakeover:"终端接管 bash",terminalBashTakeoverDesc:"此开关决定 bash 是否覆盖为终端版:关 = 原生 SDK bash(纯进程、不开终端);开 = 跑进可见终端,且 persist 参数在本开关的基础上决定一次性(false,命令跑完进程退出、输出留档)还是持久(true,shell 状态跨调用保留、静默自动转后台并通知 AI)",terminalBashIdleMs:"静默转后台阈值(毫秒)",terminalBashIdleMsDesc:"持久终端模式下,命令连续无输出达到该时长即不再阻塞等待,转入后台继续运行并通知 AI;0 = 一直等到命令结束(默认 15000)",visionBridgePromptPlaceholder:"输入自定义转写提示词…(留空 = 使用内置默认提示词,失焦后自动应用)",visionBridgePromptAppendHint:"追加模式:自定义内容拼接到内置转写提示词末尾(推荐,保留默认的逐字转写约束)。",visionBridgePromptReplaceHint:"替换模式:完全用自定义内容替换内置转写提示词。切换后输入框会显示内置默认提示词,可直接修改;不改动失焦则仍使用默认。",uninstallExt:"卸载",uninstallConfirm:"确认卸载?",uninstallConfirmHint:"再次点击确认,将在终端执行 pi remove",uninstallHint:"通过可见终端执行 pi remove 卸载此包,完成后自动刷新列表",uninstallTitle:"卸载",pluginUpdate:"更新",pluginUpdateHint:"从安装来源重新拉取并覆盖安装(保留 config.json 配置),完成后自动重载插件列表",pluginMarket:"插件市场",pluginCatalogAdd:"添加插件",pluginCatalogAddHint:"把第三方插件填进可安装列表(owner/repo 或完整 GitHub 地址)",pluginCatalogSource:"来源 owner/repo 或 owner/repo/子目录(必填)",pluginCatalogId:"id(可选,默认取仓库/子目录名)",pluginCatalogName:"名称(可选)",pluginCatalogIcon:"图标 emoji(可选)",pluginCatalogDesc:"简介(可选)",pluginCatalogAddSubmit:"添加到列表",noPluginCatalog:"列表为空 —— 点「添加插件」把第三方插件填进列表",pluginInstalled:"已安装",pluginCatalogCustom:"自定义",pluginInstall:"安装",pluginInstallHint:"从来源直接安装到界面插件(在可见终端执行)",pluginCatalogRemoveHint:"从列表移除这条自定义插件",pluginUninstallHint:"在可见终端执行 pi-web-ui uninstall 卸载此插件(再次点击确认),完成后自动刷新列表",settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",dshPatches:"DSH 用户补丁",dshPatchesDesc:"启动时按文件名序加载的 Cordis patch(<dataDir>/dsh-patches/*.yml)。新增/修改后点「重扫」重启运行时生效;失败的文件会被跳过并打印到运行时 stderr。",dshPatchesRescan:"重扫",dshPatchesRescanHint:"重新扫描补丁目录并重启 DSH 运行时使新补丁生效",dshPatchesEmpty:"未放置补丁文件",dshPatchesPath:"补丁目录:",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsSubagentTemplates:"子代理模板",settingsSubagentTemplatesDesc:"配置子代理预设(角色系统提示词 + 技能/扩展白名单 + 可选模型)。AI 派生子代理时可选用模板(subagent_spawn 的 template 参数),也可不传按默认运行;停用的模板保留在面板但对 AI 不可见。",noSubagentTemplates:"还没有子代理模板。AI 派生子代理时可选用模板(角色提示词 + 技能/扩展白名单 + 可选模型),也可以不传 template 按默认配置运行。",subagentTemplateNew:"新建模板",subagentTemplateEdit:"编辑",subagentTemplateClosed:"已停用",tplDefaultBadge:"默认",subagentTemplateOffHint:"关闭的模板保留在面板、可随时重新启用,但 AI 工具查询不到、不能选择",subagentTemplateEnable:"启用",subagentTemplateDisable:"停用",subagentDefaultModelLabel:"子代理默认模型",subagentFollowMain:"跟随主对话当前模型",subagentDefaultModelHint:"所有子代理的兜底模型(模板里指定的模型和 subagent_spawn 的 model 参数优先级更高);不改主对话模型。",subagentNoModels:"暂无可用的模型(需要先配置服务商 API Key)——子代理将跟随主对话模型。",tplNamePlaceholder:"模板名(AI 用 subagent_spawn 的 template 参数引用)…",tplDescriptionPlaceholder:"简介(AI 据此判断适用场景)…",tplPromptModeLabel:"系统提示词模式",tplModelLabel:"模型(空 = 跟随主对话)",tplSystemPromptLabel:"系统提示词",tplSystemPromptPlaceholder:"模板角色系统提示词…(append 模式可留空)",tplWhitelistHint:"白名单:勾选 = 子代理只启用这些;全部不勾 = 跟随主会话设置",tplSkillsLabel:"技能白名单",tplExtensionsLabel:"扩展白名单",tplSave:"保存模板",tplCancel:"取消编辑",tplDelete:"删除模板",tplInherit:"跟随主会话",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},qs={docTitle:"pi-web-ui — pi coding agent",cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",collapsePanel:"Collapse panel",expandPanel:"Expand panel",dragToResize:"Drag to resize · double-click to reset",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",githubRepo:"GitHub repository (xing-shuyin/pi-web-ui)",copy:"Copy",viewSwitch:"Switch view",chat:"Chat",terminal:"Terminal",selectModel:"Select model",availableModels:"Available models",allProviders:"All",providers:"Providers",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",engineBadge:"Engine",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",cwdGoUp:"Up one level",cwdPickCurrent:"Select this folder",cwdChoose:"Select",cwdEnter:"Enter",cwdEmpty:"(empty)",cwdNewFolder:"New folder",cwdNewName:"Folder name",cwdCreate:"Create",cwdCancel:"Cancel",cacheHit:"Cache hit",cacheHitTip:"read {read} · write {write} · miss {miss} (of {input} input tokens)",tps:"t/s",rateTip:"Live generation rate (estimated)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",placeholderStreaming:"The agent is working… press Enter to steer, or click Queue to send after the reply finishes",placeholderIdle:"Message pi — Enter to send, / for commands",placeholderConnecting:"Connecting to server…",stopAgent:"Stop agent",stop:"Stop",bgTasks:"Background tasks",bgTasksTip:"Servers the AI started in the background (npm run dev & etc.) — stop them individually or all at once; they survive the conversation",bgTasksEmpty:"No background tasks",bgTasksDesc:"Processes the AI started that are still listening (detected by port)",bgTaskPort:"Port",bgTaskPid:"PID",bgTaskSince:"Started",bgTaskStop:"Stop",bgTaskStopAll:"Stop all",bgTaskRefresh:"Refresh",bgTaskJustNow:"just now",bgTaskMinutes:"{n} min ago",bgTaskHours:"{n} hr ago",bgTaskDays:"{n} days ago",stopBash:"Stop",stopBashTip:"Stop the running bash command (conversation continues)",supplement:"Queue",supplementTip:"Add to queue: sent only after the whole run finishes (no interruption)",queueSteerTag:"Steer",queueFollowTag:"Queued",queueRemoveTip:"Remove this queued message",sendTip:"Send (Enter)",slashCommands:"Commands",slashMenuHint:"↑↓ select · Enter/Tab complete",slashHelpTitle:"pi commands",slashHelpHint:"Type / anytime to open the command list",slashLoading:"Loading commands… (available once connected)",slashBuiltin:"Builtin",slashExtension:"Extension",slashPrompt:"Template",slashSkill:"Skill",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",subagentBadge:"Subagent",convErrorBadge:"Subagent failed: {error}",subagentTitle:"Subagent · {title}",historySessions:"History",openHistory:"History",openFiles:"Files",streaming:"Streaming…",noHistory:"No previous chats",current:"Current",messageCount:"{n} messages",tuiTip:"Chat in the pi terminal (TUI)",deleteProject:"Remove from recent projects",deleteProjectConfirm:"Confirm remove",deleteSession:"Delete this chat transcript permanently",deleteSessionConfirm:"Confirm delete",renameSession:"Rename this chat",renameSessionPlaceholder:"Type a new name…",renameSessionConfirm:"Rename",dismissConversation:"Dismiss from running (keep in history)",dismissConversationConfirm:"Confirm dismiss",collapseSection:"Collapse",expandSection:"Expand",emptyChat:"Empty chat",editReask:"Edit & re-ask",editReaskTip:"Edit this question and re-ask from here (forks a new conversation; the original is kept)",reaskFromHere:"Re-ask from here",editPlaceholder:"Edit the question…",editHint:"⌘/Ctrl+Enter to submit · Esc to cancel",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-web-ui",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-web-ui",updateTerminalHint:"Clicking runs npm i -g pi-web-ui@latest in a visible terminal; restart the service afterwards to take effect (pi-web-ui server restart).",updatesAllTitle:"Component updates",updatesAllBadge:"{n} updates",updatesAllUpToDate:"All components up to date",kindWebUi:"Web UI",kindPiCore:"Core",kindPackage:"Package",updatesAllRefresh:"Re-check all",updateCheckFailed:"Check failed",updateBtn:"Update",updateAllBtn:"Update all",updatePkgTabTitle:"Update {name}",updateAllTabTitle:"Update all components",computer:"This PC",rootDir:"Root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",previewFile:"Preview",downloadFile:"Download file",downloadFailed:"Download failed: {error}",fileNotFoundShort:"File not found",pluginMountFailed:"Plugin {name} failed to mount",liveOutputOmitted:`…[{n} chars omitted above]…
|
|
154
154
|
`,uploadToFolder:"Upload files to this folder",uploadToCurrentDir:"Upload files to current directory",protocolMismatch:"Page version differs from the server (the app was just updated). Refresh the page to restore full functionality.",selectLinesHint:"Click a line to select; drag or Shift+click for a range",enableWrap:"Enable line wrap",disableWrap:"Disable line wrap",selectedRange:"Selected {n} lines (lines {start}-{end})",fileLines:"{n} lines",selectAll:"Select all",clearSelection:"Clear",addToChat:"Add to chat",addedToChat:"Added",previewTruncated:"⚠ File too large — previewing the first 512KB",previewLinesTruncated:"… too many lines — showing the first {n}",binaryFile:"🔣 Binary file — first 4KB shown as hex",binaryHexTruncated:" (file larger — download for the full file)",previewNotSupported:"This file type can't be previewed (only images / videos / text)",emptyFile:"(empty file)",editFile:"Edit file",exitEditFile:"Exit editing",saveFile:"Save file",discardFileChanges:"Discard unsaved changes?",fileSaved:"Saved",fileEditTruncated:"The preview is incomplete, so this file can't be edited",showMarkdownSource:"Show Markdown source",showMarkdownPreview:"Show Markdown preview",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",zoomIn:"Increase font size",zoomOut:"Decrease font size",resetZoom:"Reset zoom",pluginRequest:"Plugin request",modelQuestion:"Model question",modelQuestionCustom:"Custom answer (optional)",modelQuestionSubmit:"Submit answer",questionTimeout:"⏳ {s}s left — auto-cancels on timeout",questionTimeoutExpired:"Question timed out, resuming conversation…",modelNoVision:"Current model {name} doesn't support images — switch to DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH uses runtime-built-in skills (dsh-skill); toggling is not supported in settings yet",dshExtensionsNote:"DSH has no pi extension system; capabilities are runtime-built-in (MCP/subagent/goal/plan/skill…)",dshReviewPromptNote:"DSH has no separate reviewer: this text is appended to the system prompt for goal rounds",dshVisionHiddenNote:"DSH supports real image input (DeepSeek V4 Flash Vision (exp) only) — no vision bridge needed",dshNoReviewModel:"DSH has no separate reviewer model — the model self-certifies goal completion; max rounds = auto-iteration count",noOptions:"(no options)",inputPlaceholder:"Enter content",soundHeader:"Sound notifications",enableSound:"Enable sound",preview:"Preview",volume:"Volume",notifyHeader:"Desktop notifications",notifyEnable:"Enable desktop notifications",notifyEnableDesc:"Ping you when a session finishes or needs your input, even while you're in another app. Requires permission; only fires when this page is not focused.",notifyDenied:"Notification permission was blocked — enable notifications for this site in your browser / system settings.",notifyUnsupported:"Notifications are not supported by this browser.",notifyDoneTitle:"Task finished",notifyDoneBody:"The session finished and is ready for your input.",notifyQuestionTitle:"Needs your input",notifyQuestionBody:"pi is waiting for your answer to a question.",notifyErrorTitle:"Something went wrong",notifyErrorBody:"A session reported an error.","sound.question":"Question popup","sound.question.desc":"When ask_user_question appears","sound.done":"Reply finished","sound.done.desc":"When the agent finishes a turn","sound.start":"Reply started","sound.start.desc":"When the agent starts a new turn","sound.error":"Error","sound.error.desc":"When an error notice appears",setupTitle:"pi agent config not detected",setupDesc:"pi-web-ui needs pi's config directory (~/.pi/agent) and at least one API key to run the agent. pi has built-in providers such as openai, anthropic, and deepseek — just pick one and enter a key, no terminal needed.",installFailed:"✖ pi agent installation failed:",retryInstall:"Retry install",skip:"Skip",installDone:"✅ pi agent CLI installed. Pick a provider and enter an API key to start chatting:",cliReadyHint:"✅ pi agent CLI already installed locally. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",directory:"Directory",waitingResponse:"Waiting for model response…",backToBottom:"Back to bottom",questionNavTitle:"Questions",searchPlaceholder:"Search in conversation…",searchNoResults:"No results",searchModels:"Filter models…",noModelMatches:"No matching models",modelUsedCount:"used {n}×",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search full conversation text (AI replies included), recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching…",gsTruncated:"Too many matches — showing a subset",gsCurrentProject:"current",gsOpenPreview:"Open file preview",gsNavigate:"select",gsOpen:"open",gsCloseHint:"close",bgTaskCommand:"Command",searchPrev:"Previous (Shift+Enter)",searchNext:"Next (Enter)",searchClose:"Close (Esc)",questionNavTip:"All questions in this conversation — hover to expand, click to jump","tpl.title":"Prompt templates","tpl.hint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.clickCard":"Click to fill the input","tpl.editTpl":"Edit / delete template","tpl.openPicker":"Prompt templates (reusable prompts, anytime)","tpl.pickerTitle":"Prompt templates","tpl.pickerHint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.add":"New template","tpl.addDesc":"Save a workflow you use often","tpl.reset":"Restore defaults","tpl.resetConfirm":"Restore defaults?","tpl.builtin":"Built-in","tpl.custom":"Custom","tpl.newTitle":"New prompt template","tpl.editTitle":"Edit prompt template","tpl.fieldIcon":"Icon","tpl.fieldTitle":"Title","tpl.fieldTitlePh":"Short title shown on the card","tpl.fieldDesc":"Description","tpl.fieldDescPh":"One-liner shown on the card","tpl.fieldPrompt":"Prompt","tpl.fieldPromptPh":"The full prompt sent to the agent","tpl.required":"Title and prompt are required","tpl.save":"Save","tpl.fill":"Fill input","tpl.fillTip":"Fill the input so you can tweak it before sending","tpl.sendNow":"Send now","tpl.sendTip":"Send immediately as a new conversation","tpl.delete":"Delete","tpl.deleteTip":"Delete this custom template","tpl.remove":"Remove from library","tpl.removeTip":"Remove this built-in template; restore later via “Restore defaults”","tpl.restore":"Restore default","tpl.restoreTip":"Discard your edits and restore the built-in default","tpl.sk.setup":"Repo setup","tpl.sk.setup.desc":"Give the repo a baseline that other workflows can use","tpl.sk.setup.prompt":`Scan this repository and build the baseline context other workflows rely on, then report concisely:
|
|
155
155
|
|
|
156
156
|
1. Project type, tech stack and directory layout
|
|
@@ -301,26 +301,26 @@ Keep going until the plan holds up.`,"tpl.sk.tdd":"Test-driven","tpl.sk.tdd.desc
|
|
|
301
301
|
2. Make them pass with the minimal implementation
|
|
302
302
|
3. Refactor while keeping tests green
|
|
303
303
|
|
|
304
|
-
Avoid three test anti-patterns: tests coupled to the implementation, tautological assertions (always true), and horizontal slicing (surface only). Report after each step and run the tests.`,error:"Error",done:"Done",running:"Running…",toolQueued:"Queued",copyArgs:"Copy args",errorOutput:"Error output",output:"Output",waitingOutput:"Waiting for output…",toolDoneWaitingModel:"Done · waiting on model",waitingModel:"Waiting for model response…",thinkingNow:"Thinking",thinkingPreview:"Thinking: {preview}",commands:"Commands",newCommand:"New command",newTerminal:"New terminal",name:"Name",command:"Command",cwdHint:"(${pwd} = current working directory)",noCommands:"No commands yet — click + to add one",clickToRun:"Click to run",edit:"Edit",delete:"Delete",confirmQ:"Confirm?",builtinTerminal:"Built-in terminal",termEmptySub:"Click a command on the left to run it, or + on the right for a new terminal",noTerminal:"No terminals",exited:"(exited{code})",exitBanner:"[Process exited with code {code}]",closeTerminal:"Close terminal",renameTerminal:"Rename terminal",rerun:"Reload .pi/commands.json",terminalTitle:"Terminal {n}",aiBashGroup:"Terminal-backed bash",exampleName:"e.g. start dev server",exampleCommand:"e.g. npm run dev",scmTab:"Git",scmTitle:"Source Control",scmRefreshTip:"Re-query git status & diff",scmCurrentBranch:"Current branch",scmUpstreamGone:"Upstream deleted",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"Detached HEAD",scmSelectBranch:"Select branch…",scmRemoteBranches:"Remote branches",scmStageTip:"Stage {path}",scmUnstageTip:"Unstage {path}",scmSwitch:"Switch",scmSwitchBranch:"Switch branch",scmSwitchBranchTip:"Runs git checkout {branch} in the terminal",scmPush:"Push",scmPushTip:"Runs git push in the terminal",scmPull:"Pull",scmPullTip:"Runs git pull in the terminal",scmCommit:"Commit",scmCommitTip:'Runs git commit -m "…" in the terminal (commits staged changes only)',scmCommitAll:"Commit All",scmCommitAllTip:'Runs git add -A && git commit -m "…" in the terminal (stages all changes incl. untracked and commits)',scmCommitPlaceholder:"Type a commit message…",scmChanges:"Changes",scmHistory:"Commit tree",scmCommitDetail:"Commit details",scmSelectCommitHint:"Click a commit on the left to view its details",scmNoHistory:"No commits yet",scmNoChanges:"Working tree clean — no changes",scmNotGitRepo:"Current directory is not a Git repository",scmLoading:"Querying…",scmConnecting:"Waiting for connection…",scmDiff:"Diff",scmSelectFileHint:"Click a file on the left to view its diff",scmNoDiff:"(no diff)",scmStaged:"Staged",scmUnstaged:"Unstaged",scmStagedUnstaged:"Staged + unstaged",scmUntracked:"Untracked",scmUntrackedNote:"Untracked file — stage it with + to include (or use Commit All)",scmQueryFailed:"Git query failed: {error}",scmQueryFailedShort:"Query failed",pluginCommandFallback:"Plugin command",scmTooManyFailures:"Git queries keep failing — click refresh to retry",scmRunsInTerminal:"Commit / branch switch / push / pull run in the terminal",scmViewTerminal:"Open terminal",editProvider:"Edit provider",builtinProviders:"Built-in providers",hintKeyOnly:"Just enter an API key",configuredBadge:"✓ Configured",keyReady:"Key ready",replaceKey:"Replace key",replaceKeyTitle:"Replace the saved key",clearKey:"Clear",clearKeyTitle:"Remove this provider's key stored in auth.json; it returns to unconfigured (env-var sourced keys can't be cleared here)",clearKeyConfirm:"Clear the stored key for {id}? Its models will leave the list until you configure it again.",cloneProvider:"Add key",cloning:"Adding",cloneProviderTitle:"Add a second API key for this provider (baseUrl and model list are copied automatically)",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",addKey:"Add key",addKeyPlaceholder:"Paste the key value…",keyNamePh:"Name (optional, e.g. backup)",providerIdPlaceholder:"Provider ID",baseUrlExamplePh:"baseUrl, e.g. https://api.opencode.ai/zen/v1 or http://127.0.0.1:4096",saveAllBatch:"Save all ({n})",netDisconnected:"Network disconnected — reconnect and retry",advancedEdit:"Advanced edit",batchCreateProviders:"Batch-create providers ({n} APIs)",secondKeyTitle:"Add a second key for {api} · {baseUrl} · {n} models — just name the new provider and enter the key.",noBaseUrlShort:"(no baseUrl)",providerNameLabel:"Provider name",providerNameHint:"(new ID, e.g. opencode-2)",apiKeyLabel:"API key",secondKeyPlaceholder:"sk-… second key",batchDesc:"This provider has multiple APIs ({apis}); it was split into {n} custom providers. Save each so all models (e.g. muse-spark) work. Enter one shared second key to save all at once.",batchKeyLabel:"Shared API key (applies to all {n} providers)",modelsCountShort:"{n} models: ",noKeyYet:"No key yet — add one to use this provider",activateKey:"Set active",removeKey:"Remove",removeKeyConfirm:"Remove this key? It must be re-configured to be used again.",customProviders:"Custom providers",customDesc:"For Ollama / vLLM / OpenAI-compatible proxies, etc. Written to pi's models.json — hot-reloaded immediately.",noCustomProviders:"No custom providers yet",modelsCount:"{n} models",addProvider:"Add provider",providerId:"Provider ID",providerIdHint:"(required, e.g. ollama / my-proxy)",displayName:"Display name",displayNamePh:"My proxy",apiType:"API type",baseUrlHint:"(OpenAI-compatible endpoint)",apiKeyHint:"sk-… (optional — uses the auth.json key)",authHeader:"Auto-add Authorization header",modelsTitle:"Models",modelIdReq:"Model ID (required)",text:"Text",textImage:"Text+image",contextWindow:"Context",maxOutput:"Max output",removeModel:"Remove model",addModel:"Add model",deleteProviderConfirm:"Delete provider {id} and its {n} models?",fetchModels:"Fetch model list",fetchModelsHint:"Pull model IDs from the baseUrl /models endpoint (server-side, no CORS)",fetchingModels:"Fetching…",fetchModelsOk:"Fetched {n} models",fetchModelsEmpty:"The endpoint returned no models",fetchModelsErr:"Fetch failed: {msg}",fetchModelsNeedBaseUrl:"Enter a baseUrl first",goalBarTitle:"Goal",goalBarPlaceholder:"Set a goal; the agent's output is auto-reviewed…",goalBarSet:"Start",goalBarClear:"Cancel",goalBarLocked:"Locked: applies to every later turn",goalBarUnlocked:"This turn only (cleared afterwards)",goalBarReviewModel:"Review model",goalBarUseMainModel:"Use the main model",goalBarMaxRounds:"Max rounds",goalBarMaxRoundsTip:"Max review-revision rounds; 0 or empty = unlimited (keep revising until it passes)",goalBarUnlimitedShort:"Unlimited",goalBarReviewing:"Reviewing…",goalBarRound:"Round {n}",goalBarActive:"Goal active",goalBarPassed:"Passed",goalBarFailed:"Failed",goalBarStatusPending:"Waiting to generate…",goalWizardBtn:"AI Scrape",goalWizardTip:"Let AI refine the requirement into a goal via a Q&A survey",goalWizardRunning:"Scoping the goal",goalWizardAnswer:"Answer",goalWizardCard:"Goal survey",settings:"Settings",settingsTitle:"Settings",settingsDesc:"Changes apply immediately: system prompt, skill and extension toggles rebuild the current session; review instructions and review skills affect later goal reviews (main-session changes are deferred while streaming).",settingsSystemPrompt:"System prompt",settingsPromptHistory:"Input history",settingsPromptHistoryDesc:"Cycle previous prompts with ↑/↓ in the input — global across conversations (localStorage)",promptHistoryMax:"Max entries",promptHistoryMaxHint:"Oldest entries are dropped when exceeded (1–500)",promptHistoryCharLimit:"Limit characters per entry",promptHistoryCharLimitHint:"When enabled, overlong prompts are truncated before saving",promptHistoryCharLimitPlaceholder:"Max chars (100–20000)",promptHistoryClear:"Clear history",promptHistoryClearConfirm:"Confirm clear?",promptHistoryCleared:"Input history cleared",promptHistoryCount:"{n} entries",promptHistoryEmpty:"No history yet — ↑/↓ has nothing to cycle",settingsPromptMode:"Mode",promptModeAppend:"Append",promptModeReplace:"Replace",promptAppendHint:"Append mode: your text is appended to the end of the default system prompt (recommended — keeps the default behavior constraints).",promptReplaceHint:"Replace mode: your text fully replaces the system prompt (project context and skills are still appended automatically). After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",promptPlaceholder:"Type a custom system prompt… (applied on blur)",settingsViewPrompt:"View the current full prompt",settingsViewPromptHint:"The full system prompt actually in effect for this conversation (custom append/replace text, project context, skills and tool guidance). Read-only.",settingsViewPromptEmpty:"Session not ready yet — no system prompt available.",settingsSkills:"Skills",settingsReview:"Goal review",settingsReviewDesc:"Configure extra instructions and skills for the isolated goal-review session; the main session is unaffected.",settingsReviewSkills:"Skills available to review",reviewPromptPlaceholder:"Type custom review instructions… (applied on blur)",reviewPromptHint:"These instructions are added to the review task; pass/fail JSON output is still enforced. Skill toggles apply only to review.",settingsVisionBridge:"Vision bridge",settingsVisionBridgeDesc:"When the current model can't see images, send them to a configured vision model and transcribe into text evidence first",visionBridgeEnabled:"Enable vision bridge",visionBridgeModel:"Transcription model",visionBridgeAuto:"Auto (in order)",visionBridgeNoModels:"No configured vision model found: add any image-capable model (e.g. qwen-vl, GLM-4V, Gemini) in Model config to enable automatically",visionBridgeOffHint:"Disabled: images are sent as-is, a text-only model may not see them",visionBridgeCurrent:"Current transcription model: {model}",visionBridgePromptMode:"Transcription prompt",settingsMarkers:"Markers",settingsMarkersDesc:"Let the AI write [[todo:...]] / [[svc:...]] / [[notify:...]] / [[conv:rename:...]] inline markers in replies to update state without a tool round-trip. Global off disables all; per-marker toggles give fine control.",markersEnabled:"Markers enabled (global)",markersEnabledDesc:"Off = no marker guidance injected and no parsing; markers stay as plain text.",markersOffHint:"Globally off: all markers disabled — the AI won't write markers and no side effects fire.",markerGroupTodo:"todo — tasks",markerGroupSvc:"svc — background services",markerGroupNotify:"notify — non-blocking hints",markerGroupRename:"conv/rename — rename chat",markerRenameTip:"[[conv:rename:Title]] or [[rename:set:Title]] renames the current conversation (≤80 chars)",settingsTerminalTools:"Terminal tools",terminalToolsEnabled:"Enable persistent terminal tools",settingsTerminalToolsDesc:"Let the AI use the built-in terminal for interactive programs (REPLs/vim), long-running servers, continuous output watching, or when you ask it to work in the visible terminal; ordinary commands still go through the one-shot bash tool",terminalToolsOffHint:"Disabled: the AI has no terminal_* tools and receives no usage guidance",settingsMessageDisplay:"Message display",thinkingWrap:"Show full thinking",thinkingWrapDesc:"On: thinking always expands fully and wraps (live reasoning visible while streaming); Off: collapses to a one-line summary with the latest text shown live while streaming",toolsWrap:"Show full tools",toolsWrapDesc:"On: tool calls always expand fully showing arguments and output; Off: collapsed by default, click to expand",wideChat:"Wide chat column",wideChatDesc:"On: the center column fills the width (useful on ultrawide monitors); Off: keep the 860px cap",terminalBashTakeover:"Terminal-backed bash",terminalBashTakeoverDesc:"This switch decides whether bash is overridden to a terminal version: OFF = native SDK bash (process spawn, no terminal); ON = runs in a visible terminal, where the persist parameter decides (on top of the switch) one-shot (false — process exits when the command finishes, output retained) vs persistent (true — shell state retained across calls, silent commands move to the background and notify the AI)",terminalBashIdleMs:"Silence-to-background threshold (ms)",terminalBashIdleMsDesc:"In persistent-terminal mode, when a command produces no output for this long, stop blocking and let it keep running in the background; the AI is notified when it finishes. 0 = always wait until completion (default 15000)",visionBridgePromptPlaceholder:"Type a custom transcription prompt… (empty = built-in default, applied on blur)",visionBridgePromptAppendHint:"Append mode: custom text is appended after the built-in transcription prompt (recommended — keeps the verbatim-transcription contract).",visionBridgePromptReplaceHint:"Replace mode: custom text replaces the built-in transcription prompt entirely. After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",uninstallExt:"Uninstall",uninstallConfirm:"Confirm?",uninstallConfirmHint:"Click again to confirm — runs pi remove in the terminal",uninstallHint:"Runs pi remove in a visible terminal, then refreshes the list automatically",uninstallTitle:"Uninstall",pluginUpdate:"Update",pluginUpdateHint:"Re-installs from the recorded source (--force, keeps config.json), then refreshes the plugin list automatically",pluginMarket:"Plugin marketplace",pluginCatalogAdd:"Add plugin",pluginCatalogAddHint:"Drop a third-party plugin into the installable list (owner/repo or full GitHub URL)",pluginCatalogSource:"Source owner/repo or owner/repo/subdir (required)",pluginCatalogId:"id (optional, defaults to repo/subdir name)",pluginCatalogName:"Name (optional)",pluginCatalogIcon:"Icon emoji (optional)",pluginCatalogDesc:"Description (optional)",pluginCatalogAddSubmit:"Add to list",noPluginCatalog:'List is empty — click "Add plugin" to drop a third-party plugin in',pluginInstalled:"Installed",pluginCatalogCustom:"custom",pluginInstall:"Install",pluginInstallHint:"Install straight from the source into UI plugins (runs in a visible terminal)",pluginCatalogRemoveHint:"Remove this custom plugin from the list",pluginUninstallHint:"Runs pi-web-ui uninstall in a visible terminal (click again to confirm), then refreshes the list automatically",settingsExtensions:"Extensions",settingsUiPlugins:"UI plugins",noUiPlugins:"No UI plugins installed (<dataDir>/plugins/)",dshPatches:"DSH user patches",dshPatchesDesc:"Cordis patches loaded at runtime boot, in filename order (<dataDir>/dsh-patches/*.yml). New/edited files take effect after 'Rescan' restarts the runtime; broken files are skipped and logged to runtime stderr.",dshPatchesRescan:"Rescan",dshPatchesRescanHint:"Re-scan the patch directory and restart the DSH runtime so new patches take effect",dshPatchesEmpty:"No patch files yet",dshPatchesPath:"Patch directory: ",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",settingsPresets:"Presets",settingsSubagentTemplates:"Subagent templates",settingsSubagentTemplatesDesc:"Presets for spawned subagents (role system prompt + skills/extensions whitelist + optional model). AI may pick a template (subagent_spawn template param) or spawn without one; disabled templates stay in the panel but are invisible to AI tools.",noSubagentTemplates:"No subagent templates yet. AI can pick a template when spawning a subagent (role prompt + skills/extensions whitelist + optional model), or spawn without a template param for default config.",subagentTemplateNew:"New template",subagentTemplateEdit:"Edit",subagentTemplateClosed:"Disabled",tplDefaultBadge:"Built-in",subagentDefaultModelLabel:"Default subagent model",subagentFollowMain:"Follow the main conversation's current model",subagentDefaultModelHint:"Fallback model for all subagents (a template's own model and the subagent_spawn model param take priority); does not change the main conversation's model.",subagentNoModels:"No usable models yet (configure a provider API key first) — subagents will follow the main conversation's model.",subagentTemplateOffHint:"Disabled templates stay in the panel and can be re-enabled, but AI tools can't see or pick them",subagentTemplateEnable:"Enable",subagentTemplateDisable:"Disable",tplNamePlaceholder:"Template name (referenced by AI via subagent_spawn's template param)…",tplDescriptionPlaceholder:"Description (AI uses it to judge when to pick this template)…",tplPromptModeLabel:"System prompt mode",tplModelLabel:"Model (empty = follow main conversation)",tplSystemPromptLabel:"System prompt",tplSystemPromptPlaceholder:"Template role system prompt… (may be empty in append mode)",tplWhitelistHint:"Whitelist: checked = the subagent only gets these; none checked = follow the main session settings",tplSkillsLabel:"Skills whitelist",tplExtensionsLabel:"Extensions whitelist",tplSave:"Save template",tplCancel:"Cancel edit",tplDelete:"Delete template",tplInherit:"Follow main session",settingsEnabled:"Enabled",settingsDisabled:"Disabled",presetNamePlaceholder:"Preset name…",saveAsPreset:"Save as preset",applyPreset:"Apply",deletePreset:"Delete preset",noSkills:"No skills",noExtensions:"No extensions",noPresets:"No presets yet (tune the settings above, then save them as a preset)",loadingSession:"Loading session…",connectingServer:"Connecting to pi-web-ui server…"},Dn=l.createContext(null);function da(){try{const t=localStorage.getItem(Ln);if(t==="zh"||t==="en")return t}catch{}return"zh"}function ua({children:t}){const[s,n]=l.useState(da),r=l.useCallback(a=>{n(a);try{localStorage.setItem(Ln,a)}catch{}},[]),c=l.useCallback((a,o)=>{let u=Ks[a];if(s==="zh"&&(u=Us[a]),o)for(const[m,y]of Object.entries(o))u=u.replaceAll(`{${m}}`,String(y));return u},[s]);l.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en",document.title=s==="zh"?Us.docTitle:Ks.docTitle},[s]);const i=l.useMemo(()=>({locale:s,setLocale:r,t:c}),[s,r,c]);return e.jsx(Dn.Provider,{value:i,children:t})}function Pt(){const t=l.useContext(Dn);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function be(){return Pt().t}const pa=[{kind:"question",labelKey:"sound.question",descKey:"sound.question.desc"},{kind:"done",labelKey:"sound.done",descKey:"sound.done.desc"},{kind:"start",labelKey:"sound.start",descKey:"sound.start.desc"},{kind:"error",labelKey:"sound.error",descKey:"sound.error.desc"}];function qs({settings:t,onChange:s,onPreview:n}){const r=be(),c=i=>s({...t,...i});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:r("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Nn,{className:"sound-icon"}),e.jsx("span",{children:r("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:i=>c({enabled:i.target.checked})})]}),pa.map(({kind:i,labelKey:a,descKey:o})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:r(a)}),e.jsx("span",{className:"sound-desc",children:r(o)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:r("preview"),disabled:!t.enabled,onClick:u=>{u.preventDefault(),n(i)},children:r("preview")}),e.jsx("input",{type:"checkbox",checked:t[i],disabled:!t.enabled,onChange:u=>c({[i]:u.target.checked})})]})]},i)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:r("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:i=>c({volume:Number(i.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}let Zt=null;function ma(t){if(t===void 0){const n=globalThis.document;if(n&&typeof n.baseURI=="string"&&n.baseURI)try{t=new URL(n.baseURI).pathname}catch{}if(t===void 0)return"/"}if(!t||t==="/")return"/";let s=t.replace(/index\.html$/i,"");return s.endsWith("/")||(s+="/"),s}function An(){return Zt===null&&(Zt=ma()),Zt}function ha(t,s){return s==="/"?t:s+t.replace(/^\/+/,"")}function Ye(t){return ha(t,An())}const _n="pi-web-notify",es={enabled:!1};function Bn(){try{const t=localStorage.getItem(_n);if(!t)return{...es};const s=JSON.parse(t);return{enabled:typeof s.enabled=="boolean"?s.enabled:es.enabled}}catch{return{...es}}}function zs(t){try{localStorage.setItem(_n,JSON.stringify(t))}catch{}}function Nt(){return typeof window<"u"&&"Notification"in window}function ga(){return Nt()?Notification.permission:"denied"}async function fa(){if(!Nt())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}}async function ts(t,s){var r;if(!Nt()||document.hasFocus()||!Bn().enabled||Notification.permission!=="granted")return;const n={body:s,icon:Ye("/icons/icon-192.png"),badge:Ye("/icons/icon-192.png"),tag:"pi-web-ui"};try{const c=await((r=navigator.serviceWorker)==null?void 0:r.getRegistration());c&&typeof c.showNotification=="function"?c.showNotification(t,n):new Notification(t,n)}catch{}}function Vs(){const t=be(),[s,n]=l.useState(Bn),[r,c]=l.useState(()=>Nt()?ga():"denied"),i=async a=>{const o={...s,enabled:a};if(n(o),zs(o),a){const u=await fa();if(c(u),u!=="granted"){const m={...o,enabled:!1};n(m),zs(m)}}};return e.jsxs("div",{className:"sound-menu",style:{borderTop:"1px solid var(--border-color, rgba(255,255,255,.08))",marginTop:6,paddingTop:6},children:[e.jsx("div",{className:"dd-header",children:t("notifyHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(aa,{className:"sound-icon"}),e.jsx("span",{children:t("notifyEnable")})]}),e.jsx("input",{type:"checkbox",checked:s.enabled,onChange:a=>i(a.target.checked)})]}),e.jsx("div",{className:"sound-desc",style:{padding:"2px 8px 4px",opacity:.7,fontSize:"0.82em"},children:t("notifyEnableDesc")}),!Nt()&&e.jsx("div",{className:"sound-desc",style:{padding:"0 8px 4px",opacity:.7,fontSize:"0.82em"},children:t("notifyUnsupported")}),r==="denied"&&e.jsx("div",{className:"sound-desc",style:{padding:"0 8px 4px",opacity:.7,fontSize:"0.82em"},children:t("notifyDenied")})]})}function xa({chat:t,send:s,terminal:n,view:r,plugins:c,onViewChange:i,onOpenPanel:a,onOpenSettings:o,onOpenBgTasks:u,onOpenGlobalSearch:m,sound:y,onSoundChange:x,onSoundPreview:f,themes:b,theme:T,onThemeChange:D}){var L;const{locale:H,setLocale:N,t:j}=Pt(),[Q,V]=l.useState(!1),[J,U]=l.useState(!1),[W,K]=l.useState(!1),[G,C]=l.useState(!1),[M,k]=l.useState(!1),_=[{value:"zh",label:j("langZh")},{value:"en",label:j("langEn")}],Z=t.ready?j("connected"):t.status==="closed"?j("reconnecting"):j("connecting"),z=t.ready?"ok":"busy",I=()=>{var A,ee;if(!t.ready)return;const d=j("updateTabTitle"),E={name:d,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},h=t.terminals.find(Y=>Y.title===d);h?(n.restart(h.id),s({type:"run_command",terminalId:h.id,conversationId:h.conversationId,command:E,cols:80,rows:24})):n.create({id:Qe(),conversationId:t.activeConversationId||((A=t.state)==null?void 0:A.conversationId)||"",title:d,cwd:((ee=t.state)==null?void 0:ee.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:E}),C(!1),k(!1),i("terminal")},R=(d,E)=>{var ee,Y;if(!t.ready||d.length===0)return;const h={name:E,command:ca(d),cwd:"${pwd}"},A=t.terminals.find(se=>se.title===E);A?(n.restart(A.id),s({type:"run_command",terminalId:A.id,conversationId:A.conversationId,command:h,cols:80,rows:24})):n.create({id:Qe(),conversationId:t.activeConversationId||((ee=t.state)==null?void 0:ee.conversationId)||"",title:E,cwd:((Y=t.state)==null?void 0:Y.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:h}),C(!1),k(!1),i("terminal")},w=t.updatesAll??[],$=w.filter(d=>!d.upToDate&&!d.error).length,q=w.filter(d=>!d.upToDate&&!d.error&&d.kind!=="webui"),ie=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:j("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:j("checkingUpdate")}):w.length===0?e.jsx("div",{className:"dd-note",children:j("updatesAllUpToDate")}):e.jsx("ul",{className:"dd-all-list",children:w.map(d=>e.jsxs("li",{className:`dd-all-item${d.error?" err":d.upToDate?"":" warn"}`,children:[e.jsx("span",{className:"dd-all-name",title:d.name,children:d.name}),e.jsx("span",{className:"dd-all-kind",children:d.kind==="webui"?j("kindWebUi"):d.kind==="pi-core"?j("kindPiCore"):j("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:d.error?j("updateCheckFailed"):d.upToDate?`v${d.current}`:e.jsxs(e.Fragment,{children:["v",d.current," → v",d.latest]})}),d.kind!=="webui"&&!d.upToDate&&!d.error&&e.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>R([d],j("updatePkgTabTitle",{name:d.name})),children:j("updateBtn")})]},`${d.kind}:${d.name}`))}),e.jsxs("div",{className:"dd-actions",children:[q.length>0&&e.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>R(q,j("updateAllTabTitle")),children:j("updateAllBtn")}),e.jsx("button",{type:"button",className:"dd-refresh",style:q.length>0?{flex:1}:void 0,onClick:()=>s({type:"check_updates_all",force:!0}),children:j("updatesAllRefresh")})]})]}),v=()=>{var d,E;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dd-update",children:[e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:j("currentVersion")}),e.jsxs("b",{children:["v",((d=t.update)==null?void 0:d.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:j("latestVersion")}),e.jsx("b",{children:t.update===null?j("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:j("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:j("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:j("updateAvailable",{version:t.update.latest})}),((E=t.update)==null?void 0:E.latestPublishedAt)&&Date.now()-new Date(t.update.latestPublishedAt).getTime()<30*6e4&&e.jsx("div",{className:"dd-note warn",children:j("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:j("updateTerminalHint")})]}),e.jsxs("div",{className:"dd-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"check_update"}),children:t.update===null?j("checkingUpdate"):j("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:I,children:j("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:j("openHistory"),onClick:()=>a("left"),children:e.jsx(zi,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${z}`,title:Z}),e.jsx("span",{className:"conn-label",children:Z})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":j("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":r==="chat",className:r==="chat"?"active":"",onClick:()=>i("chat"),children:[e.jsx(ct,{}),e.jsx("span",{children:j("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":r==="terminal",className:r==="terminal"?"active":"",onClick:()=>i("terminal"),children:[e.jsx(ot,{}),e.jsx("span",{children:j("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":r==="git",className:r==="git"?"active":"",onClick:()=>i("git"),children:[e.jsx(At,{}),e.jsx("span",{children:j("scmTab")})]}),c.filter(d=>d.view!==!1).map(d=>{const E=d.error?`${d.name}: ${d.error}`:d.description?`${d.name} — ${d.description}`:d.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":r===`plugin:${d.id}`,className:`plugin-tab${r===`plugin:${d.id}`?" active":""}${d.error?" broken":""}`,title:E,onClick:()=>i(`plugin:${d.id}`),children:[d.icon?e.jsx("span",{"aria-hidden":!0,children:d.icon}):null,e.jsx("span",{children:d.name})]},d.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:j("searchGlobalTip"),onClick:m,children:[e.jsx(Wt,{}),e.jsx("span",{className:"chip-sub",children:j("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":j("bgTasksTip"),onClick:u,children:[e.jsx(Ut,{}),e.jsx("span",{className:"chip-sub",children:j("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:j("settingsTitle"),onClick:o,children:[e.jsx(Ot,{}),e.jsx("span",{className:"chip-sub",children:j("settings")})]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Nn,{}),e.jsx("span",{className:"chip-sub",children:j("sound")})]}),open:Q,onOpenChange:V,children:[e.jsx(qs,{settings:y,onChange:x,onPreview:f}),e.jsx(Vs,{})]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Zi,{}),e.jsx("span",{className:"chip-sub",children:H==="zh"?j("langZh"):"EN"})]}),open:J,onOpenChange:U,children:[e.jsx("div",{className:"dd-header",children:j("language")}),_.map(d=>e.jsx($e,{active:H===d.value,onClick:()=>{N(d.value),U(!1)},children:d.label},d.value))]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Hi,{}),e.jsx("span",{className:"chip-sub",children:j("theme")})]}),open:W,onOpenChange:K,children:[e.jsx("div",{className:"dd-header",children:j("theme")}),e.jsx($e,{active:T===null,onClick:()=>{D(null),K(!1)},children:j("themeDefault")}),b.map(d=>e.jsx($e,{active:T===d.id,onClick:()=>{D(d.id),K(!1)},children:H==="en"?d.nameEn??d.name:d.name},d.id))]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(zt,{}),e.jsxs("span",{className:"chip-sub",children:["v",((L=t.update)==null?void 0:L.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:j("updateAvailable",{version:t.update.latest??""})}),$>0&&e.jsx("span",{className:"update-badge",children:j("updatesAllBadge",{n:$})})]}),open:G,onOpenChange:d=>{C(d),d&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:j("update")}),v(),ie()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:j("githubRepo"),children:e.jsx(Os,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":j("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(Ke,{}),e.jsx("span",{children:j("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ki,{}),e.jsx("span",{className:"chip-sub",children:j("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:M,onOpenChange:d=>{k(d),d&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:j("sound")}),e.jsx("div",{className:"dd-header",children:j("settings")}),e.jsxs($e,{onClick:()=>{k(!1),o()},children:[e.jsx(Ot,{})," ",j("settingsTitle")]}),e.jsxs($e,{onClick:()=>{k(!1),m()},children:[e.jsx(Wt,{})," ",j("searchGlobal")]}),e.jsxs($e,{onClick:()=>{k(!1),u()},children:[e.jsx(Ut,{})," ",j("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(qs,{settings:y,onChange:x,onPreview:f}),e.jsx(Vs,{}),e.jsx("div",{className:"dd-header",children:j("language")}),_.map(d=>e.jsx($e,{active:H===d.value,onClick:()=>N(d.value),children:d.label},d.value)),e.jsx("div",{className:"dd-header",children:j("theme")}),e.jsx($e,{active:T===null,onClick:()=>{D(null),k(!1)},children:j("themeDefault")}),b.map(d=>e.jsx($e,{active:T===d.id,onClick:()=>{D(d.id),k(!1)},children:H==="en"?d.nameEn??d.name:d.name},d.id)),e.jsx("div",{className:"dd-header",children:j("update")}),v(),ie(),e.jsxs("a",{className:"dd-refresh dd-more-link",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",children:[e.jsx(Os,{})," ",j("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:j("openFiles"),onClick:()=>a("right"),children:e.jsx(st,{})})]})]})}function Gs(t){const s=new Date(t),n=new Date;return s.toDateString()===n.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function ya(t,s){var i;const n=new Map(t.map(a=>[a.id,a])),r=new Map;for(const a of t){const o=a.parentId?((i=n.get(a.parentId))==null?void 0:i.cwd)??a.cwd:a.cwd,u=r.get(o)??[];u.push(a),r.set(o,u)}const c=[...r.entries()].map(([a,o])=>({cwd:a,isCurrent:a===s,convs:o}));return c.sort((a,o)=>a.isCurrent?-1:o.isCurrent?1:a.cwd<o.cwd?-1:a.cwd>o.cwd?1:0),c}const va="pi-web-ui:lp-collapse-projects",ba="pi-web-ui:lp-collapse-convs",ka="pi-web-ui:lp-collapse-sessions";function ss(t,s=!1){const[n,r]=l.useState(()=>{try{const i=localStorage.getItem(t);if(i==="1")return!0;if(i==="0")return!1}catch{}return s}),c=l.useCallback(()=>{r(i=>{const a=!i;try{localStorage.setItem(t,a?"1":"0")}catch{}return a})},[t]);return[n,c]}const Fn="pi-web-ui:lp-sizes",gs={projects:1,convs:1,sessions:1};function ja(){try{const t=localStorage.getItem(Fn);if(t){const s=JSON.parse(t);return{projects:typeof s.projects=="number"&&s.projects>0?s.projects:1,convs:typeof s.convs=="number"&&s.convs>0?s.convs:1,sessions:typeof s.sessions=="number"&&s.sessions>0?s.sessions:1}}}catch{}return{...gs}}const wa=l.memo(function({ready:s,status:n,cwd:r,sessionFile:c,conversations:i,sessions:a,projects:o,activeConversationId:u,send:m,active:y,collapsible:x,onToggleCollapse:f}){const b=be(),T=c,D=r,[H,N]=l.useState(null),[j,Q]=l.useState(null),[V,J]=l.useState(""),[U,W]=ss(va,!1),[K,G]=ss(ba,!1),[C,M]=ss(ka,!1),k=l.useRef(null),[_,Z]=l.useState(()=>ja());l.useEffect(()=>{try{localStorage.setItem(Fn,JSON.stringify(_))}catch{}},[_]);const z=l.useCallback((d,E)=>h=>{h.preventDefault();const A=h.currentTarget,ee=h.clientY,Y={..._},se=k.current;if(!se)return;const X=32,ge=72,Ne=[{key:"projects",visible:o.length>0,collapsed:U},{key:"convs",visible:i.length>0,collapsed:K},{key:"sessions",visible:!0,collapsed:C}].filter(fe=>fe.visible),de=Ne.filter(fe=>fe.collapsed).length,le=Ne.filter(fe=>!fe.collapsed).map(fe=>fe.key).reduce((fe,ke)=>fe+(Y[ke]??1),0)||1,g=Math.max(120,se.clientHeight-de*X),O=(Y[d]??1)+(Y[E]??1),me=ge/g*le;A.classList.add("dragging"),document.body.classList.add("lp-resizing");const ue=fe=>{const Le=(fe.clientY-ee)/g*le;let ae=(Y[d]??1)+Le;const De=O-me;ae=Math.max(me,Math.min(De,ae));const Ae=O-ae;Z(qe=>({...qe,[d]:ae,[E]:Ae}))},ye=()=>{window.removeEventListener("pointermove",ue),window.removeEventListener("pointerup",ye),A.classList.remove("dragging"),document.body.classList.remove("lp-resizing")};window.addEventListener("pointermove",ue),window.addEventListener("pointerup",ye)},[_,o.length,i.length,U,K,C]);l.useEffect(()=>{!y||!s||n!=="open"||r&&(m({type:"list_sessions"}),m({type:"list_projects"}))},[y,s,n,r,m]);const I=d=>{const E=d.name||d.firstMessage.trim();return E.length>0?E:b("emptyChat")},R=d=>d.split(/[\\/]/).pop()||d,w=(d,E,h,A,ee)=>{const Y=H===d;return e.jsx("button",{type:"button",className:`lp-del ${Y?"confirm":""}`,title:Y?h:E,onClick:se=>{se.stopPropagation(),Y?(N(null),A()):N(d)},children:Y?e.jsx(Et,{}):ee??e.jsx(He,{})})},$=(d,E,h,A)=>e.jsxs("button",{type:"button",className:"lp-section-title panel-section-title",onClick:h,title:b(E?"expandSection":"collapseSection"),children:[e.jsxs("span",{className:"lp-section-title-text",children:[d,A!==void 0?` (${A})`:""]}),e.jsx("span",{className:"lp-section-chevron",children:E?e.jsx(Ze,{}):e.jsx(Tt,{})})]}),ie=[{key:"projects",visible:o.length>0,collapsed:U},{key:"convs",visible:i.length>0,collapsed:K},{key:"sessions",visible:!0,collapsed:C}].filter(d=>d.visible).filter(d=>!d.collapsed),v=ie.reduce((d,E)=>d+(_[E.key]??1),0)||1,L=d=>ie.length<=1?1:(_[d]??1)/v*ie.length;return e.jsxs("aside",{ref:k,className:"panel panel-left lp-panel",children:[x&&f&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:b("collapsePanel"),onClick:f,children:e.jsx(Mn,{})}),o.length>0&&e.jsxs("div",{className:`lp-section panel-projects ${U?"collapsed":""}`,style:U?void 0:{flex:`${L("projects")} 1 0px`},children:[$(b("recentProjects"),U,W,o.length),!U&&e.jsx("div",{className:"lp-section-body projects-scroll",children:o.map(d=>{const E=D===d.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>N(h=>h===`proj:${d.path}`?null:h),children:[e.jsxs("button",{type:"button",className:`project-item ${E?"active":""}`,title:d.path,onClick:()=>{E||m({type:"set_cwd",path:d.path})},children:[e.jsx(st,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:R(d.path)}),e.jsx("span",{className:"project-path",children:d.path})]}),e.jsx("span",{className:"project-time",children:Gs(d.lastUsed)})]}),w(`proj:${d.path}`,b("deleteProject"),b("deleteProjectConfirm"),()=>m({type:"remove_project",path:d.path}))]},d.path)})})]}),o.length>0&&!U&&(i.length>0?!K:!C)&&e.jsx("div",{className:"lp-sash",onPointerDown:z("projects",i.length>0?"convs":"sessions"),onDoubleClick:()=>Z({...gs}),title:b("dragToResize")}),i.length>0&&e.jsxs("div",{className:`lp-section lp-section-convs panel-convs ${K?"collapsed":""}`,style:K?void 0:{flex:`${L("convs")} 1 0px`},children:[$(b("runningConversations"),K,G,i.length),!K&&e.jsx("div",{className:"lp-section-body convs-scroll",children:ya(i,r).map(d=>e.jsxs("div",{className:"panel-conv-group",children:[!d.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:d.cwd,children:R(d.cwd)}),(()=>{const E=new Map(d.convs.map(X=>[X.id,X])),h=new Map,A=[];for(const X of d.convs)if(X.parentId&&E.has(X.parentId)){const ge=h.get(X.parentId)??[];ge.push(X),h.set(X.parentId,ge)}else A.push(X);const ee=[],Y=new Set,se=(X,ge)=>{if(!Y.has(X.id)){Y.add(X.id),ee.push({c:X,depth:ge});for(const Ne of h.get(X.id)??[])se(Ne,ge+1)}};for(const X of A)se(X,0);for(const X of d.convs)se(X,0);return ee.map(({c:X,depth:ge})=>{const Ne=u===X.id;return e.jsxs("div",{className:`lp-row${ge>0?" lp-sub":""}`,style:ge>0?{marginLeft:ge*18}:void 0,onMouseLeave:()=>N(de=>de===`conv:${X.id}`?null:de),children:[e.jsxs("button",{type:"button",className:`session-item ${Ne?"active":""}`,title:`${X.title}${d.isCurrent?"":` — ${d.cwd}`}`,onClick:()=>{Ne||m({type:"switch_conversation",id:X.id})},children:[e.jsx(ct,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[j===`conv:${X.id}`?e.jsx("input",{autoFocus:!0,className:"session-rename-input",value:V,placeholder:b("renameSessionPlaceholder"),onClick:de=>de.stopPropagation(),onChange:de=>J(de.target.value),onKeyDown:de=>{if(de.stopPropagation(),de.key==="Enter"&&!de.nativeEvent.isComposing){const Ee=V.trim();Ee&&m({type:"rename_conversation",id:X.id,name:Ee}),Q(null)}else de.key==="Escape"&&Q(null)},onBlur:()=>Q(null)}):e.jsxs("span",{className:"session-title",children:[X.isSubagent&&e.jsx("span",{className:"subagent-badge",children:b("subagentBadge")}),X.title,X.error&&e.jsx("span",{className:"conv-error-badge",title:b("convErrorBadge",{error:X.error})})]}),j===`conv:${X.id}`?null:e.jsx("span",{className:"session-sub",children:Ne?b("current"):b("messageCount",{n:X.messageCount})})]}),X.isStreaming&&e.jsx("span",{className:"conv-streaming",title:b("streaming")})]}),e.jsx("button",{type:"button",className:"lp-del lp-rename",title:b("renameSession"),onClick:de=>{de.stopPropagation(),N(null),J(X.title),Q(`conv:${X.id}`)},children:e.jsx(Kt,{})}),!X.isStreaming&&!Ne&&w(`conv:${X.id}`,b("dismissConversation"),b("dismissConversationConfirm"),()=>m({type:"dismiss_conversation",id:X.id}),e.jsx(Re,{})),X.isStreaming&&e.jsx("span",{className:"lp-row-stalled",title:b("streaming"),style:{position:"absolute",right:28,top:"50%",transform:"translateY(-50%)"}})]},X.id)})})()]},d.cwd))})]}),i.length>0&&!K&&!C&&e.jsx("div",{className:"lp-sash",onPointerDown:z("convs","sessions"),onDoubleClick:()=>Z({...gs}),title:b("dragToResize")}),e.jsxs("div",{className:`lp-section lp-section-sessions panel-sessions ${C?"collapsed":""}`,style:C?void 0:{flex:`${L("sessions")} 1 0px`},children:[$(b("historySessions"),C,M,a.length),!C&&e.jsxs("div",{className:"lp-section-body sessions-scroll",children:[a.length===0&&e.jsx("div",{className:"panel-empty",children:b("noHistory")}),a.map(d=>{const E=T===d.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>N(h=>h===`sess:${d.path}`?null:h),children:[e.jsxs("button",{type:"button",className:`session-item ${E?"active":""}`,title:d.path,onClick:()=>{j||E||m({type:"switch_session",path:d.path})},children:[e.jsx(ct,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[j===d.path?e.jsx("input",{autoFocus:!0,className:"session-rename-input",value:V,placeholder:b("renameSessionPlaceholder"),onClick:h=>h.stopPropagation(),onChange:h=>J(h.target.value),onKeyDown:h=>{if(h.stopPropagation(),h.key==="Enter"&&!h.nativeEvent.isComposing){const A=V.trim();A&&m({type:"rename_session",path:d.path,name:A}),Q(null)}else h.key==="Escape"&&Q(null)},onBlur:()=>Q(null)}):e.jsx("span",{className:"session-title",children:I(d)}),j===d.path?null:e.jsxs("span",{className:"session-sub",children:[E?b("current"):b("messageCount",{n:d.messageCount}),d.source==="tui"&&e.jsx("span",{className:"session-src",title:b("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:Gs(d.modified)})]}),e.jsx("button",{type:"button",className:"lp-del lp-rename",title:b("renameSession"),onClick:h=>{h.stopPropagation(),N(null),J(d.name??""),Q(d.path)},children:e.jsx(Kt,{})}),w(`sess:${d.path}`,b("deleteSession"),b("deleteSessionConfirm"),()=>m({type:"delete_session",path:d.path}))]},d.path)})]})]})]})}),$n="pi-web-ui:token";function Na(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem($n,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function Ca(){try{return localStorage.getItem($n)??""}catch{return""}}function Gt(t){const s=Ca();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}function Sa(t,s){const n=s.assistantMessageEvent,r=t.stats.tokens,c=s.usage!==null?{...r,...s.usage}:r,i=c===r?t.stats:{...t.stats,tokens:c};if(n.type!=="text_delta"&&n.type!=="thinking_delta")return i===t.stats?t:{...t,stats:i};const a=n.delta??"";if(!a)return i===t.stats?t:{...t,stats:i};const o=t.streamingMessage??null,u=o&&o.id===s.messageId?o:{id:s.messageId,content:[]},m=[...u.content],y=n.type==="thinking_delta"?"thinking":"text",x=n.contentIndex??m.length-1;return x>=0&&x<m.length&&m[x].type===y?m[x]=y==="thinking"?{type:"thinking",thinking:(m[x].thinking??"")+a}:{type:"text",text:(m[x].text??"")+a}:m.push(y==="thinking"?{type:"thinking",thinking:a}:{type:"text",text:a}),{...t,stats:i,streamingMessage:{...u,id:s.messageId,content:m}}}const fs="pi-web-ui:plugin-data";function Ta(t,s){window.dispatchEvent(new CustomEvent(fs,{detail:{pluginId:t,payload:s}}))}function Ea(t){const s=n=>{const r=n.detail;t(r.pluginId,r.payload)};return window.addEventListener(fs,s),()=>window.removeEventListener(fs,s)}const at=new Map,xs=new Set,nt=new Set;let Qs=-1;function Hn(){return[...at.values()]}function Pa(){const t=Hn();for(const s of xs)s(t)}function Ma(t){return xs.add(t),t(Hn()),()=>xs.delete(t)}async function Ia(t,s){s!==Qs&&(Qs=s,at.clear(),nt.clear());const n=new Set(t.map(r=>r.id));for(const r of[...at.keys()])n.has(r)||at.delete(r);for(const r of[...nt])n.has(r)||nt.delete(r);await Promise.all(t.filter(r=>r.hasClient&&r.view!==!1&&!r.error&&!at.has(r.id)&&!nt.has(r.id)).map(async r=>{try{const i=(await import(Ye(`/plugins/${encodeURIComponent(r.id)}/client/entry.mjs?e=${s}`))).default;i&&typeof i.mount=="function"?at.set(r.id,{info:r,module:i}):(nt.add(r.id),console.error(`[plugin:${r.id}] entry.mjs 缺少 default.mount`))}catch(c){nt.add(r.id),console.error(`[plugin:${r.id}] 客户端加载失败:`,c)}})),Pa()}function Ra(t,s){return{pluginId:t,send:n=>s({type:"plugin_message",pluginId:t,payload:n}),onData:n=>Ea((r,c)=>{r===t&&n(c)})}}const La=12,ns=2e5,Da=2e5,Aa="LIVE_OMIT",_a={conversationId:null,goal:null,reviewModel:null,maxRounds:3,locked:!0,reviewing:!1,round:0,status:"",verdict:"pending",wizard:{active:!1,draft:"",model:null,step:0,maxSteps:6,status:""}};function Ba(){const t=new Map,s=new Map,n=(r,c)=>`${r}:${c}`;return{write(r,c,i){const a=n(r,c),o=t.get(a);if(o&&o.size>0){for(const y of o)try{y.write(i)}catch{}return}const u=s.get(a)??"",m=u.length+i.length>Da?i:u+i;s.set(a,m)},register(r,c,i){const a=n(r,c);let o=t.get(a);o||(o=new Set,t.set(a,o)),o.add(i);const u=s.get(a);if(u){try{i.write(u)}catch{}s.delete(a)}return()=>{const m=t.get(a);m&&(m.delete(i),m.size===0&&t.delete(a)),s.delete(a)}},clear(){t.clear(),s.clear()}}}function Ys(t,s){const n=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&n.add(c.toolCallId),c.role==="bashExecution"&&n.add(`bash-${c.id}`);let r=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),r=!0);return r?new Map(t):t}function Js(t,s){if(t.size===0)return t;const n=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&n.add(c.toolCallId);let r=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),r=!0);return r?new Map(t):t}function Fa(t,s){var n,r,c,i;switch(s.type){case"status":return{...t,status:s.status,ready:s.status==="open"?t.ready:!1,terminals:s.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:s.serverVersion,engine:s.engine,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==La};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:Ys(t.liveOutputs,s.state),toolStatuses:Js(t.toolStatuses,s.state)};case"snapshot_delta":{const a=t.state,o=s.msg;if(!a||a.conversationId!==o.conversationId||a.rev!==o.baseRev)return t;const u={...a,...o.state,messages:o.appended.length>0?[...a.messages,...o.appended]:a.messages};return{...t,ready:!0,state:u,activeConversationId:u.conversationId,liveOutputs:Ys(t.liveOutputs,u),toolStatuses:Js(t.toolStatuses,u)}}case"tool_delta":{const a=t.liveOutputs.get(s.toolCallId),o=((a==null?void 0:a.text)??"")+s.delta,u=o.length>ns?`…[${Aa}:${o.length-ns}]…
|
|
305
|
-
`+o.slice(o.length-ns):o,m=new Map(t.liveOutputs);return m.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:m}}case"message_delta":{const a=t.state;return!a||a.conversationId!==s.msg.conversationId?t:{...t,state:Sa(a,s.msg)}}case"tool_status":return{...t,toolStatuses:new Map(t.toolStatuses).set(s.status.toolCallId,s.status)};case"notice":return{...t,notices:[...t.notices,s.notice].slice(-6)};case"dismiss_notice":return{...t,notices:t.notices.filter(a=>a.id!==s.id)};case"sessions":return{...t,sessions:s.sessions};case"conversations":return{...t,conversations:s.conversations,activeConversationId:s.activeId};case"projects":return{...t,projects:s.projects};case"files":return{...t,files:s.files};case"file_changed":return{...t,fileChanged:{path:s.path}};case"file_content":return{...t,fileContent:s.content};case"models":return{...t,models:s.models,modelsLoading:s.loading};case"models_config":return{...t,modelsConfig:s.providers};case"providers_status":return{...t,providers:s.providers};case"provider_keys":return{...t,providerKeys:s.keys};case"fetch_models_result":return{...t,fetchModelsResult:s.result};case"refresh_provider_result":return{...t,refreshProviderResult:s.result};case"clone_provider_result":return{...t,cloneProviderResult:s.result};case"install_result":return{...t,installResult:s.result};case"scm_data":return{...t,scmData:s.data};case"file_search_result":return{...t,fileSearch:s.result};case"session_search_result":return{...t,sessionSearch:s.result};case"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"update_status_all":return{...t,updatesAll:s.items};case"updates_check_started":return{...t,updatesAll:null};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"question":return{...t,question:s.question};case"commands":return{...t,commands:s.commands,commandsPath:s.path};case"slash_commands":return{...t,slashCommands:s.commands};case"goal_status":return{...t,goal:s.status};case"settings":return{...t,settings:s.settings};case"bg_servers":return{...t,bgServers:s.servers};case"plugins":return{...t,plugins:s.plugins,pluginsEpoch:s.epoch};case"plugin_catalog":return{...t,pluginCatalog:s.entries,pluginCatalogEpoch:s.epoch};case"dsh_patches":return{...t,dshPatches:{patchDir:s.patchDir,files:s.files}};case"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(a=>a.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(n=t.state)!=null&&n.conversationId)&&s.conversationId!==(t.activeConversationId||((r=t.state)==null?void 0:r.conversationId))?t:{...t,terminals:t.terminals.map(a=>a.id===s.terminalId?{...a,running:!1,exitCode:s.exitCode}:a)};case"terminal_restart":return{...t,terminals:t.terminals.map(a=>a.id===s.terminalId?{...a,running:!0,exitCode:null}:a)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(c=t.state)!=null&&c.conversationId)&&s.conversationId!==(t.activeConversationId||((i=t.state)==null?void 0:i.conversationId))?t:{...t,terminals:s.terminals.map(a=>{var o;return{...a,conversationId:s.conversationId??((o=t.state)==null?void 0:o.conversationId)??""}})};case"terminal_active":return{...t,terminalActiveId:s.id};default:return t}}const Xs="pi-web-client-id";let is=null;function Ts(){if(is)return is;let t=null;try{t=sessionStorage.getItem(Xs),t||(t=Qe(),sessionStorage.setItem(Xs,t))}catch{t=t??Qe()}return is=t,t}const On="pi-web-last-cwd";function $a(){try{return localStorage.getItem(On)}catch{return null}}function Ha(t){try{localStorage.setItem(On,t)}catch{}}function Oa(){const t=location.protocol==="https:"?"wss:":"ws:";return Gt(`${t}//${location.host}${Ye("/ws")}`)}function Wa(){var G;const[t,s]=l.useReducer(Fa,{status:"connecting",ready:!1,state:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:[],conversations:[],activeConversationId:"",projects:[],files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},installResult:null,pathCompletions:[],update:null,updatesAll:null,widgets:[],statuses:[],dialog:null,question:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],terminalActiveId:null,goal:_a,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,pluginCatalog:[],pluginCatalogEpoch:0,dshPatches:null,protocolMismatch:!1}),n=l.useRef(null),r=l.useRef(Ba()),c=l.useRef(0),i=l.useRef(null),a=l.useRef(!0),o=l.useRef(0),u=l.useRef(0),m=l.useRef(new Map),y=l.useRef(null),x=l.useRef(!1),f=l.useRef(null),b=()=>{y.current||(y.current=setTimeout(()=>{y.current=null;const C=n.current;C&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:"get_state"}))},300))},T=(C,M)=>{var Z;const k=m.current,_=k.get(C);if(_!==void 0&&M!==_+1){const z=K.current.chat,I=z.activeConversationId||((Z=z.state)==null?void 0:Z.conversationId);C===I&&b()}k.set(C,M)},D=l.useCallback((C,M)=>{const k=++u.current;s({type:"notice",notice:{id:k,level:C,text:M}})},[]),H=l.useCallback(C=>{const M=n.current;return M&&M.readyState===WebSocket.OPEN?(C.type==="check_updates_all"&&C.force===!0&&s({type:"updates_check_started"}),M.send(JSON.stringify(C)),!0):!1},[]),N=l.useCallback(()=>{if(!a.current)return;s({type:"status",status:"connecting"});const C=new WebSocket(Oa());n.current=C,C.onopen=()=>{n.current===C&&(s({type:"status",status:"open"}),c.current=0,o.current=Date.now(),C.send(JSON.stringify({type:"hello",clientId:Ts()})))},C.onmessage=M=>{if(n.current!==C)return;o.current=Date.now();let k;try{k=JSON.parse(M.data)}catch{return}switch(k.type){case"ready":s({type:"ready",serverVersion:k.serverVersion,protocolVersion:k.protocolVersion,engine:k.engine}),C.send(JSON.stringify({type:"get_state"})),C.send(JSON.stringify({type:"list_files"})),C.send(JSON.stringify({type:"list_models"})),C.send(JSON.stringify({type:"list_commands"})),C.send(JSON.stringify({type:"get_commands"})),C.send(JSON.stringify({type:"check_update"})),C.send(JSON.stringify({type:"check_updates_all"}));break;case"snapshot":m.current=new Map,s({type:"snapshot",state:k.state});break;case"snapshot_delta":{const _=K.current.chat.state;(!_||_.conversationId!==k.conversationId||_.rev!==k.baseRev)&&b(),s({type:"snapshot_delta",msg:k});break}case"tool_delta":T(k.conversationId,k.seq),s({type:"tool_delta",toolCallId:k.toolCallId,toolName:k.toolName,delta:k.delta});break;case"tool_status":s({type:"tool_status",status:k});break;case"message_delta":{T(k.conversationId,k.seq),s({type:"message_delta",msg:k});break}case"notice":{const _=++u.current;s({type:"notice",notice:{id:_,level:k.level,text:k.text,textEn:k.textEn}});break}case"sessions":s({type:"sessions",sessions:k.sessions});break;case"conversations":s({type:"conversations",conversations:k.conversations,activeId:k.activeId});break;case"projects":s({type:"projects",projects:k.projects});break;case"files":s({type:"files",files:k});break;case"file_changed":s({type:"file_changed",path:k.path});break;case"file_content":s({type:"file_content",content:k});break;case"models":s({type:"models",models:k.models,loading:!1});break;case"models_config":s({type:"models_config",providers:k.providers});break;case"providers_status":s({type:"providers_status",providers:k.providers});break;case"provider_keys":s({type:"provider_keys",keys:k.keys});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:k.reqId,ok:k.ok,models:k.models,error:k.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:k.reqId,ok:k.ok,added:k.added,total:k.total,error:k.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:k.reqId,ok:k.ok,config:k.config,configs:k.configs,error:k.error}});break;case"scm_data":s({type:"scm_data",data:k});break;case"search_files_result":s({type:"file_search_result",result:{reqId:k.reqId,ok:k.ok,results:k.results,truncated:k.truncated}});break;case"session_search_results":s({type:"session_search_result",result:{reqId:k.reqId,ok:k.ok,results:k.results}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:k});break;case"path_completions":s({type:"path_completions",completions:k.completions});break;case"update_status":s({type:"update_status",status:k});break;case"update_status_all":s({type:"update_status_all",items:k.items});break;case"widgets":s({type:"widgets",widgets:k.widgets});break;case"statuses":s({type:"statuses",statuses:k.statuses});break;case"dialog":s({type:"dialog",dialog:{id:k.id,kind:k.kind,title:k.title,args:k.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"question_pending":s({type:"question",question:{id:k.id,questions:k.questions}});break;case"terminal_output":r.current.write(k.conversationId??K.current.chat.activeConversationId,k.terminalId,k.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:k.conversationId,terminalId:k.terminalId,exitCode:k.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:k.conversationId,terminals:k.terminals});break;case"commands":s({type:"commands",commands:k.commands,path:k.path});break;case"slash_commands":s({type:"slash_commands",commands:k.commands});break;case"goal_status":s({type:"goal_status",status:k.status});break;case"settings_state":s({type:"settings",settings:k.settings});break;case"bg_servers":s({type:"bg_servers",servers:k.servers});break;case"plugins":s({type:"plugins",plugins:k.plugins,epoch:k.epoch});break;case"plugin_catalog":s({type:"plugin_catalog",entries:k.entries,epoch:k.epoch});break;case"dsh_patches":s({type:"dsh_patches",patchDir:k.patchDir,files:k.files});break;case"plugin_data":Ta(k.pluginId,k.payload);break}},C.onclose=()=>{if(n.current===C&&(n.current=null),r.current.clear(),!a.current||n.current&&n.current!==C)return;s({type:"status",status:"closed"});const M=Math.min(1e3*2**c.current,1e4);c.current+=1,i.current=setTimeout(()=>{i.current=null,N()},M)},C.onerror=()=>{}},[]);l.useEffect(()=>{a.current=!0,N();const C=setInterval(()=>{if(!a.current)return;const M=n.current;M&&M.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&M.close()},5e3);return()=>{var M;a.current=!1,clearInterval(C),i.current&&(clearTimeout(i.current),i.current=null),(M=n.current)==null||M.close(),n.current=null}},[N]),l.useEffect(()=>{var M;const C=(M=t.state)==null?void 0:M.cwd;if(C){if(!x.current){x.current=!0;const k=$a();if(k&&k!==C){H({type:"set_cwd",path:k});return}}f.current!==C&&(f.current=C,Ha(C))}},[(G=t.state)==null?void 0:G.cwd,H]);const j=l.useCallback(C=>s({type:"dismiss_notice",id:C}),[]),Q=l.useCallback(C=>s({type:"terminal_add",meta:C}),[]),V=l.useCallback(C=>s({type:"terminal_remove",id:C}),[]),J=l.useCallback(C=>s({type:"terminal_restart",terminalId:C}),[]),U=l.useCallback(C=>s({type:"terminal_active",id:C}),[]),W=l.useCallback((C,M,k)=>r.current.register(C,M,k),[]),K=l.useRef({chat:t,send:H,pushNotice:D,dismissNotice:j,terminal:{create:Q,close:V,register:W,restart:J,select:U}});return K.current={chat:t,send:H,pushNotice:D,dismissNotice:j,terminal:{create:Q,close:V,register:W,restart:J,select:U}},K.current}const Ua=200*1024*1024,Ka=/windows/i.test(navigator.userAgent),qa=/[<>:"/\\|?*\u0000-\u001f]/g,za=/[. ]+$/,Va=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Ga(t){const s=t.replace(qa,"_").replace(za,"");return s?Va.test(s)?`_${s}`:s:"_"}function Zs(t,s=!0){const n=new URLSearchParams({clientId:Ts(),path:t,...s?{download:"1"}:{}});return Gt(Ye(`/api/file?${n}`))}const Wn="FILE_NOT_FOUND";async function Qa(t,s){const n=Ka?Ga(s):s;try{const r=await fetch(Zs(t));if(!r.ok)return{ok:!1,cancelled:!1,error:await r.text().catch(()=>"")||(r.status===404?Wn:`HTTP ${r.status}`)};if(Number(r.headers.get("content-length")??"0")>Ua)return window.location.assign(Zs(t)),{ok:!0};const i=await r.blob();return window.showSaveFilePicker&&window.isSecureContext?Ya(i,n):ys(i,n)}catch(r){return{ok:!1,cancelled:!1,error:r instanceof Error?r.message:String(r)}}}async function Ya(t,s){let n;const r=window.showSaveFilePicker;if(!r)return ys(t,s);try{n=await r({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:ys(t,s)}try{const c=await n.createWritable();return await c.write(t),await c.close(),{ok:!0}}catch(c){return{ok:!1,cancelled:!1,error:c instanceof Error?c.message:String(c)}}}function ys(t,s){const n=URL.createObjectURL(t),r=document.createElement("a");return r.href=n,r.download=s,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}const Rt="@root",Ja=l.memo(function({files:s,fileChanged:n,widgets:r,cwd:c,send:i,onAttach:a,onPreview:o,onNotice:u,collapsible:m,onToggleCollapse:y}){const x=be(),[f,b]=l.useState(""),[T,D]=l.useState(null),[H,N]=l.useState(!1),[j,Q]=l.useState(null),V=l.useRef(""),J=l.useRef(null),U=l.useCallback((d,E)=>{d.preventDefault(),V.current=E,Q({x:Math.min(d.clientX,window.innerWidth-220),y:Math.min(d.clientY,window.innerHeight-90)})},[]),W=l.useCallback(()=>Q(null),[]);l.useEffect(()=>{if(!j)return;const d=A=>{var ee;(ee=A.target)!=null&&ee.closest(".ctx-menu")||W()},E=A=>{A.key==="Escape"&&W()};window.addEventListener("mousedown",d,!0),window.addEventListener("keydown",E);const h=()=>W();return window.addEventListener("blur",h),()=>{window.removeEventListener("mousedown",d,!0),window.removeEventListener("keydown",E),window.removeEventListener("blur",h)}},[j,W]);const K=l.useCallback(()=>{var d;W(),J.current&&(J.current.value=""),(d=J.current)==null||d.click()},[W]),G=l.useCallback((d,E)=>{for(const h of E){const A=new FileReader;A.onload=()=>{const ee=A.result,Y=ee.slice(ee.indexOf(",")+1);Y&&i({type:"upload_file",dirPath:d,name:h.name,data:Y})},A.readAsDataURL(h)}},[i]),C=l.useCallback(d=>{G(V.current,Array.from(d.target.files??[]))},[G]),M=l.useRef(null),k=d=>{var E;return Array.from(((E=d.dataTransfer)==null?void 0:E.types)??[]).includes("Files")},_=l.useCallback(()=>{var d,E;(d=M.current)==null||d.querySelectorAll(".file-item.drop-target").forEach(h=>h.classList.remove("drop-target")),(E=M.current)==null||E.classList.remove("drop-root")},[]),Z=l.useCallback(d=>{var h,A;if(_(),d==null)return;const E=(h=M.current)==null?void 0:h.querySelector(`.file-item[data-path="${CSS.escape(d)}"]`);E?E.classList.add("drop-target"):(A=M.current)==null||A.classList.add("drop-root")},[_]),z=d=>{const E=d instanceof Element?d.closest(".file-item"):null;return(E==null?void 0:E.dataset.type)==="dir"?E.dataset.path??f:f},I=l.useCallback(()=>{const d=document.querySelector(".app");d&&d.dispatchEvent(new DragEvent("dragleave",{bubbles:!0}))},[]),R=1e4,w=l.useRef(0),$=l.useRef(void 0),q=l.useCallback((d,E)=>{const h=++w.current;b(d),E!=null&&E.silent||N(!0),i({type:"list_files",path:d===""?void 0:d})||w.current===h&&N(!1)},[i]);l.useEffect(()=>{s&&s.path===f&&N(!1)},[s,f]),l.useEffect(()=>{if(c!==$.current){$.current=c,q("",{silent:!0});return}const d=setInterval(()=>{document.visibilityState!=="hidden"&&q(f,{silent:!0})},R);return()=>clearInterval(d)},[c,f,q]),l.useEffect(()=>{n&&n.path===f&&q(f,{silent:!0})},[n,f,q]);const ie=d=>q(d),v=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&q(s.parent)},L=(()=>{if(f===""||f===Rt)return[];const d=f.split("/").filter(E=>!!E&&E!==Rt);return f.startsWith("/")?d.map((E,h)=>({label:h===0?"/":d[h],path:"/"+d.slice(0,h+1).join("/")})):d.map((E,h)=>({label:d[h],path:d.slice(0,h+1).join("/")}))})();return e.jsxs("aside",{className:"panel panel-right",children:[m&&y&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:x("collapsePanel"),onClick:y,children:e.jsx(Pn,{})}),e.jsxs("div",{className:"panel-crumbs",children:[e.jsx("button",{type:"button",className:`crumb ${f===""?"active":""}`,onClick:()=>q(""),children:x("rootDir")}),e.jsx("button",{type:"button",className:`crumb ${f===Rt?"active":""}`,title:x("computer"),onClick:()=>q(Rt),children:"💻"}),L.map(d=>e.jsxs("span",{className:"crumb-seg",children:[e.jsx(Vt,{}),e.jsx("button",{type:"button",className:`crumb ${d.path===f?"active":""}`,onClick:()=>q(d.path),children:d.label})]},d.path))]}),e.jsxs("div",{ref:M,className:"panel-body",onContextMenu:d=>U(d,f),onDragOver:d=>{k(d)&&(d.preventDefault(),d.stopPropagation(),d.dataTransfer.dropEffect="copy",I(),Z(z(d.target)))},onDragLeave:d=>{d.relatedTarget&&d.currentTarget.contains(d.relatedTarget)||_()},onDrop:d=>{var h;if(_(),!k(d))return;d.preventDefault(),d.stopPropagation(),I();const E=Array.from(((h=d.dataTransfer)==null?void 0:h.files)??[]);if(E.length===0){u("warning",x("foldersNotSupported"));return}G(z(d.target),E)},onDragEnd:_,children:[e.jsx("input",{ref:J,type:"file",multiple:!0,hidden:!0,onChange:C}),H&&e.jsx("div",{className:"panel-empty",children:x("loading")}),!H&&s&&s.path===f&&e.jsxs(e.Fragment,{children:[s.parent!=null&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:v,children:[e.jsx(st,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(d=>d.type==="dir"?e.jsxs("div",{className:"file-item dir","data-type":"dir","data-path":d.path,onContextMenu:E=>{E.stopPropagation(),U(E,d.path)},children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>ie(d.path),children:[e.jsx(st,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:d.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":x("linkFolderTip"),onClick:()=>a(d.path,d.name,"reference",!0),children:e.jsx(ps,{})})]},d.path):e.jsxs("div",{className:"file-item file","data-type":"file","data-path":d.path,onContextMenu:E=>{E.stopPropagation(),U(E,f)},children:[e.jsxs("button",{type:"button",className:"file-name",title:`${d.path} — ${x("previewFile")}`,onClick:()=>o(d.path,d.name),children:[e.jsx(ea,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:d.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":x("downloadFile"),onClick:()=>{Qa(d.path,d.name).then(E=>{E.ok||E.cancelled||u("error",x("downloadFailed",{error:E.error===Wn?x("fileNotFoundShort"):E.error}))})},children:e.jsx(zt,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":x("attachInlineTip"),onClick:()=>a(d.path,d.name,"inline"),children:e.jsx(Ke,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":x("referenceTip"),onClick:()=>a(d.path,d.name,"reference"),children:e.jsx(ps,{})})]},d.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:x("filesTruncated")})]}),!H&&!s&&e.jsx("div",{className:"panel-empty",children:x("noFiles")})]}),r.filter(d=>d.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:r.filter(d=>d.lines.length>0).map(d=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:x("widgetExpand"),onClick:()=>D(d.key),children:[e.jsx("span",{children:d.key}),e.jsx(Gi,{})]}),e.jsx("pre",{className:"widget-lines",children:d.lines.join(`
|
|
306
|
-
`)})]},d.key))}),T&&(()=>{const d=r.find(E=>E.key===T);return d?e.jsx("div",{className:"modal-backdrop",onClick:()=>D(null),children:e.jsxs("div",{className:"widget-expand",onClick:E=>E.stopPropagation(),children:[e.jsxs("div",{className:"widget-expand-head",children:[e.jsx("span",{className:"widget-expand-title",children:d.key}),e.jsx("button",{type:"button",className:"btn",title:
|
|
307
|
-
`)})]})}):null})(),j&&e.jsx("div",{className:"ctx-menu",style:{left:j.x,top:j.y},onContextMenu:d=>{d.preventDefault(),d.stopPropagation()},children:e.jsxs("button",{type:"button",className:"ctx-item",onClick:K,children:[e.jsx(Fi,{}),V.current===
|
|
308
|
-
`).map(a=>a===""?[]:[a])}if(Array.isArray(r)){let i=[];for(const a of r){const o=s(a);if(i.length===0)i=o;else{const u=o[0]??[];i[i.length-1].push(...u),i.push(...o.slice(1))}}return i}if(r&&typeof r=="object"&&"props"in r){const i=r,a=(c=i.props)==null?void 0:c.children,o={...i.props,children:void 0},u=a==null?[]:s(a);return u.length===0?[[l.createElement(i.type,o)]]:u.map(m=>[l.createElement(i.type,o,...m)])}return[[r]]},n=s(t);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}function
|
|
309
|
-
`),n=[];let r=[],c=null;for(let i=0;i<s.length;i++){const a=s[i];if(c!==null){const u=
|
|
304
|
+
Avoid three test anti-patterns: tests coupled to the implementation, tautological assertions (always true), and horizontal slicing (surface only). Report after each step and run the tests.`,error:"Error",done:"Done",running:"Running…",toolQueued:"Queued",copyArgs:"Copy args",errorOutput:"Error output",output:"Output",waitingOutput:"Waiting for output…",toolDoneWaitingModel:"Done · waiting on model",waitingModel:"Waiting for model response…",thinkingNow:"Thinking",thinkingPreview:"Thinking: {preview}",commands:"Commands",newCommand:"New command",newTerminal:"New terminal",name:"Name",command:"Command",cwdHint:"(${pwd} = current working directory)",noCommands:"No commands yet — click + to add one",clickToRun:"Click to run",edit:"Edit",delete:"Delete",confirmQ:"Confirm?",builtinTerminal:"Built-in terminal",termEmptySub:"Click a command on the left to run it, or + on the right for a new terminal",noTerminal:"No terminals",exited:"(exited{code})",exitBanner:"[Process exited with code {code}]",closeTerminal:"Close terminal",renameTerminal:"Rename terminal",rerun:"Reload .pi/commands.json",terminalTitle:"Terminal {n}",aiBashGroup:"Terminal-backed bash",exampleName:"e.g. start dev server",exampleCommand:"e.g. npm run dev",scmTab:"Git",scmTitle:"Source Control",scmRefreshTip:"Re-query git status & diff",scmCurrentBranch:"Current branch",scmUpstreamGone:"Upstream deleted",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"Detached HEAD",scmSelectBranch:"Select branch…",scmRemoteBranches:"Remote branches",scmStageTip:"Stage {path}",scmUnstageTip:"Unstage {path}",scmSwitch:"Switch",scmSwitchBranch:"Switch branch",scmSwitchBranchTip:"Runs git checkout {branch} in the terminal",scmPush:"Push",scmPushTip:"Runs git push in the terminal",scmPull:"Pull",scmPullTip:"Runs git pull in the terminal",scmCommit:"Commit",scmCommitTip:'Runs git commit -m "…" in the terminal (commits staged changes only)',scmCommitAll:"Commit All",scmCommitAllTip:'Runs git add -A && git commit -m "…" in the terminal (stages all changes incl. untracked and commits)',scmCommitPlaceholder:"Type a commit message…",scmChanges:"Changes",scmHistory:"Commit tree",scmCommitDetail:"Commit details",scmSelectCommitHint:"Click a commit on the left to view its details",scmNoHistory:"No commits yet",scmNoChanges:"Working tree clean — no changes",scmNotGitRepo:"Current directory is not a Git repository",scmLoading:"Querying…",scmConnecting:"Waiting for connection…",scmDiff:"Diff",scmSelectFileHint:"Click a file on the left to view its diff",scmNoDiff:"(no diff)",scmStaged:"Staged",scmUnstaged:"Unstaged",scmStagedUnstaged:"Staged + unstaged",scmUntracked:"Untracked",scmUntrackedNote:"Untracked file — stage it with + to include (or use Commit All)",scmQueryFailed:"Git query failed: {error}",scmQueryFailedShort:"Query failed",pluginCommandFallback:"Plugin command",scmTooManyFailures:"Git queries keep failing — click refresh to retry",scmRunsInTerminal:"Commit / branch switch / push / pull run in the terminal",scmViewTerminal:"Open terminal",editProvider:"Edit provider",builtinProviders:"Built-in providers",hintKeyOnly:"Just enter an API key",configuredBadge:"✓ Configured",keyReady:"Key ready",replaceKey:"Replace key",replaceKeyTitle:"Replace the saved key",clearKey:"Clear",clearKeyTitle:"Remove this provider's key stored in auth.json; it returns to unconfigured (env-var sourced keys can't be cleared here)",clearKeyConfirm:"Clear the stored key for {id}? Its models will leave the list until you configure it again.",cloneProvider:"Add key",cloning:"Adding",cloneProviderTitle:"Add a second API key for this provider (baseUrl and model list are copied automatically)",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",addKey:"Add key",addKeyPlaceholder:"Paste the key value…",keyNamePh:"Name (optional, e.g. backup)",providerIdPlaceholder:"Provider ID",baseUrlExamplePh:"baseUrl, e.g. https://api.opencode.ai/zen/v1 or http://127.0.0.1:4096",saveAllBatch:"Save all ({n})",netDisconnected:"Network disconnected — reconnect and retry",advancedEdit:"Advanced edit",batchCreateProviders:"Batch-create providers ({n} APIs)",secondKeyTitle:"Add a second key for {api} · {baseUrl} · {n} models — just name the new provider and enter the key.",noBaseUrlShort:"(no baseUrl)",providerNameLabel:"Provider name",providerNameHint:"(new ID, e.g. opencode-2)",apiKeyLabel:"API key",secondKeyPlaceholder:"sk-… second key",batchDesc:"This provider has multiple APIs ({apis}); it was split into {n} custom providers. Save each so all models (e.g. muse-spark) work. Enter one shared second key to save all at once.",batchKeyLabel:"Shared API key (applies to all {n} providers)",modelsCountShort:"{n} models: ",noKeyYet:"No key yet — add one to use this provider",activateKey:"Set active",removeKey:"Remove",removeKeyConfirm:"Remove this key? It must be re-configured to be used again.",customProviders:"Custom providers",customDesc:"For Ollama / vLLM / OpenAI-compatible proxies, etc. Written to pi's models.json — hot-reloaded immediately.",noCustomProviders:"No custom providers yet",modelsCount:"{n} models",addProvider:"Add provider",providerId:"Provider ID",providerIdHint:"(required, e.g. ollama / my-proxy)",displayName:"Display name",displayNamePh:"My proxy",apiType:"API type",baseUrlHint:"(OpenAI-compatible endpoint)",apiKeyHint:"sk-… (optional — uses the auth.json key)",authHeader:"Auto-add Authorization header",modelsTitle:"Models",modelIdReq:"Model ID (required)",text:"Text",textImage:"Text+image",contextWindow:"Context",maxOutput:"Max output",removeModel:"Remove model",addModel:"Add model",deleteProviderConfirm:"Delete provider {id} and its {n} models?",fetchModels:"Fetch model list",fetchModelsHint:"Pull model IDs from the baseUrl /models endpoint (server-side, no CORS)",fetchingModels:"Fetching…",fetchModelsOk:"Fetched {n} models",fetchModelsEmpty:"The endpoint returned no models",fetchModelsErr:"Fetch failed: {msg}",fetchModelsNeedBaseUrl:"Enter a baseUrl first",goalBarTitle:"Goal",goalBarPlaceholder:"Set a goal; the agent's output is auto-reviewed…",goalBarSet:"Start",goalBarClear:"Cancel",goalBarLocked:"Locked: applies to every later turn",goalBarUnlocked:"This turn only (cleared afterwards)",goalBarReviewModel:"Review model",goalBarUseMainModel:"Use the main model",goalBarMaxRounds:"Max rounds",goalBarMaxRoundsTip:"Max review-revision rounds; 0 or empty = unlimited (keep revising until it passes)",goalBarUnlimitedShort:"Unlimited",goalBarReviewing:"Reviewing…",goalBarRound:"Round {n}",goalBarActive:"Goal active",goalBarPassed:"Passed",goalBarFailed:"Failed",goalBarStatusPending:"Waiting to generate…",goalWizardBtn:"AI Scrape",goalWizardTip:"Let AI refine the requirement into a goal via a Q&A survey",goalWizardRunning:"Scoping the goal",goalWizardAnswer:"Answer",goalWizardCard:"Goal survey",settings:"Settings",settingsTitle:"Settings",settingsDesc:"Changes apply immediately: system prompt, skill and extension toggles rebuild the current session; review instructions and review skills affect later goal reviews (main-session changes are deferred while streaming).",settingsSystemPrompt:"System prompt",settingsPromptHistory:"Input history",settingsPromptHistoryDesc:"Cycle previous prompts with ↑/↓ in the input — global across conversations (localStorage)",promptHistoryMax:"Max entries",promptHistoryMaxHint:"Oldest entries are dropped when exceeded (1–500)",promptHistoryCharLimit:"Limit characters per entry",promptHistoryCharLimitHint:"When enabled, overlong prompts are truncated before saving",promptHistoryCharLimitPlaceholder:"Max chars (100–20000)",promptHistoryClear:"Clear history",promptHistoryClearConfirm:"Confirm clear?",promptHistoryCleared:"Input history cleared",promptHistoryCount:"{n} entries",promptHistoryEmpty:"No history yet — ↑/↓ has nothing to cycle",settingsPromptMode:"Mode",promptModeAppend:"Append",promptModeReplace:"Replace",promptAppendHint:"Append mode: your text is appended to the end of the default system prompt (recommended — keeps the default behavior constraints).",promptReplaceHint:"Replace mode: your text fully replaces the system prompt (project context and skills are still appended automatically). After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",promptPlaceholder:"Type a custom system prompt… (applied on blur)",settingsViewPrompt:"View the current full prompt",settingsViewPromptHint:"The full system prompt actually in effect for this conversation (custom append/replace text, project context, skills and tool guidance). Read-only.",settingsViewPromptEmpty:"Session not ready yet — no system prompt available.",settingsSkills:"Skills",settingsReview:"Goal review",settingsReviewDesc:"Configure extra instructions and skills for the isolated goal-review session; the main session is unaffected.",settingsReviewSkills:"Skills available to review",reviewPromptPlaceholder:"Type custom review instructions… (applied on blur)",reviewPromptHint:"These instructions are added to the review task; pass/fail JSON output is still enforced. Skill toggles apply only to review.",settingsVisionBridge:"Vision bridge",settingsVisionBridgeDesc:"When the current model can't see images, send them to a configured vision model and transcribe into text evidence first",visionBridgeEnabled:"Enable vision bridge",visionBridgeModel:"Transcription model",visionBridgeAuto:"Auto (in order)",visionBridgeNoModels:"No configured vision model found: add any image-capable model (e.g. qwen-vl, GLM-4V, Gemini) in Model config to enable automatically",visionBridgeOffHint:"Disabled: images are sent as-is, a text-only model may not see them",visionBridgeCurrent:"Current transcription model: {model}",visionBridgePromptMode:"Transcription prompt",settingsMarkers:"Markers",settingsMarkersDesc:"Let the AI write [[todo:...]] / [[svc:...]] / [[notify:...]] / [[conv:rename:...]] inline markers in replies to update state without a tool round-trip. Global off disables all; per-marker toggles give fine control.",markersEnabled:"Markers enabled (global)",markersEnabledDesc:"Off = no marker guidance injected and no parsing; markers stay as plain text.",markersOffHint:"Globally off: all markers disabled — the AI won't write markers and no side effects fire.",markerGroupTodo:"todo — tasks",markerGroupSvc:"svc — background services",markerGroupNotify:"notify — non-blocking hints",markerGroupRename:"conv/rename — rename chat",markerRenameTip:"[[conv:rename:Title]] or [[rename:set:Title]] renames the current conversation (≤80 chars)",settingsTerminalTools:"Terminal tools",terminalToolsEnabled:"Enable persistent terminal tools",settingsTerminalToolsDesc:"Let the AI use the built-in terminal for interactive programs (REPLs/vim), long-running servers, continuous output watching, or when you ask it to work in the visible terminal; ordinary commands still go through the one-shot bash tool",terminalToolsOffHint:"Disabled: the AI has no terminal_* tools and receives no usage guidance",settingsMessageDisplay:"Message display",thinkingWrap:"Show full thinking",thinkingWrapDesc:"On: thinking always expands fully and wraps (live reasoning visible while streaming); Off: collapses to a one-line summary with the latest text shown live while streaming",toolsWrap:"Show full tools",toolsWrapDesc:"On: tool calls always expand fully showing arguments and output; Off: collapsed by default, click to expand",wideChat:"Wide chat column",wideChatDesc:"On: the center column fills the width (useful on ultrawide monitors); Off: keep the 860px cap",terminalBashTakeover:"Terminal-backed bash",terminalBashTakeoverDesc:"This switch decides whether bash is overridden to a terminal version: OFF = native SDK bash (process spawn, no terminal); ON = runs in a visible terminal, where the persist parameter decides (on top of the switch) one-shot (false — process exits when the command finishes, output retained) vs persistent (true — shell state retained across calls, silent commands move to the background and notify the AI)",terminalBashIdleMs:"Silence-to-background threshold (ms)",terminalBashIdleMsDesc:"In persistent-terminal mode, when a command produces no output for this long, stop blocking and let it keep running in the background; the AI is notified when it finishes. 0 = always wait until completion (default 15000)",visionBridgePromptPlaceholder:"Type a custom transcription prompt… (empty = built-in default, applied on blur)",visionBridgePromptAppendHint:"Append mode: custom text is appended after the built-in transcription prompt (recommended — keeps the verbatim-transcription contract).",visionBridgePromptReplaceHint:"Replace mode: custom text replaces the built-in transcription prompt entirely. After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",uninstallExt:"Uninstall",uninstallConfirm:"Confirm?",uninstallConfirmHint:"Click again to confirm — runs pi remove in the terminal",uninstallHint:"Runs pi remove in a visible terminal, then refreshes the list automatically",uninstallTitle:"Uninstall",pluginUpdate:"Update",pluginUpdateHint:"Re-installs from the recorded source (--force, keeps config.json), then refreshes the plugin list automatically",pluginMarket:"Plugin marketplace",pluginCatalogAdd:"Add plugin",pluginCatalogAddHint:"Drop a third-party plugin into the installable list (owner/repo or full GitHub URL)",pluginCatalogSource:"Source owner/repo or owner/repo/subdir (required)",pluginCatalogId:"id (optional, defaults to repo/subdir name)",pluginCatalogName:"Name (optional)",pluginCatalogIcon:"Icon emoji (optional)",pluginCatalogDesc:"Description (optional)",pluginCatalogAddSubmit:"Add to list",noPluginCatalog:'List is empty — click "Add plugin" to drop a third-party plugin in',pluginInstalled:"Installed",pluginCatalogCustom:"custom",pluginInstall:"Install",pluginInstallHint:"Install straight from the source into UI plugins (runs in a visible terminal)",pluginCatalogRemoveHint:"Remove this custom plugin from the list",pluginUninstallHint:"Runs pi-web-ui uninstall in a visible terminal (click again to confirm), then refreshes the list automatically",settingsExtensions:"Extensions",settingsUiPlugins:"UI plugins",noUiPlugins:"No UI plugins installed (<dataDir>/plugins/)",dshPatches:"DSH user patches",dshPatchesDesc:"Cordis patches loaded at runtime boot, in filename order (<dataDir>/dsh-patches/*.yml). New/edited files take effect after 'Rescan' restarts the runtime; broken files are skipped and logged to runtime stderr.",dshPatchesRescan:"Rescan",dshPatchesRescanHint:"Re-scan the patch directory and restart the DSH runtime so new patches take effect",dshPatchesEmpty:"No patch files yet",dshPatchesPath:"Patch directory: ",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",settingsPresets:"Presets",settingsSubagentTemplates:"Subagent templates",settingsSubagentTemplatesDesc:"Presets for spawned subagents (role system prompt + skills/extensions whitelist + optional model). AI may pick a template (subagent_spawn template param) or spawn without one; disabled templates stay in the panel but are invisible to AI tools.",noSubagentTemplates:"No subagent templates yet. AI can pick a template when spawning a subagent (role prompt + skills/extensions whitelist + optional model), or spawn without a template param for default config.",subagentTemplateNew:"New template",subagentTemplateEdit:"Edit",subagentTemplateClosed:"Disabled",tplDefaultBadge:"Built-in",subagentDefaultModelLabel:"Default subagent model",subagentFollowMain:"Follow the main conversation's current model",subagentDefaultModelHint:"Fallback model for all subagents (a template's own model and the subagent_spawn model param take priority); does not change the main conversation's model.",subagentNoModels:"No usable models yet (configure a provider API key first) — subagents will follow the main conversation's model.",subagentTemplateOffHint:"Disabled templates stay in the panel and can be re-enabled, but AI tools can't see or pick them",subagentTemplateEnable:"Enable",subagentTemplateDisable:"Disable",tplNamePlaceholder:"Template name (referenced by AI via subagent_spawn's template param)…",tplDescriptionPlaceholder:"Description (AI uses it to judge when to pick this template)…",tplPromptModeLabel:"System prompt mode",tplModelLabel:"Model (empty = follow main conversation)",tplSystemPromptLabel:"System prompt",tplSystemPromptPlaceholder:"Template role system prompt… (may be empty in append mode)",tplWhitelistHint:"Whitelist: checked = the subagent only gets these; none checked = follow the main session settings",tplSkillsLabel:"Skills whitelist",tplExtensionsLabel:"Extensions whitelist",tplSave:"Save template",tplCancel:"Cancel edit",tplDelete:"Delete template",tplInherit:"Follow main session",settingsEnabled:"Enabled",settingsDisabled:"Disabled",presetNamePlaceholder:"Preset name…",saveAsPreset:"Save as preset",applyPreset:"Apply",deletePreset:"Delete preset",noSkills:"No skills",noExtensions:"No extensions",noPresets:"No presets yet (tune the settings above, then save them as a preset)",loadingSession:"Loading session…",connectingServer:"Connecting to pi-web-ui server…"},Dn=l.createContext(null);function da(){try{const t=localStorage.getItem(Ln);if(t==="zh"||t==="en")return t}catch{}return"zh"}function ua({children:t}){const[s,n]=l.useState(da),r=l.useCallback(a=>{n(a);try{localStorage.setItem(Ln,a)}catch{}},[]),c=l.useCallback((a,o)=>{let u=qs[a];if(s==="zh"&&(u=Ks[a]),o)for(const[m,f]of Object.entries(o))u=u.replaceAll(`{${m}}`,String(f));return u},[s]);l.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en",document.title=s==="zh"?Ks.docTitle:qs.docTitle},[s]);const i=l.useMemo(()=>({locale:s,setLocale:r,t:c}),[s,r,c]);return e.jsx(Dn.Provider,{value:i,children:t})}function Mt(){const t=l.useContext(Dn);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function be(){return Mt().t}const pa=[{kind:"question",labelKey:"sound.question",descKey:"sound.question.desc"},{kind:"done",labelKey:"sound.done",descKey:"sound.done.desc"},{kind:"start",labelKey:"sound.start",descKey:"sound.start.desc"},{kind:"error",labelKey:"sound.error",descKey:"sound.error.desc"}];function zs({settings:t,onChange:s,onPreview:n}){const r=be(),c=i=>s({...t,...i});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:r("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Nn,{className:"sound-icon"}),e.jsx("span",{children:r("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:i=>c({enabled:i.target.checked})})]}),pa.map(({kind:i,labelKey:a,descKey:o})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:r(a)}),e.jsx("span",{className:"sound-desc",children:r(o)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:r("preview"),disabled:!t.enabled,onClick:u=>{u.preventDefault(),n(i)},children:r("preview")}),e.jsx("input",{type:"checkbox",checked:t[i],disabled:!t.enabled,onChange:u=>c({[i]:u.target.checked})})]})]},i)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:r("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:i=>c({volume:Number(i.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}let es=null;function ma(t){if(t===void 0){const n=globalThis.document;if(n&&typeof n.baseURI=="string"&&n.baseURI)try{t=new URL(n.baseURI).pathname}catch{}if(t===void 0)return"/"}if(!t||t==="/")return"/";let s=t.replace(/index\.html$/i,"");return s.endsWith("/")||(s+="/"),s}function An(){return es===null&&(es=ma()),es}function ha(t,s){return s==="/"?t:s+t.replace(/^\/+/,"")}function Ye(t){return ha(t,An())}const _n="pi-web-notify",ts={enabled:!1};function Bn(){try{const t=localStorage.getItem(_n);if(!t)return{...ts};const s=JSON.parse(t);return{enabled:typeof s.enabled=="boolean"?s.enabled:ts.enabled}}catch{return{...ts}}}function Vs(t){try{localStorage.setItem(_n,JSON.stringify(t))}catch{}}function Ct(){return typeof window<"u"&&"Notification"in window}function ga(){return Ct()?Notification.permission:"denied"}async function fa(){if(!Ct())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}}async function ss(t,s){var r;if(!Ct()||document.hasFocus()||!Bn().enabled||Notification.permission!=="granted")return;const n={body:s,icon:Ye("/icons/icon-192.png"),badge:Ye("/icons/icon-192.png"),tag:"pi-web-ui"};try{const c=await((r=navigator.serviceWorker)==null?void 0:r.getRegistration());c&&typeof c.showNotification=="function"?c.showNotification(t,n):new Notification(t,n)}catch{}}function Gs(){const t=be(),[s,n]=l.useState(Bn),[r,c]=l.useState(()=>Ct()?ga():"denied"),i=async a=>{const o={...s,enabled:a};if(n(o),Vs(o),a){const u=await fa();if(c(u),u!=="granted"){const m={...o,enabled:!1};n(m),Vs(m)}}};return e.jsxs("div",{className:"sound-menu",style:{borderTop:"1px solid var(--border-color, rgba(255,255,255,.08))",marginTop:6,paddingTop:6},children:[e.jsx("div",{className:"dd-header",children:t("notifyHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(aa,{className:"sound-icon"}),e.jsx("span",{children:t("notifyEnable")})]}),e.jsx("input",{type:"checkbox",checked:s.enabled,onChange:a=>i(a.target.checked)})]}),e.jsx("div",{className:"sound-desc",style:{padding:"2px 8px 4px",opacity:.7,fontSize:"0.82em"},children:t("notifyEnableDesc")}),!Ct()&&e.jsx("div",{className:"sound-desc",style:{padding:"0 8px 4px",opacity:.7,fontSize:"0.82em"},children:t("notifyUnsupported")}),r==="denied"&&e.jsx("div",{className:"sound-desc",style:{padding:"0 8px 4px",opacity:.7,fontSize:"0.82em"},children:t("notifyDenied")})]})}function xa({chat:t,send:s,terminal:n,view:r,plugins:c,onViewChange:i,onOpenPanel:a,onOpenSettings:o,onOpenBgTasks:u,onOpenGlobalSearch:m,sound:f,onSoundChange:y,onSoundPreview:x,themes:b,theme:T,onThemeChange:D}){var L;const{locale:H,setLocale:N,t:j}=Mt(),[Q,V]=l.useState(!1),[J,U]=l.useState(!1),[W,K]=l.useState(!1),[G,C]=l.useState(!1),[M,k]=l.useState(!1),_=[{value:"zh",label:j("langZh")},{value:"en",label:j("langEn")}],Z=t.ready?j("connected"):t.status==="closed"?j("reconnecting"):j("connecting"),z=t.ready?"ok":"busy",I=()=>{var A,ee;if(!t.ready)return;const d=j("updateTabTitle"),E={name:d,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},h=t.terminals.find(Y=>Y.title===d);h?(n.restart(h.id),s({type:"run_command",terminalId:h.id,conversationId:h.conversationId,command:E,cols:80,rows:24})):n.create({id:Qe(),conversationId:t.activeConversationId||((A=t.state)==null?void 0:A.conversationId)||"",title:d,cwd:((ee=t.state)==null?void 0:ee.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:E}),C(!1),k(!1),i("terminal")},R=(d,E)=>{var ee,Y;if(!t.ready||d.length===0)return;const h={name:E,command:ca(d),cwd:"${pwd}"},A=t.terminals.find(se=>se.title===E);A?(n.restart(A.id),s({type:"run_command",terminalId:A.id,conversationId:A.conversationId,command:h,cols:80,rows:24})):n.create({id:Qe(),conversationId:t.activeConversationId||((ee=t.state)==null?void 0:ee.conversationId)||"",title:E,cwd:((Y=t.state)==null?void 0:Y.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:h}),C(!1),k(!1),i("terminal")},w=t.updatesAll??[],$=w.filter(d=>!d.upToDate&&!d.error).length,q=w.filter(d=>!d.upToDate&&!d.error&&d.kind!=="webui"),ie=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:j("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:j("checkingUpdate")}):w.length===0?e.jsx("div",{className:"dd-note",children:j("updatesAllUpToDate")}):e.jsx("ul",{className:"dd-all-list",children:w.map(d=>e.jsxs("li",{className:`dd-all-item${d.error?" err":d.upToDate?"":" warn"}`,children:[e.jsx("span",{className:"dd-all-name",title:d.name,children:d.name}),e.jsx("span",{className:"dd-all-kind",children:d.kind==="webui"?j("kindWebUi"):d.kind==="pi-core"?j("kindPiCore"):j("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:d.error?j("updateCheckFailed"):d.upToDate?`v${d.current}`:e.jsxs(e.Fragment,{children:["v",d.current," → v",d.latest]})}),d.kind!=="webui"&&!d.upToDate&&!d.error&&e.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>R([d],j("updatePkgTabTitle",{name:d.name})),children:j("updateBtn")})]},`${d.kind}:${d.name}`))}),e.jsxs("div",{className:"dd-actions",children:[q.length>0&&e.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>R(q,j("updateAllTabTitle")),children:j("updateAllBtn")}),e.jsx("button",{type:"button",className:"dd-refresh",style:q.length>0?{flex:1}:void 0,onClick:()=>s({type:"check_updates_all",force:!0}),children:j("updatesAllRefresh")})]})]}),v=()=>{var d,E;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dd-update",children:[e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:j("currentVersion")}),e.jsxs("b",{children:["v",((d=t.update)==null?void 0:d.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:j("latestVersion")}),e.jsx("b",{children:t.update===null?j("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:j("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:j("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:j("updateAvailable",{version:t.update.latest})}),((E=t.update)==null?void 0:E.latestPublishedAt)&&Date.now()-new Date(t.update.latestPublishedAt).getTime()<30*6e4&&e.jsx("div",{className:"dd-note warn",children:j("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:j("updateTerminalHint")})]}),e.jsxs("div",{className:"dd-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"check_update"}),children:t.update===null?j("checkingUpdate"):j("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:I,children:j("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:j("openHistory"),onClick:()=>a("left"),children:e.jsx(zi,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${z}`,title:Z}),e.jsx("span",{className:"conn-label",children:Z})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":j("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":r==="chat",className:r==="chat"?"active":"",onClick:()=>i("chat"),children:[e.jsx(dt,{}),e.jsx("span",{children:j("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":r==="terminal",className:r==="terminal"?"active":"",onClick:()=>i("terminal"),children:[e.jsx(ct,{}),e.jsx("span",{children:j("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":r==="git",className:r==="git"?"active":"",onClick:()=>i("git"),children:[e.jsx(_t,{}),e.jsx("span",{children:j("scmTab")})]}),c.filter(d=>d.view!==!1).map(d=>{const E=d.error?`${d.name}: ${d.error}`:d.description?`${d.name} — ${d.description}`:d.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":r===`plugin:${d.id}`,className:`plugin-tab${r===`plugin:${d.id}`?" active":""}${d.error?" broken":""}`,title:E,onClick:()=>i(`plugin:${d.id}`),children:[d.icon?e.jsx("span",{"aria-hidden":!0,children:d.icon}):null,e.jsx("span",{children:d.name})]},d.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:j("searchGlobalTip"),onClick:m,children:[e.jsx(Ut,{}),e.jsx("span",{className:"chip-sub",children:j("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":j("bgTasksTip"),onClick:u,children:[e.jsx(Kt,{}),e.jsx("span",{className:"chip-sub",children:j("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:j("settingsTitle"),onClick:o,children:[e.jsx(Wt,{}),e.jsx("span",{className:"chip-sub",children:j("settings")})]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Nn,{}),e.jsx("span",{className:"chip-sub",children:j("sound")})]}),open:Q,onOpenChange:V,children:[e.jsx(zs,{settings:f,onChange:y,onPreview:x}),e.jsx(Gs,{})]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Zi,{}),e.jsx("span",{className:"chip-sub",children:H==="zh"?j("langZh"):"EN"})]}),open:J,onOpenChange:U,children:[e.jsx("div",{className:"dd-header",children:j("language")}),_.map(d=>e.jsx($e,{active:H===d.value,onClick:()=>{N(d.value),U(!1)},children:d.label},d.value))]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Hi,{}),e.jsx("span",{className:"chip-sub",children:j("theme")})]}),open:W,onOpenChange:K,children:[e.jsx("div",{className:"dd-header",children:j("theme")}),e.jsx($e,{active:T===null,onClick:()=>{D(null),K(!1)},children:j("themeDefault")}),b.map(d=>e.jsx($e,{active:T===d.id,onClick:()=>{D(d.id),K(!1)},children:H==="en"?d.nameEn??d.name:d.name},d.id))]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Vt,{}),e.jsxs("span",{className:"chip-sub",children:["v",((L=t.update)==null?void 0:L.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:j("updateAvailable",{version:t.update.latest??""})}),$>0&&e.jsx("span",{className:"update-badge",children:j("updatesAllBadge",{n:$})})]}),open:G,onOpenChange:d=>{C(d),d&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:j("update")}),v(),ie()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:j("githubRepo"),children:e.jsx(Ws,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":j("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(Ke,{}),e.jsx("span",{children:j("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ki,{}),e.jsx("span",{className:"chip-sub",children:j("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:M,onOpenChange:d=>{k(d),d&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:j("sound")}),e.jsx("div",{className:"dd-header",children:j("settings")}),e.jsxs($e,{onClick:()=>{k(!1),o()},children:[e.jsx(Wt,{})," ",j("settingsTitle")]}),e.jsxs($e,{onClick:()=>{k(!1),m()},children:[e.jsx(Ut,{})," ",j("searchGlobal")]}),e.jsxs($e,{onClick:()=>{k(!1),u()},children:[e.jsx(Kt,{})," ",j("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(zs,{settings:f,onChange:y,onPreview:x}),e.jsx(Gs,{}),e.jsx("div",{className:"dd-header",children:j("language")}),_.map(d=>e.jsx($e,{active:H===d.value,onClick:()=>N(d.value),children:d.label},d.value)),e.jsx("div",{className:"dd-header",children:j("theme")}),e.jsx($e,{active:T===null,onClick:()=>{D(null),k(!1)},children:j("themeDefault")}),b.map(d=>e.jsx($e,{active:T===d.id,onClick:()=>{D(d.id),k(!1)},children:H==="en"?d.nameEn??d.name:d.name},d.id)),e.jsx("div",{className:"dd-header",children:j("update")}),v(),ie(),e.jsxs("a",{className:"dd-refresh dd-more-link",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",children:[e.jsx(Ws,{})," ",j("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:j("openFiles"),onClick:()=>a("right"),children:e.jsx(st,{})})]})]})}function Qs(t){const s=new Date(t),n=new Date;return s.toDateString()===n.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function ya(t,s){var i;const n=new Map(t.map(a=>[a.id,a])),r=new Map;for(const a of t){const o=a.parentId?((i=n.get(a.parentId))==null?void 0:i.cwd)??a.cwd:a.cwd,u=r.get(o)??[];u.push(a),r.set(o,u)}const c=[...r.entries()].map(([a,o])=>({cwd:a,isCurrent:a===s,convs:o}));return c.sort((a,o)=>a.isCurrent?-1:o.isCurrent?1:a.cwd<o.cwd?-1:a.cwd>o.cwd?1:0),c}const va="pi-web-ui:lp-collapse-projects",ba="pi-web-ui:lp-collapse-convs",ka="pi-web-ui:lp-collapse-sessions";function ns(t,s=!1){const[n,r]=l.useState(()=>{try{const i=localStorage.getItem(t);if(i==="1")return!0;if(i==="0")return!1}catch{}return s}),c=l.useCallback(()=>{r(i=>{const a=!i;try{localStorage.setItem(t,a?"1":"0")}catch{}return a})},[t]);return[n,c]}const Fn="pi-web-ui:lp-sizes",fs={projects:1,convs:1,sessions:1};function ja(){try{const t=localStorage.getItem(Fn);if(t){const s=JSON.parse(t);return{projects:typeof s.projects=="number"&&s.projects>0?s.projects:1,convs:typeof s.convs=="number"&&s.convs>0?s.convs:1,sessions:typeof s.sessions=="number"&&s.sessions>0?s.sessions:1}}}catch{}return{...fs}}const wa=l.memo(function({ready:s,status:n,cwd:r,sessionFile:c,conversations:i,sessions:a,projects:o,activeConversationId:u,send:m,active:f,collapsible:y,onToggleCollapse:x}){const b=be(),T=c,D=r,[H,N]=l.useState(null),[j,Q]=l.useState(null),[V,J]=l.useState(""),[U,W]=ns(va,!1),[K,G]=ns(ba,!1),[C,M]=ns(ka,!1),k=l.useRef(null),[_,Z]=l.useState(()=>ja());l.useEffect(()=>{try{localStorage.setItem(Fn,JSON.stringify(_))}catch{}},[_]);const z=l.useCallback((d,E)=>h=>{h.preventDefault();const A=h.currentTarget,ee=h.clientY,Y={..._},se=k.current;if(!se)return;const X=32,ge=72,Ne=[{key:"projects",visible:o.length>0,collapsed:U},{key:"convs",visible:i.length>0,collapsed:K},{key:"sessions",visible:!0,collapsed:C}].filter(fe=>fe.visible),de=Ne.filter(fe=>fe.collapsed).length,le=Ne.filter(fe=>!fe.collapsed).map(fe=>fe.key).reduce((fe,ke)=>fe+(Y[ke]??1),0)||1,g=Math.max(120,se.clientHeight-de*X),O=(Y[d]??1)+(Y[E]??1),me=ge/g*le;A.classList.add("dragging"),document.body.classList.add("lp-resizing");const ue=fe=>{const Le=(fe.clientY-ee)/g*le;let ae=(Y[d]??1)+Le;const De=O-me;ae=Math.max(me,Math.min(De,ae));const Ae=O-ae;Z(qe=>({...qe,[d]:ae,[E]:Ae}))},ye=()=>{window.removeEventListener("pointermove",ue),window.removeEventListener("pointerup",ye),A.classList.remove("dragging"),document.body.classList.remove("lp-resizing")};window.addEventListener("pointermove",ue),window.addEventListener("pointerup",ye)},[_,o.length,i.length,U,K,C]);l.useEffect(()=>{!f||!s||n!=="open"||r&&(m({type:"list_sessions"}),m({type:"list_projects"}))},[f,s,n,r,m]);const I=d=>{const E=d.name||d.firstMessage.trim();return E.length>0?E:b("emptyChat")},R=d=>d.split(/[\\/]/).pop()||d,w=(d,E,h,A,ee)=>{const Y=H===d;return e.jsx("button",{type:"button",className:`lp-del ${Y?"confirm":""}`,title:Y?h:E,onClick:se=>{se.stopPropagation(),Y?(N(null),A()):N(d)},children:Y?e.jsx(Pt,{}):ee??e.jsx(He,{})})},$=(d,E,h,A)=>e.jsxs("button",{type:"button",className:"lp-section-title panel-section-title",onClick:h,title:b(E?"expandSection":"collapseSection"),children:[e.jsxs("span",{className:"lp-section-title-text",children:[d,A!==void 0?` (${A})`:""]}),e.jsx("span",{className:"lp-section-chevron",children:E?e.jsx(Ze,{}):e.jsx(Et,{})})]}),ie=[{key:"projects",visible:o.length>0,collapsed:U},{key:"convs",visible:i.length>0,collapsed:K},{key:"sessions",visible:!0,collapsed:C}].filter(d=>d.visible).filter(d=>!d.collapsed),v=ie.reduce((d,E)=>d+(_[E.key]??1),0)||1,L=d=>ie.length<=1?1:(_[d]??1)/v*ie.length;return e.jsxs("aside",{ref:k,className:"panel panel-left lp-panel",children:[y&&x&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:b("collapsePanel"),onClick:x,children:e.jsx(Mn,{})}),o.length>0&&e.jsxs("div",{className:`lp-section panel-projects ${U?"collapsed":""}`,style:U?void 0:{flex:`${L("projects")} 1 0px`},children:[$(b("recentProjects"),U,W,o.length),!U&&e.jsx("div",{className:"lp-section-body projects-scroll",children:o.map(d=>{const E=D===d.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>N(h=>h===`proj:${d.path}`?null:h),children:[e.jsxs("button",{type:"button",className:`project-item ${E?"active":""}`,title:d.path,onClick:()=>{E||m({type:"set_cwd",path:d.path})},children:[e.jsx(st,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:R(d.path)}),e.jsx("span",{className:"project-path",children:d.path})]}),e.jsx("span",{className:"project-time",children:Qs(d.lastUsed)})]}),w(`proj:${d.path}`,b("deleteProject"),b("deleteProjectConfirm"),()=>m({type:"remove_project",path:d.path}))]},d.path)})})]}),o.length>0&&!U&&(i.length>0?!K:!C)&&e.jsx("div",{className:"lp-sash",onPointerDown:z("projects",i.length>0?"convs":"sessions"),onDoubleClick:()=>Z({...fs}),title:b("dragToResize")}),i.length>0&&e.jsxs("div",{className:`lp-section lp-section-convs panel-convs ${K?"collapsed":""}`,style:K?void 0:{flex:`${L("convs")} 1 0px`},children:[$(b("runningConversations"),K,G,i.length),!K&&e.jsx("div",{className:"lp-section-body convs-scroll",children:ya(i,r).map(d=>e.jsxs("div",{className:"panel-conv-group",children:[!d.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:d.cwd,children:R(d.cwd)}),(()=>{const E=new Map(d.convs.map(X=>[X.id,X])),h=new Map,A=[];for(const X of d.convs)if(X.parentId&&E.has(X.parentId)){const ge=h.get(X.parentId)??[];ge.push(X),h.set(X.parentId,ge)}else A.push(X);const ee=[],Y=new Set,se=(X,ge)=>{if(!Y.has(X.id)){Y.add(X.id),ee.push({c:X,depth:ge});for(const Ne of h.get(X.id)??[])se(Ne,ge+1)}};for(const X of A)se(X,0);for(const X of d.convs)se(X,0);return ee.map(({c:X,depth:ge})=>{const Ne=u===X.id;return e.jsxs("div",{className:`lp-row${ge>0?" lp-sub":""}`,style:ge>0?{marginLeft:ge*18}:void 0,onMouseLeave:()=>N(de=>de===`conv:${X.id}`?null:de),children:[e.jsxs("button",{type:"button",className:`session-item ${Ne?"active":""}`,title:`${X.title}${d.isCurrent?"":` — ${d.cwd}`}`,onClick:()=>{Ne||m({type:"switch_conversation",id:X.id})},children:[e.jsx(dt,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[j===`conv:${X.id}`?e.jsx("input",{autoFocus:!0,className:"session-rename-input",value:V,placeholder:b("renameSessionPlaceholder"),onClick:de=>de.stopPropagation(),onChange:de=>J(de.target.value),onKeyDown:de=>{if(de.stopPropagation(),de.key==="Enter"&&!de.nativeEvent.isComposing){const Ee=V.trim();Ee&&m({type:"rename_conversation",id:X.id,name:Ee}),Q(null)}else de.key==="Escape"&&Q(null)},onBlur:()=>Q(null)}):e.jsxs("span",{className:"session-title",children:[X.isSubagent&&e.jsx("span",{className:"subagent-badge",children:b("subagentBadge")}),X.title,X.error&&e.jsx("span",{className:"conv-error-badge",title:b("convErrorBadge",{error:X.error})})]}),j===`conv:${X.id}`?null:e.jsx("span",{className:"session-sub",children:Ne?b("current"):b("messageCount",{n:X.messageCount})})]}),X.isStreaming&&e.jsx("span",{className:"conv-streaming",title:b("streaming")})]}),e.jsx("button",{type:"button",className:"lp-del lp-rename",title:b("renameSession"),onClick:de=>{de.stopPropagation(),N(null),J(X.title),Q(`conv:${X.id}`)},children:e.jsx(qt,{})}),!X.isStreaming&&!Ne&&w(`conv:${X.id}`,b("dismissConversation"),b("dismissConversationConfirm"),()=>m({type:"dismiss_conversation",id:X.id}),e.jsx(Re,{})),X.isStreaming&&e.jsx("span",{className:"lp-row-stalled",title:b("streaming"),style:{position:"absolute",right:28,top:"50%",transform:"translateY(-50%)"}})]},X.id)})})()]},d.cwd))})]}),i.length>0&&!K&&!C&&e.jsx("div",{className:"lp-sash",onPointerDown:z("convs","sessions"),onDoubleClick:()=>Z({...fs}),title:b("dragToResize")}),e.jsxs("div",{className:`lp-section lp-section-sessions panel-sessions ${C?"collapsed":""}`,style:C?void 0:{flex:`${L("sessions")} 1 0px`},children:[$(b("historySessions"),C,M,a.length),!C&&e.jsxs("div",{className:"lp-section-body sessions-scroll",children:[a.length===0&&e.jsx("div",{className:"panel-empty",children:b("noHistory")}),a.map(d=>{const E=T===d.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>N(h=>h===`sess:${d.path}`?null:h),children:[e.jsxs("button",{type:"button",className:`session-item ${E?"active":""}`,title:d.path,onClick:()=>{j||E||m({type:"switch_session",path:d.path})},children:[e.jsx(dt,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[j===d.path?e.jsx("input",{autoFocus:!0,className:"session-rename-input",value:V,placeholder:b("renameSessionPlaceholder"),onClick:h=>h.stopPropagation(),onChange:h=>J(h.target.value),onKeyDown:h=>{if(h.stopPropagation(),h.key==="Enter"&&!h.nativeEvent.isComposing){const A=V.trim();A&&m({type:"rename_session",path:d.path,name:A}),Q(null)}else h.key==="Escape"&&Q(null)},onBlur:()=>Q(null)}):e.jsx("span",{className:"session-title",children:I(d)}),j===d.path?null:e.jsxs("span",{className:"session-sub",children:[E?b("current"):b("messageCount",{n:d.messageCount}),d.source==="tui"&&e.jsx("span",{className:"session-src",title:b("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:Qs(d.modified)})]}),e.jsx("button",{type:"button",className:"lp-del lp-rename",title:b("renameSession"),onClick:h=>{h.stopPropagation(),N(null),J(d.name??""),Q(d.path)},children:e.jsx(qt,{})}),w(`sess:${d.path}`,b("deleteSession"),b("deleteSessionConfirm"),()=>m({type:"delete_session",path:d.path}))]},d.path)})]})]})]})}),$n="pi-web-ui:token";function Na(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem($n,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function Ca(){try{return localStorage.getItem($n)??""}catch{return""}}function Qt(t){const s=Ca();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}function Sa(t,s){const n=s.assistantMessageEvent,r=t.stats.tokens,c=s.usage!==null?{...r,...s.usage}:r,i=c===r?t.stats:{...t.stats,tokens:c};if(n.type!=="text_delta"&&n.type!=="thinking_delta")return i===t.stats?t:{...t,stats:i};const a=n.delta??"";if(!a)return i===t.stats?t:{...t,stats:i};const o=t.streamingMessage??null,u=o&&o.id===s.messageId?o:{id:s.messageId,content:[]},m=[...u.content],f=n.type==="thinking_delta"?"thinking":"text",y=n.contentIndex??m.length-1;return y>=0&&y<m.length&&m[y].type===f?m[y]=f==="thinking"?{type:"thinking",thinking:(m[y].thinking??"")+a}:{type:"text",text:(m[y].text??"")+a}:m.push(f==="thinking"?{type:"thinking",thinking:a}:{type:"text",text:a}),{...t,stats:i,streamingMessage:{...u,id:s.messageId,content:m}}}const xs="pi-web-ui:plugin-data";function Ta(t,s){window.dispatchEvent(new CustomEvent(xs,{detail:{pluginId:t,payload:s}}))}function Ea(t){const s=n=>{const r=n.detail;t(r.pluginId,r.payload)};return window.addEventListener(xs,s),()=>window.removeEventListener(xs,s)}const at=new Map,ys=new Set,nt=new Set;let Ys=-1;function Hn(){return[...at.values()]}function Pa(){const t=Hn();for(const s of ys)s(t)}function Ma(t){return ys.add(t),t(Hn()),()=>ys.delete(t)}async function Ia(t,s){s!==Ys&&(Ys=s,at.clear(),nt.clear());const n=new Set(t.map(r=>r.id));for(const r of[...at.keys()])n.has(r)||at.delete(r);for(const r of[...nt])n.has(r)||nt.delete(r);await Promise.all(t.filter(r=>r.hasClient&&r.view!==!1&&!r.error&&!at.has(r.id)&&!nt.has(r.id)).map(async r=>{try{const i=(await import(Ye(`/plugins/${encodeURIComponent(r.id)}/client/entry.mjs?e=${s}`))).default;i&&typeof i.mount=="function"?at.set(r.id,{info:r,module:i}):(nt.add(r.id),console.error(`[plugin:${r.id}] entry.mjs 缺少 default.mount`))}catch(c){nt.add(r.id),console.error(`[plugin:${r.id}] 客户端加载失败:`,c)}})),Pa()}function Ra(t,s){return{pluginId:t,send:n=>s({type:"plugin_message",pluginId:t,payload:n}),onData:n=>Ea((r,c)=>{r===t&&n(c)})}}const La=12,is=2e5,Da=2e5,Aa="LIVE_OMIT",_a={conversationId:null,goal:null,reviewModel:null,maxRounds:3,locked:!0,reviewing:!1,round:0,status:"",verdict:"pending",wizard:{active:!1,draft:"",model:null,step:0,maxSteps:6,status:""}};function Ba(){const t=new Map,s=new Map,n=(r,c)=>`${r}:${c}`;return{write(r,c,i){const a=n(r,c),o=t.get(a);if(o&&o.size>0){for(const f of o)try{f.write(i)}catch{}return}const u=s.get(a)??"",m=u.length+i.length>Da?i:u+i;s.set(a,m)},register(r,c,i){const a=n(r,c);let o=t.get(a);o||(o=new Set,t.set(a,o)),o.add(i);const u=s.get(a);if(u){try{i.write(u)}catch{}s.delete(a)}return()=>{const m=t.get(a);m&&(m.delete(i),m.size===0&&t.delete(a)),s.delete(a)}},clear(){t.clear(),s.clear()}}}function Js(t,s){const n=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&n.add(c.toolCallId),c.role==="bashExecution"&&n.add(`bash-${c.id}`);let r=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),r=!0);return r?new Map(t):t}function Xs(t,s){if(t.size===0)return t;const n=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&n.add(c.toolCallId);let r=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),r=!0);return r?new Map(t):t}function Fa(t,s){var n,r,c,i;switch(s.type){case"status":return{...t,status:s.status,ready:s.status==="open"?t.ready:!1,terminals:s.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:s.serverVersion,engine:s.engine,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==La};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:Js(t.liveOutputs,s.state),toolStatuses:Xs(t.toolStatuses,s.state)};case"snapshot_delta":{const a=t.state,o=s.msg;if(!a||a.conversationId!==o.conversationId||a.rev!==o.baseRev)return t;const u={...a,...o.state,messages:o.appended.length>0?[...a.messages,...o.appended]:a.messages};return{...t,ready:!0,state:u,activeConversationId:u.conversationId,liveOutputs:Js(t.liveOutputs,u),toolStatuses:Xs(t.toolStatuses,u)}}case"tool_delta":{const a=t.liveOutputs.get(s.toolCallId),o=((a==null?void 0:a.text)??"")+s.delta,u=o.length>is?`…[${Aa}:${o.length-is}]…
|
|
305
|
+
`+o.slice(o.length-is):o,m=new Map(t.liveOutputs);return m.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:m}}case"message_delta":{const a=t.state;return!a||a.conversationId!==s.msg.conversationId?t:{...t,state:Sa(a,s.msg)}}case"tool_status":return{...t,toolStatuses:new Map(t.toolStatuses).set(s.status.toolCallId,s.status)};case"notice":return{...t,notices:[...t.notices,s.notice].slice(-6)};case"dismiss_notice":return{...t,notices:t.notices.filter(a=>a.id!==s.id)};case"sessions":return{...t,sessions:s.sessions};case"conversations":return{...t,conversations:s.conversations,activeConversationId:s.activeId};case"projects":return{...t,projects:s.projects};case"files":return{...t,files:s.files};case"file_changed":return{...t,fileChanged:{path:s.path}};case"file_content":return{...t,fileContent:s.content};case"models":return{...t,models:s.models,modelsLoading:s.loading};case"models_config":return{...t,modelsConfig:s.providers};case"providers_status":return{...t,providers:s.providers};case"provider_keys":return{...t,providerKeys:s.keys};case"fetch_models_result":return{...t,fetchModelsResult:s.result};case"refresh_provider_result":return{...t,refreshProviderResult:s.result};case"clone_provider_result":return{...t,cloneProviderResult:s.result};case"install_result":return{...t,installResult:s.result};case"scm_data":return{...t,scmData:s.data};case"file_search_result":return{...t,fileSearch:s.result};case"session_search_result":return{...t,sessionSearch:s.result};case"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"update_status_all":return{...t,updatesAll:s.items};case"updates_check_started":return{...t,updatesAll:null};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"question":return{...t,question:s.question};case"commands":return{...t,commands:s.commands,commandsPath:s.path};case"slash_commands":return{...t,slashCommands:s.commands};case"goal_status":return{...t,goal:s.status};case"settings":return{...t,settings:s.settings};case"bg_servers":return{...t,bgServers:s.servers};case"plugins":return{...t,plugins:s.plugins,pluginsEpoch:s.epoch};case"plugin_catalog":return{...t,pluginCatalog:s.entries,pluginCatalogEpoch:s.epoch};case"dsh_patches":return{...t,dshPatches:{patchDir:s.patchDir,files:s.files}};case"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(a=>a.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(n=t.state)!=null&&n.conversationId)&&s.conversationId!==(t.activeConversationId||((r=t.state)==null?void 0:r.conversationId))?t:{...t,terminals:t.terminals.map(a=>a.id===s.terminalId?{...a,running:!1,exitCode:s.exitCode}:a)};case"terminal_restart":return{...t,terminals:t.terminals.map(a=>a.id===s.terminalId?{...a,running:!0,exitCode:null}:a)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(c=t.state)!=null&&c.conversationId)&&s.conversationId!==(t.activeConversationId||((i=t.state)==null?void 0:i.conversationId))?t:{...t,terminals:s.terminals.map(a=>{var o;return{...a,conversationId:s.conversationId??((o=t.state)==null?void 0:o.conversationId)??""}})};case"terminal_active":return{...t,terminalActiveId:s.id};default:return t}}const Zs="pi-web-client-id";let as=null;function Es(){if(as)return as;let t=null;try{t=sessionStorage.getItem(Zs),t||(t=Qe(),sessionStorage.setItem(Zs,t))}catch{t=t??Qe()}return as=t,t}const On="pi-web-last-cwd";function $a(){try{return localStorage.getItem(On)}catch{return null}}function Ha(t){try{localStorage.setItem(On,t)}catch{}}function Oa(){const t=location.protocol==="https:"?"wss:":"ws:";return Qt(`${t}//${location.host}${Ye("/ws")}`)}function Wa(){var G;const[t,s]=l.useReducer(Fa,{status:"connecting",ready:!1,state:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:[],conversations:[],activeConversationId:"",projects:[],files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},installResult:null,pathCompletions:[],update:null,updatesAll:null,widgets:[],statuses:[],dialog:null,question:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],terminalActiveId:null,goal:_a,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,pluginCatalog:[],pluginCatalogEpoch:0,dshPatches:null,protocolMismatch:!1}),n=l.useRef(null),r=l.useRef(Ba()),c=l.useRef(0),i=l.useRef(null),a=l.useRef(!0),o=l.useRef(0),u=l.useRef(0),m=l.useRef(new Map),f=l.useRef(null),y=l.useRef(!1),x=l.useRef(null),b=()=>{f.current||(f.current=setTimeout(()=>{f.current=null;const C=n.current;C&&C.readyState===WebSocket.OPEN&&C.send(JSON.stringify({type:"get_state"}))},300))},T=(C,M)=>{var Z;const k=m.current,_=k.get(C);if(_!==void 0&&M!==_+1){const z=K.current.chat,I=z.activeConversationId||((Z=z.state)==null?void 0:Z.conversationId);C===I&&b()}k.set(C,M)},D=l.useCallback((C,M)=>{const k=++u.current;s({type:"notice",notice:{id:k,level:C,text:M}})},[]),H=l.useCallback(C=>{const M=n.current;return M&&M.readyState===WebSocket.OPEN?(C.type==="check_updates_all"&&C.force===!0&&s({type:"updates_check_started"}),M.send(JSON.stringify(C)),!0):!1},[]),N=l.useCallback(()=>{if(!a.current)return;s({type:"status",status:"connecting"});const C=new WebSocket(Oa());n.current=C,C.onopen=()=>{n.current===C&&(s({type:"status",status:"open"}),c.current=0,o.current=Date.now(),C.send(JSON.stringify({type:"hello",clientId:Es()})))},C.onmessage=M=>{if(n.current!==C)return;o.current=Date.now();let k;try{k=JSON.parse(M.data)}catch{return}switch(k.type){case"ready":s({type:"ready",serverVersion:k.serverVersion,protocolVersion:k.protocolVersion,engine:k.engine}),C.send(JSON.stringify({type:"get_state"})),C.send(JSON.stringify({type:"list_files"})),C.send(JSON.stringify({type:"list_models"})),C.send(JSON.stringify({type:"list_commands"})),C.send(JSON.stringify({type:"get_commands"})),C.send(JSON.stringify({type:"check_update"})),C.send(JSON.stringify({type:"check_updates_all"}));break;case"snapshot":m.current=new Map,s({type:"snapshot",state:k.state});break;case"snapshot_delta":{const _=K.current.chat.state;(!_||_.conversationId!==k.conversationId||_.rev!==k.baseRev)&&b(),s({type:"snapshot_delta",msg:k});break}case"tool_delta":T(k.conversationId,k.seq),s({type:"tool_delta",toolCallId:k.toolCallId,toolName:k.toolName,delta:k.delta});break;case"tool_status":s({type:"tool_status",status:k});break;case"message_delta":{T(k.conversationId,k.seq),s({type:"message_delta",msg:k});break}case"notice":{const _=++u.current;s({type:"notice",notice:{id:_,level:k.level,text:k.text,textEn:k.textEn}});break}case"sessions":s({type:"sessions",sessions:k.sessions});break;case"conversations":s({type:"conversations",conversations:k.conversations,activeId:k.activeId});break;case"projects":s({type:"projects",projects:k.projects});break;case"files":s({type:"files",files:k});break;case"file_changed":s({type:"file_changed",path:k.path});break;case"file_content":s({type:"file_content",content:k});break;case"models":s({type:"models",models:k.models,loading:!1});break;case"models_config":s({type:"models_config",providers:k.providers});break;case"providers_status":s({type:"providers_status",providers:k.providers});break;case"provider_keys":s({type:"provider_keys",keys:k.keys});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:k.reqId,ok:k.ok,models:k.models,error:k.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:k.reqId,ok:k.ok,added:k.added,total:k.total,error:k.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:k.reqId,ok:k.ok,config:k.config,configs:k.configs,error:k.error}});break;case"scm_data":s({type:"scm_data",data:k});break;case"search_files_result":s({type:"file_search_result",result:{reqId:k.reqId,ok:k.ok,results:k.results,truncated:k.truncated}});break;case"session_search_results":s({type:"session_search_result",result:{reqId:k.reqId,ok:k.ok,results:k.results}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:k});break;case"path_completions":s({type:"path_completions",completions:k.completions});break;case"update_status":s({type:"update_status",status:k});break;case"update_status_all":s({type:"update_status_all",items:k.items});break;case"widgets":s({type:"widgets",widgets:k.widgets});break;case"statuses":s({type:"statuses",statuses:k.statuses});break;case"dialog":s({type:"dialog",dialog:{id:k.id,kind:k.kind,title:k.title,args:k.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"question_pending":s({type:"question",question:{id:k.id,questions:k.questions}});break;case"terminal_output":r.current.write(k.conversationId??K.current.chat.activeConversationId,k.terminalId,k.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:k.conversationId,terminalId:k.terminalId,exitCode:k.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:k.conversationId,terminals:k.terminals});break;case"commands":s({type:"commands",commands:k.commands,path:k.path});break;case"slash_commands":s({type:"slash_commands",commands:k.commands});break;case"goal_status":s({type:"goal_status",status:k.status});break;case"settings_state":s({type:"settings",settings:k.settings});break;case"bg_servers":s({type:"bg_servers",servers:k.servers});break;case"plugins":s({type:"plugins",plugins:k.plugins,epoch:k.epoch});break;case"plugin_catalog":s({type:"plugin_catalog",entries:k.entries,epoch:k.epoch});break;case"dsh_patches":s({type:"dsh_patches",patchDir:k.patchDir,files:k.files});break;case"plugin_data":Ta(k.pluginId,k.payload);break}},C.onclose=()=>{if(n.current===C&&(n.current=null),r.current.clear(),!a.current||n.current&&n.current!==C)return;s({type:"status",status:"closed"});const M=Math.min(1e3*2**c.current,1e4);c.current+=1,i.current=setTimeout(()=>{i.current=null,N()},M)},C.onerror=()=>{}},[]);l.useEffect(()=>{a.current=!0,N();const C=setInterval(()=>{if(!a.current)return;const M=n.current;M&&M.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&M.close()},5e3);return()=>{var M;a.current=!1,clearInterval(C),i.current&&(clearTimeout(i.current),i.current=null),(M=n.current)==null||M.close(),n.current=null}},[N]),l.useEffect(()=>{var M;const C=(M=t.state)==null?void 0:M.cwd;if(C){if(!y.current){y.current=!0;const k=$a();if(k&&k!==C){H({type:"set_cwd",path:k});return}}x.current!==C&&(x.current=C,Ha(C))}},[(G=t.state)==null?void 0:G.cwd,H]);const j=l.useCallback(C=>s({type:"dismiss_notice",id:C}),[]),Q=l.useCallback(C=>s({type:"terminal_add",meta:C}),[]),V=l.useCallback(C=>s({type:"terminal_remove",id:C}),[]),J=l.useCallback(C=>s({type:"terminal_restart",terminalId:C}),[]),U=l.useCallback(C=>s({type:"terminal_active",id:C}),[]),W=l.useCallback((C,M,k)=>r.current.register(C,M,k),[]),K=l.useRef({chat:t,send:H,pushNotice:D,dismissNotice:j,terminal:{create:Q,close:V,register:W,restart:J,select:U}});return K.current={chat:t,send:H,pushNotice:D,dismissNotice:j,terminal:{create:Q,close:V,register:W,restart:J,select:U}},K.current}const Ua=200*1024*1024,Ka=/windows/i.test(navigator.userAgent),qa=/[<>:"/\\|?*\u0000-\u001f]/g,za=/[. ]+$/,Va=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Ga(t){const s=t.replace(qa,"_").replace(za,"");return s?Va.test(s)?`_${s}`:s:"_"}function en(t,s=!0){const n=new URLSearchParams({clientId:Es(),path:t,...s?{download:"1"}:{}});return Qt(Ye(`/api/file?${n}`))}const Wn="FILE_NOT_FOUND";async function Qa(t,s){const n=Ka?Ga(s):s;try{const r=await fetch(en(t));if(!r.ok)return{ok:!1,cancelled:!1,error:await r.text().catch(()=>"")||(r.status===404?Wn:`HTTP ${r.status}`)};if(Number(r.headers.get("content-length")??"0")>Ua)return window.location.assign(en(t)),{ok:!0};const i=await r.blob();return window.showSaveFilePicker&&window.isSecureContext?Ya(i,n):vs(i,n)}catch(r){return{ok:!1,cancelled:!1,error:r instanceof Error?r.message:String(r)}}}async function Ya(t,s){let n;const r=window.showSaveFilePicker;if(!r)return vs(t,s);try{n=await r({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:vs(t,s)}try{const c=await n.createWritable();return await c.write(t),await c.close(),{ok:!0}}catch(c){return{ok:!1,cancelled:!1,error:c instanceof Error?c.message:String(c)}}}function vs(t,s){const n=URL.createObjectURL(t),r=document.createElement("a");return r.href=n,r.download=s,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}const Lt="@root",Ja=l.memo(function({files:s,fileChanged:n,widgets:r,cwd:c,send:i,onAttach:a,onPreview:o,onNotice:u,collapsible:m,onToggleCollapse:f}){const y=be(),[x,b]=l.useState(""),[T,D]=l.useState(null),[H,N]=l.useState(!1),[j,Q]=l.useState(null),V=l.useRef(""),J=l.useRef(null),U=l.useCallback((d,E)=>{d.preventDefault(),V.current=E,Q({x:Math.min(d.clientX,window.innerWidth-220),y:Math.min(d.clientY,window.innerHeight-90)})},[]),W=l.useCallback(()=>Q(null),[]);l.useEffect(()=>{if(!j)return;const d=A=>{var ee;(ee=A.target)!=null&&ee.closest(".ctx-menu")||W()},E=A=>{A.key==="Escape"&&W()};window.addEventListener("mousedown",d,!0),window.addEventListener("keydown",E);const h=()=>W();return window.addEventListener("blur",h),()=>{window.removeEventListener("mousedown",d,!0),window.removeEventListener("keydown",E),window.removeEventListener("blur",h)}},[j,W]);const K=l.useCallback(()=>{var d;W(),J.current&&(J.current.value=""),(d=J.current)==null||d.click()},[W]),G=l.useCallback((d,E)=>{for(const h of E){const A=new FileReader;A.onload=()=>{const ee=A.result,Y=ee.slice(ee.indexOf(",")+1);Y&&i({type:"upload_file",dirPath:d,name:h.name,data:Y})},A.readAsDataURL(h)}},[i]),C=l.useCallback(d=>{G(V.current,Array.from(d.target.files??[]))},[G]),M=l.useRef(null),k=d=>{var E;return Array.from(((E=d.dataTransfer)==null?void 0:E.types)??[]).includes("Files")},_=l.useCallback(()=>{var d,E;(d=M.current)==null||d.querySelectorAll(".file-item.drop-target").forEach(h=>h.classList.remove("drop-target")),(E=M.current)==null||E.classList.remove("drop-root")},[]),Z=l.useCallback(d=>{var h,A;if(_(),d==null)return;const E=(h=M.current)==null?void 0:h.querySelector(`.file-item[data-path="${CSS.escape(d)}"]`);E?E.classList.add("drop-target"):(A=M.current)==null||A.classList.add("drop-root")},[_]),z=d=>{const E=d instanceof Element?d.closest(".file-item"):null;return(E==null?void 0:E.dataset.type)==="dir"?E.dataset.path??x:x},I=l.useCallback(()=>{const d=document.querySelector(".app");d&&d.dispatchEvent(new DragEvent("dragleave",{bubbles:!0}))},[]),R=1e4,w=l.useRef(0),$=l.useRef(void 0),q=l.useCallback((d,E)=>{const h=++w.current;b(d),E!=null&&E.silent||N(!0),i({type:"list_files",path:d===""?void 0:d})||w.current===h&&N(!1)},[i]);l.useEffect(()=>{s&&s.path===x&&N(!1)},[s,x]),l.useEffect(()=>{if(c!==$.current){$.current=c,q("",{silent:!0});return}const d=setInterval(()=>{document.visibilityState!=="hidden"&&q(x,{silent:!0})},R);return()=>clearInterval(d)},[c,x,q]),l.useEffect(()=>{n&&n.path===x&&q(x,{silent:!0})},[n,x,q]);const ie=d=>q(d),v=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&q(s.parent)},L=(()=>{if(x===""||x===Lt)return[];const d=x.split("/").filter(E=>!!E&&E!==Lt);return x.startsWith("/")?d.map((E,h)=>({label:h===0?"/":d[h],path:"/"+d.slice(0,h+1).join("/")})):d.map((E,h)=>({label:d[h],path:d.slice(0,h+1).join("/")}))})();return e.jsxs("aside",{className:"panel panel-right",children:[m&&f&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:y("collapsePanel"),onClick:f,children:e.jsx(Pn,{})}),e.jsxs("div",{className:"panel-crumbs",children:[e.jsx("button",{type:"button",className:`crumb ${x===""?"active":""}`,onClick:()=>q(""),children:y("rootDir")}),e.jsx("button",{type:"button",className:`crumb ${x===Lt?"active":""}`,title:y("computer"),onClick:()=>q(Lt),children:"💻"}),L.map(d=>e.jsxs("span",{className:"crumb-seg",children:[e.jsx(Gt,{}),e.jsx("button",{type:"button",className:`crumb ${d.path===x?"active":""}`,onClick:()=>q(d.path),children:d.label})]},d.path))]}),e.jsxs("div",{ref:M,className:"panel-body",onContextMenu:d=>U(d,x),onDragOver:d=>{k(d)&&(d.preventDefault(),d.stopPropagation(),d.dataTransfer.dropEffect="copy",I(),Z(z(d.target)))},onDragLeave:d=>{d.relatedTarget&&d.currentTarget.contains(d.relatedTarget)||_()},onDrop:d=>{var h;if(_(),!k(d))return;d.preventDefault(),d.stopPropagation(),I();const E=Array.from(((h=d.dataTransfer)==null?void 0:h.files)??[]);if(E.length===0){u("warning",y("foldersNotSupported"));return}G(z(d.target),E)},onDragEnd:_,children:[e.jsx("input",{ref:J,type:"file",multiple:!0,hidden:!0,onChange:C}),H&&e.jsx("div",{className:"panel-empty",children:y("loading")}),!H&&s&&s.path===x&&e.jsxs(e.Fragment,{children:[s.parent!=null&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:v,children:[e.jsx(st,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(d=>d.type==="dir"?e.jsxs("div",{className:"file-item dir","data-type":"dir","data-path":d.path,onContextMenu:E=>{E.stopPropagation(),U(E,d.path)},children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>ie(d.path),children:[e.jsx(st,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:d.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":y("linkFolderTip"),onClick:()=>a(d.path,d.name,"reference",!0),children:e.jsx(ms,{})})]},d.path):e.jsxs("div",{className:"file-item file","data-type":"file","data-path":d.path,onContextMenu:E=>{E.stopPropagation(),U(E,x)},children:[e.jsxs("button",{type:"button",className:"file-name",title:`${d.path} — ${y("previewFile")}`,onClick:()=>o(d.path,d.name),children:[e.jsx(ea,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:d.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":y("downloadFile"),onClick:()=>{Qa(d.path,d.name).then(E=>{E.ok||E.cancelled||u("error",y("downloadFailed",{error:E.error===Wn?y("fileNotFoundShort"):E.error}))})},children:e.jsx(Vt,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":y("attachInlineTip"),onClick:()=>a(d.path,d.name,"inline"),children:e.jsx(Ke,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":y("referenceTip"),onClick:()=>a(d.path,d.name,"reference"),children:e.jsx(ms,{})})]},d.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:y("filesTruncated")})]}),!H&&!s&&e.jsx("div",{className:"panel-empty",children:y("noFiles")})]}),r.filter(d=>d.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:r.filter(d=>d.lines.length>0).map(d=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:y("widgetExpand"),onClick:()=>D(d.key),children:[e.jsx("span",{children:d.key}),e.jsx(Gi,{})]}),e.jsx("pre",{className:"widget-lines",children:d.lines.join(`
|
|
306
|
+
`)})]},d.key))}),T&&(()=>{const d=r.find(E=>E.key===T);return d?e.jsx("div",{className:"modal-backdrop",onClick:()=>D(null),children:e.jsxs("div",{className:"widget-expand",onClick:E=>E.stopPropagation(),children:[e.jsxs("div",{className:"widget-expand-head",children:[e.jsx("span",{className:"widget-expand-title",children:d.key}),e.jsx("button",{type:"button",className:"btn",title:y("close"),onClick:()=>D(null),children:e.jsx(Re,{})})]}),e.jsx("pre",{className:"widget-expand-lines",children:d.lines.join(`
|
|
307
|
+
`)})]})}):null})(),j&&e.jsx("div",{className:"ctx-menu",style:{left:j.x,top:j.y},onContextMenu:d=>{d.preventDefault(),d.stopPropagation()},children:e.jsxs("button",{type:"button",className:"ctx-item",onClick:K,children:[e.jsx(Fi,{}),V.current===x?y("uploadToCurrentDir"):y("uploadToFolder")]})})]})});var Xa=kn();const Ps=l.memo(function({text:s}){const n=be(),[r,c]=l.useState(!1);return s?e.jsx("button",{type:"button",className:"copy-btn",title:n("copy"),onClick:()=>{navigator.clipboard.writeText(s).then(()=>{c(!0),setTimeout(()=>c(!1),1200)})},children:r?e.jsx(Pt,{}):e.jsx(En,{})}):null});function Za(t){const s=r=>{var c;if(typeof r=="string"||typeof r=="number"){const i=String(r);return i===""?[[]]:i.split(`
|
|
308
|
+
`).map(a=>a===""?[]:[a])}if(Array.isArray(r)){let i=[];for(const a of r){const o=s(a);if(i.length===0)i=o;else{const u=o[0]??[];i[i.length-1].push(...u),i.push(...o.slice(1))}}return i}if(r&&typeof r=="object"&&"props"in r){const i=r,a=(c=i.props)==null?void 0:c.children,o={...i.props,children:void 0},u=a==null?[]:s(a);return u.length===0?[[l.createElement(i.type,o)]]:u.map(m=>[l.createElement(i.type,o,...m)])}return[[r]]},n=s(t);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}function bs(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(bs).join("");if(t&&typeof t=="object"&&"props"in t){const s=t.props;return bs(s==null?void 0:s.children)}return""}function er(t){const s=Array.isArray(t)?t[0]:t;return!s||typeof s!="object"||!("props"in s)?null:s}function tr(t){var c;const s=er(t),n=(c=s==null?void 0:s.props)==null?void 0:c.className;if(typeof n!="string")return null;const r=n.match(/(?:^|\s)language-([A-Za-z0-9_+\-]+)(?:\s|$)/);return r?r[1]:null}const tn="pi-web-ui:plugin-data";let jt=new Map,wt=new Map,ot=new Set,ks=-1,Un=0;const js=new Set;function sr(){Un++;for(const t of js)t()}function nr(t){return js.add(t),()=>{js.delete(t)}}function ir(){return Un}let Bt=null;function ar(t){Bt=t}function rr(t,s){s!==ks&&(ks=s,wt.clear(),ot.clear());const n=new Map;for(const c of t)if(!(c.error||!c.renderers))for(const i of c.renderers)n.has(i)||n.set(i,c.id);let r=n.size!==jt.size;if(!r){for(const[c,i]of n)if(jt.get(c)!==i){r=!0;break}}if(r){for(const c of wt.keys())n.has(c)||wt.delete(c);for(const c of ot)n.has(c)||ot.delete(c);jt=n,sr()}}async function lr(t,s){var i,a;const n=jt.get(t);if(!n)return null;let r=wt.get(t);if(!r&&!ot.has(t))try{const u=(a=(i=(await import(Ye(`/plugins/${encodeURIComponent(n)}/client/entry.mjs?e=${ks}`))).default)==null?void 0:i.renderers)==null?void 0:a[t];typeof u=="function"?(r={pluginId:n,renderer:u},wt.set(t,r)):(ot.add(t),console.error(`[plugin:${n}] entry.mjs 未提供 renderers["${t}"]`))}catch(o){ot.add(t),console.error(`[plugin:${n}] renderer 加载失败(${t}):`,o)}if(!r)return null;const c={pluginId:r.pluginId,send:o=>{Bt==null||Bt({type:"plugin_message",pluginId:r.pluginId,payload:o})},onData:o=>{const u=m=>{const f=m.detail;f.pluginId===r.pluginId&&o(f.payload)};return window.addEventListener(tn,u),()=>window.removeEventListener(tn,u)}};try{const o=await r.renderer(s,c);return o instanceof HTMLElement?o:null}catch(o){return console.error(`[plugin:${r.pluginId}] renderer("${t}") 执行失败:`,o),null}}function or(t){return jt.has(t)}const ws="pi-web-ui:theme",Kn="dark",sn="theme-stylesheet",rt="pi-web-ui:theme-change";function qn(){try{const t=localStorage.getItem(ws);if(t&&t!==Kn)return t}catch{}return null}function cr(t){try{t?localStorage.setItem(ws,t):localStorage.removeItem(ws)}catch{}}function zn(t){let s=document.getElementById(sn);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(rt));return}s||(s=document.createElement("link"),s.id=sn,s.rel="stylesheet",document.head.appendChild(s)),s.href=Ye(`/themes/${encodeURIComponent(t)}.css`),s.onload=()=>window.dispatchEvent(new CustomEvent(rt))}async function dr(){try{const t=await fetch(Qt(Ye("/api/themes")));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function ur(){const[t,s]=l.useState([]),[n,r]=l.useState(()=>qn());return l.useEffect(()=>{let i=!1;return dr().then(a=>{i||s(a)}),()=>{i=!0}},[]),l.useEffect(()=>{zn(n),cr(n)},[n]),{themes:t,theme:n,switchTheme:i=>r(i===Kn?null:i)}}function yo(){const t=getComputedStyle(document.documentElement),s=(n,r)=>t.getPropertyValue(n).trim()||r;return{background:s("--term-bg","#0b0d12"),foreground:s("--term-fg","#e6e8ef"),cursor:s("--term-cursor","#8b5cf6"),cursorAccent:s("--term-cursor-accent","#0b0d12"),selectionBackground:s("--term-selection","rgba(139, 92, 246, 0.35)"),black:s("--term-black","#1a1d26"),red:s("--term-red","#f87171"),green:s("--term-green","#34d399"),yellow:s("--term-yellow","#fbbf24"),blue:s("--term-blue","#60a5fa"),magenta:s("--term-magenta","#c084fc"),cyan:s("--term-cyan","#22d3ee"),white:s("--term-white","#e6e8ef"),brightBlack:s("--term-bright-black","#6b7284"),brightRed:s("--term-bright-red","#f87171"),brightGreen:s("--term-bright-green","#34d399"),brightYellow:s("--term-bright-yellow","#fbbf24"),brightBlue:s("--term-bright-blue","#60a5fa"),brightMagenta:s("--term-bright-magenta","#c084fc"),brightCyan:s("--term-bright-cyan","#22d3ee"),brightWhite:s("--term-bright-white","#ffffff")}}function pr({lang:t,code:s}){const n=l.useRef(null),r=l.useRef(null),c=l.useRef(0),i=l.useRef(new WeakMap),[a,o]=l.useState(null);return l.useEffect(()=>{const u=()=>{const m=++c.current,f=r.current;f&&(f.dispatchEvent(new CustomEvent(rt)),i.current.set(f,m))};return window.addEventListener(rt,u),()=>window.removeEventListener(rt,u)},[]),l.useEffect(()=>{let u=!1;const m=c.current;return o(null),lr(t,s).then(f=>{u||(f&&i.current.set(f,m),o(f))}),()=>{u=!0}},[t,s]),l.useEffect(()=>{r.current=a;const u=n.current;return u&&(u.replaceChildren(),a&&(u.appendChild(a),(i.current.get(a)??c.current)<c.current&&(a.dispatchEvent(new CustomEvent(rt)),i.current.set(a,c.current)))),()=>{r.current===a&&(r.current=null)}},[a]),a?e.jsx("div",{className:"plugin-fence",ref:n}):e.jsxs("div",{className:"codeblock",children:[e.jsx(Ps,{text:s}),e.jsx("pre",{children:e.jsx("code",{children:s})})]})}const mr=[wi],hr=[[ji,{detect:!0,ignoreMissing:!0}]];function Ms({text:t}){return e.jsx(ki,{remarkPlugins:mr,rehypePlugins:hr,components:{pre:gr},children:t})}const Yt=l.memo(function({text:s}){return e.jsx("div",{className:"md",children:e.jsx(Ms,{text:s})})});function gr({children:t,...s}){l.useSyncExternalStore(nr,ir);const n=tr(t);return n&&or(n)?e.jsx(pr,{lang:n,code:bs(t)}):e.jsx(fr,{children:t,...s})}function fr({children:t,...s}){var a;const n=t&&typeof t=="object"&&"props"in t?(a=t.props)==null?void 0:a.children:t,r=Za(n),c=r.length>1,i=c?`${String(r.length).length+1}ch`:void 0;return e.jsxs("div",{className:"codeblock",children:[e.jsx(Ps,{text:Ns(t)}),e.jsx("pre",{...s,children:r.map((o,u)=>e.jsxs("div",{className:"code-line",children:[c&&e.jsx("span",{className:"code-num",style:i?{width:i}:void 0,children:u+1}),e.jsx("code",{className:"code-line-body hljs",children:o})]},u))})]})}function Ns(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(Ns).join("");if(t&&typeof t=="object"&&"props"in t){const s=t.props;return Ns(s==null?void 0:s.children)}return""}const xr=/^\s{0,3}(`{3,}|~{3,})/,yr=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function rs(t){return t.trim()===""}function nn(t){const s=xr.exec(t);return s?s[1]:null}function vr(t){const s=t.split(`
|
|
309
|
+
`),n=[];let r=[],c=null;for(let i=0;i<s.length;i++){const a=s[i];if(c!==null){const u=nn(a);u&&u[0]===c[0]&&u.length>=c.length&&(c=null),r.push(a);continue}const o=nn(a);if(o&&!rs(a)){c=o,r.push(a);continue}if(rs(a)){let u=i;for(;u<s.length&&rs(s[u]);)u++;if(!(u<s.length&&yr.test(s[u]))&&r.length>0){n.push(r.join(`
|
|
310
310
|
`)),r=[];continue}r.push(a);continue}r.push(a)}return{frozen:n,active:r.join(`
|
|
311
|
-
`),inFence:c!==null}}const
|
|
312
|
-
`)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${u?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>a(!o),children:[u?e.jsx(Ze,{}):e.jsx(
|
|
313
|
-
`),z=s.role==="user"?
|
|
314
|
-
`).join(" ").trim(),R=i&&a&&s.content.length===0,w=s.role==="user"&&!i&&!R&&!!o,$=async h=>{const A=[];for(const ee of h){if(!Ge(ee.type))continue;const Y=await
|
|
315
|
-
`)),W(
|
|
316
|
-
`).length+1)),onChange:h=>J(h.target.value),onPaste:h=>{var ee;const A=[];for(const Y of((ee=h.clipboardData)==null?void 0:ee.items)??[])if(Y.kind==="file"&&Ge(Y.type)){const se=Y.getAsFile();se&&A.push(se)}A.length!==0&&(h.preventDefault(),$(A))},onKeyDown:h=>{h.key==="Enter"&&(h.metaKey||h.ctrlKey)?(h.preventDefault(),L()):h.key==="Escape"&&Q(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(Ji,{})," ",N("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>Q(!1),children:N("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!V.trim(),title:N("reaskFromHere"),onClick:L,children:[e.jsx(
|
|
317
|
-
`),
|
|
318
|
-
`).length;return e.jsxs("div",{className:`attachcard ${m?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>c(D=>s?!0:!D),children:[e.jsx("span",{className:"attachcard-icon",children:u?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:o}),a.path&&e.jsx("span",{className:"attachcard-path",children:a.path}),e.jsx("span",{className:`attachcard-mode ${a.mode==="lines"?"lines":m?"ref":
|
|
319
|
-
`)}function
|
|
320
|
-
`)}function Gr(t,s){let n=0,r=t.indexOf(s);for(;r!==-1;)n++,r=t.indexOf(s,r+s.length);return n}function Qr(t,s,n,r){const c=new Map,i=n.toLowerCase();if(!i)return c;for(const a of t){if(!s.has(a.id))continue;const o=Gr(Vr(a,r).toLowerCase(),i);o>0&&c.set(a.id,o)}return c}function Yr(t,s){var i;const n=[],r=s.toLowerCase();if(!r)return n;const c=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(a){const o=a.parentElement;return!o||o.closest(".search-bar")||o.closest(".msg-collapsed")?NodeFilter.FILTER_REJECT:(a.textContent??"").toLowerCase().includes(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let a=c.nextNode();a;a=c.nextNode()){const o=(a.textContent??"").toLowerCase();if(!((i=a.parentElement)!=null&&i.closest("[data-msg-id]")))continue;let u=o.indexOf(r);for(;u!==-1;){const m=document.createRange();m.setStart(a,u),m.setEnd(a,u+r.length),n.push(m),u=o.indexOf(r,u+r.length)}}return n}function Jr(t,s,n,r,c){var u;const i=Qr(n,r,s,c),a=new Map;for(const m of Yr(t,s)){const y=(u=m.startContainer.parentElement)==null?void 0:u.closest("[data-msg-id]");if(!(y!=null&&y.dataset.msgId))continue;const x=a.get(y.dataset.msgId);x?x.push(m):a.set(y.dataset.msgId,[m])}const o=[];for(const m of n){const y=a.get(m.id);if(y)for(let f=0;f<y.length;f++)o.push({kind:"dom",range:y[f],msgId:m.id,k:f});const x=i.get(m.id);if(x)for(let f=0;f<x;f++)o.push({kind:"folded",msgId:m.id,k:f})}return o}function rs(t,s){return t.findIndex(n=>n.msgId===s.msgId&&n.k===s.k)}function Ue(t,s){const n=CSS;if(!n.highlights)return;if(s.length===0){n.highlights.delete(t);return}const r=window.Highlight;r&&n.highlights.set(t,new r(...s))}function Xr(t,s){const n=[];let r=t;for(;r&&r!==s;){const c=getComputedStyle(r);/(auto|scroll|hidden)/.test(c.overflowY+c.overflowX)&&(r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth)&&n.push(r),r=r.parentElement}return n}function Zr(t,s){const n=s.startContainer.parentElement;for(const o of Xr(n,t)){const u=s.getBoundingClientRect(),m=o.getBoundingClientRect();if(u.height<=0||u.width<=0)return;u.top>=m.top+4&&u.bottom<=m.bottom-4||(o.scrollTop+=u.top-m.top-(o.clientHeight-u.height)/2),u.left>=m.left+4&&u.right<=m.right-4||(o.scrollLeft+=u.left-m.left-(o.clientWidth-u.width)/2)}const r=s.getBoundingClientRect(),c=t.getBoundingClientRect();if(r.height<=0||r.width<=0)return;const i=r.top>=c.top+6&&r.bottom<=c.bottom-6,a=r.left>=c.left+6&&r.right<=c.right-6;i&&a||(i||(t.scrollTop+=r.top-c.top-(c.height-r.height)/2),a||(t.scrollLeft+=r.left-c.left-(c.width-r.width)/2))}function el({containerRef:t,messages:s,collapsedIds:n,toolResults:r,onExpand:c,onProgrammaticScroll:i,open:a,onClose:o}){const u=be(),m=l.useRef(null),[y,x]=l.useState(""),[f,b]=l.useState(null),[T,D]=l.useState(0),[,H]=l.useState(0),N=l.useDeferredValue(y),j=a?N.trim():"",Q=l.useRef(null);Q.current=f;const V=l.useRef([]),J=l.useRef({key:null}),U=l.useRef("");l.useEffect(()=>{a&&(b(null),requestAnimationFrame(()=>{var G;return(G=m.current)==null?void 0:G.select()}))},[a]),l.useEffect(()=>{if(!a)return;const G=C=>{C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),o())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[a,o]),l.useEffect(()=>(a||(Ue("msg-search",[]),Ue("msg-search-active",[])),()=>{Ue("msg-search",[]),Ue("msg-search-active",[])}),[a]),l.useLayoutEffect(()=>{const G=()=>{D(0),b(null),H(0),V.current=[],Ue("msg-search",[]),Ue("msg-search-active",[]),J.current={key:null},U.current=""};if(!a||!j){G();return}const C=t.current;if(!C)return;let M=!1,k=0;return k=requestAnimationFrame(()=>{var ie,v;if(M)return;const _=Jr(C,j,s,n,r);V.current=_;const Z=_.length;if(D(Z),Z===0){b(null),H(0),Ue("msg-search",[]),Ue("msg-search-active",[]),J.current={key:null},U.current=j;return}const z=Q.current;let I;if(z){if(I=rs(_,z),I===-1){const L=[];for(let d=0;d<_.length;d++)_[d].msgId===z.msgId&&L.push(d);if(L.length>0){const d=Math.min(z.k,L.length-1);I=L[d]}else I=0}}else I=0;I<0&&(I=0),I>=Z&&(I=Z-1),(!z||z.msgId!==_[I].msgId||z.k!==_[I].k)&&b({msgId:_[I].msgId,k:_[I].k}),H(I);const R=_[I],w=J.current,$=((ie=w.key)==null?void 0:ie.msgId)!==R.msgId||((v=w.key)==null?void 0:v.k)!==R.k||w.kind==="folded"&&R.kind==="dom"||j!==U.current;J.current={key:{msgId:R.msgId,k:R.k},kind:R.kind},U.current=j;const q=_.filter(L=>L.kind==="dom").map(L=>L.range);if(Ue("msg-search",q),R.kind==="folded"){Ue("msg-search-active",[]),$&&c(R.msgId);return}Ue("msg-search-active",[R.range]),$&&(i==null||i(),Zr(C,R.range))}),()=>{M=!0,cancelAnimationFrame(k)}},[a,j,s,t,f,n,r,c,i]);const W=l.useCallback(G=>{const C=V.current,M=C.length;if(M===0)return;const k=Q.current,_=k?rs(C,k):0,Z=C[(_+G+M)%M];b(Z.kind==="dom"||Z.kind==="folded"?{msgId:Z.msgId,k:Z.k}:null)},[]);if(!a)return null;const K=f?(()=>{const G=rs(V.current,f);return G===-1?0:G})():0;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:m,className:"search-input",type:"text",value:y,placeholder:u("searchPlaceholder"),onChange:G=>{x(G.target.value)},onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),W(G.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${T===0?"empty":""}`,children:T===0?u("searchNoResults"):`${Math.min(K+1,T)}/${T}`}),e.jsx("button",{type:"button",className:"search-btn",title:u("searchPrev"),disabled:T===0,onClick:()=>W(-1),children:e.jsx(Tt,{})}),e.jsx("button",{type:"button",className:"search-btn",title:u("searchNext"),disabled:T===0,onClick:()=>W(1),children:e.jsx(Ze,{})}),e.jsx("button",{type:"button",className:"search-btn",title:u("searchClose"),onClick:o,children:e.jsx(Re,{})})]})}function tl(t){const{dSt:s,dSh:n,escaped:r,graceActive:c,stuck:i}=t;return c?{flipEscape:!1,reassert:!1}:s>=-4||s<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:i&&!r}:{flipEscape:!0,reassert:!1}}const Jn=[{id:"setup-matt-pocock-skills",icon:"🛠",titleKey:"tpl.sk.setup",descKey:"tpl.sk.setup.desc",promptKey:"tpl.sk.setup.prompt"},{id:"ask-matt",icon:"🧭",titleKey:"tpl.sk.ask",descKey:"tpl.sk.ask.desc",promptKey:"tpl.sk.ask.prompt"},{id:"grill-with-docs",icon:"🗣",titleKey:"tpl.sk.grilldocs",descKey:"tpl.sk.grilldocs.desc",promptKey:"tpl.sk.grilldocs.prompt"},{id:"to-spec",icon:"📝",titleKey:"tpl.sk.tospec",descKey:"tpl.sk.tospec.desc",promptKey:"tpl.sk.tospec.prompt"},{id:"to-tickets",icon:"🎫",titleKey:"tpl.sk.totickets",descKey:"tpl.sk.totickets.desc",promptKey:"tpl.sk.totickets.prompt"},{id:"implement",icon:"🏗",titleKey:"tpl.sk.implement",descKey:"tpl.sk.implement.desc",promptKey:"tpl.sk.implement.prompt"},{id:"code-review",icon:"🧹",titleKey:"tpl.sk.codeview",descKey:"tpl.sk.codeview.desc",promptKey:"tpl.sk.codeview.prompt"},{id:"wayfinder",icon:"🗺",titleKey:"tpl.sk.wayfinder",descKey:"tpl.sk.wayfinder.desc",promptKey:"tpl.sk.wayfinder.prompt"},{id:"prototype",icon:"🔬",titleKey:"tpl.sk.prototype",descKey:"tpl.sk.prototype.desc",promptKey:"tpl.sk.prototype.prompt"},{id:"research",icon:"📚",titleKey:"tpl.sk.research",descKey:"tpl.sk.research.desc",promptKey:"tpl.sk.research.prompt"},{id:"improve-codebase-architecture",icon:"🏛",titleKey:"tpl.sk.arch",descKey:"tpl.sk.arch.desc",promptKey:"tpl.sk.arch.prompt"},{id:"diagnosing-bugs",icon:"🐛",titleKey:"tpl.sk.debug",descKey:"tpl.sk.debug.desc",promptKey:"tpl.sk.debug.prompt"},{id:"resolving-merge-conflicts",icon:"🔀",titleKey:"tpl.sk.merge",descKey:"tpl.sk.merge.desc",promptKey:"tpl.sk.merge.prompt"},{id:"triage",icon:"🗂",titleKey:"tpl.sk.triage",descKey:"tpl.sk.triage.desc",promptKey:"tpl.sk.triage.prompt"},{id:"wizard",icon:"✨",titleKey:"tpl.sk.wizard",descKey:"tpl.sk.wizard.desc",promptKey:"tpl.sk.wizard.prompt"},{id:"grill-me",icon:"🔍",titleKey:"tpl.sk.grillme",descKey:"tpl.sk.grillme.desc",promptKey:"tpl.sk.grillme.prompt"},{id:"handoff",icon:"🤝",titleKey:"tpl.sk.handoff",descKey:"tpl.sk.handoff.desc",promptKey:"tpl.sk.handoff.prompt"},{id:"to-questionnaire",icon:"📋",titleKey:"tpl.sk.questionnaire",descKey:"tpl.sk.questionnaire.desc",promptKey:"tpl.sk.questionnaire.prompt"},{id:"teach",icon:"🎓",titleKey:"tpl.sk.teach",descKey:"tpl.sk.teach.desc",promptKey:"tpl.sk.teach.prompt"},{id:"wait-what",icon:"💬",titleKey:"tpl.sk.ww",descKey:"tpl.sk.ww.desc",promptKey:"tpl.sk.ww.prompt"},{id:"writing-for-agents",icon:"📄",titleKey:"tpl.sk.wfa",descKey:"tpl.sk.wfa.desc",promptKey:"tpl.sk.wfa.prompt"},{id:"codebase-design",icon:"🧱",titleKey:"tpl.sk.codesign",descKey:"tpl.sk.codesign.desc",promptKey:"tpl.sk.codesign.prompt"},{id:"domain-modeling",icon:"🏷",titleKey:"tpl.sk.domain",descKey:"tpl.sk.domain.desc",promptKey:"tpl.sk.domain.prompt"},{id:"grilling",icon:"🔥",titleKey:"tpl.sk.grilling",descKey:"tpl.sk.grilling.desc",promptKey:"tpl.sk.grilling.prompt"},{id:"tdd",icon:"🧪",titleKey:"tpl.sk.tdd",descKey:"tpl.sk.tdd.desc",promptKey:"tpl.sk.tdd.prompt"}],Xn="pi-web-ui:prompt-templates";function sl(){try{const t=localStorage.getItem(Xn);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(n=>!!n&&typeof n=="object"&&typeof n.id=="string"):[]}catch{return[]}}function on(t){return Jn.some(s=>s.id===t)}function Lt(t){return typeof t.title=="string"}const Zn=l.createContext(null);function ei(){const t=l.useContext(Zn);if(!t)throw new Error("useTemplates must be used within TemplateProvider");return t}function nl({send:t,children:s}){const n=be(),[r,c]=l.useState(sl),[i,a]=l.useState(!1),[o,u]=l.useState(null),[m,y]=l.useState(!1),[x,f]=l.useState(!1),[b,T]=l.useState(!1);l.useEffect(()=>{try{localStorage.setItem(Xn,JSON.stringify(r))}catch{}},[r]);const D=l.useMemo(()=>{const _=new Map,Z=new Set;for(const R of r)R.hidden?Z.add(R.id):(Lt(R)&&!on(R.id)||Lt(R))&&_.set(R.id,R);const z=Jn.filter(R=>!Z.has(R.id)).map(R=>{const w=_.get(R.id);return{id:R.id,icon:(w==null?void 0:w.icon)??R.icon,title:(w==null?void 0:w.title)??n(R.titleKey),desc:(w==null?void 0:w.desc)??n(R.descKey),prompt:(w==null?void 0:w.prompt)??n(R.promptKey),builtin:!0}}),I=r.filter(R=>Lt(R)&&!on(R.id)).map(R=>({id:R.id,icon:R.icon??"📌",title:R.title??"",desc:R.desc??"",prompt:R.prompt??""}));return[...z,...I]},[r,n]),H=l.useCallback(()=>a(!0),[]),N=l.useCallback(_=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:_}))},[]),j=l.useCallback((_,Z=!1)=>{T(Z),_?(y(!1),u({..._})):(y(!0),u({id:Qe(),icon:"📌",title:"",desc:"",prompt:""}))},[]),Q=l.useCallback(()=>{a(!1),u(null),T(!1)},[]),V=l.useCallback(()=>{x?(c([]),f(!1)):(f(!0),setTimeout(()=>f(!1),5e3))},[x]),J=l.useCallback(_=>{a(!1),N(_.prompt)},[N]),U=l.useCallback(_=>{a(!1),j(_,!0)},[j]),W=l.useCallback(()=>{a(!1),j(void 0,!0)},[j]),K=l.useCallback(_=>{c(Z=>{const z=Z.findIndex(I=>I.id===_.id);if(z>=0){const I=[...Z];return I[z]=_,I}return[...Z,_]}),u(null),b&&(a(!0),T(!1))},[b]),G=l.useCallback(_=>{c(Z=>_.builtin?[...Z.filter(I=>I.id!==_.id),{id:_.id,hidden:!0}]:Z.filter(z=>z.id!==_.id)),u(null),b&&(a(!0),T(!1))},[b]),C=l.useCallback(_=>{c(Z=>Z.filter(z=>z.id!==_.id||z.hidden)),u(null),b&&(a(!0),T(!1))},[b]),M=l.useMemo(()=>({templates:D,fill:N,openPicker:H,openEdit:j,resetConfirm:x,toggleReset:V}),[D,N,H,j,x,V]),k=o?r.some(_=>_.id===o.id&&!_.hidden&&Lt(_)):!1;return e.jsxs(Zn.Provider,{value:M,children:[s,i&&e.jsx(al,{templates:D,resetConfirm:x,onFill:J,onEditTpl:U,onNew:W,onResetToggle:V,onClose:Q}),o&&e.jsx(rl,{editing:o,isNew:m,hasOverride:k,onDraft:u,onSave:K,onRestore:()=>C(o),onRemove:()=>G(o),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:o.prompt})),Q()},onSend:()=>{const _=o.prompt.trim();_&&t({type:"prompt",text:_,queue:!1})&&Q()},onClose:Q})]})}function il(){const t=be(),{templates:s,fill:n,openEdit:r,toggleReset:c,resetConfirm:i}=ei();return e.jsxs("div",{className:"empty-templates",children:[e.jsxs("div",{className:"empty-templates-head",children:[e.jsx("span",{className:"empty-templates-title",children:t("tpl.title")}),e.jsx("span",{className:"empty-templates-hint",children:t("tpl.hint")})]}),e.jsxs("div",{className:"empty-templates-grid",children:[s.map(a=>e.jsx(ti,{tpl:a,title:t("tpl.clickCard"),onFill:()=>n(a.prompt),onEdit:()=>r(a),editTitle:t("tpl.editTpl")},a.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>r(),title:t("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(Ke,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:t("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"empty-templates-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:c,children:[e.jsx(Sn,{}),t(i?"tpl.resetConfirm":"tpl.reset")]})})]})}function ti({tpl:t,title:s,onFill:n,onEdit:r,editTitle:c}){const i=be();return e.jsxs("button",{type:"button",className:"empty-template",title:s,onClick:n,children:[e.jsx("span",{className:"empty-template-icon",children:t.icon}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t.title}),e.jsx("span",{className:"empty-template-desc",children:t.desc})]}),e.jsx("span",{className:"template-card-ops",role:"button",title:c??i("tpl.editTpl"),onClick:a=>{a.stopPropagation(),r()},children:e.jsx(Kt,{})})]})}function al({templates:t,resetConfirm:s,onFill:n,onEditTpl:r,onNew:c,onResetToggle:i,onClose:a}){const o=be();return l.useEffect(()=>{const u=m=>{m.key==="Escape"&&a()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[a]),e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"modal template-picker",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"template-picker-head",children:[e.jsx("span",{className:"template-picker-title",children:o("tpl.pickerTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:o("close"),onClick:a,children:e.jsx(Re,{})})]}),e.jsx("div",{className:"template-picker-hint",children:o("tpl.pickerHint")}),e.jsxs("div",{className:"template-picker-grid",children:[t.map(u=>e.jsx(ti,{tpl:u,title:o("tpl.clickCard"),onFill:()=>n(u),onEdit:()=>r(u),editTitle:o("tpl.editTpl")},u.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:c,title:o("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(Ke,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:o("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:o("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"template-picker-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:i,children:[e.jsx(Sn,{}),o(s?"tpl.resetConfirm":"tpl.reset")]})})]})})}function rl({editing:t,isNew:s,hasOverride:n,onDraft:r,onSave:c,onRestore:i,onRemove:a,onFill:o,onSend:u,onClose:m}){const y=be(),x=l.useRef(null);l.useEffect(()=>{const T=D=>{D.key==="Escape"&&m()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[m]),l.useEffect(()=>{const T=x.current;if(!T)return;T.style.height="auto";const D=T.scrollHeight>300;T.style.height=`${Math.min(T.scrollHeight,300)}px`,T.style.overflowY=D?"auto":"hidden"},[t.prompt]);const f=()=>{const T=t.title.trim(),D=t.prompt.trim();if(!T||!D){r({...t,error:y("tpl.required")});return}c({id:t.id,icon:t.icon.trim()||"📌",title:T,desc:t.desc.trim(),prompt:D})},b=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:m,children:e.jsxs("div",{className:"modal template-modal",onClick:T=>T.stopPropagation(),children:[e.jsxs("div",{className:"template-modal-head",children:[e.jsx("span",{className:"template-modal-icon",children:t.icon}),e.jsx("span",{className:"template-modal-badge",children:y(b?"tpl.builtin":"tpl.custom")}),e.jsx("span",{className:"template-modal-title",children:y(s?"tpl.newTitle":"tpl.editTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:y("close"),onClick:m,children:e.jsx(Re,{})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:y("tpl.fieldIcon")}),e.jsx("input",{className:"template-field-input icon",value:t.icon,maxLength:4,onChange:T=>r({...t,icon:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:y("tpl.fieldTitle")}),e.jsx("input",{className:"template-field-input",value:t.title,placeholder:y("tpl.fieldTitlePh"),onChange:T=>r({...t,title:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:y("tpl.fieldDesc")}),e.jsx("input",{className:"template-field-input",value:t.desc,placeholder:y("tpl.fieldDescPh"),onChange:T=>r({...t,desc:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:y("tpl.fieldPrompt")}),e.jsx("textarea",{ref:x,className:"template-field-prompt",value:t.prompt,placeholder:y("tpl.fieldPromptPh"),onChange:T=>r({...t,prompt:T.target.value})})]}),t.error&&e.jsx("div",{className:"template-error",children:t.error}),e.jsxs("div",{className:"template-modal-actions",children:[e.jsxs("div",{className:"template-modal-actions-left",children:[!s&&b&&n&&e.jsx("button",{type:"button",className:"btn template-btn ghost",title:y("tpl.restoreTip"),onClick:i,children:y("tpl.restore")}),!s&&b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:y("tpl.removeTip"),onClick:a,children:[e.jsx(He,{})," ",y("tpl.remove")]}),!s&&!b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:y("tpl.deleteTip"),onClick:a,children:[e.jsx(He,{})," ",y("tpl.delete")]})]}),e.jsxs("div",{className:"template-modal-actions-right",children:[e.jsx("button",{type:"button",className:"btn template-btn",onClick:f,children:y("tpl.save")}),e.jsx("button",{type:"button",className:"btn template-btn fill",onClick:o,title:y("tpl.fillTip"),children:y("tpl.fill")}),e.jsxs("button",{type:"button",className:"btn template-btn send",onClick:u,title:y("tpl.sendTip"),children:[e.jsx(Cn,{})," ",y("tpl.sendNow")]})]})]})]})})}const cn=new Map,ll=15,dn=30,ls=250,un=1200,ol=1600;function pn(t){return t.content.some(s=>s.type==="toolCall")}function cl({state:t,liveOutputs:s,toolStatuses:n,onEdit:r,onKillBash:c,onRemoveQueued:i,thinkingWrap:a,toolsWrap:o,jumpTarget:u,onJumpDone:m}){const y=be(),x=l.useRef(null),[f,b]=l.useState(!0),T=l.useRef(!0),D=l.useRef(0),H=l.useRef(0),N=l.useRef(!1),j=l.useRef(0),[Q,V]=l.useState(()=>new Set),[J,U]=l.useState(!1),W=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,K=l.useMemo(()=>{const S=new Map;for(const B of t.messages)B.role==="toolResult"&&B.toolCallId&&S.set(B.toolCallId,B);return S},[t.messages]),G=l.useMemo(()=>_r(t.messages),[t.messages]),C=W.length>0?W[W.length-1].id:null,M=t.messages.length>dn?Math.max(0,t.messages.length-ll):0,k=l.useMemo(()=>{const S=new Set;for(let B=0;B<M;B++){const oe=t.messages[B];oe.role!=="toolResult"&&(Q.has(oe.id)||S.add(oe.id))}return S},[t.messages,M,Q]),[_,Z]=l.useState(()=>new Set),[z,I]=l.useState(()=>new Set),R=l.useRef(new Map),w=l.useRef(new Map),$=l.useRef(new Map),q=l.useRef(0),ie=l.useMemo(()=>{const S=new Map;for(const B of t.messages)S.set(B.id,Kr(B));return S},[t.messages]),v=l.useRef(ie);v.current=ie;const L=l.useRef(_);L.current=_;const d=t.messages.length>dn&&!J,E=l.useRef(d);E.current=d;const h=Wr(t.messages,R.current,ol),A=l.useRef(h);A.current=h;const ee=l.useCallback(()=>{const S=x.current;if(!S)return;if(!E.current){Z(we=>we.size?new Set:we);return}const B=S.getBoundingClientRect(),oe={top:B.top-un,bottom:B.bottom+un},ce=[];for(const[we,Ie]of $.current){const Oe=Ie.getBoundingClientRect();ce.push({id:we,top:Oe.top,bottom:Oe.bottom}),L.current.has(we)||X(we,Oe.bottom-Oe.top,v.current.get(we))}const je=Hr(ce,oe,A.current,L.current);for(const we of je.hide){const Ie=$.current.get(we);Ie&&X(we,Ie.offsetHeight,v.current.get(we))}Z(we=>Or(we,je))},[]),Y=l.useCallback(()=>{q.current||(q.current=requestAnimationFrame(()=>{q.current=0,ee()}))},[ee]);l.useLayoutEffect(()=>{ee()},[ee]);const se=l.useRef(J);l.useLayoutEffect(()=>{se.current&&!J&&ee(),se.current=J},[J,ee]);const X=l.useCallback((S,B,oe)=>{oe!==void 0&&(w.current.set(S,{h:B,len:oe}),R.current.set(S,B))},[]),ge=l.useCallback((S,B)=>{X(S,B,v.current.get(S))},[X]),Ne=l.useCallback(S=>{S&&$.current.set(S.dataset.lazyId??"",S)},[]);l.useEffect(()=>{const S=new Set(t.messages.map(B=>B.id));for(const B of $.current.keys())S.has(B)||($.current.delete(B),R.current.delete(B),w.current.delete(B));Z(B=>{let oe=!1;const ce=new Set;for(const je of B)S.has(je)?ce.add(je):oe=!0;return oe?ce:B})},[t.messages,Q]),l.useEffect(()=>()=>cancelAnimationFrame(q.current),[]);const de=l.useMemo(()=>{const S=[];for(const B of t.messages){if(B.role!=="user")continue;const oe=B.content.map(we=>{var Ie;return((Ie=Ct(we))==null?void 0:Ie.text)??""}).filter(Boolean).join(" "),ce=Ms(oe),je=ce?ce.userMessage??`skill:${ce.name}`:oe.trim();je&&S.push({id:B.id,text:je})}return S},[t.messages]),Ee=l.useMemo(()=>{const S=new Map;return de.forEach((B,oe)=>S.set(B.id,oe)),S},[de]),[le,g]=l.useState(-1),O=l.useRef(-1),me=l.useRef(de);l.useEffect(()=>{me.current=de},[de]);const ue=l.useCallback(()=>{const S=x.current,B=me.current;if(!S||B.length===0)return;const oe=S.getBoundingClientRect().top,ce=140;let je=-1;for(let we=0;we<B.length;we++){const Ie=S.querySelector(`[data-msg-id="${B[we].id}"]`);if(Ie)if(Ie.getBoundingClientRect().top<=oe+ce)je=we;else break}je!==O.current&&(O.current=je,g(je))},[]);l.useEffect(()=>{ue()},[de,ue]);const ye=l.useCallback(S=>{V(B=>B.has(S)?B:new Set(B).add(S))},[]);l.useEffect(()=>{const S=B=>{if(!(B.ctrlKey||B.metaKey)||B.key.toLowerCase()!=="f")return;const oe=B.target;oe&&(oe.tagName==="INPUT"||oe.tagName==="TEXTAREA"||oe.isContentEditable)||(B.preventDefault(),U(!0))};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[]);const fe=l.useCallback(S=>{V(B=>{if(!B.has(S))return B;const oe=new Set(B);return oe.delete(S),oe})},[]),ke=l.useCallback(S=>{const B=t.messages.findIndex(ce=>ce.id===S);Xa.flushSync(()=>{B>=0&&B<M&&!Q.has(S)&&ye(S),I(ce=>ce.has(S)?ce:new Set(ce).add(S))});const oe=me.current.findIndex(ce=>ce.id===S);O.current=oe,g(oe),requestAnimationFrame(()=>{var je,we,Ie;const ce=(je=x.current)==null?void 0:je.querySelector(`[data-msg-id="${S}"]`);ce&&((we=x.current)==null||we.querySelectorAll(".msg-flash").forEach(Oe=>Oe.classList.remove("msg-flash")),ce.scrollIntoView({block:"start"}),ce.classList.remove("msg-flash"),ce.offsetWidth,ce.classList.add("msg-flash"),ce!==((Ie=x.current)==null?void 0:Ie.lastElementChild)&&(N.current=!0))})},[t.messages,M,Q,ye]),Le=l.useMemo(()=>{var S;return u?((S=t.messages.find(B=>B.role===u.role&&B.timestamp===u.timestamp))==null?void 0:S.id)??null:null},[t.messages,u]);l.useEffect(()=>{if(u){if(Le){ke(Le),m==null||m();return}t.sessionFile===u.path&&t.messages.length>0&&(m==null||m())}},[Le,ke,m,u,t.sessionFile,t.messages.length]);const ae=l.useCallback(()=>{const S=x.current;if(!S)return;const B=S.scrollTop-D.current,oe=S.scrollHeight-H.current;D.current=S.scrollTop,H.current=S.scrollHeight;const ce=S.scrollHeight-S.scrollTop-S.clientHeight<80,je=Date.now()<j.current,we=tl({dSt:B,dSh:oe,escaped:N.current,graceActive:je,stuck:T.current});we.reassert&&(j.current=Date.now()+ls,S.scrollTop=S.scrollHeight),we.flipEscape&&(N.current=!0),ce&&B>=0&&(N.current=!1),je||(B<0?T.current=ce&&!N.current:ce&&(T.current=!0)),b(T.current),ue(),Y()},[ue,Y]),De=l.useRef(!1);l.useEffect(()=>{const S=De.current;if(De.current=!!t.isStreaming,S&&!t.isStreaming&&!N.current){const B=()=>{const ce=x.current;ce&&!N.current&&(ce.scrollTop=ce.scrollHeight,T.current=!0,b(!0))};requestAnimationFrame(()=>requestAnimationFrame(B));const oe=setTimeout(B,180);return()=>clearTimeout(oe)}},[t.isStreaming]),l.useEffect(()=>{const S=x.current;S&&T.current&&(S.scrollTop=S.scrollHeight)},[W,t.isStreaming,s]);const Ae=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");l.useEffect(()=>{const S=x.current;S&&T.current&&(S.scrollTop=S.scrollHeight)},[Ae]),l.useEffect(()=>{const S=x.current;if(!S||typeof ResizeObserver>"u")return;const B=new ResizeObserver(()=>{T.current&&!N.current&&(S.scrollTop=S.scrollHeight,b(!0))});return B.observe(S),()=>B.disconnect()},[]),l.useEffect(()=>{const S=x.current;if(!S||typeof MutationObserver>"u")return;let B=!1;const oe=new MutationObserver(()=>{B||(B=!0,requestAnimationFrame(()=>{B=!1;const ce=x.current;ce&&T.current&&!N.current&&(ce.scrollTop=ce.scrollHeight,b(!0))}))});return oe.observe(S,{childList:!0,subtree:!0,characterData:!0}),()=>oe.disconnect()},[]);const qe=l.useCallback(()=>{if(!x.current)return;T.current=!0,N.current=!1,b(!0),j.current=Date.now()+ls;const B=()=>{const oe=x.current;!oe||!T.current||N.current||(j.current=Date.now()+ls,oe.scrollTop=oe.scrollHeight)};B(),requestAnimationFrame(()=>requestAnimationFrame(B)),setTimeout(B,120),setTimeout(B,300),setTimeout(B,600)},[]),ze=l.useRef(null);l.useEffect(()=>{const S=ze.current,B=x.current;if(!S||!B)return;const oe=ce=>{ce.preventDefault();const je=S.querySelector(".qn-list");if(je&&je.contains(ce.target)&&je.scrollHeight>je.clientHeight){je.scrollTop+=ce.deltaY;return}B.scrollTop+=ce.deltaY};return S.addEventListener("wheel",oe,{passive:!1}),()=>S.removeEventListener("wheel",oe)},[]);const[P,xe]=l.useState(0);l.useEffect(()=>{const S=()=>{var B;xe(((B=x.current)==null?void 0:B.clientHeight)??0),Y()};return S(),window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[Y]);const pe=de.length,Se=l.useMemo(()=>pe===0?27:Math.max(4,Math.min(27,Math.floor(((P||600)-16)/pe)-3)),[pe,P]),ve=Se<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:`messages${J||f?"":" anchor-live"}`,ref:x,onScroll:ae,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(il,{})}),t.messages.map((S,B)=>{const oe=B<M,ce=oe&&Q.has(S.id);if(oe&&!ce)return S.role==="toolResult"?null:e.jsx(Br,{message:S,onExpand:ye},S.id);const je=S.role==="user"?Ee.get(S.id):void 0,we=!d||h.has(S.id)||z.has(S.id)||!_.has(S.id);return e.jsx($r,{id:S.id,show:we,height:qr(S.id,ie.get(S.id)??-1,w.current,Yn(S.role,S.customType)),containerRef:x,onMeasured:ge,lazyRef:Ne,children:e.jsx(nn,{message:S,qnIndex:je,qnActive:je!==void 0?je===le:void 0,onJump:ke,toolResults:K,liveOutputs:pn(S)?s:cn,toolStatuses:n,streaming:t.isStreaming,onKillBash:c,toolsWrap:o,thinkingWrap:a,isLast:S.id===C,onEdit:r,questionAttachments:G.get(S.id),onCollapse:ce?fe:void 0,searchActive:J},S.id)},S.id)}),t.streamingMessage&&e.jsx(nn,{message:t.streamingMessage,toolResults:K,liveOutputs:pn(t.streamingMessage)?s:cn,toolStatuses:n,streaming:!0,isLast:!0,onEdit:r,onKillBash:c,toolsWrap:o,thinkingWrap:a,searchActive:J},t.streamingMessage.id),t.isStreaming&&W.length===0&&e.jsx("div",{className:"streaming-wait",children:y("waitingResponse")}),t.queue.steering.map((S,B)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:y("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:S}),i&&e.jsx("button",{type:"button",className:"queued-remove",title:y("queueRemoveTip"),onClick:()=>i("steer",S),children:"✕"})]})},`q-steer-${B}`)),t.queue.followUp.map((S,B)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:y("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:S}),i&&e.jsx("button",{type:"button",className:"queued-remove",title:y("queueRemoveTip"),onClick:()=>i("followUp",S),children:"✕"})]})},`q-fu-${B}`))]}),!f&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:qe,children:[e.jsx(Rn,{})," ",y("backToBottom")]}),e.jsx(el,{containerRef:x,messages:W,collapsedIds:k,toolResults:K,onExpand:ye,onProgrammaticScroll:()=>{N.current=!0,T.current=!1,b(!1)},open:J,onClose:()=>U(!1)}),de.length>0&&e.jsxs("div",{className:`qn-rail ${ve?"many":""}`,ref:ze,"aria-label":y("questionNavTitle"),style:{"--rail-gap":`${Se}px`},children:[de.map((S,B)=>e.jsx("button",{type:"button",className:`qn-bar ${B===le?"active":""}`,"aria-label":`${B+1}. ${S.text}`,onClick:()=>ke(S.id),children:e.jsxs("span",{className:"qn-bar-text",children:[B+1,". ",S.text]})},S.id)),ve&&e.jsx("div",{className:"qn-list",children:de.map((S,B)=>e.jsxs("button",{type:"button",className:`qn-list-item ${B===le?"active":""}`,"aria-label":`${B+1}. ${S.text}`,onClick:()=>ke(S.id),children:[e.jsx("span",{className:"qn-list-idx",children:B+1}),e.jsx("span",{className:"qn-list-text",children:S.text})]},S.id))})]})]})}const si="pi-web-model-usage";function dl(t){if(!t||typeof t!="object")return{};const s={};for(const[n,r]of Object.entries(t)){const c=typeof r=="number"?Math.floor(r):0;Number.isFinite(c)&&c>0&&(s[n]=c)}return s}function ul(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function pl(t,s){const n=s;return t.map((r,c)=>({m:r,i:c,count:n[r.id]??0})).sort((r,c)=>c.count-r.count||r.i-c.i).map(r=>r.m)}function ni(){try{const t=localStorage.getItem(si);return t?dl(JSON.parse(t)):{}}catch{return{}}}function ml(t){try{localStorage.setItem(si,JSON.stringify(t))}catch{}}function hl(t){const s=ul(ni(),t);return ml(s),s}const Is="pi-web-ui:prompt-history",gl=100,ii="pi-web-ui:prompt-history-settings",ws={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function ai(t){const s=ws;if(!t||typeof t!="object")return{...s};const n=t;let r=typeof n.maxEntries=="number"?Math.floor(n.maxEntries):s.maxEntries;(!Number.isFinite(r)||r<1)&&(r=1),r>500&&(r=500);let c=typeof n.charLimit=="number"?Math.floor(n.charLimit):s.charLimit;(!Number.isFinite(c)||c<100)&&(c=100),c>2e4&&(c=2e4);const i=typeof n.charLimitEnabled=="boolean"?n.charLimitEnabled:s.charLimitEnabled;return{maxEntries:r,charLimitEnabled:i,charLimit:c}}function ri(){try{const t=localStorage.getItem(ii);return t?ai(JSON.parse(t)):{...ws}}catch{return{...ws}}}function os(t){const s=ai(t);try{localStorage.setItem(ii,JSON.stringify(s))}catch{}try{let n=St();s.charLimitEnabled&&(n=n.map(r=>r.length>s.charLimit?r.slice(0,s.charLimit):r)),n.length>s.maxEntries&&(n=n.slice(n.length-s.maxEntries)),li(n)}catch{}}function fl(t){if(!Array.isArray(t))return[];const s=[];for(const n of t){if(typeof n!="string")continue;const r=n.trim();r&&s.push(r)}return s}function xl(t,s,n=gl){const r=s.trim();if(!r||t.length>0&&t[t.length-1]===r)return t;const c=[...t,r];return c.length>n?c.slice(c.length-n):c}function St(){try{const t=localStorage.getItem(Is);return t?fl(JSON.parse(t)):[]}catch{return[]}}function li(t){let s=t;for(;s;)try{localStorage.setItem(Is,JSON.stringify(s));return}catch(n){if(!(n instanceof DOMException&&(n.name==="QuotaExceededError"||n.code===22))||s.length<=1)return;s=s.slice(Math.ceil(s.length/2))}}function yl(t){let s=t.trim();if(!s)return;const n=ri();n.charLimitEnabled&&s.length>n.charLimit&&(s=s.slice(0,n.charLimit));const r=St(),c=xl(r,s,n.maxEntries);c!==r&&li(c)}function vl(){try{localStorage.removeItem(Is)}catch{}}const bl=["off","minimal","low","medium","high","xhigh","max"],kl=l.memo(function({state:s,models:n,modelsLoading:r,send:c,onManageModels:i,providerKeys:a,compact:o=!1}){const u=be(),m=s==null?void 0:s.model,y=m?`${m.provider}/${m.id}`:null,[x,f]=l.useState(!1),[b,T]=l.useState(!1),[D,H]=l.useState(""),[N,j]=l.useState(null),[Q,V]=l.useState({}),J=l.useRef(null),U=l.useRef(null),[W,K]=l.useState(null);l.useEffect(()=>{if(!x){K(null);return}if(n.length===0)return;const w=requestAnimationFrame(()=>{const $=U.current;$&&K($.offsetWidth)});return()=>cancelAnimationFrame(w)},[x,n.length]),l.useEffect(()=>{x&&V(ni())},[x]),l.useEffect(()=>{x||(H(""),j(null))},[x]);const G=l.useMemo(()=>{const w=new Map;for(const q of n)w.set(q.provider,(w.get(q.provider)??0)+1);const $=[];for(const[q,ie]of[...w.entries()].sort((v,L)=>v[0].localeCompare(L[0]))){const v=a[q];if(v&&v.length>1)for(const L of v)$.push({provider:q,keyName:L.name,count:ie});else $.push({provider:q,keyName:null,count:ie})}return $},[n,a]),C=l.useMemo(()=>pl(n,Q),[n,Q]),M=l.useMemo(()=>{let w=C;N&&(w=w.filter(q=>q.provider===N.provider));const $=D.trim().toLowerCase();return $?w.filter(q=>q.name.toLowerCase().includes($)||q.provider.toLowerCase().includes($)||q.id.toLowerCase().includes($)):w},[C,D,N]),k=l.useMemo(()=>{const w=[];for(const $ of M){const q=a[$.provider];if(!q||q.length<=1){w.push({model:$,key:null});continue}let ie=q.find(v=>v.active)??q[0];if((N==null?void 0:N.provider)===$.provider&&N.keyName){const v=q.find(L=>L.name===N.keyName);v&&(ie=v)}w.push({model:$,key:ie})}return w},[M,a,N]),[_,Z]=l.useState(!1),z=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,I=bl.map(w=>({value:w,label:u(`thinking.${w}`),supported:z?z.has(w):!0})),R=w=>{var $;return(($=I.find(q=>q.value===w))==null?void 0:$.label)??w};return l.useEffect(()=>{x&&n.length===0&&!_&&!r&&(Z(!0),c({type:"list_models"}))},[x,n.length,_,r,c]),l.useEffect(()=>{n.length>0&&Z(!1)},[n.length]),l.useEffect(()=>{var $;if(!x)return;const w=($=J.current)==null?void 0:$.querySelector(".dd-item.active");w==null||w.scrollIntoView({block:"nearest"})},[x,y,n.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(wt,{}),e.jsx("span",{className:"chip-model",children:m?m.name:u("selectModel")}),!o&&(m==null?void 0:m.vision)&&e.jsx("span",{className:"chip-vision",title:u("vision"),children:"🖼"}),!o&&m&&e.jsx("span",{className:"chip-sub",children:m.provider})]}),open:x,onOpenChange:f,menuClassName:"dd-menu-model",menuRef:U,menuStyle:W!=null?{width:W}:void 0,direction:"up",children:[e.jsx("div",{className:"dd-header",children:u("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(Wt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:u("searchModels"),value:D,onChange:w=>H(w.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[G.length>1&&e.jsxs("div",{className:"dd-provider-col",children:[e.jsx("div",{className:"dd-provider-head",children:u("providers")}),e.jsx("button",{type:"button",className:`dd-provider-item ${N===null?"active":""}`,onClick:()=>j(null),children:e.jsx("span",{children:u("allProviders")})}),G.map(w=>{const $=(N==null?void 0:N.provider)===w.provider&&(N==null?void 0:N.keyName)===w.keyName;return e.jsxs("button",{type:"button",className:`dd-provider-item ${$?"active":""}`,onClick:()=>j($?null:{provider:w.provider,keyName:w.keyName}),title:w.keyName?`${w.provider} · ${w.keyName}`:`${w.provider} · ${w.count}`,children:[e.jsxs("span",{className:"dd-provider-txt",children:[e.jsx("span",{className:"dd-provider-name",children:w.provider}),w.keyName&&e.jsx("span",{className:"dd-provider-key",children:w.keyName})]}),e.jsx("span",{className:"dd-provider-count",children:w.count})]},w.keyName?`${w.provider}::${w.keyName}`:w.provider)})]}),e.jsxs("div",{className:"dd-model-scroll",ref:J,children:[(_||r)&&e.jsx("div",{className:"dd-loading",children:u("loading")}),n.length===0&&!_&&!r&&e.jsx("div",{className:"dd-loading",children:u("noModels")}),M.length===0&&n.length>0&&e.jsx("div",{className:"dd-loading",children:u("noModelMatches")}),k.map(w=>{const $=w.model,q=y===$.id&&(!w.key||w.key.active);return e.jsx($e,{active:q,onClick:()=>{w.key&&!w.key.active&&c({type:"activate_provider_key",provider:$.provider,keyName:w.key.name}),y!==$.id&&c({type:"set_model",modelId:$.id}),f(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:$.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:$.provider}),w.key&&e.jsxs("span",{className:`dd-model-key ${w.key.active?"active":""}`,children:[w.key.active?"●":"○"," ",w.key.name]}),(Q[$.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:u("modelUsedCount",{n:Q[$.id]})}),($.reasoning||$.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[$.reasoning&&e.jsx("span",{className:"dd-model-badge",children:u("reasoning")}),$.vision&&e.jsx("span",{className:"dd-model-badge",children:u("vision")})]})]})]})},w.key?`${$.id}::${w.key.name}`:$.id)})]})]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>c({type:"list_models"}),children:u("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{f(!1),i()},children:u("manageModels")})]})]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Dt,{}),e.jsx("span",{className:"chip-sub",children:u("thinkingChip",{level:s?R(s.thinkingLevel):"—"})})]}),open:b,onOpenChange:T,direction:"up",children:[e.jsx("div",{className:"dd-header",children:u("thinkingLevel")}),I.map(w=>e.jsx($e,{active:(s==null?void 0:s.thinkingLevel)===w.value,disabled:!w.supported,title:w.supported?void 0:u("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==w.value&&c({type:"set_thinking",level:w.value}),T(!1)},children:w.label},w.value))]})]})}),jl=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches,wl=l.memo(function({ready:s,streaming:n,messages:r,slashCommands:c,modelState:i,models:a,modelsLoading:o,send:u,attachments:m,onRemoveAttachment:y,onAddImageFiles:x,onAddLocalFiles:f,onNotice:b,onSent:T,onManageModels:D,providerKeys:H}){const N=be(),{locale:j}=Pt(),{openPicker:Q}=ei(),V=g=>j==="en"&&g.descriptionEn?g.descriptionEn:g.description??"",J=g=>j==="en"&&g.argumentHintEn?g.argumentHintEn:g.argumentHint??"",[U,W]=l.useState(""),[K,G]=l.useState(!1),[C,M]=l.useState(null),[k,_]=l.useState(0),[Z,z]=l.useState(!1),[I,R]=l.useState(void 0),w=l.useRef(null),$=l.useRef(null),q=l.useRef(null),ie=l.useRef(-1),v=l.useRef(""),L={builtin:N("slashBuiltin"),extension:N("slashExtension"),prompt:N("slashPrompt"),skill:N("slashSkill"),plugin:N("slashPlugin")},d=g=>{const O=g.match(/^\/([^\s]*)$/);if(O&&s){const me=O[1].toLowerCase(),ue=c.filter(ye=>ye.name.toLowerCase().startsWith(me));M(ue.length>0?ue:null),_(0)}else M(null)};l.useEffect(()=>{var O;const g=(O=q.current)==null?void 0:O.querySelector(".slash-item.active");g==null||g.scrollIntoView({block:"nearest"})},[k,C]);const E=g=>{var fe;const O=C??[],me=g??O[k%Math.max(O.length,1)];if(!me){M(null);return}const ue=U.match(/^\/([^\s]*)([\s\S]*)$/),ye=ue?ue[2]:"";W(`/${me.name} ${ye}`),M(null),(fe=w.current)==null||fe.focus()},h=async()=>{const O=[...r].reverse().find(ue=>ue.role==="assistant"&&ue.content.some(ye=>ye.type==="text"&&ye.text)),me=O==null?void 0:O.content.filter(ue=>ue.type==="text").map(ue=>ue.text).join(`
|
|
321
|
-
`);if(!me){b("warning",N("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(me),b("info",N("slashCopied"))}catch{b("error",N("slashCopyFailed"))}},A=g=>{if(!g||g.length===0){b("warning",N("foldersNotSupported"));return}const O=Array.from(g).filter(ye=>Ge(ye.type)),me=Array.from(g).filter(ye=>!Ge(ye.type)),ue=Y();O.length>0&&ue?b("warning",ue):O.length>0&&
|
|
311
|
+
`),inFence:c!==null}}const br=l.memo(function({text:s}){return e.jsx(Ms,{text:s})}),an=200;function kr({text:t,inFence:s}){const[n,r]=l.useState(t),c=l.useRef(0),i=l.useRef(null);return l.useEffect(()=>{if(s)return;const a=Date.now()-c.current,o=()=>{c.current=Date.now(),r(t)};if(a>=an){o();return}return i.current=setTimeout(o,an-a),()=>{i.current&&clearTimeout(i.current)}},[t,s]),s?e.jsx("div",{className:"codeblock",children:e.jsx("pre",{children:e.jsx("code",{children:t})})}):e.jsx(Ms,{text:n})}const jr=l.memo(function({text:s}){const{frozen:n,active:r,inFence:c}=l.useMemo(()=>vr(s),[s]);return e.jsxs("div",{className:"md",children:[n.map((i,a)=>e.jsx(br,{text:i},a)),r.length>0&&e.jsx(kr,{text:r,inFence:c},n.length)]})});function wr({thinking:t,streaming:s,wrap:n=!0,forceOpen:r=!1}){const c=be(),[i,a]=l.useState(null),o=i??n,u=o||r,m=s?t.trimEnd().slice(-80):t.split(`
|
|
312
|
+
`)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${u?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>a(!o),children:[u?e.jsx(Ze,{}):e.jsx(Gt,{}),e.jsx(Nt,{className:"thinking-icon"}),e.jsx("span",{className:"thinking-label",children:s&&u?e.jsxs("span",{className:"thinking-live-label",children:[c("thinkingNow"),e.jsx("span",{className:"dots"})]}):u?c("thinking"):c("thinkingPreview",{preview:m})})]}),u&&e.jsx("div",{className:"thinking-body",children:t})]})}const Nr={bash:"$",read:"📄",write:"✍️",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function Cr(t){return Nr[t]??"🛠"}const Sr=l.memo(function({block:s,view:n,onKillBash:r,wrap:c=!0,forceOpen:i=!1}){var K,G,C,M;const a=be(),[o,u]=l.useState(c),m=o||i,[f,y]=l.useState(!1),x=!n.result&&n.streaming&&!n.status,b=s.name==="bash"&&x,T=n.result!==void 0,D=!n.result&&!!n.status,H=((K=n.result)==null?void 0:K.isError)??((G=n.status)==null?void 0:G.isError)??!1,j=(n.result?n.result.content.map(k=>k.type==="text"?k.text:"").join(""):n.liveOutput??"").replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(k,_)=>a("liveOutputOmitted",{n:_})),Q=H?"err":T?"ok":x||D?"run":"idle";let V=a(H?"error":T?"done":x?"running":D?"toolDoneWaitingModel":"toolQueued");const J=D&&((C=n.status)==null?void 0:C.durationMs)!==void 0?Er(n.status.durationMs):"";D&&J&&(V=`${V} · ${J}`);const U=D&&((M=n.status)==null?void 0:M.exitCode)!==void 0?`exit ${n.status.exitCode}`:"",W=()=>{s.argumentsText&&(navigator.clipboard.writeText(s.argumentsText),y(!0),setTimeout(()=>y(!1),1200))};return e.jsxs("div",{className:`toolcall ${Q}`,children:[e.jsxs("div",{className:"toolcall-head",children:[e.jsx("span",{className:"toolcall-icon",children:Cr(s.name)}),e.jsx("span",{className:"toolcall-name",children:s.name}),e.jsxs("span",{className:"toolcall-status",children:[V,U&&e.jsx("em",{className:"toolcall-exit",children:U})]}),e.jsx("span",{className:"toolcall-spacer"}),b&&r&&e.jsxs("button",{type:"button",className:"toolcall-kill",title:a("stopBashTip"),onClick:r,children:[e.jsx(Ot,{}),e.jsx("span",{children:a("stopBash")})]}),e.jsx("button",{type:"button",className:"toolcall-copy",title:a("copyArgs"),onClick:W,children:f?e.jsx(na,{}):e.jsx(En,{})}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>u(k=>i?!0:!k),children:m?e.jsx(Ze,{}):e.jsx(Gt,{})})]}),m&&e.jsxs("div",{className:"toolcall-body",children:[s.argumentsText&&e.jsx("div",{className:"toolcall-args",children:s.name==="bash"&&s.argumentsText.startsWith("{")?e.jsx(Tr,{args:s.argumentsText}):e.jsx("pre",{children:s.argumentsText})}),j.length>0&&e.jsxs("div",{className:"toolcall-output",children:[e.jsxs("div",{className:"toolcall-output-label",children:[a(H?"errorOutput":"output"),(x||D)&&e.jsx("span",{className:"cursor"})]}),e.jsx("pre",{children:j})]}),x&&j.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",a("waitingOutput")]}),D&&j.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",a("waitingModel")]})]})]})});function Tr({args:t}){let s=null;try{s=JSON.parse(t)}catch{return e.jsx("pre",{children:t})}return typeof s.command!="string"?e.jsx("pre",{children:t}):e.jsxs("div",{className:"termline",children:[e.jsx(ct,{className:"termline-icon"}),e.jsx("code",{children:s.command}),typeof s.timeout=="number"&&e.jsxs("span",{className:"termline-timeout",children:["⏱ ",s.timeout,"s"]})]})}function Er(t){if(t===void 0)return"";const s=t/1e3;if(s<60)return`${s.toFixed(1)}s`;const n=Math.floor(s/60),r=Math.round(s%60);return`${n}m ${String(r).padStart(2,"0")}s`}const Pr=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function Is(t){var n;const s=t.match(Pr);return s?{name:s[1],location:s[2],content:s[3],userMessage:((n=s[4])==null?void 0:n.trim())||void 0}:null}const Mr=1568,Ir=2*1024*1024;function Ge(t){return t.startsWith("image/")&&t!=="image/svg+xml"&&t!=="image/svg"}async function Vn(t){if(!t.type.startsWith("image/"))return null;let s;try{s=await createImageBitmap(t,{imageOrientation:"from-image"})}catch{return null}try{const n=Math.min(1,Mr/Math.max(s.width,s.height)),r=Math.max(1,Math.round(s.width*n)),c=Math.max(1,Math.round(s.height*n)),i=t.type==="image/jpeg"||t.type==="image/jpg"?[["image/jpeg",.85],["image/jpeg",.6],["image/webp",.8]]:[["image/png",1],["image/jpeg",.85],["image/jpeg",.6]];let a=null;for(const[o,u]of i){const m=document.createElement("canvas");m.width=r,m.height=c;const f=m.getContext("2d");if(!f)continue;o!=="image/png"&&(f.fillStyle="#ffffff",f.fillRect(0,0,r,c)),f.drawImage(s,0,0,r,c);const y=m.toDataURL(o,u),x=y.match(/^data:([^;]+);base64,/),b=x?x[1]:o,T=y.replace(/^data:[^;]*;base64,/,""),D=Math.floor(T.length*3/4);if(a={data:T,mimeType:b,name:t.name,size:D},D<=Ir)return a}return a}finally{s.close()}}const Rr=20*1024*1024;function St(t){return t.type==="text"&&typeof t.text=="string"?t:null}function Gn(t){return t.type==="thinking"&&typeof t.thinking=="string"?t:null}function Qn(t){return t.type==="toolCall"&&typeof t.id=="string"&&typeof t.name=="string"?t:null}function Yn(t){return t.type==="image"&&typeof t.dataUrl=="string"?t:null}function Jn(t){return t.type==="bash"&&typeof t.command=="string"?t:null}function Lr(t){return t.imageData?"image":t.uploadPath?"upload":t.fileData?"file":"path"}function Dr(t,s){if(t.imageData)return s("attachImage",{name:t.name??"image"});if(t.uploadPath)return s("attachFile",{name:t.name??t.uploadPath});if(t.fileData)return s("attachFile",{name:t.name??"file"});const n=t.path.split("/").pop()??t.path;return t.mode==="lines"&&t.lines?s("attachLines",{path:n,start:t.lines.start,end:t.lines.end}):t.mode==="reference"?s("refOnly",{path:n}):s("attachContent",{path:n})}const rn=l.memo(function({message:s,toolResults:n,liveOutputs:r,toolStatuses:c,streaming:i,isLast:a,onEdit:o,onKillBash:u,onCollapse:m,questionAttachments:f,qnIndex:y,qnActive:x,onJump:b,thinkingWrap:T,toolsWrap:D,searchActive:H}){const N=be(),[j,Q]=l.useState(!1),[V,J]=l.useState(""),[U,W]=l.useState([]),[K,G]=l.useState(!1),[C,M]=l.useState(null),k=h=>{M(h),window.setTimeout(()=>M(A=>A===h?null:A),4e3)};if(s.role==="toolResult")return null;const _=s.role==="custom"&&s.customType==="file",Z=s.content.map(h=>{var A;return((A=St(h))==null?void 0:A.text)??""}).filter(Boolean).join(`
|
|
313
|
+
`),z=s.role==="user"?Is(Z):null,I=z?z.userMessage??`skill:${z.name}`:Z.split(`
|
|
314
|
+
`).join(" ").trim(),R=i&&a&&s.content.length===0,w=s.role==="user"&&!i&&!R&&!!o,$=async h=>{const A=[];for(const ee of h){if(!Ge(ee.type))continue;const Y=await Vn(ee);Y&&A.push({path:"",imageData:Y.data,mimeType:Y.mimeType,name:Y.name})}A.length>0&&W(ee=>[...ee,...A])},q=async h=>{if(h.size>Rr){k(N("fileTooLarge",{name:h.name,size:20}));return}let A;try{A=(await new Promise((Y,se)=>{const X=new FileReader;X.onload=()=>Y(X.result),X.onerror=()=>se(X.error??new Error("read failed")),X.readAsDataURL(h)})).replace(/^data:[^;]*;base64,/,"")}catch{k(N("fileLoadFailed",{name:h.name}));return}W(ee=>[...ee,{path:"",fileData:A,name:h.name,size:h.size,mimeType:h.type||void 0}])},ie=async h=>{const A=[];for(const ee of h)Ge(ee.type)?A.push(ee):q(ee);A.length>0&&await $(A)},v=()=>{J(z?`/skill:${z.name}${z.userMessage?` ${z.userMessage}`:""}`:s.content.map(h=>{var A;return((A=St(h))==null?void 0:A.text)??""}).filter(Boolean).join(`
|
|
315
|
+
`)),W(f??[]),Q(!0)},L=()=>{const h=V.trim();h&&(o==null||o(s.id,h,U.length>0?U:void 0),Q(!1))},d=s.role==="custom"&&(s.customType==="goal-review"||s.customType==="goal-wizard"),E=s.role==="custom"&&s.customType==="goal-wizard";return e.jsxs("div",{className:`msg msg-${s.role}${d?" msg-goal-review":""}`,"data-role":s.role,"data-msg-id":s.id,children:[e.jsxs("div",{className:"msg-meta",children:[e.jsx("span",{className:"msg-role",children:s.role==="custom"?E?N("goalWizardCard"):d?N("goalBarTitle"):s.customType==="file"?N("attachment"):`${N("plugin")} · ${s.customType??N("unknown")}`:Xn(s.role,N)}),s.model&&e.jsx("span",{className:"msg-model",children:s.model}),s.timestamp&&e.jsx("span",{className:"msg-time",children:Fr(s.timestamp)}),m&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:N("collapseMsg"),onClick:()=>m(s.id),children:[e.jsx(Et,{})," ",N("collapseMsg")]}),y!==void 0&&b&&e.jsxs("button",{type:"button",className:`qn-tag ${x?"active":""}`,title:`${y+1}. ${I}`,"aria-label":`${y+1}. ${I}`,onClick:()=>b(s.id),children:[e.jsx("span",{className:"qn-tag-bar"}),e.jsx("span",{className:"qn-tag-idx",children:y+1})]})]}),e.jsx("div",{className:"msg-body",children:j?e.jsxs("div",{className:`msg-editor${K?" drag-over":""}`,onDragOver:h=>{h.preventDefault(),h.stopPropagation(),G(!0)},onDragLeave:h=>{h.currentTarget.contains(h.relatedTarget)||G(!1)},onDrop:h=>{var A;h.preventDefault(),h.stopPropagation(),G(!1),ie(Array.from(((A=h.dataTransfer)==null?void 0:A.files)??[]))},children:[U.length>0&&e.jsx("div",{className:"msg-editor-images",children:U.map((h,A)=>{var Y;const ee=Lr(h);return e.jsxs("span",{className:`msg-editor-img ${ee==="image"?"":"file-chip"}`,title:Dr(h,N),children:[ee==="image"?e.jsx("img",{src:`data:${h.mimeType??"image/png"};base64,${h.imageData}`,alt:h.name}):e.jsxs("span",{className:"msg-editor-file",children:[e.jsx("span",{className:"msg-editor-file-icon",children:ee==="path"?h.mode==="reference"?"🔗":"📎":"📄"}),e.jsx("span",{className:"msg-editor-file-name",children:h.name??((Y=h.path)==null?void 0:Y.split("/").pop())})]}),e.jsx("button",{type:"button",className:"msg-editor-img-remove",title:N("removeAttachment"),onClick:()=>W(se=>se.filter((X,ge)=>ge!==A)),children:e.jsx(Re,{})})]},`${h.name??h.path??"att"}-${A}`)})}),C&&e.jsx("div",{className:"msg-editor-notice",children:C}),e.jsx("textarea",{className:"msg-editor-input",value:V,autoFocus:!0,placeholder:N("editPlaceholder"),rows:Math.max(2,Math.min(10,V.split(`
|
|
316
|
+
`).length+1)),onChange:h=>J(h.target.value),onPaste:h=>{var ee;const A=[];for(const Y of((ee=h.clipboardData)==null?void 0:ee.items)??[])if(Y.kind==="file"&&Ge(Y.type)){const se=Y.getAsFile();se&&A.push(se)}A.length!==0&&(h.preventDefault(),$(A))},onKeyDown:h=>{h.key==="Enter"&&(h.metaKey||h.ctrlKey)?(h.preventDefault(),L()):h.key==="Escape"&&Q(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(Ji,{})," ",N("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>Q(!1),children:N("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!V.trim(),title:N("reaskFromHere"),onClick:L,children:[e.jsx(gs,{})," ",N("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),_?e.jsx(Ar,{message:s,forceOpen:H}):z?e.jsxs(e.Fragment,{children:[e.jsx(Br,{block:z,forceOpen:H}),z.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(Yt,{text:z.userMessage})}),s.content.map((h,A)=>h.type==="text"?null:e.jsx(on,{block:h,toolResults:n,liveOutputs:r,toolStatuses:c,streaming:i,isLast:a,onKillBash:u,toolsWrap:D,thinkingWrap:T,searchActive:H},`${s.id}-${A}`))]}):s.content.map((h,A)=>e.jsx(on,{block:h,toolResults:n,liveOutputs:r,toolStatuses:c,streaming:i,isLast:a,onKillBash:u,toolsWrap:D,thinkingWrap:T,searchActive:H},`${s.id}-${A}`)),R&&e.jsxs("div",{className:"thinking-wait",children:[N("thinkingWait"),e.jsx("span",{className:"dot"})]}),i&&a&&!R&&e.jsx("span",{className:"stream-cursor"})]})}),w&&!j&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:N("editReaskTip"),onClick:v,children:[e.jsx(gs,{})," ",N("editReask")]})})]})});function Ar({message:t,forceOpen:s=!1}){const n=be(),[r,c]=l.useState(!1),i=r||s,a=t.details??{},o=a.name??a.path??n("attachment"),u=a.type==="folder",m=a.mode==="reference",f=a.mode==="bridged",y=t.content.filter(D=>D.type==="text").map(D=>D.text).join(`
|
|
317
|
+
`),x=_r(y),b=t.content.find(D=>D.type==="image"),T=x.split(`
|
|
318
|
+
`).length;return e.jsxs("div",{className:`attachcard ${m?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>c(D=>s?!0:!D),children:[e.jsx("span",{className:"attachcard-icon",children:u?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:o}),a.path&&e.jsx("span",{className:"attachcard-path",children:a.path}),e.jsx("span",{className:`attachcard-mode ${a.mode==="lines"?"lines":m?"ref":f?"bridged":"inline"}`,children:m?u?n("folderRefShort"):`${n("refOnlyShort")} · ${ln(a.size)}`:f?n("bridgedVision"):b?n("image"):a.mode==="lines"?n("inlineLinesRange",{start:a.startLine??1,end:a.endLine??a.lines??1}):n("inlineLines",{n:a.lines??T})}),!m&&(i?e.jsx(Ze,{}):e.jsx(Gt,{}))]}),!m&&i&&(f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:n("bridgedVisionDetail")}),(b==null?void 0:b.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:b.dataUrl,alt:o})}),x&&e.jsx("pre",{className:"attachcard-content",children:x})]}):b!=null&&b.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:b.dataUrl,alt:o})}):e.jsx("pre",{className:"attachcard-content",children:x})),m&&e.jsx("div",{className:"attachcard-refnote",children:u?n("folderNotExpanded"):n("fileNotExpanded",{size:ln(a.size)})})]})}function ln(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function _r(t){const s=t.match(/^\s*<file path="[^"]*"(?:\s+lines="[^"]*")?>\s*```\s*\n?([\s\S]*?)\n?```\s*<\/file>\s*$/);if(s)return s[1].trim();const n=t.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return n?n[1].trim():t.trim()}function Br({block:t,forceOpen:s=!1}){const n=be(),[r,c]=l.useState(!1),i=r||s;return e.jsxs("div",{className:`skillcard${r?" expanded":""}`,children:[e.jsxs("button",{type:"button",className:"skillcard-head",onClick:()=>c(a=>s?!0:!a),title:t.location,children:[e.jsx("span",{className:"skillcard-icon",children:e.jsx(ia,{})}),e.jsx("span",{className:"skillcard-name",children:t.name}),e.jsx("span",{className:"skillcard-path",children:t.location}),e.jsxs("span",{className:"skillcard-action",children:[i?e.jsx(Et,{}):e.jsx(Ze,{}),n(i?"collapseMsg":"expandMsg")]})]}),i&&e.jsx("div",{className:"skillcard-body",children:e.jsx(Yt,{text:t.content})})]})}function on({block:t,toolResults:s,liveOutputs:n,toolStatuses:r,streaming:c,isLast:i,onKillBash:a,thinkingWrap:o,toolsWrap:u,searchActive:m}){const f=be(),y=St(t);if(y){const H=c&&i;return e.jsxs("div",{className:"msg-text",children:[H?e.jsx(jr,{text:y.text}):e.jsx(Yt,{text:y.text}),y.truncated&&e.jsx("div",{className:"trunc-note",children:f("truncated")})]})}const x=Gn(t);if(x)return e.jsx(wr,{thinking:x.thinking,streaming:c&&i,wrap:o,forceOpen:m});const b=Qn(t);if(b){const H=s.get(b.id),N=n.get(b.id),j={result:H,liveOutput:N==null?void 0:N.text,streaming:c,status:r.get(b.id)};return e.jsx(Sr,{block:b,view:j,onKillBash:a,wrap:u,forceOpen:m})}const T=Yn(t);if(T&&T.dataUrl)return e.jsx("div",{className:"msg-image",children:e.jsx("img",{src:T.dataUrl,alt:"attachment"})});const D=Jn(t);return D?e.jsxs("div",{className:"bashblock",children:[e.jsxs("div",{className:"bashblock-command",children:[e.jsx("span",{className:"bashblock-prompt",children:"$"}),e.jsx("code",{children:D.command}),D.exitCode!==void 0&&e.jsx("span",{className:`bashblock-exit ${D.exitCode===0?"ok":"err"}`,children:f("exitCode",{code:D.exitCode})}),D.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:f("cancelled")})]}),D.output&&e.jsx("pre",{className:"bashblock-output",children:D.output}),D.truncated&&e.jsx("div",{className:"trunc-note",children:f("outputTruncated")})]}):null}function Xn(t,s){switch(t){case"user":return s("role.user");case"assistant":return s("role.assistant");case"toolResult":return s("role.tool");case"bashExecution":return s("role.bash");case"branchSummary":return s("role.branch");case"compactionSummary":return s("role.compaction");default:return t}}function Fr(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),r=String(s.getMinutes()).padStart(2,"0");return`${n}:${r}`}function cn(t,s,n){let r=!1;for(const c of s){const i=c;if(i.type!=="image"||typeof i.dataUrl!="string"||!i.dataUrl.startsWith("data:"))continue;const a=i.dataUrl.match(/^data:([^;]*);base64,(.+)$/);a&&(r=!0,t.push({path:"",imageData:a[2],mimeType:a[1]||"image/png",name:n??`image.${(a[1]||"image/png").split("/")[1]??"png"}`}))}return r}function $r(t){const s=new Map;for(let n=0;n<t.length;n++){const r=t[n];if(r.role!=="user"||!r.id)continue;const c=[];cn(c,r.content);for(let i=n+1;i<t.length&&t[i].role==="custom"&&t[i].customType==="file";i++){const a=t[i].details??{};if(!cn(c,t[i].content,a.name)){if(a.upload&&a.path){c.push({path:"",uploadPath:a.path,name:a.name??a.path,size:a.size});continue}if(a.path&&a.mode){const o=a.mode==="inline"||a.mode==="lines"?a.mode:"reference",u={path:a.path,mode:o};a.mode==="lines"&&typeof a.startLine=="number"&&typeof a.endLine=="number"&&(u.lines={start:a.startLine,end:a.endLine}),c.push(u)}}}c.length>0&&s.set(r.id,c)}return s}const Hr=l.memo(function({message:s,onExpand:n}){const r=be();let c="";for(const y of s.content){const x=St(y);if(x&&x.text.trim()){const b=Is(x.text);b?c=`skill:${b.name}`+(b.userMessage?` · ${b.userMessage.replace(/\s+/g," ").trim()}`:""):c=x.text.replace(/\s+/g," ").trim();break}}if(!c&&s.role==="custom"&&s.customType==="file"){const y=s.details??{};c=y.name??y.path??""}c.length>90&&(c=`${c.slice(0,90)}…`);let a=0,o=0,u=0,m=0;for(const y of s.content)Gn(y)?a++:Qn(y)?o++:Jn(y)?u++:Yn(y)&&m++;const f=[];return a&&f.push(`${r("thinking")} ${a}`),o&&f.push(`${r("toolCalls")} ${o}`),u&&f.push(`${r("bashRuns")} ${u}`),m&&f.push(`${r("images")} ${m}`),e.jsxs("button",{type:"button",className:"msg-collapsed","data-msg-id":s.id,title:`${r("expandMsg")} · ${c||f.join(" · ")||s.role}`,onClick:()=>n(s.id),children:[e.jsx("span",{className:`msg-collapsed-role role-${s.role}`,children:s.role==="custom"&&s.customType==="file"?r("attachment"):Xn(s.role,r)}),e.jsxs("span",{className:"msg-collapsed-body",children:[c&&e.jsx("span",{className:"msg-collapsed-preview",children:c}),f.length>0&&e.jsx("span",{className:"msg-collapsed-chips",children:f.map((y,x)=>e.jsx("span",{className:"msg-collapsed-chip",children:y},x))})]}),s.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:Or(s.timestamp)}):null,e.jsxs("span",{className:"msg-collapsed-action",children:[e.jsx(Ze,{})," ",r("expandMsg")]})]})});function Or(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),r=String(s.getMinutes()).padStart(2,"0");return`${n}:${r}`}const Wr=l.memo(function({id:s,show:n,height:r,containerRef:c,onMeasured:i,lazyRef:a,children:o}){const u=l.useRef(null),m=l.useRef(null);return l.useLayoutEffect(()=>{const f=m.current;if(m.current=n,!n||f!==!1)return;const y=u.current,x=c.current;if(!y||!x)return;const b=y.offsetHeight;i==null||i(s,b);const T=b-r;if(T!==0){const D=y.parentElement;D&&D.getBoundingClientRect().bottom<=x.getBoundingClientRect().top&&(x.scrollTop+=T)}},[n]),n?e.jsx("div",{ref:a,"data-lazy-id":s,children:e.jsx("div",{ref:u,children:o})}):e.jsx("div",{ref:a,className:"msg-lazy-ph","data-msg-id":s,"data-lazy-id":s,style:{height:r},"aria-hidden":"true"})});function Ur(t,s,n,r){const c=[],i=[];let a=0;for(const o of t){if(n.has(o.id))continue;o.top<s.bottom&&o.bottom>s.top?r.has(o.id)&&c.push(o.id):r.has(o.id)||(i.push(o.id),o.bottom<=s.top&&(a+=o.bottom-o.top))}return{show:c,hide:i,shrinkAbove:a}}function Kr(t,s){if(s.show.length===0&&s.hide.length===0)return t;const n=new Set(t);for(const r of s.show)n.delete(r);for(const r of s.hide)n.add(r);return n}function qr(t,s,n){const r=new Set;let c=0;for(let i=t.length-1;i>=0&&!(i<t.length-1&&c>=n);i--){const a=t[i];r.add(a.id),c+=s.get(a.id)??Zn(a.role,a.customType)}return r}function Zn(t,s){switch(t){case"user":return 72;case"assistant":return 280;case"toolResult":return 8;case"custom":return s==="file"?96:72;default:return 60}}const zr=["text","thinking","argumentsText","output","command"];function Vr(t){let s=0;for(const n of t.content){n.type==="image"&&(s+=1);for(const r of zr){const c=n[r];typeof c=="string"&&(s+=c.length)}}return s}function Gr(t,s,n,r){const c=n.get(t);return c&&c.len===s?c.h:r}function Qr(t){const s=[];for(const n of t.content)n.type==="text"&&typeof n.text=="string"&&s.push(n.text);return s.join(`
|
|
319
|
+
`)}function Yr(t,s){const n=[];for(const r of t.content)if(r.type==="text"&&typeof r.text=="string")n.push(r.text);else if(r.type==="thinking"&&typeof r.thinking=="string")n.push(r.thinking);else if(r.type==="toolCall"){if(typeof r.name=="string"&&n.push(r.name),typeof r.argumentsText=="string"&&n.push(r.argumentsText),typeof r.id=="string"){const c=s.get(r.id);if(c){const i=Qr(c);i&&n.push(i)}}}else r.type==="bash"&&(typeof r.command=="string"&&n.push(r.command),typeof r.output=="string"&&n.push(r.output));return n.join(`
|
|
320
|
+
`)}function Jr(t,s){let n=0,r=t.indexOf(s);for(;r!==-1;)n++,r=t.indexOf(s,r+s.length);return n}function Xr(t,s,n,r){const c=new Map,i=n.toLowerCase();if(!i)return c;for(const a of t){if(!s.has(a.id))continue;const o=Jr(Yr(a,r).toLowerCase(),i);o>0&&c.set(a.id,o)}return c}function Zr(t,s){var i;const n=[],r=s.toLowerCase();if(!r)return n;const c=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(a){const o=a.parentElement;return!o||o.closest(".search-bar")||o.closest(".msg-collapsed")?NodeFilter.FILTER_REJECT:(a.textContent??"").toLowerCase().includes(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let a=c.nextNode();a;a=c.nextNode()){const o=(a.textContent??"").toLowerCase();if(!((i=a.parentElement)!=null&&i.closest("[data-msg-id]")))continue;let u=o.indexOf(r);for(;u!==-1;){const m=document.createRange();m.setStart(a,u),m.setEnd(a,u+r.length),n.push(m),u=o.indexOf(r,u+r.length)}}return n}function el(t,s,n,r,c){var u;const i=Xr(n,r,s,c),a=new Map;for(const m of Zr(t,s)){const f=(u=m.startContainer.parentElement)==null?void 0:u.closest("[data-msg-id]");if(!(f!=null&&f.dataset.msgId))continue;const y=a.get(f.dataset.msgId);y?y.push(m):a.set(f.dataset.msgId,[m])}const o=[];for(const m of n){const f=a.get(m.id);if(f)for(let x=0;x<f.length;x++)o.push({kind:"dom",range:f[x],msgId:m.id,k:x});const y=i.get(m.id);if(y)for(let x=0;x<y;x++)o.push({kind:"folded",msgId:m.id,k:x})}return o}function ls(t,s){return t.findIndex(n=>n.msgId===s.msgId&&n.k===s.k)}function Ue(t,s){const n=CSS;if(!n.highlights)return;if(s.length===0){n.highlights.delete(t);return}const r=window.Highlight;r&&n.highlights.set(t,new r(...s))}function tl(t,s){const n=[];let r=t;for(;r&&r!==s;){const c=getComputedStyle(r);/(auto|scroll|hidden)/.test(c.overflowY+c.overflowX)&&(r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth)&&n.push(r),r=r.parentElement}return n}function sl(t,s){const n=s.startContainer.parentElement;for(const o of tl(n,t)){const u=s.getBoundingClientRect(),m=o.getBoundingClientRect();if(u.height<=0||u.width<=0)return;u.top>=m.top+4&&u.bottom<=m.bottom-4||(o.scrollTop+=u.top-m.top-(o.clientHeight-u.height)/2),u.left>=m.left+4&&u.right<=m.right-4||(o.scrollLeft+=u.left-m.left-(o.clientWidth-u.width)/2)}const r=s.getBoundingClientRect(),c=t.getBoundingClientRect();if(r.height<=0||r.width<=0)return;const i=r.top>=c.top+6&&r.bottom<=c.bottom-6,a=r.left>=c.left+6&&r.right<=c.right-6;i&&a||(i||(t.scrollTop+=r.top-c.top-(c.height-r.height)/2),a||(t.scrollLeft+=r.left-c.left-(c.width-r.width)/2))}function nl({containerRef:t,messages:s,collapsedIds:n,toolResults:r,onExpand:c,onProgrammaticScroll:i,open:a,onClose:o}){const u=be(),m=l.useRef(null),[f,y]=l.useState(""),[x,b]=l.useState(null),[T,D]=l.useState(0),[,H]=l.useState(0),N=l.useDeferredValue(f),j=a?N.trim():"",Q=l.useRef(null);Q.current=x;const V=l.useRef([]),J=l.useRef({key:null}),U=l.useRef("");l.useEffect(()=>{a&&(b(null),requestAnimationFrame(()=>{var G;return(G=m.current)==null?void 0:G.select()}))},[a]),l.useEffect(()=>{if(!a)return;const G=C=>{C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),o())};return window.addEventListener("keydown",G,!0),()=>window.removeEventListener("keydown",G,!0)},[a,o]),l.useEffect(()=>(a||(Ue("msg-search",[]),Ue("msg-search-active",[])),()=>{Ue("msg-search",[]),Ue("msg-search-active",[])}),[a]),l.useLayoutEffect(()=>{const G=()=>{D(0),b(null),H(0),V.current=[],Ue("msg-search",[]),Ue("msg-search-active",[]),J.current={key:null},U.current=""};if(!a||!j){G();return}const C=t.current;if(!C)return;let M=!1,k=0;return k=requestAnimationFrame(()=>{var ie,v;if(M)return;const _=el(C,j,s,n,r);V.current=_;const Z=_.length;if(D(Z),Z===0){b(null),H(0),Ue("msg-search",[]),Ue("msg-search-active",[]),J.current={key:null},U.current=j;return}const z=Q.current;let I;if(z){if(I=ls(_,z),I===-1){const L=[];for(let d=0;d<_.length;d++)_[d].msgId===z.msgId&&L.push(d);if(L.length>0){const d=Math.min(z.k,L.length-1);I=L[d]}else I=0}}else I=0;I<0&&(I=0),I>=Z&&(I=Z-1),(!z||z.msgId!==_[I].msgId||z.k!==_[I].k)&&b({msgId:_[I].msgId,k:_[I].k}),H(I);const R=_[I],w=J.current,$=((ie=w.key)==null?void 0:ie.msgId)!==R.msgId||((v=w.key)==null?void 0:v.k)!==R.k||w.kind==="folded"&&R.kind==="dom"||j!==U.current;J.current={key:{msgId:R.msgId,k:R.k},kind:R.kind},U.current=j;const q=_.filter(L=>L.kind==="dom").map(L=>L.range);if(Ue("msg-search",q),R.kind==="folded"){Ue("msg-search-active",[]),$&&c(R.msgId);return}Ue("msg-search-active",[R.range]),$&&(i==null||i(),sl(C,R.range))}),()=>{M=!0,cancelAnimationFrame(k)}},[a,j,s,t,x,n,r,c,i]);const W=l.useCallback(G=>{const C=V.current,M=C.length;if(M===0)return;const k=Q.current,_=k?ls(C,k):0,Z=C[(_+G+M)%M];b(Z.kind==="dom"||Z.kind==="folded"?{msgId:Z.msgId,k:Z.k}:null)},[]);if(!a)return null;const K=x?(()=>{const G=ls(V.current,x);return G===-1?0:G})():0;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:m,className:"search-input",type:"text",value:f,placeholder:u("searchPlaceholder"),onChange:G=>{y(G.target.value)},onKeyDown:G=>{G.key==="Enter"&&(G.preventDefault(),W(G.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${T===0?"empty":""}`,children:T===0?u("searchNoResults"):`${Math.min(K+1,T)}/${T}`}),e.jsx("button",{type:"button",className:"search-btn",title:u("searchPrev"),disabled:T===0,onClick:()=>W(-1),children:e.jsx(Et,{})}),e.jsx("button",{type:"button",className:"search-btn",title:u("searchNext"),disabled:T===0,onClick:()=>W(1),children:e.jsx(Ze,{})}),e.jsx("button",{type:"button",className:"search-btn",title:u("searchClose"),onClick:o,children:e.jsx(Re,{})})]})}function il(t){const{dSt:s,dSh:n,escaped:r,graceActive:c,stuck:i}=t;return c?{flipEscape:!1,reassert:!1}:s>=-4||s<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:i&&!r}:{flipEscape:!0,reassert:!1}}const ei=[{id:"setup-matt-pocock-skills",icon:"🛠",titleKey:"tpl.sk.setup",descKey:"tpl.sk.setup.desc",promptKey:"tpl.sk.setup.prompt"},{id:"ask-matt",icon:"🧭",titleKey:"tpl.sk.ask",descKey:"tpl.sk.ask.desc",promptKey:"tpl.sk.ask.prompt"},{id:"grill-with-docs",icon:"🗣",titleKey:"tpl.sk.grilldocs",descKey:"tpl.sk.grilldocs.desc",promptKey:"tpl.sk.grilldocs.prompt"},{id:"to-spec",icon:"📝",titleKey:"tpl.sk.tospec",descKey:"tpl.sk.tospec.desc",promptKey:"tpl.sk.tospec.prompt"},{id:"to-tickets",icon:"🎫",titleKey:"tpl.sk.totickets",descKey:"tpl.sk.totickets.desc",promptKey:"tpl.sk.totickets.prompt"},{id:"implement",icon:"🏗",titleKey:"tpl.sk.implement",descKey:"tpl.sk.implement.desc",promptKey:"tpl.sk.implement.prompt"},{id:"code-review",icon:"🧹",titleKey:"tpl.sk.codeview",descKey:"tpl.sk.codeview.desc",promptKey:"tpl.sk.codeview.prompt"},{id:"wayfinder",icon:"🗺",titleKey:"tpl.sk.wayfinder",descKey:"tpl.sk.wayfinder.desc",promptKey:"tpl.sk.wayfinder.prompt"},{id:"prototype",icon:"🔬",titleKey:"tpl.sk.prototype",descKey:"tpl.sk.prototype.desc",promptKey:"tpl.sk.prototype.prompt"},{id:"research",icon:"📚",titleKey:"tpl.sk.research",descKey:"tpl.sk.research.desc",promptKey:"tpl.sk.research.prompt"},{id:"improve-codebase-architecture",icon:"🏛",titleKey:"tpl.sk.arch",descKey:"tpl.sk.arch.desc",promptKey:"tpl.sk.arch.prompt"},{id:"diagnosing-bugs",icon:"🐛",titleKey:"tpl.sk.debug",descKey:"tpl.sk.debug.desc",promptKey:"tpl.sk.debug.prompt"},{id:"resolving-merge-conflicts",icon:"🔀",titleKey:"tpl.sk.merge",descKey:"tpl.sk.merge.desc",promptKey:"tpl.sk.merge.prompt"},{id:"triage",icon:"🗂",titleKey:"tpl.sk.triage",descKey:"tpl.sk.triage.desc",promptKey:"tpl.sk.triage.prompt"},{id:"wizard",icon:"✨",titleKey:"tpl.sk.wizard",descKey:"tpl.sk.wizard.desc",promptKey:"tpl.sk.wizard.prompt"},{id:"grill-me",icon:"🔍",titleKey:"tpl.sk.grillme",descKey:"tpl.sk.grillme.desc",promptKey:"tpl.sk.grillme.prompt"},{id:"handoff",icon:"🤝",titleKey:"tpl.sk.handoff",descKey:"tpl.sk.handoff.desc",promptKey:"tpl.sk.handoff.prompt"},{id:"to-questionnaire",icon:"📋",titleKey:"tpl.sk.questionnaire",descKey:"tpl.sk.questionnaire.desc",promptKey:"tpl.sk.questionnaire.prompt"},{id:"teach",icon:"🎓",titleKey:"tpl.sk.teach",descKey:"tpl.sk.teach.desc",promptKey:"tpl.sk.teach.prompt"},{id:"wait-what",icon:"💬",titleKey:"tpl.sk.ww",descKey:"tpl.sk.ww.desc",promptKey:"tpl.sk.ww.prompt"},{id:"writing-for-agents",icon:"📄",titleKey:"tpl.sk.wfa",descKey:"tpl.sk.wfa.desc",promptKey:"tpl.sk.wfa.prompt"},{id:"codebase-design",icon:"🧱",titleKey:"tpl.sk.codesign",descKey:"tpl.sk.codesign.desc",promptKey:"tpl.sk.codesign.prompt"},{id:"domain-modeling",icon:"🏷",titleKey:"tpl.sk.domain",descKey:"tpl.sk.domain.desc",promptKey:"tpl.sk.domain.prompt"},{id:"grilling",icon:"🔥",titleKey:"tpl.sk.grilling",descKey:"tpl.sk.grilling.desc",promptKey:"tpl.sk.grilling.prompt"},{id:"tdd",icon:"🧪",titleKey:"tpl.sk.tdd",descKey:"tpl.sk.tdd.desc",promptKey:"tpl.sk.tdd.prompt"}],ti="pi-web-ui:prompt-templates";function al(){try{const t=localStorage.getItem(ti);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(n=>!!n&&typeof n=="object"&&typeof n.id=="string"):[]}catch{return[]}}function dn(t){return ei.some(s=>s.id===t)}function Dt(t){return typeof t.title=="string"}const si=l.createContext(null);function ni(){const t=l.useContext(si);if(!t)throw new Error("useTemplates must be used within TemplateProvider");return t}function rl({send:t,children:s}){const n=be(),[r,c]=l.useState(al),[i,a]=l.useState(!1),[o,u]=l.useState(null),[m,f]=l.useState(!1),[y,x]=l.useState(!1),[b,T]=l.useState(!1);l.useEffect(()=>{try{localStorage.setItem(ti,JSON.stringify(r))}catch{}},[r]);const D=l.useMemo(()=>{const _=new Map,Z=new Set;for(const R of r)R.hidden?Z.add(R.id):(Dt(R)&&!dn(R.id)||Dt(R))&&_.set(R.id,R);const z=ei.filter(R=>!Z.has(R.id)).map(R=>{const w=_.get(R.id);return{id:R.id,icon:(w==null?void 0:w.icon)??R.icon,title:(w==null?void 0:w.title)??n(R.titleKey),desc:(w==null?void 0:w.desc)??n(R.descKey),prompt:(w==null?void 0:w.prompt)??n(R.promptKey),builtin:!0}}),I=r.filter(R=>Dt(R)&&!dn(R.id)).map(R=>({id:R.id,icon:R.icon??"📌",title:R.title??"",desc:R.desc??"",prompt:R.prompt??""}));return[...z,...I]},[r,n]),H=l.useCallback(()=>a(!0),[]),N=l.useCallback(_=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:_}))},[]),j=l.useCallback((_,Z=!1)=>{T(Z),_?(f(!1),u({..._})):(f(!0),u({id:Qe(),icon:"📌",title:"",desc:"",prompt:""}))},[]),Q=l.useCallback(()=>{a(!1),u(null),T(!1)},[]),V=l.useCallback(()=>{y?(c([]),x(!1)):(x(!0),setTimeout(()=>x(!1),5e3))},[y]),J=l.useCallback(_=>{a(!1),N(_.prompt)},[N]),U=l.useCallback(_=>{a(!1),j(_,!0)},[j]),W=l.useCallback(()=>{a(!1),j(void 0,!0)},[j]),K=l.useCallback(_=>{c(Z=>{const z=Z.findIndex(I=>I.id===_.id);if(z>=0){const I=[...Z];return I[z]=_,I}return[...Z,_]}),u(null),b&&(a(!0),T(!1))},[b]),G=l.useCallback(_=>{c(Z=>_.builtin?[...Z.filter(I=>I.id!==_.id),{id:_.id,hidden:!0}]:Z.filter(z=>z.id!==_.id)),u(null),b&&(a(!0),T(!1))},[b]),C=l.useCallback(_=>{c(Z=>Z.filter(z=>z.id!==_.id||z.hidden)),u(null),b&&(a(!0),T(!1))},[b]),M=l.useMemo(()=>({templates:D,fill:N,openPicker:H,openEdit:j,resetConfirm:y,toggleReset:V}),[D,N,H,j,y,V]),k=o?r.some(_=>_.id===o.id&&!_.hidden&&Dt(_)):!1;return e.jsxs(si.Provider,{value:M,children:[s,i&&e.jsx(ol,{templates:D,resetConfirm:y,onFill:J,onEditTpl:U,onNew:W,onResetToggle:V,onClose:Q}),o&&e.jsx(cl,{editing:o,isNew:m,hasOverride:k,onDraft:u,onSave:K,onRestore:()=>C(o),onRemove:()=>G(o),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:o.prompt})),Q()},onSend:()=>{const _=o.prompt.trim();_&&t({type:"prompt",text:_,queue:!1})&&Q()},onClose:Q})]})}function ll(){const t=be(),{templates:s,fill:n,openEdit:r,toggleReset:c,resetConfirm:i}=ni();return e.jsxs("div",{className:"empty-templates",children:[e.jsxs("div",{className:"empty-templates-head",children:[e.jsx("span",{className:"empty-templates-title",children:t("tpl.title")}),e.jsx("span",{className:"empty-templates-hint",children:t("tpl.hint")})]}),e.jsxs("div",{className:"empty-templates-grid",children:[s.map(a=>e.jsx(ii,{tpl:a,title:t("tpl.clickCard"),onFill:()=>n(a.prompt),onEdit:()=>r(a),editTitle:t("tpl.editTpl")},a.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>r(),title:t("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(Ke,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:t("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"empty-templates-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:c,children:[e.jsx(Sn,{}),t(i?"tpl.resetConfirm":"tpl.reset")]})})]})}function ii({tpl:t,title:s,onFill:n,onEdit:r,editTitle:c}){const i=be();return e.jsxs("button",{type:"button",className:"empty-template",title:s,onClick:n,children:[e.jsx("span",{className:"empty-template-icon",children:t.icon}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t.title}),e.jsx("span",{className:"empty-template-desc",children:t.desc})]}),e.jsx("span",{className:"template-card-ops",role:"button",title:c??i("tpl.editTpl"),onClick:a=>{a.stopPropagation(),r()},children:e.jsx(qt,{})})]})}function ol({templates:t,resetConfirm:s,onFill:n,onEditTpl:r,onNew:c,onResetToggle:i,onClose:a}){const o=be();return l.useEffect(()=>{const u=m=>{m.key==="Escape"&&a()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[a]),e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"modal template-picker",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"template-picker-head",children:[e.jsx("span",{className:"template-picker-title",children:o("tpl.pickerTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:o("close"),onClick:a,children:e.jsx(Re,{})})]}),e.jsx("div",{className:"template-picker-hint",children:o("tpl.pickerHint")}),e.jsxs("div",{className:"template-picker-grid",children:[t.map(u=>e.jsx(ii,{tpl:u,title:o("tpl.clickCard"),onFill:()=>n(u),onEdit:()=>r(u),editTitle:o("tpl.editTpl")},u.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:c,title:o("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(Ke,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:o("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:o("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"template-picker-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:i,children:[e.jsx(Sn,{}),o(s?"tpl.resetConfirm":"tpl.reset")]})})]})})}function cl({editing:t,isNew:s,hasOverride:n,onDraft:r,onSave:c,onRestore:i,onRemove:a,onFill:o,onSend:u,onClose:m}){const f=be(),y=l.useRef(null);l.useEffect(()=>{const T=D=>{D.key==="Escape"&&m()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[m]),l.useEffect(()=>{const T=y.current;if(!T)return;T.style.height="auto";const D=T.scrollHeight>300;T.style.height=`${Math.min(T.scrollHeight,300)}px`,T.style.overflowY=D?"auto":"hidden"},[t.prompt]);const x=()=>{const T=t.title.trim(),D=t.prompt.trim();if(!T||!D){r({...t,error:f("tpl.required")});return}c({id:t.id,icon:t.icon.trim()||"📌",title:T,desc:t.desc.trim(),prompt:D})},b=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:m,children:e.jsxs("div",{className:"modal template-modal",onClick:T=>T.stopPropagation(),children:[e.jsxs("div",{className:"template-modal-head",children:[e.jsx("span",{className:"template-modal-icon",children:t.icon}),e.jsx("span",{className:"template-modal-badge",children:f(b?"tpl.builtin":"tpl.custom")}),e.jsx("span",{className:"template-modal-title",children:f(s?"tpl.newTitle":"tpl.editTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:f("close"),onClick:m,children:e.jsx(Re,{})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldIcon")}),e.jsx("input",{className:"template-field-input icon",value:t.icon,maxLength:4,onChange:T=>r({...t,icon:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldTitle")}),e.jsx("input",{className:"template-field-input",value:t.title,placeholder:f("tpl.fieldTitlePh"),onChange:T=>r({...t,title:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldDesc")}),e.jsx("input",{className:"template-field-input",value:t.desc,placeholder:f("tpl.fieldDescPh"),onChange:T=>r({...t,desc:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldPrompt")}),e.jsx("textarea",{ref:y,className:"template-field-prompt",value:t.prompt,placeholder:f("tpl.fieldPromptPh"),onChange:T=>r({...t,prompt:T.target.value})})]}),t.error&&e.jsx("div",{className:"template-error",children:t.error}),e.jsxs("div",{className:"template-modal-actions",children:[e.jsxs("div",{className:"template-modal-actions-left",children:[!s&&b&&n&&e.jsx("button",{type:"button",className:"btn template-btn ghost",title:f("tpl.restoreTip"),onClick:i,children:f("tpl.restore")}),!s&&b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:f("tpl.removeTip"),onClick:a,children:[e.jsx(He,{})," ",f("tpl.remove")]}),!s&&!b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:f("tpl.deleteTip"),onClick:a,children:[e.jsx(He,{})," ",f("tpl.delete")]})]}),e.jsxs("div",{className:"template-modal-actions-right",children:[e.jsx("button",{type:"button",className:"btn template-btn",onClick:x,children:f("tpl.save")}),e.jsx("button",{type:"button",className:"btn template-btn fill",onClick:o,title:f("tpl.fillTip"),children:f("tpl.fill")}),e.jsxs("button",{type:"button",className:"btn template-btn send",onClick:u,title:f("tpl.sendTip"),children:[e.jsx(Cn,{})," ",f("tpl.sendNow")]})]})]})]})})}const un=new Map,dl=15,pn=30,os=250,mn=1200,ul=1600;function hn(t){return t.content.some(s=>s.type==="toolCall")}function pl({state:t,liveOutputs:s,toolStatuses:n,onEdit:r,onKillBash:c,onRemoveQueued:i,thinkingWrap:a,toolsWrap:o,jumpTarget:u,onJumpDone:m}){const f=be(),y=l.useRef(null),[x,b]=l.useState(!0),T=l.useRef(!0),D=l.useRef(0),H=l.useRef(0),N=l.useRef(!1),j=l.useRef(0),[Q,V]=l.useState(()=>new Set),[J,U]=l.useState(!1),W=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,K=l.useMemo(()=>{const S=new Map;for(const B of t.messages)B.role==="toolResult"&&B.toolCallId&&S.set(B.toolCallId,B);return S},[t.messages]),G=l.useMemo(()=>$r(t.messages),[t.messages]),C=W.length>0?W[W.length-1].id:null,M=t.messages.length>pn?Math.max(0,t.messages.length-dl):0,k=l.useMemo(()=>{const S=new Set;for(let B=0;B<M;B++){const oe=t.messages[B];oe.role!=="toolResult"&&(Q.has(oe.id)||S.add(oe.id))}return S},[t.messages,M,Q]),[_,Z]=l.useState(()=>new Set),[z,I]=l.useState(()=>new Set),R=l.useRef(new Map),w=l.useRef(new Map),$=l.useRef(new Map),q=l.useRef(0),ie=l.useMemo(()=>{const S=new Map;for(const B of t.messages)S.set(B.id,Vr(B));return S},[t.messages]),v=l.useRef(ie);v.current=ie;const L=l.useRef(_);L.current=_;const d=t.messages.length>pn&&!J,E=l.useRef(d);E.current=d;const h=qr(t.messages,R.current,ul),A=l.useRef(h);A.current=h;const ee=l.useCallback(()=>{const S=y.current;if(!S)return;if(!E.current){Z(we=>we.size?new Set:we);return}const B=S.getBoundingClientRect(),oe={top:B.top-mn,bottom:B.bottom+mn},ce=[];for(const[we,Ie]of $.current){const Oe=Ie.getBoundingClientRect();ce.push({id:we,top:Oe.top,bottom:Oe.bottom}),L.current.has(we)||X(we,Oe.bottom-Oe.top,v.current.get(we))}const je=Ur(ce,oe,A.current,L.current);for(const we of je.hide){const Ie=$.current.get(we);Ie&&X(we,Ie.offsetHeight,v.current.get(we))}Z(we=>Kr(we,je))},[]),Y=l.useCallback(()=>{q.current||(q.current=requestAnimationFrame(()=>{q.current=0,ee()}))},[ee]);l.useLayoutEffect(()=>{ee()},[ee]);const se=l.useRef(J);l.useLayoutEffect(()=>{se.current&&!J&&ee(),se.current=J},[J,ee]);const X=l.useCallback((S,B,oe)=>{oe!==void 0&&(w.current.set(S,{h:B,len:oe}),R.current.set(S,B))},[]),ge=l.useCallback((S,B)=>{X(S,B,v.current.get(S))},[X]),Ne=l.useCallback(S=>{S&&$.current.set(S.dataset.lazyId??"",S)},[]);l.useEffect(()=>{const S=new Set(t.messages.map(B=>B.id));for(const B of $.current.keys())S.has(B)||($.current.delete(B),R.current.delete(B),w.current.delete(B));Z(B=>{let oe=!1;const ce=new Set;for(const je of B)S.has(je)?ce.add(je):oe=!0;return oe?ce:B})},[t.messages,Q]),l.useEffect(()=>()=>cancelAnimationFrame(q.current),[]);const de=l.useMemo(()=>{const S=[];for(const B of t.messages){if(B.role!=="user")continue;const oe=B.content.map(we=>{var Ie;return((Ie=St(we))==null?void 0:Ie.text)??""}).filter(Boolean).join(" "),ce=Is(oe),je=ce?ce.userMessage??`skill:${ce.name}`:oe.trim();je&&S.push({id:B.id,text:je})}return S},[t.messages]),Ee=l.useMemo(()=>{const S=new Map;return de.forEach((B,oe)=>S.set(B.id,oe)),S},[de]),[le,g]=l.useState(-1),O=l.useRef(-1),me=l.useRef(de);l.useEffect(()=>{me.current=de},[de]);const ue=l.useCallback(()=>{const S=y.current,B=me.current;if(!S||B.length===0)return;const oe=S.getBoundingClientRect().top,ce=140;let je=-1;for(let we=0;we<B.length;we++){const Ie=S.querySelector(`[data-msg-id="${B[we].id}"]`);if(Ie)if(Ie.getBoundingClientRect().top<=oe+ce)je=we;else break}je!==O.current&&(O.current=je,g(je))},[]);l.useEffect(()=>{ue()},[de,ue]);const ye=l.useCallback(S=>{V(B=>B.has(S)?B:new Set(B).add(S))},[]);l.useEffect(()=>{const S=B=>{if(!(B.ctrlKey||B.metaKey)||B.key.toLowerCase()!=="f")return;const oe=B.target;oe&&(oe.tagName==="INPUT"||oe.tagName==="TEXTAREA"||oe.isContentEditable)||(B.preventDefault(),U(!0))};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[]);const fe=l.useCallback(S=>{V(B=>{if(!B.has(S))return B;const oe=new Set(B);return oe.delete(S),oe})},[]),ke=l.useCallback(S=>{const B=t.messages.findIndex(ce=>ce.id===S);Xa.flushSync(()=>{B>=0&&B<M&&!Q.has(S)&&ye(S),I(ce=>ce.has(S)?ce:new Set(ce).add(S))});const oe=me.current.findIndex(ce=>ce.id===S);O.current=oe,g(oe),requestAnimationFrame(()=>{var je,we,Ie;const ce=(je=y.current)==null?void 0:je.querySelector(`[data-msg-id="${S}"]`);ce&&((we=y.current)==null||we.querySelectorAll(".msg-flash").forEach(Oe=>Oe.classList.remove("msg-flash")),ce.scrollIntoView({block:"start"}),ce.classList.remove("msg-flash"),ce.offsetWidth,ce.classList.add("msg-flash"),ce!==((Ie=y.current)==null?void 0:Ie.lastElementChild)&&(N.current=!0))})},[t.messages,M,Q,ye]),Le=l.useMemo(()=>{var S;return u?((S=t.messages.find(B=>B.role===u.role&&B.timestamp===u.timestamp))==null?void 0:S.id)??null:null},[t.messages,u]);l.useEffect(()=>{if(u){if(Le){ke(Le),m==null||m();return}t.sessionFile===u.path&&t.messages.length>0&&(m==null||m())}},[Le,ke,m,u,t.sessionFile,t.messages.length]);const ae=l.useCallback(()=>{const S=y.current;if(!S)return;const B=S.scrollTop-D.current,oe=S.scrollHeight-H.current;D.current=S.scrollTop,H.current=S.scrollHeight;const ce=S.scrollHeight-S.scrollTop-S.clientHeight<80,je=Date.now()<j.current,we=il({dSt:B,dSh:oe,escaped:N.current,graceActive:je,stuck:T.current});we.reassert&&(j.current=Date.now()+os,S.scrollTop=S.scrollHeight),we.flipEscape&&(N.current=!0),ce&&B>=0&&(N.current=!1),je||(B<0?T.current=ce&&!N.current:ce&&(T.current=!0)),b(T.current),ue(),Y()},[ue,Y]),De=l.useRef(!1);l.useEffect(()=>{const S=De.current;if(De.current=!!t.isStreaming,S&&!t.isStreaming&&!N.current){const B=()=>{const ce=y.current;ce&&!N.current&&(ce.scrollTop=ce.scrollHeight,T.current=!0,b(!0))};requestAnimationFrame(()=>requestAnimationFrame(B));const oe=setTimeout(B,180);return()=>clearTimeout(oe)}},[t.isStreaming]),l.useEffect(()=>{const S=y.current;S&&T.current&&(S.scrollTop=S.scrollHeight)},[W,t.isStreaming,s]);const Ae=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");l.useEffect(()=>{const S=y.current;S&&T.current&&(S.scrollTop=S.scrollHeight)},[Ae]),l.useEffect(()=>{const S=y.current;if(!S||typeof ResizeObserver>"u")return;const B=new ResizeObserver(()=>{T.current&&!N.current&&(S.scrollTop=S.scrollHeight,b(!0))});return B.observe(S),()=>B.disconnect()},[]),l.useEffect(()=>{const S=y.current;if(!S||typeof MutationObserver>"u")return;let B=!1;const oe=new MutationObserver(()=>{B||(B=!0,requestAnimationFrame(()=>{B=!1;const ce=y.current;ce&&T.current&&!N.current&&(ce.scrollTop=ce.scrollHeight,b(!0))}))});return oe.observe(S,{childList:!0,subtree:!0,characterData:!0}),()=>oe.disconnect()},[]);const qe=l.useCallback(()=>{if(!y.current)return;T.current=!0,N.current=!1,b(!0),j.current=Date.now()+os;const B=()=>{const oe=y.current;!oe||!T.current||N.current||(j.current=Date.now()+os,oe.scrollTop=oe.scrollHeight)};B(),requestAnimationFrame(()=>requestAnimationFrame(B)),setTimeout(B,120),setTimeout(B,300),setTimeout(B,600)},[]),ze=l.useRef(null);l.useEffect(()=>{const S=ze.current,B=y.current;if(!S||!B)return;const oe=ce=>{ce.preventDefault();const je=S.querySelector(".qn-list");if(je&&je.contains(ce.target)&&je.scrollHeight>je.clientHeight){je.scrollTop+=ce.deltaY;return}B.scrollTop+=ce.deltaY};return S.addEventListener("wheel",oe,{passive:!1}),()=>S.removeEventListener("wheel",oe)},[]);const[P,xe]=l.useState(0);l.useEffect(()=>{const S=()=>{var B;xe(((B=y.current)==null?void 0:B.clientHeight)??0),Y()};return S(),window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[Y]);const pe=de.length,Se=l.useMemo(()=>pe===0?27:Math.max(4,Math.min(27,Math.floor(((P||600)-16)/pe)-3)),[pe,P]),ve=Se<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:`messages${J||x?"":" anchor-live"}`,ref:y,onScroll:ae,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(ll,{})}),t.messages.map((S,B)=>{const oe=B<M,ce=oe&&Q.has(S.id);if(oe&&!ce)return S.role==="toolResult"?null:e.jsx(Hr,{message:S,onExpand:ye},S.id);const je=S.role==="user"?Ee.get(S.id):void 0,we=!d||h.has(S.id)||z.has(S.id)||!_.has(S.id);return e.jsx(Wr,{id:S.id,show:we,height:Gr(S.id,ie.get(S.id)??-1,w.current,Zn(S.role,S.customType)),containerRef:y,onMeasured:ge,lazyRef:Ne,children:e.jsx(rn,{message:S,qnIndex:je,qnActive:je!==void 0?je===le:void 0,onJump:ke,toolResults:K,liveOutputs:hn(S)?s:un,toolStatuses:n,streaming:t.isStreaming,onKillBash:c,toolsWrap:o,thinkingWrap:a,isLast:S.id===C,onEdit:r,questionAttachments:G.get(S.id),onCollapse:ce?fe:void 0,searchActive:J},S.id)},S.id)}),t.streamingMessage&&e.jsx(rn,{message:t.streamingMessage,toolResults:K,liveOutputs:hn(t.streamingMessage)?s:un,toolStatuses:n,streaming:!0,isLast:!0,onEdit:r,onKillBash:c,toolsWrap:o,thinkingWrap:a,searchActive:J},t.streamingMessage.id),t.isStreaming&&W.length===0&&e.jsx("div",{className:"streaming-wait",children:f("waitingResponse")}),t.queue.steering.map((S,B)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:f("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:S}),i&&e.jsx("button",{type:"button",className:"queued-remove",title:f("queueRemoveTip"),onClick:()=>i("steer",S),children:"✕"})]})},`q-steer-${B}`)),t.queue.followUp.map((S,B)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:f("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:S}),i&&e.jsx("button",{type:"button",className:"queued-remove",title:f("queueRemoveTip"),onClick:()=>i("followUp",S),children:"✕"})]})},`q-fu-${B}`))]}),!x&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:qe,children:[e.jsx(Rn,{})," ",f("backToBottom")]}),e.jsx(nl,{containerRef:y,messages:W,collapsedIds:k,toolResults:K,onExpand:ye,onProgrammaticScroll:()=>{N.current=!0,T.current=!1,b(!1)},open:J,onClose:()=>U(!1)}),de.length>0&&e.jsxs("div",{className:`qn-rail ${ve?"many":""}`,ref:ze,"aria-label":f("questionNavTitle"),style:{"--rail-gap":`${Se}px`},children:[de.map((S,B)=>e.jsx("button",{type:"button",className:`qn-bar ${B===le?"active":""}`,"aria-label":`${B+1}. ${S.text}`,onClick:()=>ke(S.id),children:e.jsxs("span",{className:"qn-bar-text",children:[B+1,". ",S.text]})},S.id)),ve&&e.jsx("div",{className:"qn-list",children:de.map((S,B)=>e.jsxs("button",{type:"button",className:`qn-list-item ${B===le?"active":""}`,"aria-label":`${B+1}. ${S.text}`,onClick:()=>ke(S.id),children:[e.jsx("span",{className:"qn-list-idx",children:B+1}),e.jsx("span",{className:"qn-list-text",children:S.text})]},S.id))})]})]})}const ai="pi-web-model-usage";function ml(t){if(!t||typeof t!="object")return{};const s={};for(const[n,r]of Object.entries(t)){const c=typeof r=="number"?Math.floor(r):0;Number.isFinite(c)&&c>0&&(s[n]=c)}return s}function hl(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function gl(t,s){const n=s;return t.map((r,c)=>({m:r,i:c,count:n[r.id]??0})).sort((r,c)=>c.count-r.count||r.i-c.i).map(r=>r.m)}function ri(){try{const t=localStorage.getItem(ai);return t?ml(JSON.parse(t)):{}}catch{return{}}}function fl(t){try{localStorage.setItem(ai,JSON.stringify(t))}catch{}}function xl(t){const s=hl(ri(),t);return fl(s),s}const Rs="pi-web-ui:prompt-history",yl=100,li="pi-web-ui:prompt-history-settings",Cs={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function oi(t){const s=Cs;if(!t||typeof t!="object")return{...s};const n=t;let r=typeof n.maxEntries=="number"?Math.floor(n.maxEntries):s.maxEntries;(!Number.isFinite(r)||r<1)&&(r=1),r>500&&(r=500);let c=typeof n.charLimit=="number"?Math.floor(n.charLimit):s.charLimit;(!Number.isFinite(c)||c<100)&&(c=100),c>2e4&&(c=2e4);const i=typeof n.charLimitEnabled=="boolean"?n.charLimitEnabled:s.charLimitEnabled;return{maxEntries:r,charLimitEnabled:i,charLimit:c}}function ci(){try{const t=localStorage.getItem(li);return t?oi(JSON.parse(t)):{...Cs}}catch{return{...Cs}}}function cs(t){const s=oi(t);try{localStorage.setItem(li,JSON.stringify(s))}catch{}try{let n=Tt();s.charLimitEnabled&&(n=n.map(r=>r.length>s.charLimit?r.slice(0,s.charLimit):r)),n.length>s.maxEntries&&(n=n.slice(n.length-s.maxEntries)),di(n)}catch{}}function vl(t){if(!Array.isArray(t))return[];const s=[];for(const n of t){if(typeof n!="string")continue;const r=n.trim();r&&s.push(r)}return s}function bl(t,s,n=yl){const r=s.trim();if(!r||t.length>0&&t[t.length-1]===r)return t;const c=[...t,r];return c.length>n?c.slice(c.length-n):c}function Tt(){try{const t=localStorage.getItem(Rs);return t?vl(JSON.parse(t)):[]}catch{return[]}}function di(t){let s=t;for(;s;)try{localStorage.setItem(Rs,JSON.stringify(s));return}catch(n){if(!(n instanceof DOMException&&(n.name==="QuotaExceededError"||n.code===22))||s.length<=1)return;s=s.slice(Math.ceil(s.length/2))}}function kl(t){let s=t.trim();if(!s)return;const n=ci();n.charLimitEnabled&&s.length>n.charLimit&&(s=s.slice(0,n.charLimit));const r=Tt(),c=bl(r,s,n.maxEntries);c!==r&&di(c)}function jl(){try{localStorage.removeItem(Rs)}catch{}}const wl=["off","minimal","low","medium","high","xhigh","max"],Nl=l.memo(function({state:s,models:n,modelsLoading:r,send:c,onManageModels:i,providerKeys:a,compact:o=!1}){const u=be(),m=s==null?void 0:s.model,f=m?`${m.provider}/${m.id}`:null,[y,x]=l.useState(!1),[b,T]=l.useState(!1),[D,H]=l.useState(""),[N,j]=l.useState(null),[Q,V]=l.useState({}),J=l.useRef(null),U=l.useRef(null),[W,K]=l.useState(null);l.useEffect(()=>{if(!y){K(null);return}if(n.length===0)return;const w=requestAnimationFrame(()=>{const $=U.current;$&&K($.offsetWidth)});return()=>cancelAnimationFrame(w)},[y,n.length]),l.useEffect(()=>{y&&V(ri())},[y]),l.useEffect(()=>{y||(H(""),j(null))},[y]);const G=l.useMemo(()=>{const w=new Map;for(const q of n)w.set(q.provider,(w.get(q.provider)??0)+1);const $=[];for(const[q,ie]of[...w.entries()].sort((v,L)=>v[0].localeCompare(L[0]))){const v=a[q];if(v&&v.length>1)for(const L of v)$.push({provider:q,keyName:L.name,count:ie});else $.push({provider:q,keyName:null,count:ie})}return $},[n,a]),C=l.useMemo(()=>gl(n,Q),[n,Q]),M=l.useMemo(()=>{let w=C;N&&(w=w.filter(q=>q.provider===N.provider));const $=D.trim().toLowerCase();return $?w.filter(q=>q.name.toLowerCase().includes($)||q.provider.toLowerCase().includes($)||q.id.toLowerCase().includes($)):w},[C,D,N]),k=l.useMemo(()=>{const w=[];for(const $ of M){const q=a[$.provider];if(!q||q.length<=1){w.push({model:$,key:null});continue}let ie=q.find(v=>v.active)??q[0];if((N==null?void 0:N.provider)===$.provider&&N.keyName){const v=q.find(L=>L.name===N.keyName);v&&(ie=v)}w.push({model:$,key:ie})}return w},[M,a,N]),[_,Z]=l.useState(!1),z=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,I=wl.map(w=>({value:w,label:u(`thinking.${w}`),supported:z?z.has(w):!0})),R=w=>{var $;return(($=I.find(q=>q.value===w))==null?void 0:$.label)??w};return l.useEffect(()=>{y&&n.length===0&&!_&&!r&&(Z(!0),c({type:"list_models"}))},[y,n.length,_,r,c]),l.useEffect(()=>{n.length>0&&Z(!1)},[n.length]),l.useEffect(()=>{var $;if(!y)return;const w=($=J.current)==null?void 0:$.querySelector(".dd-item.active");w==null||w.scrollIntoView({block:"nearest"})},[y,f,n.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Nt,{}),e.jsx("span",{className:"chip-model",children:m?m.name:u("selectModel")}),!o&&(m==null?void 0:m.vision)&&e.jsx("span",{className:"chip-vision",title:u("vision"),children:"🖼"}),!o&&m&&e.jsx("span",{className:"chip-sub",children:m.provider})]}),open:y,onOpenChange:x,menuClassName:"dd-menu-model",menuRef:U,menuStyle:W!=null?{width:W}:void 0,direction:"up",children:[e.jsx("div",{className:"dd-header",children:u("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(Ut,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:u("searchModels"),value:D,onChange:w=>H(w.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[G.length>1&&e.jsxs("div",{className:"dd-provider-col",children:[e.jsx("div",{className:"dd-provider-head",children:u("providers")}),e.jsx("button",{type:"button",className:`dd-provider-item ${N===null?"active":""}`,onClick:()=>j(null),children:e.jsx("span",{children:u("allProviders")})}),G.map(w=>{const $=(N==null?void 0:N.provider)===w.provider&&(N==null?void 0:N.keyName)===w.keyName;return e.jsxs("button",{type:"button",className:`dd-provider-item ${$?"active":""}`,onClick:()=>j($?null:{provider:w.provider,keyName:w.keyName}),title:w.keyName?`${w.provider} · ${w.keyName}`:`${w.provider} · ${w.count}`,children:[e.jsxs("span",{className:"dd-provider-txt",children:[e.jsx("span",{className:"dd-provider-name",children:w.provider}),w.keyName&&e.jsx("span",{className:"dd-provider-key",children:w.keyName})]}),e.jsx("span",{className:"dd-provider-count",children:w.count})]},w.keyName?`${w.provider}::${w.keyName}`:w.provider)})]}),e.jsxs("div",{className:"dd-model-scroll",ref:J,children:[(_||r)&&e.jsx("div",{className:"dd-loading",children:u("loading")}),n.length===0&&!_&&!r&&e.jsx("div",{className:"dd-loading",children:u("noModels")}),M.length===0&&n.length>0&&e.jsx("div",{className:"dd-loading",children:u("noModelMatches")}),k.map(w=>{const $=w.model,q=f===$.id&&(!w.key||w.key.active);return e.jsx($e,{active:q,onClick:()=>{w.key&&!w.key.active&&c({type:"activate_provider_key",provider:$.provider,keyName:w.key.name}),f!==$.id&&c({type:"set_model",modelId:$.id}),x(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:$.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:$.provider}),w.key&&e.jsxs("span",{className:`dd-model-key ${w.key.active?"active":""}`,children:[w.key.active?"●":"○"," ",w.key.name]}),(Q[$.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:u("modelUsedCount",{n:Q[$.id]})}),($.reasoning||$.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[$.reasoning&&e.jsx("span",{className:"dd-model-badge",children:u("reasoning")}),$.vision&&e.jsx("span",{className:"dd-model-badge",children:u("vision")})]})]})]})},w.key?`${$.id}::${w.key.name}`:$.id)})]})]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>c({type:"list_models"}),children:u("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{x(!1),i()},children:u("manageModels")})]})]}),e.jsxs(Xe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(At,{}),e.jsx("span",{className:"chip-sub",children:u("thinkingChip",{level:s?R(s.thinkingLevel):"—"})})]}),open:b,onOpenChange:T,direction:"up",children:[e.jsx("div",{className:"dd-header",children:u("thinkingLevel")}),I.map(w=>e.jsx($e,{active:(s==null?void 0:s.thinkingLevel)===w.value,disabled:!w.supported,title:w.supported?void 0:u("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==w.value&&c({type:"set_thinking",level:w.value}),T(!1)},children:w.label},w.value))]})]})}),Cl=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches,Sl=l.memo(function({ready:s,streaming:n,messages:r,slashCommands:c,modelState:i,models:a,modelsLoading:o,send:u,attachments:m,onRemoveAttachment:f,onAddImageFiles:y,onAddLocalFiles:x,onNotice:b,onSent:T,onManageModels:D,providerKeys:H}){const N=be(),{locale:j}=Mt(),{openPicker:Q}=ni(),V=g=>j==="en"&&g.descriptionEn?g.descriptionEn:g.description??"",J=g=>j==="en"&&g.argumentHintEn?g.argumentHintEn:g.argumentHint??"",[U,W]=l.useState(""),[K,G]=l.useState(!1),[C,M]=l.useState(null),[k,_]=l.useState(0),[Z,z]=l.useState(!1),[I,R]=l.useState(void 0),w=l.useRef(null),$=l.useRef(null),q=l.useRef(null),ie=l.useRef(-1),v=l.useRef(""),L={builtin:N("slashBuiltin"),extension:N("slashExtension"),prompt:N("slashPrompt"),skill:N("slashSkill"),plugin:N("slashPlugin")},d=g=>{const O=g.match(/^\/([^\s]*)$/);if(O&&s){const me=O[1].toLowerCase(),ue=c.filter(ye=>ye.name.toLowerCase().startsWith(me));M(ue.length>0?ue:null),_(0)}else M(null)};l.useEffect(()=>{var O;const g=(O=q.current)==null?void 0:O.querySelector(".slash-item.active");g==null||g.scrollIntoView({block:"nearest"})},[k,C]);const E=g=>{var fe;const O=C??[],me=g??O[k%Math.max(O.length,1)];if(!me){M(null);return}const ue=U.match(/^\/([^\s]*)([\s\S]*)$/),ye=ue?ue[2]:"";W(`/${me.name} ${ye}`),M(null),(fe=w.current)==null||fe.focus()},h=async()=>{const O=[...r].reverse().find(ue=>ue.role==="assistant"&&ue.content.some(ye=>ye.type==="text"&&ye.text)),me=O==null?void 0:O.content.filter(ue=>ue.type==="text").map(ue=>ue.text).join(`
|
|
321
|
+
`);if(!me){b("warning",N("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(me),b("info",N("slashCopied"))}catch{b("error",N("slashCopyFailed"))}},A=g=>{if(!g||g.length===0){b("warning",N("foldersNotSupported"));return}const O=Array.from(g).filter(ye=>Ge(ye.type)),me=Array.from(g).filter(ye=>!Ge(ye.type)),ue=Y();O.length>0&&ue?b("warning",ue):O.length>0&&y(O),me.length>0&&x(me)},ee=g=>{var ye;const O=(ye=g.clipboardData)==null?void 0:ye.items;if(!O)return;const me=[];for(const fe of O)if(fe.kind==="file"&&Ge(fe.type)){const ke=fe.getAsFile();ke&&me.push(ke)}if(me.length===0)return;g.preventDefault();const ue=Y();if(ue){b("warning",ue);return}y(me)},Y=()=>{const g=i==null?void 0:i.model;if(!(g!=null&&g.id))return null;const O=a.find(me=>me.id===g.id);return O&&O.vision===!1?N("modelNoVision",{name:O.name}):null},se=s,X=l.useRef(U);l.useEffect(()=>{X.current=U},[U]),l.useEffect(()=>{d(X.current)},[c]),l.useEffect(()=>{const g=O=>{var ue;const me=O.detail;W(me),(ue=w.current)==null||ue.focus()};return window.addEventListener("pi-web:fill",g),()=>window.removeEventListener("pi-web:fill",g)},[]),l.useEffect(()=>{if(!Z)return;const g=O=>{O.key==="Escape"&&z(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[Z]),l.useEffect(()=>{const g=w.current;if(!g)return;g.style.height="auto";const O=g.scrollHeight>220;g.style.height=`${Math.min(g.scrollHeight,220)}px`,g.style.overflowY=O?"auto":"hidden"},[U]);const ge=g=>g.selectionStart!==g.selectionEnd?!1:!g.value.slice(0,g.selectionStart).includes(`
|
|
322
322
|
`),Ne=g=>g.selectionStart!==g.selectionEnd?!1:!g.value.slice(g.selectionStart).includes(`
|
|
323
|
-
`),de=(g=!1)=>{var ue,ye,fe,ke,Le;const O=U.trim(),me=m.some(ae=>ae.imageData||ae.fileData);if(!(!se||!O&&!me)){if(O==="/help"){const ae=(ye=(ue=w.current)==null?void 0:ue.closest(".inputbox"))==null?void 0:ye.getBoundingClientRect();R(ae==null?void 0:ae.width),z(!0),W(""),(fe=w.current)==null||fe.focus();return}if(O==="/copy"){W(""),(ke=w.current)==null||ke.focus(),h();return}if(u({type:"prompt",text:O,queue:g,attachments:m.map(ae=>ae.imageData?{path:"",imageData:ae.imageData,mimeType:ae.mimeType,name:ae.name}:ae.fileData?{path:"",fileData:ae.fileData,mimeType:ae.mimeType,name:ae.name,size:ae.size}:{path:ae.path,mode:ae.mode,...ae.lines?{lines:ae.lines}:{}})})){O&&yl(O),ie.current=-1,v.current="",W(""),T();const ae=i==null?void 0:i.model;ae&&hl(`${ae.provider}/${ae.id}`),(Le=w.current)==null||Le.focus()}}},Ee=g=>{if(!g.nativeEvent.isComposing){if(C&&C.length>0)switch(g.key){case"ArrowDown":g.preventDefault(),_(O=>(O+1)%C.length);return;case"ArrowUp":g.preventDefault(),_(O=>(O-1+C.length)%C.length);return;case"Tab":case"Enter":g.preventDefault(),E();return;case"Escape":g.preventDefault(),M(null);return}if(g.key==="ArrowUp"||g.key==="ArrowDown"){if(g.ctrlKey||g.metaKey||g.altKey)return;const O=w.current;if(!O)return;const me=g.key==="ArrowUp";if(me&&!ge(O)||!me&&!Ne(O)||!me&&ie.current===-1)return;const ue=St();if(ue.length===0)return;if(g.preventDefault(),me){if(ie.current===-1){v.current=U;const ye=ue.length-1;ie.current=ye;const fe=ue[ye];W(fe),d(fe),requestAnimationFrame(()=>{const ke=w.current;ke&&(ke.selectionStart=ke.selectionEnd=fe.length)})}else if(ie.current>0){const ye=ie.current-1;ie.current=ye;const fe=ue[ye];W(fe),d(fe),requestAnimationFrame(()=>{const ke=w.current;ke&&(ke.selectionStart=ke.selectionEnd=fe.length)})}}else{const ye=ie.current+1;if(ye<ue.length){ie.current=ye;const fe=ue[ye];W(fe),d(fe),requestAnimationFrame(()=>{const ke=w.current;ke&&(ke.selectionStart=ke.selectionEnd=fe.length)})}else{ie.current=-1;const fe=v.current;W(fe),d(fe),requestAnimationFrame(()=>{const ke=w.current;ke&&(ke.selectionStart=ke.selectionEnd=fe.length)})}}return}if(g.key==="Escape"&&ie.current!==-1){g.preventDefault();const O=v.current;ie.current=-1,W(O),d(O),requestAnimationFrame(()=>{const me=w.current;me&&(me.selectionStart=me.selectionEnd=O.length)});return}if(g.key==="Enter"){if(jl&&!g.shiftKey&&!(g.ctrlKey||g.metaKey))return;g.shiftKey||(g.preventDefault(),de())}}},le=()=>e.jsx("div",{className:"inputbox-actions",children:n?e.jsxs(e.Fragment,{children:[U.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:N("supplementTip"),onClick:()=>de(!0),children:[e.jsx(Cn,{})," ",N("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:N("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(Ht,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:N("sendTip"),disabled:!se||!U.trim()&&!m.some(g=>g.imageData||g.fileData),onClick:()=>de(),children:e.jsx(In,{})})});return e.jsxs("div",{className:`inputbar${K?" drop-active":""}`,onDragOver:g=>{g.preventDefault(),g.stopPropagation(),G(!0)},onDragLeave:g=>{g.currentTarget.contains(g.relatedTarget)||G(!1)},onDrop:g=>{var O;g.preventDefault(),g.stopPropagation(),G(!1),A(((O=g.dataTransfer)==null?void 0:O.files)??null)},children:[K&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",N("dropHereToAttach")]})}),m.length>0&&e.jsxs("div",{className:"attach-row",children:[m.map(g=>e.jsxs("span",{className:`attach-chip ${g.imageData?"image":g.fileData?"file":g.mode}`,title:g.imageData?N("attachImage",{name:g.name}):g.fileData?N("attachFile",{name:g.name}):g.isDir?N("folderRef",{path:g.path}):g.mode==="reference"?N("refOnly",{path:g.path}):g.mode==="lines"&&g.lines?N("attachLines",{path:g.path,start:g.lines.start,end:g.lines.end}):N("attachContent",{path:g.path}),children:[g.imageData?"🖼":g.fileData?"📄":g.isDir?"📁":g.mode==="reference"?"🔗":"📎"," ",g.name,g.mode==="lines"&&g.lines&&e.jsxs("span",{className:"attach-range",children:["L",g.lines.start,"-",g.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:N("removeAttachment"),onClick:()=>y(g.key??g.path),children:"×"})]},g.key??`${g.path}|${g.mode}|${g.lines?`${g.lines.start}-${g.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:N("attachHint")})]}),C&&C.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:q,"aria-label":N("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:N("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>M(null),children:"Esc"})]}),C.map((g,O)=>e.jsxs("button",{type:"button",className:`slash-item${O===k?" active":""}`,onMouseEnter:()=>_(O),onClick:()=>E(g),children:[e.jsxs("span",{className:"slash-name",children:["/",g.name]}),e.jsx("span",{className:`slash-source ${g.source}`,children:L[g.source]}),e.jsxs("span",{className:"slash-desc",children:[V(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:J(g)})]})]},g.name))]}),Z&&e.jsx("div",{className:"modal-backdrop",onClick:()=>z(!1),children:e.jsxs("div",{className:"slash-help",style:I?{width:I}:void 0,onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",N("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>z(!1),children:N("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:N("slashLoading")}):c.map(g=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",g.name]}),e.jsx("span",{className:`slash-source ${g.source}`,children:L[g.source]}),e.jsxs("span",{className:"slash-help-desc",children:[V(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:J(g)})]})]},g.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:$,type:"file",multiple:!0,hidden:!0,onChange:g=>{A(g.target.files),g.target.value=""}}),e.jsx("textarea",{ref:w,value:U,rows:1,placeholder:N(se?n?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!se,onChange:g=>{ie.current=-1,W(g.target.value),d(g.target.value)},onKeyDown:Ee,onPaste:ee}),e.jsxs("div",{className:"composer-tools",children:[e.jsxs("div",{className:"composer-tools-left",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:N("uploadFile"),disabled:!se,onClick:()=>{var g;return(g=$.current)==null?void 0:g.click()},children:e.jsx(Ui,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:N("tpl.openPicker"),onClick:Q,children:e.jsx(Xi,{})}),e.jsx(kl,{state:i,models:a,modelsLoading:o,send:u,onManageModels:D,providerKeys:H,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:le()})]})]})]})}),Nl=l.memo(function({goal:s,models:n,modelsLoading:r,activeConversationId:c,engine:i,send:a}){var I,R,w,$,q,ie,v;const o=be(),{locale:u}=Pt(),m=u==="en"&&s.statusEn?s.statusEn:s.status||"",y=u==="en"&&((I=s.wizard)!=null&&I.statusEn)?s.wizard.statusEn:((R=s.wizard)==null?void 0:R.status)||"",x=i==="dsh",f=!s.conversationId||s.conversationId===c,b=s.goal!==null&&f,[T,D]=l.useState(""),[H,N]=l.useState(s.reviewModel??""),[j,Q]=l.useState(s.maxRounds),[V,J]=l.useState(s.locked),[U,W]=l.useState(!1),[K,G]=l.useState(!1),[C,M]=l.useState(!0);l.useEffect(()=>{N(s.reviewModel??""),Q(s.maxRounds||0),J(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),l.useEffect(()=>{U&&n.length===0&&!K&&!r&&(G(!0),a({type:"list_models"}))},[U,n.length,K,r,a]),l.useEffect(()=>{n.length>0&&G(!1)},[n.length]);const k=()=>{var L;return H?((L=n.find(d=>d.id===H))==null?void 0:L.name)??H:o("goalBarUseMainModel")},_=()=>{const L=T.trim();L&&(a({type:"set_goal",goal:L,...H?{reviewModel:H}:{},maxRounds:j,locked:V}),D(""),M(!1))},Z=()=>{const L=T.trim();L&&(a({type:"start_goal_wizard",text:L,...H?{wizardModel:H}:{},maxRounds:j,locked:V}),D(""),M(!1))},z=(((w=s.wizard)==null?void 0:w.active)??!1)&&f;return z?e.jsx("div",{className:`goalbar goalbar-active ${z?"wizard":""}`,children:e.jsxs("div",{className:"goalbar-active-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx("span",{className:"goalbar-spin",children:"🔍"})}),e.jsxs("span",{className:"goalbar-text",title:(($=s.wizard)==null?void 0:$.draft)??"",children:[o("goalWizardRunning"),": ",(q=s.wizard)==null?void 0:q.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[o("goalBarRound",{n:(((ie=s.wizard)==null?void 0:ie.step)??0)+1})," / ",((v=s.wizard)==null?void 0:v.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:y||o("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),onClick:()=>{a({type:"clear_goal"}),M(!0)},children:e.jsx(Re,{})})]})}):b?e.jsx("div",{className:`goalbar goalbar-active ${s.reviewing?"reviewing":""}`,children:e.jsxs("div",{className:"goalbar-active-row",children:[e.jsx("span",{className:"goalbar-icon",children:s.reviewing?e.jsx("span",{className:"goalbar-spin",children:"◌"}):"🎯"}),e.jsx("span",{className:"goalbar-text",title:s.goal??"",children:s.goal}),s.reviewing?e.jsxs("span",{className:"goalbar-chip reviewing",children:[o("goalBarReviewing")," ",o("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?o("goalBarPassed"):s.verdict==="fail"?o("goalBarFailed"):`${o("goalBarRound",{n:s.round||1})} · ${s.locked?o("goalBarLocked"):o("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:m}),e.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),disabled:s.reviewing,onClick:()=>{a({type:"clear_goal"}),M(!0)},children:e.jsx(Re,{})})]})}):C?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:o("goalBarPlaceholder"),onClick:()=>M(!1),children:[e.jsx($s,{})," ",e.jsx("span",{children:o("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx($s,{})}),e.jsx("input",{className:"goalbar-input",value:T,placeholder:o("goalBarPlaceholder"),onChange:L=>D(L.target.value),onKeyDown:L=>{L.key==="Enter"&&_()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!T.trim(),onClick:_,children:o("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!T.trim(),title:o("goalWizardTip"),onClick:Z,children:["🔍 ",o("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o(V?"goalBarLocked":"goalBarUnlocked"),onClick:()=>J(L=>(a({type:"set_goal_prefs",locked:!L}),!L)),children:V?e.jsx(Qi,{}):e.jsx($i,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o("goalBarClear"),onClick:()=>M(!0),children:e.jsx(Tt,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[x?e.jsx("p",{className:"goalbar-dsh-note",children:o("dshNoReviewModel")}):e.jsxs(Xe,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[o("goalBarReviewModel"),": ",e.jsx("b",{children:k()})]}),open:U,onOpenChange:W,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("goalBarReviewModel")}),(K||r)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),n.length===0&&!K&&!r&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),e.jsx($e,{active:H==="",onClick:()=>{N(""),W(!1),a({type:"set_goal_prefs",reviewModel:""})},children:o("goalBarUseMainModel")}),n.map(L=>e.jsx($e,{active:H===L.id,onClick:()=>{N(L.id),W(!1),a({type:"set_goal_prefs",reviewModel:L.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:L.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:L.provider})})]})},L.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>a({type:"list_models"}),children:o("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:o("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:o("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:j,placeholder:o("goalBarUnlimitedShort"),onChange:L=>{const d=parseInt(L.target.value,10);if(Number.isNaN(d)||d<0){Q(0);return}Q(d)},onBlur:()=>a({type:"set_goal_prefs",maxRounds:j}),onKeyDown:L=>{L.key==="Enter"&&(a({type:"set_goal_prefs",maxRounds:j}),L.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:o(V?"goalBarLocked":"goalBarUnlocked")})]})]})});function Cl(t){const s=Math.max(0,t.input??0),n=Math.max(0,t.cacheRead??0),r=Math.max(0,t.cacheWrite??0),c=s+n+r;return{totalInput:c,miss:s,read:n,write:r,hitRate:c>0?Math.min(n/c,1):0,writeRate:c>0?Math.min(r/c,1):0}}const oi=2e3;function Sl(t,s,n=oi){return t.filter(r=>s-r.t<=n)}function Tl(t,s=oi){if(t.length<2)return 0;const n=t[t.length-1],r=t.find(i=>i.t>=n.t-s)??t[0],c=(n.t-r.t)/1e3;return c<=0?0:Math.max(0,(n.out-r.out)/c)}function mn(t){if(!t)return 0;let s=0;for(let r=0;r<t.length;r++){const c=t.charCodeAt(r);(c>=12352&&c<=12543||c>=13312&&c<=19903||c>=19968&&c<=40959||c>=63744&&c<=64255||c>=65280&&c<=65519||c===12288)&&s++}const n=t.length-s;return Math.round(s+n/4)}function El(t){let s=0;for(const n of t)n.type==="text"&&typeof n.text=="string"&&n.text?s+=mn(n.text):n.type==="thinking"&&typeof n.thinking=="string"&&n.thinking&&(s+=mn(n.thinking));return s}const et="@root";function Pl({chat:t,send:s}){const n=be(),r=t.state,[c,i]=l.useState(!1),[a,o]=l.useState(""),[u,m]=l.useState(""),[y,x]=l.useState(!1),[f,b]=l.useState(""),[T,D]=l.useState(-1),H=l.useRef(null),N=l.useRef(null),j=t.pathCompletions.filter(h=>h.type==="dir"),Q=h=>h.endsWith("/")?h:h+"/",V=h=>{let A=h.endsWith("/")&&h!=="/"?h.slice(0,-1):h;if(A===et||A==="/")return null;const ee=A.lastIndexOf("/");if(ee<0)return/^[A-Za-z]:$/.test(A)?et:null;if(ee===0)return"/";const Y=A.slice(0,ee);return/^[A-Za-z]:$/.test(Y)?Y+"/":Y};l.useEffect(()=>{if(!c)return;const h=setTimeout(()=>{s({type:"complete_path",path:Q(a)})},60);return()=>clearTimeout(h)},[a,c,s]),l.useEffect(()=>{if(!c||u===a)return;const h=setTimeout(()=>{s({type:"complete_path",path:u})},150);return()=>clearTimeout(h)},[u,a,c,s]);const J=l.useRef([]),U=(r==null?void 0:r.isStreaming)??!1,W=r!=null&&r.streamingMessage?El(r.streamingMessage.content):0;if(l.useEffect(()=>{if(!U){J.current=[];return}const h=Date.now(),A=J.current,ee=A[A.length-1];ee&&h-ee.t<250||(J.current=Sl([...A,{t:h,out:W}],h))},[U,W]),!r)return null;const K=r.stats,G=Cl(K.tokens),C=G.hitRate*100,M=G.totalInput===0?"":G.hitRate>=.7?"ok":G.hitRate>=.4?"mid":"warn",k=G.totalInput>0?`${C.toFixed(1)}%`:"—",_=U?Tl(J.current):0,Z=t.ready?"ok":"busy",z=t.ready?n("connected"):n("connecting"),I=K.contextUsage,R=I.tokens!==null&&I.percent!==null?`${it(I.tokens)} / ${it(I.contextWindow)}`:"—",w=I.percent??null,$=w===null?"":w>=80?"warn":w>=50?"mid":"ok",q=r.queue.steering.length+r.queue.followUp.length,ie=()=>{m(r.cwd),o(r.cwd),x(!1),b(""),i(!0)},v=h=>{const A=h.trim();A!==et&&(A&&A!==r.cwd&&s({type:"set_cwd",path:A}),i(!1))},L=()=>{const h=f.trim();h&&(s({type:"make_dir",path:`${Q(a)}${h}`}),setTimeout(()=>{s({type:"complete_path",path:Q(a)})},80),b(""),x(!1))},d=h=>{if(h.key==="Escape")h.stopPropagation(),i(!1);else if(h.key==="Enter"&&!h.nativeEvent.isComposing)v(u);else if(h.key==="Tab"){if(j.length===0)return;h.preventDefault();const A=T>=0?(T+1)%j.length:0;D(A),m(j[A].path),o(j[A].path)}},E=V(a);return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${Z}`,title:z}),e.jsx("span",{className:"status-item",children:z}),e.jsx("span",{className:"status-sep",children:"·"}),t.engine&&t.engine!=="pi"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`status-item engine-badge engine-${t.engine}`,title:`${n("engineBadge")}: ${t.engine}`,children:t.engine==="dsh"?"DSH":t.engine}),e.jsx("span",{className:"status-sep",children:"·"})]}),e.jsxs("span",{className:"status-item status-ctx",title:n("contextUsage"),children:[n("context"),e.jsx("span",{className:`ctx-bar ${$}`,children:w!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(w,100)}%`}})}),R]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("cumulativeCost"),children:["$",Ml(K.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-cache",title:n("cacheHitTip",{read:it(G.read),write:it(G.write),miss:it(G.miss),input:it(G.totalInput)}),children:[n("cacheHit"),e.jsx("b",{className:`cache-pct ${M}`,children:k})]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("sessionMessages"),children:[n("messages")," ",K.totalMessages]}),t.statuses.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsx("span",{className:"status-item ext-status",title:n("pluginStatus"),children:t.statuses.map(h=>h.text).join(" · ")})]}),r.isStreaming&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item working",children:[e.jsx("span",{className:"working-spin"}),n("working"),q>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",q," ",n("queued")]})]}),e.jsx("span",{className:"status-item status-rate",title:n("rateTip"),children:_>0?`${Math.round(_)}${n("tps")}`:"…"})]}),c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"status-cwd-backdrop",onClick:()=>i(!1)}),e.jsxs("div",{className:"cwd-picker",children:[e.jsxs("div",{className:"cwd-picker-head",children:[e.jsxs("span",{className:"cwd-picker-title",title:a===et?n("computer"):a,children:[a===et?"💻":e.jsx(st,{}),e.jsx("span",{children:a===et?n("computer"):a})]}),e.jsxs("button",{type:"button",className:"cwd-up",disabled:!E,title:n("cwdGoUp"),onClick:()=>{E&&(o(E),m(E),D(-1))},children:["↑ ",n("cwdGoUp")]})]}),e.jsxs("div",{className:"cwd-picker-row",children:[e.jsx("input",{ref:H,className:"status-cwd-input cwd-picker-input",value:u,placeholder:n("enterPath"),spellCheck:!1,onChange:h=>{m(h.target.value),D(-1)},onKeyDown:d}),e.jsx("button",{type:"button",className:"cwd-choose-btn primary",title:n("cwdPickCurrent"),disabled:a===et,onClick:()=>v(a),children:n("cwdPickCurrent")})]}),e.jsxs("div",{className:"cwd-list",children:[j.length===0&&e.jsx("div",{className:"cwd-empty",children:n("cwdEmpty")}),j.map(h=>e.jsxs("div",{className:"cwd-item",children:[e.jsxs("button",{type:"button",className:"cwd-enter",title:`${n("cwdEnter")} ${h.path}`,onClick:()=>{o(h.path),m(h.path),D(-1)},children:[e.jsx(st,{}),e.jsx("span",{className:"cwd-name",children:h.name})]}),e.jsx("button",{type:"button",className:"cwd-choose-btn",title:n("cwdChoose"),onClick:()=>v(h.path),children:n("cwdChoose")})]},h.path))]}),e.jsx("div",{className:"cwd-picker-foot",children:y?e.jsxs("div",{className:"cwd-newrow",children:[e.jsx("input",{ref:N,value:f,autoFocus:!0,spellCheck:!1,placeholder:n("cwdNewName"),onChange:h=>b(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.nativeEvent.isComposing?(h.preventDefault(),L()):h.key==="Escape"&&(h.stopPropagation(),x(!1),b(""))}}),e.jsx("button",{type:"button",className:"cwd-choose-btn primary",onClick:L,children:n("cwdCreate")}),e.jsx("button",{type:"button",className:"cwd-choose-btn",onClick:()=>{x(!1),b("")},children:n("cwdCancel")})]}):e.jsxs("button",{type:"button",className:"cwd-newbtn",onClick:()=>x(!0),children:["+ ",n("cwdNewFolder")]})})]})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:n("cwdTip",{path:r.cwd}),onClick:ie,children:["📁 ",r.cwd]})]})}function it(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function Ml(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function Il({dialog:t,send:s}){const n=be(),[r,c]=l.useState(""),[i,a]=l.useState(0),o=y=>{s({type:"dialog_response",id:t.id,value:y})};l.useEffect(()=>{c(""),a(0);const y=x=>{x.key==="Escape"&&o(null)};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t.id]);const u=Array.isArray(t.args[0])?t.args[0]:[],m=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("pluginRequest")}),t.title&&t.title!==n("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>o(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[u.map((y,x)=>e.jsx("button",{type:"button",className:`dialog-option ${x===i?"sel":""}`,onMouseEnter:()=>a(x),onClick:()=>o(y),children:y},x)),u.length===0&&e.jsx("div",{className:"dialog-hint",children:n("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:m}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(!1),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(!0),children:n("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:r,placeholder:m||n("inputPlaceholder"),autoFocus:!0,onChange:y=>c(y.target.value),onKeyDown:y=>{y.key==="Enter"&&!y.nativeEvent.isComposing&&o(r)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(null),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(r),children:n("ok")})]})]})]})}function Rl({question:t,send:s}){const n=be(),[r,c]=l.useState({}),[i,a]=l.useState({}),[o,u]=l.useState(()=>t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1);l.useEffect(()=>{c({}),a({}),u(t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1)},[t.id,t.deadline]),l.useEffect(()=>{if(!t.deadline)return;const f=setInterval(()=>{u(b=>{const T=Math.max(0,Math.ceil((t.deadline-Date.now())/1e3));return T<=0&&b>0&&s({type:"question_answer",id:t.id,answers:[],cancelled:!0}),T})},1e3);return()=>clearInterval(f)},[t.id,t.deadline]);const m=f=>{if(f){s({type:"question_answer",id:t.id,answers:[],cancelled:!0});return}const b=t.questions.map(T=>{const D=r[T.id]??[],H=(i[T.id]??"").trim();return{id:T.id,selected:D,...H?{custom:H}:{}}});s({type:"question_answer",id:t.id,answers:b})};l.useEffect(()=>{const f=b=>{b.key==="Escape"&&m(!0)};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t.id]);const y=(f,b,T)=>{c(D=>{const H=D[f]??[];return T?{...D,[f]:H.includes(b)?H.filter(N=>N!==b):[...H,b]}:{...D,[f]:[b]}})},x=t.questions.every(f=>{var b;return(((b=r[f.id])==null?void 0:b.length)??0)>0||(i[f.id]??"").trim()!==""});return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":"select",children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("modelQuestion")}),o>=0&&e.jsx("span",{className:"question-timer",children:o>0?n("questionTimeout",{s:o}):n("questionTimeoutExpired")}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>m(!0),children:"✕"})]}),t.questions.map((f,b)=>{var T;return e.jsxs("div",{className:"set-section",children:[e.jsx("div",{className:"set-section-title",children:f.header??`${n("modelQuestion")} ${b+1}`}),e.jsx("p",{className:"set-row-desc",children:f.question}),f.detail&&e.jsx("p",{className:"set-hint",children:f.detail}),(((T=f.options)==null?void 0:T.length)??0)>0&&e.jsx("div",{className:"set-list",children:f.options.map(D=>{const H=(r[f.id]??[]).includes(D.label);return e.jsxs("button",{type:"button",className:`set-row question-option${H?" active":""}`,onClick:()=>y(f.id,D.label,!!f.multiSelect),children:[e.jsxs("span",{className:"set-row-name",children:[f.multiSelect?H?"☑ ":"☐ ":H?"● ":"○ ",D.label]}),D.description&&e.jsx("span",{className:"set-row-desc",children:D.description})]},D.label)})}),e.jsx("input",{className:"set-prompt-input question-custom",placeholder:n("modelQuestionCustom"),value:i[f.id]??"",onChange:D=>a(H=>({...H,[f.id]:D.target.value}))})]},f.id)}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"dialog-submit",disabled:!x,onClick:()=>m(!1),children:n("modelQuestionSubmit")}),e.jsx("button",{type:"button",className:"dialog-dismiss-inline",onClick:()=>m(!0),children:n("cancel")})]})]})}const hn=t=>`'${t.replace(/'/g,"'\\''")}'`;function Ll(t){if(t.x==="?"&&t.y==="?")return"untracked";const s=t.x!==" "&&t.x!=="?",n=t.y!==" "&&t.y!=="?";return s&&n?"both":s?"staged":"unstaged"}function Dl({chat:t,send:s,terminal:n,active:r,onSwitchToTerminal:c}){var qe,ze;const i=be(),[a,o]=l.useState(null),[u,m]=l.useState([]),[y,x]=l.useState(""),[f,b]=l.useState(new Map),[T,D]=l.useState("changes"),[H,N]=l.useState([]),[j,Q]=l.useState(null),[V,J]=l.useState(""),[U,W]=l.useState(!1),[K,G]=l.useState(null),[C,M]=l.useState(null),[k,_]=l.useState(!1),[Z,z]=l.useState(!1),[I,R]=l.useState(!1),[w,$]=l.useState(null),[q,ie]=l.useState(!1),[v,L]=l.useState(""),d=l.useRef(0),E=l.useRef(-1),h=l.useRef(-1),A=l.useRef(-1),ee=l.useRef(-1),Y=l.useRef(void 0),se=l.useRef(null),X=l.useRef([]),ge=l.useCallback(P=>{if(P.reqId===E.current){if(E.current=-1,z(!1),$(null),!P.ok){$(P.error??i("scmQueryFailedShort"));return}if(P.notRepo){ie(!0),o(null),m([]),b(new Map),N([]),Q(null),J(""),M(null);return}ie(!1);const xe={branch:P.branch??"",detached:!!P.detached,upstream:P.upstream??null,ahead:P.ahead??0,behind:P.behind??0,upstreamGone:!!P.upstreamGone,files:(P.files??[]).map(ve=>({...ve}))},pe=(P.branches??[]).map(ve=>({...ve})),Se=new Map;for(const[ve,S]of Object.entries(P.stats??{}))Se.set(ve,{add:S[0],del:S[1]});o(xe),m(pe),b(Se),x(ve=>{var S;return xe.detached?ve||"":xe.branch&&pe.some(B=>B.name===xe.branch)?xe.branch:ve&&pe.some(B=>B.name===ve)?ve:((S=pe[0])==null?void 0:S.name)??""}),M(ve=>ve&&!xe.files.some(S=>S.path===ve.file.path)?null:ve)}else if(P.reqId===h.current){if(h.current=-1,_(!1),!P.ok){$(P.error??i("scmQueryFailedShort"));return}const xe=se.current;if(!xe)return;M({file:xe,staged:P.stagedText??"",worktree:P.worktreeText??"",untracked:!1})}else if(P.reqId===ee.current){if(ee.current=-1,R(!1),!P.ok){$(P.error??i("scmQueryFailedShort"));return}N((P.history??[]).map(xe=>({...xe})))}else if(P.reqId===A.current){if(A.current=-1,W(!1),!P.ok){$(P.error??i("scmQueryFailedShort"));return}J(P.text??"")}},[]);l.useEffect(()=>{const P=t.scmData;P&&P.type==="scm_data"&&ge(P)},[t.scmData,ge]);const Ne=l.useCallback((P,xe)=>{if(!t.ready||t.status!=="open")return!1;const pe=++d.current;return s({...P,reqId:pe})?(xe.current=pe,!0):(d.current-=1,!1)},[t.ready,t.status,s]),de=l.useCallback((P=!1,xe=!1)=>{var pe;!t.ready||t.status!=="open"||(pe=t.state)!=null&&pe.cwd&&(Y.current!==void 0&&Y.current!==t.state.cwd&&(o(null),m([]),b(new Map),N([]),R(!1),ee.current=-1,Q(null),J(""),M(null),G(null)),Y.current=t.state.cwd,$(null),Ne({type:"scm_status"},E)&&(xe||z(!0)))},[t.ready,(qe=t.state)==null?void 0:qe.cwd,t.status,Ne]),Ee=l.useCallback(P=>{if(G(P),Q(null),se.current=P,P.x==="?"&&P.y==="?"){M({file:P,staged:"",worktree:"",untracked:!0});return}_(!0),$(null),Ne({type:"scm_filediff",path:P.path},h)||_(!1)},[Ne]),le=l.useCallback(P=>{Q(P),G(null),M(null),J(""),W(!0),$(null),Ne({type:"scm_commit",hash:P.hash},A)||W(!1)},[Ne]),g=l.useCallback((P,xe)=>{var S,B;if(!t.ready)return;const pe={name:P,command:xe,cwd:"${pwd}"};let Se;const ve=t.terminals.find(oe=>oe.title===P);ve?(n.restart(ve.id),s({type:"run_command",terminalId:ve.id,conversationId:ve.conversationId,command:pe,cols:80,rows:24}),Se=ve.id):(Se=Qe(),n.create({id:Se,conversationId:t.activeConversationId||((S=t.state)==null?void 0:S.conversationId)||"",title:P,cwd:((B=t.state)==null?void 0:B.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:pe})),n.select(Se),c()},[t.ready,(ze=t.state)==null?void 0:ze.cwd,t.terminals,c,s,n]),O=l.useCallback(()=>{const P=v.trim();if(!P||q)return;const xe=P.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");g("git commit",`git commit -m "${xe}"`),L("")},[v,q,g]),me=l.useCallback(()=>{const P=v.trim();if(!P||q)return;const xe=P.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");g("git commit",`git add -A && git commit -m "${xe}"`),L("")},[v,q,g]),ue=l.useCallback(P=>{q||g("git add",`git add -- ${hn(P.path)}`)},[q,g]),ye=l.useCallback(P=>{q||g("git reset",`git reset HEAD -- ${hn(P.path)}`)},[q,g]),fe=l.useCallback(()=>{if(!y||q)return;const P=u.find(xe=>xe.name===y);if(P!=null&&P.remote&&typeof P.remote=="string"){const xe=y.slice(P.remote.length+1);g("git checkout",`git checkout -b ${xe} ${y} || git checkout ${y}`)}else g("git checkout",`git checkout ${y}`)},[y,u,q,g]),ke=l.useCallback(()=>g("git push","git push"),[g]),Le=l.useCallback(()=>g("git pull","git pull"),[g]),ae=l.useCallback(()=>{Ne({type:"scm_history"},ee)||(ee.current=-1)},[Ne]);l.useEffect(()=>{r&&de()},[r,de]),l.useEffect(()=>{T==="history"&&a&&ae()},[T,a,ae]),l.useEffect(()=>{t.scmDirty>0&&r&&de(!1,!0)},[t.scmDirty]),l.useEffect(()=>{if(!r||!t.ready||t.status!=="open")return;const P=setInterval(()=>{document.visibilityState!=="hidden"&&de(!1,!0)},3e4);return()=>clearInterval(P)},[r,t.ready,t.status,de]),l.useEffect(()=>{const P=X.current;if(X.current=t.terminals,!r)return;t.terminals.some(pe=>{var ve;return pe.running!==!1?!1:((ve=P.find(S=>S.id===pe.id))==null?void 0:ve.running)===!0&&pe.title.startsWith("git ")})&&t.ready&&t.status==="open"&&(de(!1,!0),T==="history"&&a&&ae())},[t.terminals,r,t.ready,t.status,de,T,a,ae]);const De={staged:i("scmStaged"),unstaged:i("scmUnstaged"),untracked:i("scmUntracked"),both:i("scmStagedUnstaged")},Ae=P=>{const xe=P.split(`
|
|
324
|
-
`);return e.jsx("pre",{className:"scm-diff-pre",children:xe.map((pe,Se)=>{let ve="";return pe.startsWith("diff --git")||pe.startsWith("index ")||pe.startsWith("new file")||pe.startsWith("deleted file")||pe.startsWith("old mode")||pe.startsWith("new mode")||pe.startsWith("similarity index")||pe.startsWith("rename ")||pe.startsWith("copy ")||pe.startsWith("Binary files")||pe.startsWith("---")||pe.startsWith("+++")?ve="hdr":pe.startsWith("@@")?ve="hunk":pe.startsWith("+")?ve="add":pe.startsWith("-")&&(ve="del"),e.jsx("div",{className:`scm-diff-line ${ve}`,children:pe||" "},Se)})})};return e.jsxs("div",{className:"scm-view",children:[e.jsxs("div",{className:"scm-header",children:[e.jsxs("div",{className:"scm-title-row",children:[e.jsxs("span",{className:"scm-title",children:[e.jsx(At,{}),i("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":T==="changes",className:T==="changes"?"active":"",onClick:()=>{D("changes"),$(null)},children:i("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":T==="history",className:T==="history"?"active":"",onClick:()=>{D("history"),$(null)},children:i("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:i("scmRefreshTip"),disabled:Z,onClick:()=>de(!0),children:e.jsx(rt,{className:Z?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:i("scmCurrentBranch"),children:[e.jsx(At,{}),a?a.detached?i("scmDetached"):a.branch:"…",(a==null?void 0:a.upstream)&&e.jsx("span",{className:"scm-upstream",children:a.upstreamGone?i("scmUpstreamGone"):a.ahead>0||a.behind>0?i("scmAheadBehind",{ahead:a.ahead,behind:a.behind}):a.upstream})]}),e.jsxs("select",{className:"scm-select",value:y,disabled:q||u.length===0,title:i("scmSwitchBranch"),onChange:P=>x(P.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:i("scmSelectBranch")}),u.filter(P=>!P.remote).map(P=>e.jsx("option",{value:P.name,children:P.current?`* ${P.name}`:P.name},P.name)),u.some(P=>P.remote)&&e.jsx("optgroup",{label:i("scmRemoteBranches"),children:u.filter(P=>P.remote).map(P=>e.jsx("option",{value:P.name,children:P.name},P.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!y||y===(a==null?void 0:a.branch)||q,title:i("scmSwitchBranchTip",{branch:y}),onClick:fe,children:[e.jsx(At,{}),i("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!a||a.detached||q,title:i("scmPushTip"),onClick:ke,children:[e.jsx(In,{}),i("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!a||a.detached||q,title:i("scmPullTip"),onClick:Le,children:[e.jsx(Rn,{}),i("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:v,placeholder:i("scmCommitPlaceholder"),disabled:q,onChange:P=>L(P.target.value),onKeyDown:P=>{P.key==="Enter"&&!P.nativeEvent.isComposing&&O()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!v.trim()||q,title:i("scmCommitTip"),onClick:O,children:[e.jsx(Et,{}),i("scmCommit")]}),e.jsx("button",{type:"button",className:"btn",disabled:!v.trim()||q,title:i("scmCommitAllTip"),onClick:me,children:i("scmCommitAll")})]})]}),e.jsxs("div",{className:"scm-body",children:[T==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmHistory")}),H.length>0&&e.jsx("span",{className:"scm-files-count",children:H.length})]}),e.jsx("div",{className:"scm-history-list",children:q?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):!a||I?e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")}):H.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoHistory")}):H.map(P=>e.jsxs("button",{type:"button",className:`scm-commit ${(j==null?void 0:j.hash)===P.hash?"active":""}`,onClick:()=>le(P),title:P.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:P.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:P.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[P.shortHash," · ",P.author," · ",P.date]}),P.decorations&&e.jsx("span",{className:"scm-commit-refs",children:P.decorations})]})]},P.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmChanges")}),a&&a.files.length>0&&e.jsx("span",{className:"scm-files-count",children:a.files.length})]}),e.jsx("div",{className:"scm-files-list",children:q?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):a?a.files.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoChanges")}):a.files.map(P=>{const xe=Ll(P),pe=f.get(P.path);return e.jsxs("div",{className:`scm-file ${(K==null?void 0:K.path)===P.path?"active":""}`,title:De[xe],onClick:()=>Ee(P),children:[e.jsx("span",{className:`scm-file-xy ${xe==="untracked"?"q":"x"}`,children:P.x!==" "?P.x:" "}),e.jsx("span",{className:`scm-file-xy ${xe==="untracked"?"q":"y"}`,children:P.y!==" "?P.y:" "}),e.jsx("span",{className:"scm-file-path",children:P.path}),pe&&(pe.add>0||pe.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[pe.add>0&&e.jsxs("span",{className:"add",children:["+",pe.add]}),pe.del>0&&e.jsxs("span",{className:"del",children:["-",pe.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(P.y!==" "||xe==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:i("scmStageTip",{path:P.path}),onClick:Se=>{Se.stopPropagation(),ue(P)},children:"+"}),xe==="staged"||xe==="both"?e.jsx("button",{type:"button",className:"scm-act",title:i("scmUnstageTip",{path:P.path}),onClick:Se=>{Se.stopPropagation(),ye(P)},children:"−"}):null]})]},P.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:T==="history"?j?`${j.shortHash} ${j.subject}`:i("scmCommitDetail"):K?K.path:i("scmDiff")}),(T==="history"?U:k)&&e.jsx("span",{className:"scm-diff-loading",children:i("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:T==="history"?e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{className:"scm-error",children:w}),!j&&!w&&e.jsx("div",{className:"scm-empty",children:i("scmSelectCommitHint")}),j&&U&&!w&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),j&&!U&&!w&&V?Ae(V):null]}):e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{className:"scm-error",children:w}),!K&&!w&&e.jsx("div",{className:"scm-empty",children:i("scmSelectFileHint")}),K&&!C&&!w&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),K&&C&&C.untracked&&e.jsx("div",{className:"scm-empty",children:i("scmUntrackedNote")}),K&&C&&!C.untracked&&e.jsxs(e.Fragment,{children:[C.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmStaged")}),Ae(C.staged)]}),C.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmUnstaged")}),Ae(C.worktree)]}),!C.staged&&!C.worktree&&e.jsx("div",{className:"scm-empty",children:i("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(ot,{}),e.jsx("span",{children:i("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:c,children:i("scmViewTerminal")})]})]})}function Al({entry:t,send:s}){const n=l.useRef(null),r=be();return l.useEffect(()=>{const c=n.current;if(!c)return;let i;try{i=t.module.mount(c,Ra(t.info.id,a=>s(a)))}catch(a){console.error(`[plugin:${t.info.id}] mount failed:`,a),c.textContent=r("pluginMountFailed",{name:t.info.name})}return()=>{if(typeof i=="function")try{i()}catch(a){console.error(`[plugin:${t.info.id}] cleanup failed:`,a)}c.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:n})}function _l({send:t,piConfigured:s,piAgentInstalled:n,providers:r,installResult:c,onClose:i}){const a=be(),[o,u]=l.useState(!1),[m,y]=l.useState(""),[x,f]=l.useState(""),[b,T]=l.useState(!1);l.useEffect(()=>{t({type:"list_providers"})},[t]),l.useEffect(()=>{s&&i()},[s,i]),l.useEffect(()=>{c&&u(!1)},[c]),l.useEffect(()=>{var V;!m&&r.length>0&&y(((V=r.find(J=>!J.configured))==null?void 0:V.id)??r[0].id)},[r,m]);const D=()=>{o||(u(!0),t({type:"install_pi_agent"}))},H=()=>{!x.trim()||b||(T(!0),t({type:"set_provider_api_key",provider:m.trim(),apiKey:x.trim()}),setTimeout(()=>T(!1),3e3))},N=()=>{t({type:"get_state"}),t({type:"list_providers"})},j=r.find(V=>V.id===m),Q=c!==null&&!c.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":a("close"),onClick:i,children:e.jsx(Re,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(wt,{className:"modal-head-icon"}),e.jsx("h2",{children:a("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:a("setupDesc")}),Q?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:a("installFailed")}),e.jsx("pre",{className:"setup-detail",children:c.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:D,children:a("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:a("skip")})]})]}):n||c!=null&&c.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:c!=null&&c.ok?a("installDone"):a("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:a("provider")}),e.jsxs("select",{value:m,onChange:V=>y(V.target.value),children:[r.length===0&&e.jsx("option",{value:"",children:a("loading")}),r.map(V=>e.jsxs("option",{value:V.id,children:[V.name,"(",V.id,")",V.configured?` · ${a("configured")}`:""]},V.id))]}),(j==null?void 0:j.configured)&&e.jsx("div",{className:"field-hint",children:a("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:a("apiKey")}),e.jsx("input",{type:"password",value:x,onChange:V=>f(V.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!x.trim()||b||!m,onClick:H,children:a(b?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:N,children:[e.jsx(rt,{})," ",a("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:D,children:a(o?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:a("skip")})]})]})})}const Bl=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],Rs=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),Fl=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[Rs()]});function cs(t){return{providerId:t.providerId,name:t.name??"",api:t.api??"openai-completions",baseUrl:t.baseUrl??"",apiKey:t.apiKey??"",authHeader:t.authHeader??!1,models:(t.models.length?t.models:[Rs()]).map(s=>{var n;return{id:s.id,name:s.name??"",reasoning:s.reasoning??!1,input:(n=s.input)!=null&&n.includes("image")?"text-image":"text",contextWindow:s.contextWindow?String(s.contextWindow):"",maxTokens:s.maxTokens?String(s.maxTokens):""}})}}function $l({send:t,providers:s,providerStatus:n,providerKeys:r,fetchModelsResult:c,cloneProviderResult:i,onClose:a}){const o=be(),[u,m]=l.useState(null),[y,x]=l.useState({}),[f,b]=l.useState({}),[T,D]=l.useState(null),[H,N]=l.useState(!1),[j,Q]=l.useState(0),[V,J]=l.useState(null),U=l.useRef(0),[W,K]=l.useState(null),[G,C]=l.useState(""),[M,k]=l.useState(null);l.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"}),t({type:"list_provider_keys"})},[t]);const _=()=>{if(!u)return;const v=u.baseUrl.trim();if(!v){J({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(H)return;N(!0),J(null);const L=j+1;Q(L),t({type:"fetch_models",reqId:L,baseUrl:v,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};l.useEffect(()=>{var v;if(!(!c||c.reqId===U.current))if(U.current=c.reqId,N(!1),c.ok&&((v=c.models)!=null&&v.length)){const L=c.models;m(d=>{if(!d)return d;const E=d.models.map(Y=>{var ge;if(!Y.id.trim())return Y;const se=L.find(Ne=>Ne.id===Y.id.trim());if(!se)return Y;const X={...Y};return!X.name&&se.name&&(X.name=se.name),!X.contextWindow&&se.contextWindow&&(X.contextWindow=String(se.contextWindow)),!X.maxTokens&&se.maxTokens&&(X.maxTokens=String(se.maxTokens)),X.input==="text"&&((ge=se.input)!=null&&ge.includes("image"))&&(X.input="text-image"),!X.reasoning&&se.reasoning&&(X.reasoning=!0),X}),h=new Set(E.map(Y=>Y.id.trim()).filter(Boolean)),A=L.filter(Y=>!h.has(Y.id)).map(Y=>{var se;return{id:Y.id,name:Y.name??"",reasoning:Y.reasoning??!1,input:(se=Y.input)!=null&&se.includes("image")?"text-image":"text",contextWindow:Y.contextWindow?String(Y.contextWindow):"",maxTokens:Y.maxTokens?String(Y.maxTokens):""}}),ee=[...E,...A];return ee.some(Y=>Y.id.trim())?{...d,models:ee.filter(Y=>Y.id.trim())}:d}),J({ok:!0,text:o("fetchModelsOk",{n:L.length})})}else J({ok:!1,text:c.error||o("fetchModelsEmpty")})},[c]);const Z=v=>{const L=(y[v.id]??"").trim();!L||T||(D(v.id),t({type:"add_provider_key",provider:v.id,apiKey:L,name:(f[v.id]??"").trim()||void 0}),setTimeout(()=>{D(null),x(d=>({...d,[v.id]:""})),b(d=>({...d,[v.id]:""})),t({type:"list_providers"}),t({type:"list_provider_keys"})},1500))},z=(v,L)=>{t({type:"activate_provider_key",provider:v,keyName:L}),t({type:"list_provider_keys"})},I=(v,L)=>{window.confirm(o("removeKeyConfirm"))&&(t({type:"remove_provider_key",provider:v,keyName:L}),t({type:"list_provider_keys"}))},R=()=>{if(!M)return;const v=M.providerId.trim();if(!v||!M.apiKey.trim())return;const L=M.models.filter(E=>E.id.trim()).map(E=>({id:E.id.trim(),name:E.name.trim()||void 0,reasoning:E.reasoning||void 0,input:E.input==="text-image"?["text","image"]:void 0,contextWindow:E.contextWindow?Number(E.contextWindow):void 0,maxTokens:E.maxTokens?Number(E.maxTokens):void 0})),d={providerId:v,name:M.name.trim()||void 0,api:M.api.trim()||void 0,baseUrl:M.baseUrl.trim()||void 0,apiKey:M.apiKey.trim()||void 0,authHeader:M.authHeader||void 0,models:L};t({type:"save_model_config",providerId:v,config:d}),k(null),a()},w=()=>{if(!u)return;const v=u.providerId.trim(),L=u.models.filter(E=>E.id.trim()).map(E=>({id:E.id.trim(),name:E.name.trim()||void 0,reasoning:E.reasoning||void 0,input:E.input==="text-image"?["text","image"]:void 0,contextWindow:E.contextWindow?Number(E.contextWindow):void 0,maxTokens:E.maxTokens?Number(E.maxTokens):void 0})),d={providerId:v,name:u.name.trim()||void 0,api:u.api.trim()||void 0,baseUrl:u.baseUrl.trim()||void 0,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader||void 0,models:L};t({type:"save_model_config",providerId:v,config:d}),a()};l.useEffect(()=>{if(i&&i.ok){const v=i.configs;if(v&&v.length>1){K(v.map(L=>cs({...L,apiKey:""}))),C("");return}if(i.config){k(cs({...i.config,apiKey:""}));return}}},[i]);const $=v=>{window.confirm(o("clearKeyConfirm",{id:v}))&&t({type:"clear_provider_api_key",provider:v})},q=v=>{window.confirm(o("deleteProviderConfirm",{id:v.providerId,n:v.models.length}))&&t({type:"delete_model_config",providerId:v.providerId})},ie=(v,L)=>{u&&m({...u,models:u.models.map((d,E)=>E===v?{...d,...L}:d)})};return e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"modal model-modal",onClick:v=>v.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:a,children:e.jsx(Re,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:M?o("addKey"):W?o("batchCreateProviders",{n:W.length}):o(u?"editProvider":"manageModelsTitle")})}),M?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:o("secondKeyTitle",{api:M.api,baseUrl:M.baseUrl||o("noBaseUrlShort"),n:M.models.length})}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[o("providerNameLabel")," ",e.jsx("em",{children:o("providerNameHint")})]}),e.jsx("input",{type:"text",value:M.providerId,onChange:v=>k({...M,providerId:v.target.value}),placeholder:"opencode-2"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKeyLabel")}),e.jsx("input",{type:"password",value:M.apiKey,onChange:v=>k({...M,apiKey:v.target.value}),placeholder:o("secondKeyPlaceholder")})]})]}),e.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:8},children:[M.models.slice(0,5).map(v=>v.id).join(", "),M.models.length>5?` … +${M.models.length-5}`:""]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>k(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn",onClick:()=>{const v=M;k(null),m(v)},children:o("advancedEdit")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!M.providerId.trim()||!M.apiKey.trim(),onClick:R,children:o("save")})]})]}):W?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:o("batchDesc",{apis:W.map(v=>v.api).join("、"),n:W.length})}),e.jsxs("label",{className:"field",style:{marginBottom:16},children:[e.jsx("span",{className:"field-label",children:o("batchKeyLabel",{n:W.length})}),e.jsx("input",{type:"password",value:G,onChange:v=>C(v.target.value),placeholder:o("secondKeyPlaceholder")})]}),e.jsx("div",{className:"provider-list",style:{marginBottom:16},children:W.map((v,L)=>e.jsxs("div",{className:"provider-row",style:{flexDirection:"column",alignItems:"stretch",gap:6},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[e.jsx("strong",{children:v.providerId}),e.jsx("span",{style:{opacity:.7},children:v.api})]}),e.jsxs("div",{className:"provider-sub",style:{fontSize:12,opacity:.7},children:[v.baseUrl||o("noBaseUrlShort")," · ",o("modelsCountShort",{n:v.models.length}),v.models.slice(0,3).map(d=>d.id).join(", "),v.models.length>3?` … +${v.models.length-3}`:""]}),e.jsx("input",{type:"text",value:v.providerId,onChange:d=>K(E=>E.map((h,A)=>A===L?{...h,providerId:d.target.value}:h)),placeholder:o("providerIdPlaceholder"),style:{fontSize:12}}),e.jsx("input",{type:"text",value:v.baseUrl,onChange:d=>K(E=>E.map((h,A)=>A===L?{...h,baseUrl:d.target.value}:h)),placeholder:o("baseUrlExamplePh"),style:{fontSize:12}})]},L))})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>K(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!G.trim(),onClick:()=>{for(const v of W){const L=v.providerId.trim();if(!L)continue;const d=v.models.filter(h=>h.id.trim()).map(h=>({id:h.id.trim(),name:h.name.trim()||void 0,reasoning:h.reasoning||void 0,input:h.input==="text-image"?["text","image"]:void 0,contextWindow:h.contextWindow?Number(h.contextWindow):void 0,maxTokens:h.maxTokens?Number(h.maxTokens):void 0})),E={providerId:L,name:v.name.trim()||void 0,api:v.api.trim()||void 0,baseUrl:v.baseUrl.trim()||void 0,apiKey:G.trim()||void 0,authHeader:v.authHeader||void 0,models:d};t({type:"save_model_config",providerId:L,config:E})}K(null),a()},children:o("saveAllBatch",{n:W.length})})]})]}):u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[o("providerId")," ",e.jsx("em",{children:o("providerIdHint")})]}),e.jsx("input",{type:"text",value:u.providerId,disabled:s.some(v=>v.providerId===u.providerId),onChange:v=>m({...u,providerId:v.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("displayName")}),e.jsx("input",{type:"text",value:u.name,onChange:v=>m({...u,name:v.target.value}),placeholder:o("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiType")}),e.jsx("select",{value:u.api,onChange:v=>m({...u,api:v.target.value}),children:Bl.map(v=>e.jsx("option",{value:v,children:v},v))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:o("baseUrlHint")})]}),e.jsx("input",{type:"text",value:u.baseUrl,onChange:v=>m({...u,baseUrl:v.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKey")}),e.jsx("input",{type:"password",value:u.apiKey,onChange:v=>m({...u,apiKey:v.target.value}),placeholder:o("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:v=>m({...u,authHeader:v.target.checked})}),e.jsx("span",{children:o("authHeader")})]})]}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:o("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[V&&e.jsx("span",{className:`fetch-msg ${V.ok?"ok":"err"}`,title:V.text,children:V.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:H||!u.baseUrl.trim(),title:o("fetchModelsHint"),onClick:_,children:[e.jsx(zt,{})," ",o(H?"fetchingModels":"fetchModels")]})]})]}),u.models.map((v,L)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:v.id,onChange:d=>ie(L,{id:d.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:v.name,onChange:d=>ie(L,{name:d.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:v.input,onChange:d=>ie(L,{input:d.target.value}),children:[e.jsx("option",{value:"text",children:o("text")}),e.jsx("option",{value:"text-image",children:o("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:v.reasoning,onChange:d=>ie(L,{reasoning:d.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:v.contextWindow,onChange:d=>ie(L,{contextWindow:d.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:v.maxTokens,onChange:d=>ie(L,{maxTokens:d.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>m({...u,models:u.models.filter((d,E)=>E!==L)}),children:e.jsx(He,{})})]},L)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>m({...u,models:[...u.models,Rs()]}),children:[e.jsx(Ke,{})," ",o("addModel")]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>m(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(v=>v.id.trim()),onClick:w,children:o("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-fixed-hint",children:e.jsxs("div",{className:"form-section-title",children:[o("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:o("hintKeyOnly")})]})}),e.jsxs("div",{className:"model-modal-body",children:[e.jsxs("div",{className:"provider-list",children:[n.length===0&&e.jsx("div",{className:"dd-loading",children:o("loading")}),n.map(v=>{const L=r[v.id]??[];return e.jsxs("div",{className:"provider-row provider-key-row",children:[e.jsxs("div",{className:"provider-key-head",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:v.name}),e.jsxs("span",{className:"provider-sub",children:[v.id,v.configured&&e.jsx("span",{className:"auth-badge",children:o("configuredBadge")}),v.source&&!v.configured&&e.jsx("span",{className:"auth-badge dim",children:v.source})]})]}),v.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>$(v.id),children:[e.jsx(He,{})," ",o("clearKey")]})]}),e.jsxs("div",{className:"provider-keys",children:[L.length===0&&e.jsx("div",{className:"provider-key-empty",children:o("noKeyYet")}),L.map(d=>e.jsxs("div",{className:`provider-key-item ${d.active?"active":""}`,children:[e.jsx("span",{className:"provider-key-dot",children:d.active?"●":"○"}),e.jsx("span",{className:"provider-key-label",children:d.name}),!d.active&&e.jsx("button",{type:"button",className:"iconbtn",title:o("activateKey"),onClick:()=>z(v.id,d.name),children:e.jsx(Et,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeKey"),onClick:()=>I(v.id,d.name),children:e.jsx(He,{})})]},d.name)),e.jsxs("div",{className:"provider-add-key",children:[e.jsx("input",{type:"text",className:"key-input key-input-name",placeholder:o("keyNamePh"),value:f[v.id]??"",onChange:d=>b(E=>({...E,[v.id]:d.target.value}))}),e.jsx("input",{type:"password",className:"key-input key-input-value",placeholder:o("addKeyPlaceholder"),value:y[v.id]??"",onChange:d=>x(E=>({...E,[v.id]:d.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(y[v.id]??"").trim()||T===v.id,onClick:()=>Z(v),children:[e.jsx(Ke,{})," ",T===v.id?o("savingKey"):o("addKey")]})]})]})]},v.id)})]}),e.jsx("div",{className:"form-section-title",children:o("customProviders")}),e.jsx("p",{className:"modal-desc",children:o("customDesc")}),s.length===0&&e.jsx("div",{className:"dd-loading",children:o("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:s.map(v=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:v.providerId}),e.jsxs("span",{className:"provider-sub",children:[v.api??"—",v.baseUrl?` · ${v.baseUrl}`:"",v.models.length>0&&` · ${o("modelsCount",{n:v.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:o("edit"),onClick:()=>m(cs(v)),children:e.jsx(Kt,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>q(v),children:e.jsx(He,{})})]})]},v.providerId))})]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>m(Fl()),children:[e.jsx(Ke,{})," ",o("addProvider")]})})]})]})})}function Hl({plugin:t,send:s}){const n=be(),r=t.settingsSchema??[],[c,i]=l.useState(()=>({...t.settingsValues})),[a,o]=l.useState(!1);if(r.length===0)return null;const u=(f,b)=>i(T=>({...T,[f]:b})),m=r.some(f=>{var b;return c[f.key]!==((b=t.settingsValues)==null?void 0:b[f.key])}),y=()=>{o(!0),s({type:"plugin_settings",pluginId:t.id,values:c}),setTimeout(()=>o(!1),800)},x=()=>i({...t.settingsValues});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:r.map(f=>e.jsxs("label",{className:"plugin-settings-field",title:f.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:f.label}),f.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!c[f.key],onChange:b=>u(f.key,b.target.checked)}):f.type==="select"?e.jsx("select",{value:String(c[f.key]??""),onChange:b=>u(f.key,b.target.value),children:(f.options??[]).map(b=>e.jsx("option",{value:b,children:b},b))}):e.jsx("input",{type:f.type==="password"?"password":f.type==="number"?"number":"text",value:String(c[f.key]??""),min:f.min,max:f.max,onChange:b=>u(f.key,f.type==="number"?Number(b.target.value):b.target.value)})]},f.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!m||a,onClick:y,children:n(a?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:x,children:n("pluginSettingsReset")})]})]})}const ci="pi-web-ui:wide-chat",qt={wide:!1};function di(t){if(!t||typeof t!="object")return{...qt};const s=t;return{wide:typeof s.wide=="boolean"?s.wide:qt.wide}}function Ol(){try{const t=localStorage.getItem(ci);return t?di(JSON.parse(t)):{...qt}}catch{return{...qt}}}function Wl(t){const s=di(t);try{localStorage.setItem(ci,JSON.stringify(s))}catch{}Bt=s;for(const n of Ns)n()}let Bt=null;const Ns=new Set;function Ul(t){return Ns.add(t),()=>{Ns.delete(t)}}function Kl(){return Bt||(Bt=Ol()),Bt.wide}function ui(){return l.useSyncExternalStore(Ul,Kl)}function ql(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Ve({text:t}){const s=l.useRef(null),[n,r]=l.useState(!1),c=()=>{var a;const i=(a=s.current)==null?void 0:a.getBoundingClientRect();i&&r(window.innerWidth-i.right<340)};return e.jsxs("span",{ref:s,className:`set-tip${n?" flip":""}`,tabIndex:0,"aria-label":t,onMouseEnter:c,onFocus:c,children:["?",e.jsx("span",{className:"set-tip-bubble",role:"tooltip",children:t})]})}function Fe({title:t,subtitle:s,tip:n,enabled:r,onToggle:c,action:i}){const a=be();return e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[t,n&&e.jsx(Ve,{text:n})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),i,e.jsx("button",{type:"button",className:`set-switch ${r?"on":""}`,role:"switch","aria-checked":r,title:a(r?"settingsEnabled":"settingsDisabled"),onClick:c,children:e.jsx("span",{className:"set-switch-knob"})})]})}function zl({chat:t,send:s,terminal:n,onSwitchToTerminal:r,onClose:c}){var dt,ut,pt,mt,ht,gt;const i=be(),a=t.settings,o=t.engine==="dsh",[u,m]=l.useState("prompt"),y=l.useRef(null);l.useEffect(()=>{var p;(p=y.current)==null||p.scrollTo({top:0})},[u]),l.useEffect(()=>{u==="plugins"&&t.engine==="dsh"&&s({type:"dsh_patches_list"})},[u,t.engine,s]);const[x,f]=l.useState(""),[b,T]=l.useState("append"),D=l.useRef(!1),[H,N]=l.useState(""),[j,Q]=l.useState("append"),V=l.useRef(!1),[J,U]=l.useState(""),W=l.useRef(!1),[K,G]=l.useState(""),[C,M]=l.useState(null),[k,_]=l.useState(null),[Z,z]=l.useState(!1),I=ui(),[R,w]=l.useState(()=>ri()),[$,q]=l.useState(()=>{try{return St().length}catch{return 0}}),[ie,v]=l.useState(!1),L=()=>{try{q(St().length)}catch{q(0)}};l.useEffect(()=>{u==="prompt-history"&&L()},[u]),l.useEffect(()=>{if(!ie)return;const p=window.setTimeout(()=>v(!1),3e3);return()=>window.clearTimeout(p)},[ie]);const[d,E]=l.useState(null),[h,A]=l.useState(null),[ee,Y]=l.useState(""),[se,X]=l.useState(""),[ge,Ne]=l.useState(""),[de,Ee]=l.useState(""),[le,g]=l.useState(""),[O,me]=l.useState(!1);l.useEffect(()=>{a&&(T(a.promptMode),!D.current&&(f(b==="append"||a.customSystemPrompt?a.customSystemPrompt:a.defaultSystemPrompt||""),Q(a.visionBridgePromptMode),!V.current&&(N(j==="append"||a.visionBridgePrompt?a.visionBridgePrompt:a.visionBridgeDefaultPrompt||""),W.current||U(a.reviewPrompt))))},[a,b,j]);const[ue,ye]=l.useState(String((a==null?void 0:a.terminalBashIdleMs)??15e3));if(l.useEffect(()=>{ye(String((a==null?void 0:a.terminalBashIdleMs)??15e3))},[a==null?void 0:a.terminalBashIdleMs]),!a)return null;const fe=[{id:"prompt",icon:e.jsx(Tn,{}),label:i("settingsSystemPrompt")},{id:"prompt-history",icon:e.jsx(Ws,{}),label:i("settingsPromptHistory"),count:$},{id:"terminal",icon:e.jsx(ot,{}),label:i("settingsTerminalTools")},{id:"display",icon:e.jsx(ct,{}),label:i("settingsMessageDisplay")},{id:"markers",icon:e.jsx(Hs,{}),label:i("settingsMarkers"),count:((dt=a.markers)==null?void 0:dt.length)??0},{id:"skills",icon:e.jsx(wt,{}),label:i("settingsSkills"),count:a.skills.length},{id:"extensions",icon:e.jsx(Jt,{}),label:i("settingsExtensions"),count:a.extensions.length},{id:"plugins",icon:e.jsx(Xt,{}),label:i("settingsUiPlugins"),count:t.plugins.length},{id:"review",icon:e.jsx(Dt,{}),label:i("settingsReview"),count:a.reviewSkills.length},...o?[]:[{id:"vision",icon:e.jsx(ms,{}),label:i("settingsVisionBridge")}],{id:"presets",icon:e.jsx(Oi,{}),label:i("settingsPresets"),count:a.presets.length},...o?[]:[{id:"subagent-templates",icon:e.jsx(Fs,{}),label:i("settingsSubagentTemplates"),count:a.subagentTemplates.length}]],ke=new Set(a.disabledSkills),Le=new Set(a.disabledExtensions),ae=p=>s({type:"set_settings",...p}),De=p=>{const re=new Set(ke);re.has(p.name)?re.delete(p.name):re.add(p.name),ae({disabledSkills:[...re]})},Ae=new Set(a.disabledPlugins??[]),qe=new Set(t.plugins.map(p=>p.id)),ze=p=>{const re=new Set(Ae);re.has(p.id)?re.delete(p.id):re.add(p.id),ae({disabledPlugins:[...re]})},P=p=>{const re=new Set(Le);re.has(p.id)?re.delete(p.id):re.add(p.id),ae({disabledExtensions:[...re]})},xe=a.markersEnabled??!0,pe=new Set(a.disabledMarkers??[]),Se=p=>{const re=new Set(pe),Pe=p==="conv"||p==="rename"||p==="title"?["conv","rename","title"]:[p],_e=!Pe.some(Be=>re.has(Be));for(const Be of Pe)_e?re.add(Be):re.delete(Be);ae({disabledMarkers:[...re]})},ve=(p,re)=>{var ft,xt;const Pe={name:p,command:re,cwd:"${pwd}"};let _e;const Be=t.terminals.find(Mt=>Mt.title===p);Be?(n.restart(Be.id),s({type:"run_command",terminalId:Be.id,conversationId:Be.conversationId,command:Pe,cols:80,rows:24}),_e=Be.id):(_e=Qe(),n.create({id:_e,conversationId:t.activeConversationId||((ft=t.state)==null?void 0:ft.conversationId)||"",title:p,cwd:((xt=t.state)==null?void 0:xt.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Pe})),n.select(_e),r(),c()},S=p=>{E(null),ve(`${i("uninstallTitle")} ${p}`,`pi remove npm:${p}`)},B=p=>{A(null),ve(`${i("uninstallTitle")} ${p}`,`pi-web-ui uninstall ${p}`)},oe=(p,re)=>{ve(`${i("pluginUpdate")} ${p}`,`pi-web-ui install ${re} --name ${p} --force`)},ce=p=>{ve(`${i("pluginInstall")} ${p.id}`,`pi-web-ui install ${p.source} --name ${p.id}`)},je=p=>{s({type:"plugin_catalog_remove",id:p})},we=()=>{const p=ee.trim();p&&(s({type:"plugin_catalog_add",entry:{source:p,...se.trim()?{id:se.trim()}:{},...ge.trim()?{name:ge.trim()}:{},...de.trim()?{description:de.trim()}:{},...le.trim()?{icon:le.trim()}:{}}}),Y(""),X(""),Ne(""),Ee(""),g(""),me(!1))},Ie=p=>{const re=new Set(a.reviewSkills.filter(Pe=>!Pe.enabled).map(Pe=>Pe.name));re.has(p.name)?re.delete(p.name):re.add(p.name),ae({reviewDisabledSkills:[...re]})},Oe=()=>{const p=b==="replace"&&a.defaultSystemPrompt&&x===a.defaultSystemPrompt?"":x;ae({promptMode:b,customSystemPrompt:p})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal settings-modal",onClick:p=>p.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:c,children:e.jsx(Re,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(Ot,{className:"modal-head-icon"}),e.jsx("h2",{children:i("settingsTitle")}),e.jsx(Ve,{text:i("settingsDesc")})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-rail","aria-label":i("settingsTitle"),children:fe.map(p=>e.jsxs("button",{type:"button",className:`settings-tab${u===p.id?" active":""}`,"aria-current":u===p.id?"true":void 0,title:p.label,onClick:()=>m(p.id),children:[e.jsx("span",{className:"settings-tab-icon",children:p.icon}),e.jsx("span",{className:"settings-tab-label",children:p.label}),p.count!==void 0&&e.jsx("span",{className:"set-count",children:p.count})]},p.id))}),e.jsxs("div",{className:"modal-body",ref:y,children:[u==="prompt"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Dt,{className:"set-section-icon"}),i("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:b,onChange:p=>{const re=p.target.value;T(re),ae({promptMode:re})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]}),e.jsx(Ve,{text:i(b==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:i("promptPlaceholder"),value:x,onFocus:()=>D.current=!0,onBlur:()=>{D.current=!1,Oe()},onChange:p=>f(p.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":Z,onClick:()=>z(p=>!p),children:[i("settingsViewPrompt")," ",Z?"▴":"▾"]}),Z&&e.jsxs("div",{className:"set-prompt-view",children:[e.jsxs("div",{className:"set-prompt-view-head",children:[e.jsx("span",{children:i("settingsViewPromptHint")}),e.jsx(Es,{text:a.effectiveSystemPrompt})]}),a.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:a.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:i("settingsViewPromptEmpty")})]})]}),u==="prompt-history"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ws,{className:"set-section-icon"}),i("settingsPromptHistory"),e.jsx(Ve,{text:i("settingsPromptHistoryDesc")}),e.jsx("span",{className:"set-count",children:i("promptHistoryCount",{n:String($)})})]}),$===0?e.jsx("p",{className:"set-empty",children:i("promptHistoryEmpty")}):e.jsx("p",{className:"set-hint",children:i("promptHistoryCount",{n:String($)})}),e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"ph-max",children:i("promptHistoryMax")}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("input",{id:"ph-max",className:"set-input",type:"number",min:1,max:500,step:1,value:String(R.maxEntries),onChange:p=>{const re=Math.floor(Number(p.target.value)||0),Pe={...R,maxEntries:re};w(Pe)},onBlur:()=>{const p={...R};(!Number.isFinite(p.maxEntries)||p.maxEntries<1)&&(p.maxEntries=1),p.maxEntries>500&&(p.maxEntries=500),p.maxEntries=Math.floor(p.maxEntries),w(p),os(p),L()}}),e.jsx(Ve,{text:i("promptHistoryMaxHint")})]})]}),e.jsx(Fe,{title:i("promptHistoryCharLimit"),tip:i("promptHistoryCharLimitHint"),enabled:R.charLimitEnabled,onToggle:()=>{const p={...R,charLimitEnabled:!R.charLimitEnabled};w(p),os(p),L()}}),R.charLimitEnabled&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"ph-char-limit",children:i("promptHistoryCharLimit")}),e.jsx("input",{id:"ph-char-limit",className:"set-input",type:"number",min:100,max:2e4,step:100,placeholder:i("promptHistoryCharLimitPlaceholder"),value:String(R.charLimit),onChange:p=>{const re=Math.floor(Number(p.target.value)||0);w({...R,charLimit:re})},onBlur:()=>{let p=Math.floor(Number(R.charLimit)||0);(!Number.isFinite(p)||p<100)&&(p=100),p>2e4&&(p=2e4);const re={...R,charLimit:p};w(re),os(re),L()}})]}),e.jsxs("div",{className:"set-field",style:{marginTop:12},children:[e.jsxs("button",{type:"button",className:`set-uninstall${ie?" confirm":""}`,disabled:$===0,title:i($===0?"promptHistoryEmpty":"promptHistoryClear"),onClick:()=>{if(!ie){v(!0);return}vl(),v(!1),L()},children:[e.jsx(He,{})," ",i(ie?"promptHistoryClearConfirm":"promptHistoryClear")]}),$>0&&e.jsx("span",{className:"set-hint",style:{marginLeft:8},children:i("promptHistoryCount",{n:String($)})})]}),e.jsxs("p",{className:"set-hint",children:[e.jsx(ra,{style:{verticalAlign:"-2px",marginRight:4}}),i("settingsPromptHistoryDesc")]})]}),u==="terminal"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ot,{className:"set-section-icon"}),i("settingsTerminalTools")]}),e.jsx(Fe,{title:i("terminalToolsEnabled"),tip:i("settingsTerminalToolsDesc"),enabled:a.terminalToolsEnabled,onToggle:()=>ae({terminalToolsEnabled:!a.terminalToolsEnabled})}),!a.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:i("terminalToolsOffHint")}),e.jsx(Fe,{title:i("terminalBashTakeover"),tip:i("terminalBashTakeoverDesc"),enabled:a.terminalBash,onToggle:()=>ae({terminalBash:!a.terminalBash})}),a.terminalBash&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:i("terminalBashIdleMs")}),e.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:ue,onChange:p=>ye(p.target.value),onBlur:()=>{const p=Math.max(0,Math.floor(Number(ue)||0));ye(String(p)),p!==a.terminalBashIdleMs&&ae({terminalBashIdleMs:p})}})]})]}),u==="display"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ct,{className:"set-section-icon"}),i("settingsMessageDisplay")]}),e.jsx(Fe,{title:i("thinkingWrap"),tip:i("thinkingWrapDesc"),enabled:a.thinkingWrap??!0,onToggle:()=>ae({thinkingWrap:!(a.thinkingWrap??!0)})}),e.jsx(Fe,{title:i("toolsWrap"),tip:i("toolsWrapDesc"),enabled:a.toolsWrap??!0,onToggle:()=>ae({toolsWrap:!(a.toolsWrap??!0)})}),e.jsx("hr",{className:"set-sep"}),e.jsx(Fe,{title:i("wideChat"),tip:i("wideChatDesc"),enabled:I,onToggle:()=>Wl({wide:!I})})]}),u==="markers"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Hs,{className:"set-section-icon"}),i("settingsMarkers"),e.jsx(Ve,{text:i("settingsMarkersDesc")}),e.jsx("span",{className:"set-count",children:((ut=a.markers)==null?void 0:ut.length)??0})]}),e.jsx(Fe,{title:i("markersEnabled"),tip:i("markersEnabledDesc"),enabled:xe,onToggle:()=>ae({markersEnabled:!xe})}),!xe&&e.jsx("p",{className:"set-hint",children:i("markersOffHint")}),xe&&(((pt=a.markers)==null?void 0:pt.length)??0)===0&&e.jsxs("p",{className:"set-empty",children:[i("loading"),"..."]}),xe&&a.markers&&a.markers.length>0&&e.jsx("div",{className:"set-list",children:a.markers.map(p=>e.jsx(Fe,{title:p.name==="todo"?i("markerGroupTodo"):p.name==="svc"?i("markerGroupSvc"):p.name==="notify"?i("markerGroupNotify"):p.name==="conv"||p.name==="rename"||p.name==="title"?i("markerGroupRename"):p.name,subtitle:(p.guidance[0]??"").slice(0,120),tip:p.guidance.join(`
|
|
325
|
-
`),enabled:p.enabled,onToggle:()=>Se(p.name)},p.name))}),xe&&e.jsx("p",{className:"set-hint",children:i("markerRenameTip")})]}),u==="skills"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(wt,{className:"set-section-icon"}),i("settingsSkills"),e.jsx("span",{className:"set-count",children:a.skills.length})]}),a.skills.length===0?e.jsx("p",{className:"set-empty",children:i(o?"dshSkillsNote":"noSkills")}):e.jsx("div",{className:"set-list",children:a.skills.map(p=>e.jsx(Fe,{title:p.name,subtitle:p.description,enabled:p.enabled,onToggle:()=>De(p)},p.name))})]}),u==="extensions"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Jt,{className:"set-section-icon"}),i("settingsExtensions"),e.jsx("span",{className:"set-count",children:a.extensions.length})]}),a.extensions.length===0?e.jsx("p",{className:"set-empty",children:i(o?"dshExtensionsNote":"noExtensions")}):e.jsx("div",{className:"set-list",children:a.extensions.map(p=>{const re=p.id.startsWith("npm:")?p.id.slice(4):null;return e.jsx(Fe,{title:p.name,subtitle:p.path,enabled:p.enabled,onToggle:()=>P(p),action:re?d===p.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>S(re),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("uninstallHint"),onClick:()=>E(p.id),children:[e.jsx(He,{}),i("uninstallExt")]}):void 0},p.id)})})]}),u==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Jt,{className:"set-section-icon"}),i("pluginMarket"),e.jsx("span",{className:"set-count",children:t.pluginCatalog.length}),e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginCatalogAddHint"),onClick:()=>me(p=>!p),children:[e.jsx(Ke,{}),i("pluginCatalogAdd")]})]}),O&&e.jsxs("div",{className:"set-catalog-add",children:[e.jsx("input",{className:"set-input",placeholder:i("pluginCatalogSource"),value:ee,onChange:p=>Y(p.target.value)}),e.jsx("input",{className:"set-input",placeholder:i("pluginCatalogId"),value:se,onChange:p=>X(p.target.value)}),e.jsx("input",{className:"set-input",placeholder:i("pluginCatalogName"),value:ge,onChange:p=>Ne(p.target.value)}),e.jsx("input",{className:"set-input",placeholder:i("pluginCatalogIcon"),value:le,onChange:p=>g(p.target.value)}),e.jsx("textarea",{className:"set-input",rows:2,placeholder:i("pluginCatalogDesc"),value:de,onChange:p=>Ee(p.target.value)}),e.jsxs("div",{className:"set-catalog-add-actions",children:[e.jsx("button",{type:"button",className:"set-uninstall confirm",disabled:!ee.trim(),onClick:we,children:i("pluginCatalogAddSubmit")}),e.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>me(!1),children:i("cancel")})]})]}),t.pluginCatalog.length===0?e.jsx("p",{className:"set-empty",children:i("noPluginCatalog")}):e.jsx("div",{className:"set-list",children:t.pluginCatalog.map(p=>{const re=qe.has(p.id);return e.jsxs("div",{className:"set-catalog-row",children:[e.jsxs("div",{className:"set-catalog-main",children:[e.jsxs("div",{className:"set-catalog-title",children:[e.jsxs("span",{children:[p.icon?`${p.icon} `:"",p.name]}),re&&e.jsx("span",{className:"set-catalog-installed",children:i("pluginInstalled")}),!p.builtin&&e.jsx("span",{className:"set-catalog-custom",children:i("pluginCatalogCustom")})]}),p.description&&e.jsx("div",{className:"set-catalog-desc",children:p.description}),e.jsx("div",{className:"set-catalog-source",children:p.source})]}),e.jsxs("div",{className:"set-row-actions",children:[re?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>oe(p.id,p.source),children:[e.jsx(rt,{}),i("pluginUpdate")]}),h===p.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>B(p.id),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>A(p.id),children:[e.jsx(He,{}),i("uninstallExt")]})]}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginInstallHint"),onClick:()=>ce(p),children:[e.jsx(zt,{}),i("pluginInstall")]}),!p.builtin&&e.jsx("button",{type:"button",className:"set-uninstall",title:i("pluginCatalogRemoveHint"),onClick:()=>je(p.id),children:e.jsx(Re,{})})]})]},p.id)})})]}),u==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Xt,{className:"set-section-icon"}),i("settingsUiPlugins"),e.jsx("span",{className:"set-count",children:t.plugins.length})]}),t.plugins.length===0?e.jsx("p",{className:"set-empty",children:i("noUiPlugins")}):e.jsx("div",{className:"set-list",children:t.plugins.map(p=>{var re;return e.jsxs(e.Fragment,{children:[e.jsx(Fe,{title:`${p.icon?`${p.icon} `:""}${p.name}`,subtitle:(p.error?`${p.id} · ${p.error}`:p.source?`${p.id} · ${p.source}`:`${p.id} · ${i("uiPluginNoSource")}`)+((re=p.permissions)!=null&&re.length?` · ${i("uiPluginPerms")}: ${p.permissions.join(", ")}`:""),enabled:!Ae.has(p.id)&&!p.error,onToggle:()=>!p.error&&ze(p),action:e.jsxs("div",{className:"set-row-actions",children:[p.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>oe(p.id,p.source),children:[e.jsx(rt,{}),i("pluginUpdate")]}),h===p.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>B(p.id),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>A(p.id),children:[e.jsx(He,{}),i("uninstallExt")]})]})},p.id),p.settingsSchema&&p.settingsSchema.length>0&&e.jsx(Hl,{plugin:p,send:s})]})})})]}),u==="plugins"&&t.engine==="dsh"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Xt,{className:"set-section-icon"}),i("dshPatches"),e.jsx(Ve,{text:i("dshPatchesDesc")}),e.jsx("span",{className:"set-count",children:((mt=t.dshPatches)==null?void 0:mt.files.length)??0}),e.jsxs("button",{type:"button",className:"set-uninstall",title:i("dshPatchesRescanHint"),onClick:()=>s({type:"dsh_patches_rescan"}),children:[e.jsx(rt,{}),i("dshPatchesRescan")]})]}),(((ht=t.dshPatches)==null?void 0:ht.files.length)??0)===0?e.jsx("p",{className:"set-empty",children:i("dshPatchesEmpty")}):e.jsx("div",{className:"set-list",children:t.dshPatches.files.map(p=>e.jsx("div",{className:"set-row",children:e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:p.name}),e.jsxs("div",{className:"set-row-desc",children:[ql(p.size)," · ",new Date(p.mtimeMs).toLocaleString()]})]})},p.name))}),e.jsxs("p",{className:"set-hint",children:[i("dshPatchesPath")," ",((gt=t.dshPatches)==null?void 0:gt.patchDir)??""]})]}),u==="review"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Dt,{className:"set-section-icon"}),i("settingsReview"),e.jsx(Ve,{text:i("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:a.reviewSkills.length})]}),o&&e.jsx("p",{className:"set-hint",children:i("dshReviewPromptNote")}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:i("reviewPromptPlaceholder"),value:J,onFocus:()=>W.current=!0,onBlur:()=>{W.current=!1,ae({reviewPrompt:J})},onChange:p=>U(p.target.value)}),e.jsx("div",{className:"set-field-label",children:i("settingsReviewSkills")}),a.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:a.reviewSkills.map(p=>e.jsx(Fe,{title:p.name,subtitle:p.description,enabled:p.enabled,onToggle:()=>Ie(p)},`review-${p.name}`))})]}),u==="vision"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ms,{className:"set-section-icon"}),i("settingsVisionBridge")]}),e.jsx(Fe,{title:i("visionBridgeEnabled"),tip:i("settingsVisionBridgeDesc"),enabled:a.visionBridgeEnabled,onToggle:()=>ae({visionBridgeEnabled:!a.visionBridgeEnabled})}),!a.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:i("visionBridgeOffHint")}),a.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:a.visionBridgeModel??"",onChange:p=>ae({visionBridgeModel:p.target.value||null}),children:[e.jsx("option",{value:"",children:i("visionBridgeAuto")}),a.visionModels.map(p=>e.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.id}`))]})]}),a.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:j,onChange:p=>{const re=p.target.value;Q(re),ae({visionBridgePromptMode:re})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]})]}),a.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:i("visionBridgePromptPlaceholder"),value:H,onFocus:()=>V.current=!0,onBlur:()=>{V.current=!1;const p=j==="replace"&&a.visionBridgeDefaultPrompt&&H===a.visionBridgeDefaultPrompt?"":H;ae({visionBridgePromptMode:j,visionBridgePrompt:p})},onChange:p=>N(p.target.value)}),a.visionBridgeEnabled&&(a.visionModels.length===0?e.jsx("p",{className:"set-hint",children:i("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:i("visionBridgeCurrent",{model:a.visionBridgeModel??i("visionBridgeAuto")})}))]}),u==="presets"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ot,{className:"set-section-icon"}),i("settingsPresets"),e.jsx("span",{className:"set-count",children:a.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:i("presetNamePlaceholder"),value:K,onChange:p=>G(p.target.value),onKeyDown:p=>{p.key==="Enter"&&K.trim()&&(s({type:"save_preset",name:K.trim()}),G(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!K.trim(),onClick:()=>{s({type:"save_preset",name:K.trim()}),G("")},children:[e.jsx(Ke,{})," ",i("saveAsPreset")]})]}),a.presets.length===0?e.jsx("p",{className:"set-empty",children:i("noPresets")}):e.jsx("div",{className:"set-list",children:a.presets.map(p=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:p.name}),e.jsxs("div",{className:"set-row-desc",children:[p.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend"),p.disabledSkills.length>0&&` · ${i("settingsSkills")} ${p.disabledSkills.length}`,p.disabledExtensions.length>0&&` · ${i("settingsExtensions")} ${p.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:p.name}),children:i("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("deletePreset"),onClick:()=>s({type:"delete_preset",name:p.name}),children:e.jsx(He,{})})]})]},p.name))})]}),u==="subagent-templates"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Fs,{className:"set-section-icon"}),i("settingsSubagentTemplates"),e.jsx(Ve,{text:i("settingsSubagentTemplatesDesc")}),e.jsx("span",{className:"set-count",children:a.subagentTemplates.length}),e.jsxs("button",{type:"button",className:"set-save-btn",title:i("subagentTemplateNew"),onClick:()=>M({name:"",description:"",promptMode:"replace",systemPrompt:"",enabledSkills:[],enabledExtensions:[],model:"",enabled:!0}),children:[e.jsx(Ke,{})," ",i("subagentTemplateNew")]})]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("subagentDefaultModelLabel")}),e.jsxs("select",{className:"set-select",value:a.subagentDefaultModel??"",onChange:p=>ae({subagentDefaultModel:p.target.value||null}),children:[e.jsx("option",{value:"",children:i("subagentFollowMain")}),a.subagentModels.map(p=>e.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.id}`))]})]}),a.subagentModels.length===0?e.jsx("p",{className:"set-hint",children:i("subagentNoModels")}):e.jsx("p",{className:"set-hint",children:i("subagentDefaultModelHint")}),C&&e.jsxs("div",{className:"tpl-editor",children:[e.jsxs("div",{className:"tpl-fields",children:[e.jsx("input",{className:"set-input",placeholder:i("tplNamePlaceholder"),value:C.name,onChange:p=>M({...C,name:p.target.value})}),e.jsx("input",{className:"set-input",placeholder:i("tplDescriptionPlaceholder"),value:C.description,onChange:p=>M({...C,description:p.target.value})})]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("tplPromptModeLabel")}),e.jsxs("select",{className:"set-select",value:C.promptMode,onChange:p=>M({...C,promptMode:p.target.value}),children:[e.jsx("option",{value:"replace",children:i("promptModeReplace")}),e.jsx("option",{value:"append",children:i("promptModeAppend")})]})]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("tplModelLabel")}),e.jsxs("select",{className:"set-select",value:C.model??"",onChange:p=>M({...C,model:p.target.value}),children:[e.jsx("option",{value:"",children:i("subagentFollowMain")}),a.subagentModels.map(p=>e.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.id}`))]})]}),e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:`${i("tplSystemPromptLabel")}:${i("tplSystemPromptPlaceholder")}`,value:C.systemPrompt,onChange:p=>M({...C,systemPrompt:p.target.value})}),e.jsxs("div",{className:"tpl-pick-block",children:[e.jsx("div",{className:"tpl-pick-head",children:e.jsxs("span",{children:[i("tplSkillsLabel")," · ",i("tplWhitelistHint")]})}),a.skills.length===0?e.jsx("p",{className:"set-hint",children:i("noSkills")}):e.jsx("div",{className:"tpl-pick",children:a.skills.map(p=>e.jsxs("label",{className:`tpl-chip${C.enabledSkills.includes(p.name)?" on":""}`,children:[e.jsx("input",{type:"checkbox",checked:C.enabledSkills.includes(p.name),onChange:re=>{const Pe=re.target.checked;M({...C,enabledSkills:Pe?[...C.enabledSkills,p.name]:C.enabledSkills.filter(_e=>_e!==p.name)})}}),p.name]},p.name))})]}),e.jsxs("div",{className:"tpl-pick-block",children:[e.jsx("div",{className:"tpl-pick-head",children:e.jsxs("span",{children:[i("tplExtensionsLabel")," · ",i("tplWhitelistHint")]})}),a.extensions.length===0?e.jsx("p",{className:"set-hint",children:i("noExtensions")}):e.jsx("div",{className:"tpl-pick",children:a.extensions.map(p=>e.jsxs("label",{className:`tpl-chip${C.enabledExtensions.includes(p.id)?" on":""}`,children:[e.jsx("input",{type:"checkbox",checked:C.enabledExtensions.includes(p.id),onChange:re=>{const Pe=re.target.checked;M({...C,enabledExtensions:Pe?[...C.enabledExtensions,p.id]:C.enabledExtensions.filter(_e=>_e!==p.id)})}}),p.name]},p.id))})]}),e.jsxs("div",{className:"tpl-actions",children:[e.jsx("button",{type:"button",className:"set-save-btn",disabled:!C.name.trim(),onClick:()=>{s({type:"save_subagent_template",template:{...C,name:C.name.trim()}}),M(null)},children:i("tplSave")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>M(null),children:i("tplCancel")})]})]}),a.subagentTemplates.length===0?e.jsx("p",{className:"set-empty",children:i("noSubagentTemplates")}):e.jsx("div",{className:"set-list",children:a.subagentTemplates.map(p=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[p.name,a.subagentDefaultTemplates.includes(p.name)&&e.jsx("span",{className:"tpl-badge default",children:i("tplDefaultBadge")}),!p.enabled&&e.jsx("span",{className:"tpl-badge",children:i("subagentTemplateClosed")})]}),e.jsxs("div",{className:"set-row-desc",children:[p.description||`${p.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend")}`,p.model?` · ${i("tplModelLabel")} ${p.model}`:` · ${i("subagentFollowMain")}`,p.enabledSkills.length>0&&` · ${i("tplSkillsLabel")} ${p.enabledSkills.length}`,p.enabledExtensions.length>0&&` · ${i("tplExtensionsLabel")} ${p.enabledExtensions.length}`,!p.description&&p.enabledSkills.length===0&&p.enabledExtensions.length===0&&` · ${i("tplInherit")}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:`set-switch${p.enabled?" on":""}`,role:"switch","aria-checked":p.enabled,title:`${p.enabled?i("subagentTemplateDisable"):i("subagentTemplateEnable")} · ${i("subagentTemplateOffHint")}`,onClick:()=>s({type:"save_subagent_template",template:{...p,enabled:!p.enabled}}),children:e.jsx("span",{className:"set-switch-knob"})}),e.jsx("button",{type:"button",className:"dd-refresh",title:i("subagentTemplateEdit"),onClick:()=>M({...p}),children:i("subagentTemplateEdit")}),k===p.name?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>{s({type:"delete_subagent_template",name:p.name}),_(null)},children:i("uninstallConfirm")}):e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("tplDelete"),onClick:()=>_(p.name),children:e.jsx(He,{})})]})]},p.name))})]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:c,children:i("close")})})]})})}function Vl(t,s){const n=Math.max(0,Date.now()-t),r=Math.floor(n/6e4);if(r<1)return s("bgTaskJustNow");if(r<60)return s("bgTaskMinutes",{n:r});const c=Math.floor(r/60);return c<24?s("bgTaskHours",{n:c}):s("bgTaskDays",{n:Math.floor(c/24)})}function Gl({servers:t,send:s,onClose:n}){const r=be(),[c,i]=l.useState(new Set),a=o=>i(u=>{const m=new Set(u);return m.has(o)?m.delete(o):m.add(o),m});return l.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"bg-task-modal",onClick:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(Ut,{})," ",r("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:r("close"),onClick:n,children:e.jsx(Re,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(Ut,{}),e.jsx("span",{children:r("bgTasksEmpty")}),e.jsx("small",{children:r("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(o=>{const u=!!o.taskId,m=o.taskId??String(o.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:u?o.plugin:r("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[u?e.jsxs("span",{className:"bg-task-port",title:o.taskId,children:["🧩 ",o.plugin]}):e.jsxs("span",{className:"bg-task-port",children:[":",o.port]}),o.name&&e.jsx("span",{className:"bg-task-name",children:o.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[!u&&e.jsxs("span",{children:[r("bgTaskPid")," ",o.pid]}),e.jsxs("span",{children:[r("bgTaskSince")," ",Vl(o.since,r)]}),u&&o.status&&e.jsx("span",{className:"bg-task-status",children:o.status})]}),o.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${c.has(m)?"open":""}`,title:`${r("bgTaskCommand")}: ${o.command}`,onClick:()=>a(m),children:[e.jsx(ot,{}),e.jsx("code",{children:o.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:r("bgTaskStop"),onClick:()=>s(u?{type:"kill_background_server",taskId:o.taskId}:{type:"kill_background_server",port:o.port}),children:[e.jsx(Ht,{}),e.jsx("span",{children:r("bgTaskStop")})]})]},m)})}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:r("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(rt,{}),e.jsx("span",{children:r("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:r("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(Ht,{}),e.jsx("span",{children:r("bgTaskStopAll")})]})]})]})})}function Ql(t,s){return t.toLowerCase().includes(s)}function Yl({open:t,send:s,projects:n,cwd:r,fileSearch:c,sessionSearch:i,onClose:a,onSwitchSession:o,onSwitchProject:u,onPreviewFile:m}){const y=be(),x=l.useRef(null),[f,b]=l.useState(""),T=l.useDeferredValue(f),[D,H]=l.useState(0),N=l.useRef(1),j=l.useRef(0),Q=l.useRef(null);l.useEffect(()=>{if(!t)return;s({type:"list_sessions"}),s({type:"list_projects"});const I=f.trim();if(I){const R=++N.current;j.current=R,J(!0),s({type:"search_files",reqId:R,query:I}),s({type:"search_sessions",reqId:R,query:I})}requestAnimationFrame(()=>{var R;return(R=x.current)==null?void 0:R.select()})},[t]);const[V,J]=l.useState(!1);l.useEffect(()=>{Q.current&&clearTimeout(Q.current);const I=T.trim();if(!I){J(!1);return}return Q.current=setTimeout(()=>{const R=++N.current;j.current=R,J(!0),s({type:"search_files",reqId:R,query:I}),s({type:"search_sessions",reqId:R,query:I})},300),()=>{Q.current&&clearTimeout(Q.current)}},[T]);const U=T.trim().toLowerCase(),W=l.useMemo(()=>!U||!i||i.reqId!==j.current||!i.ok?[]:i.results,[i,U]),K=l.useMemo(()=>U?n.filter(I=>Ql(I.path,U)).slice(0,10):[],[n,U]),G=l.useMemo(()=>!U||!c||c.reqId!==j.current||!c.ok?[]:c.results,[c,U]);l.useEffect(()=>{c&&c.reqId===j.current&&i&&i.reqId===j.current&&j.current!==0&&J(!1)},[c,i]);const C=!!c&&c.ok&&c.truncated,M=l.useMemo(()=>[...W.map(I=>({kind:"session",path:I.path,anchors:I.anchors})),...K.map(I=>({kind:"project",path:I.path})),...G.filter(I=>I.type==="file").map(I=>({kind:"file",path:I.path,name:I.name}))],[W,K,G]);l.useEffect(()=>{H(0)},[T]);const k=l.useCallback(I=>{if(I)if(I.kind==="session")o(I.path,I.anchors),a();else if(I.kind==="project"){u(I.path),s({type:"list_sessions"}),s({type:"list_projects"});const R=T.trim();if(R){const w=++N.current;j.current=w,J(!0),s({type:"search_files",reqId:w,query:R}),s({type:"search_sessions",reqId:w,query:R})}}else m(I.path,I.name)},[o,u,m,s,T]);l.useEffect(()=>{if(!t)return;const I=R=>{R.key==="Escape"?(R.preventDefault(),R.stopPropagation(),a()):R.key==="ArrowDown"?(R.preventDefault(),H(w=>Math.min(w+1,M.length-1))):R.key==="ArrowUp"?(R.preventDefault(),H(w=>Math.max(w-1,0))):R.key==="Enter"&&(R.preventDefault(),k(M[D]))};return window.addEventListener("keydown",I,!0),()=>window.removeEventListener("keydown",I,!0)},[M,D,k,a,t]);const _=W.length+K.length+G.length,Z=(I,R,w)=>e.jsxs("div",{className:"gs-section-head",children:[w,e.jsx("span",{children:I}),e.jsx("em",{children:R})]});let z=-1;return t?e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:a,children:e.jsxs("div",{className:"gs-modal",onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(Wt,{}),e.jsx("input",{ref:x,type:"text",value:f,placeholder:y("gsPlaceholder"),onChange:I=>b(I.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:y("close"),onClick:a,children:e.jsx(Re,{})})]}),e.jsxs("div",{className:"gs-results",children:[!U&&e.jsx("div",{className:"gs-empty",children:y("gsHint")}),U&&_===0&&!C&&e.jsx("div",{className:"gs-empty",children:y(V?"gsSearching":"gsNoResults")}),W.length>0&&e.jsxs("div",{className:"gs-section",children:[Z(y("gsSessions"),W.length,e.jsx(ct,{})),W.map(I=>{z++;const R=z;return e.jsxs("button",{type:"button",className:R===D?"gs-item active":"gs-item",onMouseEnter:()=>H(R),onClick:()=>k({kind:"session",path:I.path,anchors:I.anchors}),children:[e.jsxs("span",{className:"gs-item-title",children:[I.name||I.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:I.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:I.firstMessage})]},I.path)})]}),K.length>0&&e.jsxs("div",{className:"gs-section",children:[Z(y("gsProjects"),K.length,e.jsx(st,{})),K.map(I=>{z++;const R=z,w=r&&I.path===r;return e.jsxs("button",{type:"button",className:R===D?"gs-item active":"gs-item",onMouseEnter:()=>H(R),onClick:()=>k({kind:"project",path:I.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[I.path.split(/[\\/]/).pop(),w&&e.jsx("em",{className:"gs-item-meta",children:y("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:I.path})]},I.path)})]}),(G.length>0||U&&C)&&e.jsxs("div",{className:"gs-section",children:[Z(y("gsFiles"),G.length,e.jsx(Tn,{})),G.map(I=>{z++;const R=z;return e.jsxs("button",{type:"button",className:R===D?"gs-item active":"gs-item",disabled:I.type==="dir",title:I.type==="dir"?void 0:y("gsOpenPreview"),onMouseEnter:()=>H(R),onClick:()=>{I.type==="file"&&k({kind:"file",path:I.path,name:I.name})},children:[e.jsx("span",{className:"gs-item-title",children:I.name}),e.jsx("span",{className:"gs-item-sub",children:I.path})]},`${I.type}:${I.path}`)}),C&&e.jsx("div",{className:"gs-truncated",children:y("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",y("gsNavigate")]}),e.jsxs("span",{children:["Enter ",y("gsOpen")]}),e.jsxs("span",{children:["Esc ",y("gsCloseHint")]})]})]})}):null}const ds=5e3;function Jl({file:t,content:s,send:n,onAddLines:r,onAttach:c,onClose:i}){const a=be(),[o,u]=l.useState(null),[m,y]=l.useState(!1),[x,f]=l.useState(null),[b,T]=l.useState(!1),[D,H]=l.useState(!1),[N,j]=l.useState(!1),[Q,V]=l.useState(""),[J,U]=l.useState(!0),W=l.useRef(!1),[K,G]=l.useState(!0),[C,M]=l.useState(!1),[k,_]=l.useState(100),Z=l.useRef(0),z=l.useRef(!1),I=l.useRef(null);l.useEffect(()=>{y(!0),u(null),f(null),j(!1),V(""),U(!0),W.current=!1,n({type:"read_file",path:t.path})},[t.path,n]),l.useEffect(()=>{s&&s.path===t.path&&(u(s),N||V(s.text),y(!1))},[s,N,t.path]),l.useEffect(()=>{const le=g=>{if(g.key==="Escape"){A();return}if((g.ctrlKey||g.metaKey)&&g.key.toLowerCase()==="s"&&N){g.preventDefault(),h();return}const O=g.target,me=O&&(O.tagName==="INPUT"||O.tagName==="TEXTAREA"||O.isContentEditable);(g.ctrlKey||g.metaKey)&&g.key.toLowerCase()==="a"&&!me&&(g.preventDefault(),ie())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[i,o,N,Q]),l.useEffect(()=>{const le=()=>{z.current=!1,T(!1)};return window.addEventListener("mouseup",le),()=>window.removeEventListener("mouseup",le)},[]);const R=l.useMemo(()=>{if(!o)return[];const le=o.text.split(`
|
|
326
|
-
`);return le.length>0&&le[le.length-1]===""&&le.pop(),le.slice(0,ds)},[o]),w=(o==null?void 0:o.lines)??0,$=w>ds,q=(le,g)=>{if(g){const O=Z.current>0?Z.current:le;f({start:Math.min(O,le),end:Math.max(O,le)})}else Z.current=le,f({start:le,end:le})},ie=()=>{R.length!==0&&(Z.current=1,f({start:1,end:R.length}))},v=()=>{x&&(r(t.path,t.name,x.start,x.end),H(!0),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>H(!1),1400))},L=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,d=()=>{V((o==null?void 0:o.text)??""),j(!1),W.current&&U(!0)},E=()=>{if(N){if(Q!==((o==null?void 0:o.text)??"")&&!window.confirm(a("discardFileChanges")))return;d();return}!L||!o||(W.current=us(t.name)&&J,us(t.name)&&U(!1),f(null),V(o.text),j(!0))},h=()=>{!N||!o||!L||n({type:"write_file",path:t.path,text:Q})&&(j(!1),W.current&&U(!0),f(null))},A=()=>{N&&Q!==((o==null?void 0:o.text)??"")&&!window.confirm(a("discardFileChanges"))||i()},ee=le=>{_(Math.min(200,Math.max(50,le)))},Y=x?x.end-x.start+1:0,se=(o==null?void 0:o.binary)??!1,X=(o==null?void 0:o.truncated)??!1,ge=(o==null?void 0:o.kind)??"text",Ne=us(t.name),de=Ne&&J&&!N&&ge==="text"&&!se,Ee=le=>Gt(Ye(`/api/file?clientId=${encodeURIComponent(Ts())}&path=${encodeURIComponent(le)}`));return e.jsx("div",{className:`fp-overlay ${C?"fullscreen":""}`,onMouseDown:le=>{le.target===le.currentTarget&&A()},children:e.jsxs("div",{className:`fp ${C?"fullscreen":""}`,style:{"--fp-zoom":k/100},children:[e.jsxs("div",{className:"fp-head",children:[e.jsx("span",{className:"fp-name",title:t.path,children:t.name}),e.jsx("span",{className:"fp-path",children:t.path}),e.jsxs("span",{className:"fp-meta",children:[o&&ge==="text"&&!se&&a("fileLines",{n:w}),o&&` · ${Xl(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[Ne&&ge==="text"&&!se&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${J?"on":""}`,"data-tip":a(J?"showMarkdownSource":"showMarkdownPreview"),disabled:N,onClick:()=>U(le=>!le),children:J?e.jsx(ms,{}):e.jsx(sa,{})}),ge==="text"&&!se&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${N?"on":""}`,"data-tip":a(X?"fileEditTruncated":N?"exitEditFile":"editFile"),disabled:!L&&!N,onClick:E,children:e.jsx(hs,{})}),ge==="text"&&!se&&!de&&e.jsx("button",{type:"button",className:`fp-attach wrap ${K?"on":""}`,"data-tip":a(K?"disableWrap":"enableWrap"),onClick:()=>G(le=>!le),children:e.jsx(ta,{})}),ge==="text"&&o&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":a("zoomOut"),disabled:k<=50,onClick:()=>ee(k-10),children:e.jsx(_i,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:a("resetZoom"),onClick:()=>_(100),children:[k,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":a("zoomIn"),disabled:k>=200,onClick:()=>ee(k+10),children:e.jsx(Bi,{})})]}),ge!=="video"&&ge!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":a("attachInlineTip"),onClick:()=>c(t.path,t.name,"inline"),children:e.jsx(Ke,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":a("referenceTip"),onClick:()=>c(t.path,t.name,"reference"),children:e.jsx(ps,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${C?"on":""}`,"data-tip":a(C?"exitFullscreen":"fullscreen"),onClick:()=>M(le=>!le),children:C?e.jsx(qi,{}):e.jsx(Vi,{})}),e.jsx("button",{type:"button",className:"fp-close",title:a("close"),onClick:A,children:e.jsx(Re,{})})]})]}),X&&ge==="text"&&!se&&e.jsx("div",{className:"fp-notice",children:a("previewTruncated")}),m&&!o&&e.jsx("div",{className:"fp-empty",children:a("loading")}),!m&&ge==="none"&&!se&&e.jsx("div",{className:"fp-empty",children:a("previewNotSupported")}),!m&&ge==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:Ee(t.path),alt:t.name})}),!m&&ge==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:Ee(t.path),controls:!0,preload:"metadata"})}),!m&&de&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(Qt,{text:o.text})})}),!m&&se&&ge!=="image"&&ge!=="video"&&o&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[a("binaryFile"),o.truncated&&a("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:o.text})]}),!m&&N&&ge==="text"&&!se&&o&&e.jsx("textarea",{className:`fp-editor ${K?"":"no-wrap"}`,value:Q,onChange:le=>V(le.target.value),wrap:K?"soft":"off",spellCheck:!1,autoFocus:!0}),!m&&!de&&!N&&ge==="text"&&!se&&o&&R.length===0&&e.jsx("div",{className:"fp-empty",children:a("emptyFile")}),!m&&!de&&!N&&ge==="text"&&!se&&R.length>0&&e.jsxs("div",{className:`fp-code ${b?"dragging":""} ${K?"":"no-wrap"}`,onMouseDown:le=>{le.button===0&&le.preventDefault()},children:[R.map((le,g)=>{const O=g+1,me=x!==null&&O>=x.start&&O<=x.end;return e.jsxs("div",{className:`fp-line ${me?"sel":""}`,onMouseDown:ue=>{ue.button===0&&(q(O,ue.shiftKey),z.current=!0,T(!0))},onMouseEnter:()=>{z.current&&q(O,!0)},children:[e.jsx("span",{className:"fp-num",children:O}),e.jsx("span",{className:"fp-code-text",children:le})]},O)}),$&&e.jsx("div",{className:"fp-lines-note",children:a("previewLinesTruncated",{n:ds})})]}),e.jsx("div",{className:"fp-foot",children:N?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:a("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:E,children:a("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:Q===((o==null?void 0:o.text)??""),onClick:h,children:[e.jsx(Wi,{})," ",a("saveFile")]})]})]}):!de&&ge==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:x?a("selectedRange",{n:Y,start:x.start,end:x.end}):a("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:R.length===0,onClick:ie,children:a("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!x,onClick:()=>f(null),children:a("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!x||se,onClick:v,children:[D?e.jsx(Et,{}):null,a(D?"addedToChat":"addToChat")]})]})]})})]})})}function us(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function Xl(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const pi="pi-web-sounds",yt={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function mi(){try{const t=localStorage.getItem(pi);if(!t)return{...yt};const s=JSON.parse(t),n={...yt,...s};for(const r of["enabled","question","done","start","error"])typeof n[r]!="boolean"&&(n[r]=yt[r]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=yt.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...yt}}}function Zl(t){try{localStorage.setItem(pi,JSON.stringify(t))}catch{}}let vt=null;function eo(){try{if(!vt){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;vt=new t}return vt.state==="suspended"&&vt.resume(),vt}catch{return null}}const to=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],so=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],no=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],io=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],ao={question:to,done:so,start:no,error:io};function ro(t,s,n){const r=t.createOscillator(),c=t.createGain();r.type=s.type,r.frequency.value=s.freq;const i=t.currentTime+s.start,a=Math.max(1e-4,s.peak*n);c.gain.setValueAtTime(1e-4,i),c.gain.exponentialRampToValueAtTime(a,i+.012),c.gain.exponentialRampToValueAtTime(1e-4,i+s.dur),r.connect(c),c.connect(t.destination),r.start(i),r.stop(i+s.dur+.05)}function bt(t,s=mi()){if(!s.enabled||!s[t])return;const n=eo();if(!n)return;const r=Math.max(0,Math.min(1,s.volume/100));for(const c of ao[t])ro(n,c,r)}const Cs="pi-web-ui:theme",hi="dark",gn="theme-stylesheet",fn="pi-web-ui:theme-change";function gi(){try{const t=localStorage.getItem(Cs);if(t&&t!==hi)return t}catch{}return null}function lo(t){try{t?localStorage.setItem(Cs,t):localStorage.removeItem(Cs)}catch{}}function fi(t){let s=document.getElementById(gn);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(fn));return}s||(s=document.createElement("link"),s.id=gn,s.rel="stylesheet",document.head.appendChild(s)),s.href=Ye(`/themes/${encodeURIComponent(t)}.css`),s.onload=()=>window.dispatchEvent(new CustomEvent(fn))}async function oo(){try{const t=await fetch(Gt(Ye("/api/themes")));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function co(){const[t,s]=l.useState([]),[n,r]=l.useState(()=>gi());return l.useEffect(()=>{let i=!1;return oo().then(a=>{i||s(a)}),()=>{i=!0}},[]),l.useEffect(()=>{fi(n),lo(n)},[n]),{themes:t,theme:n,switchTheme:i=>r(i===hi?null:i)}}function yo(){const t=getComputedStyle(document.documentElement),s=(n,r)=>t.getPropertyValue(n).trim()||r;return{background:s("--term-bg","#0b0d12"),foreground:s("--term-fg","#e6e8ef"),cursor:s("--term-cursor","#8b5cf6"),cursorAccent:s("--term-cursor-accent","#0b0d12"),selectionBackground:s("--term-selection","rgba(139, 92, 246, 0.35)"),black:s("--term-black","#1a1d26"),red:s("--term-red","#f87171"),green:s("--term-green","#34d399"),yellow:s("--term-yellow","#fbbf24"),blue:s("--term-blue","#60a5fa"),magenta:s("--term-magenta","#c084fc"),cyan:s("--term-cyan","#22d3ee"),white:s("--term-white","#e6e8ef"),brightBlack:s("--term-bright-black","#6b7284"),brightRed:s("--term-bright-red","#f87171"),brightGreen:s("--term-bright-green","#34d399"),brightYellow:s("--term-bright-yellow","#fbbf24"),brightBlue:s("--term-bright-blue","#60a5fa"),brightMagenta:s("--term-bright-magenta","#c084fc"),brightCyan:s("--term-bright-cyan","#22d3ee"),brightWhite:s("--term-bright-white","#ffffff")}}const uo=l.lazy(()=>Ei(()=>import("./TerminalPanel-B_ACe6Lp.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function po({notice:t,onDismiss:s}){const n=be(),{locale:r}=Pt(),c=r==="en"&&t.textEn?t.textEn:t.text,[i,a]=l.useState(!1);l.useEffect(()=>{if(i)return;const u=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(u)},[i,t.id,t.level,s]);const o=t.level==="error"?oa:t.level==="warning"?la:Yi;return e.jsxs("div",{className:`notice notice-${t.level}${i?" paused":""}`,role:"status",onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[e.jsx(o,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:c}),e.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>s(t.id),children:e.jsx(Re,{})})]})}const mo=[],xi=180,yi=520,vi=240,bi=t=>`pi-web-ui:${t}-panel-width`;function xn(t){const s=Number(localStorage.getItem(bi(t)));return Number.isFinite(s)&&s>=xi&&s<=yi?s:vi}const Ss=t=>`pi-web-ui:${t}-panel-collapsed`;function yn(t){return localStorage.getItem(Ss(t))==="1"}function vn({side:t,width:s,onResize:n}){const r=be(),c=l.useCallback(i=>{i.preventDefault();const a=i.clientX,o=s;let u=o;const m=x=>{const f=t==="left"?x.clientX-a:a-x.clientX;u=Math.min(yi,Math.max(xi,Math.round(o+f))),n(u)},y=()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",y),document.body.classList.remove("panel-resizing"),localStorage.setItem(bi(t),String(u))};window.addEventListener("pointermove",m),window.addEventListener("pointerup",y),document.body.classList.add("panel-resizing")},[t,s,n]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:r("dragToResize"),onPointerDown:c,onDoubleClick:()=>n(vi)})}function bn({side:t,onClick:s}){const n=be();return e.jsx("button",{type:"button",className:`panel-rail panel-rail-${t}`,title:n("expandPanel"),onClick:s,children:t==="left"?e.jsx(Pn,{}):e.jsx(Mn,{})})}function ho(){var dt,ut,pt,mt,ht,gt,p,re,Pe,_e,Be,ft,xt,Mt;const t=be(),{chat:s,send:n,dismissNotice:r,pushNotice:c,terminal:i}=Wa(),[a,o]=l.useState([]),[u,m]=l.useState(null),[y,x]=l.useState(!1),[f,b]=l.useState("chat"),T=l.useMemo(()=>s.plugins.filter(F=>{var te,he;return!((he=(te=s.settings)==null?void 0:te.disabledPlugins)!=null&&he.includes(F.id))}),[s.plugins,(dt=s.settings)==null?void 0:dt.disabledPlugins]),[D,H]=l.useState([]);l.useEffect(()=>Ma(H),[]),l.useEffect(()=>{ar(n),rr(T,s.pluginsEpoch),Ia(T,s.pluginsEpoch)},[T,s.pluginsEpoch,n]);const[N,j]=l.useState(()=>xn("left")),[Q,V]=l.useState(()=>xn("right")),J=l.useCallback(F=>j(F),[]),U=l.useCallback(F=>V(F),[]),[W,K]=l.useState(()=>yn("left")),[G,C]=l.useState(()=>yn("right")),M=l.useCallback(()=>{K(F=>(localStorage.setItem(Ss("left"),F?"0":"1"),!F))},[]),k=l.useCallback(()=>{C(F=>(localStorage.setItem(Ss("right"),F?"0":"1"),!F))},[]),[_,Z]=l.useState(null),[z,I]=l.useState(()=>window.matchMedia("(max-width: 768px)").matches);l.useEffect(()=>{const F=window.matchMedia("(max-width: 768px)"),te=he=>I(he.matches);return F.addEventListener("change",te),()=>F.removeEventListener("change",te)},[]);const[R,w]=l.useState(!1),[$,q]=l.useState(!1),[ie,v]=l.useState(!1),L=ui(),[d,E]=l.useState(!1),[h,A]=l.useState(!1),[ee,Y]=l.useState(null);l.useEffect(()=>{if(!ee)return;const F=setTimeout(()=>Y(null),15e3);return()=>clearTimeout(F)},[ee]),l.useEffect(()=>{const F=te=>{var Je,Ls;const he=te.detail,Ce=(he==null?void 0:he.title)||t("pluginCommandFallback"),Te=he==null?void 0:he.command;if(!Te||!s.ready)return;const We={name:Ce,command:Te,cwd:"${pwd}"},Me=s.terminals.find(Yt=>Yt.title===Ce);if(Me)i.restart(Me.id),n({type:"run_command",terminalId:Me.id,conversationId:Me.conversationId,command:We,cols:80,rows:24});else{const Yt=Qe();i.create({id:Yt,conversationId:s.activeConversationId||((Je=s.state)==null?void 0:Je.conversationId)||"",title:Ce,cwd:((Ls=s.state)==null?void 0:Ls.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:We})}b("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",F),()=>window.removeEventListener("pi-web-ui:plugin-run-command",F)},[s,i,n]),l.useEffect(()=>{const F=te=>{!(te.ctrlKey||te.metaKey)||te.key.toLowerCase()!=="k"||(te.preventDefault(),A(he=>!he))};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[]);const[se,X]=l.useState(mi),{themes:ge,theme:Ne,switchTheme:de}=co(),Ee=l.useRef(null),le=l.useRef(null),g=l.useRef(0),O=l.useRef(!1),me=l.useRef(s.terminals);l.useEffect(()=>{Zl(se)},[se]),l.useEffect(()=>{var te;const F=me.current;me.current=s.terminals;for(const he of s.terminals){const Ce=((te=he.command)==null?void 0:te.command)??"",Te=F.find(We=>We.id===he.id);!(Te!=null&&Te.running)||he.running||(Ce.startsWith("pi remove ")?n({type:"extensions_reload"}):Ce.startsWith("pi-web-ui install ")||Ce.startsWith("pi-web-ui uninstall ")?n({type:"plugins_reload"}):Ce.startsWith("npm i -g ")&&(n({type:"extensions_reload"}),n({type:"plugins_reload"}),n({type:"check_updates_all",force:!0})))}},[s.terminals,n]),l.useEffect(()=>{var he;const F=((he=s.state)==null?void 0:he.isStreaming)??!1,te=Ee.current;Ee.current=F,te!==null&&(!te&&F?bt("start",se):te&&!F&&(bt("done",se),ts(t("notifyDoneTitle"),t("notifyDoneBody"))))},[(ut=s.state)==null?void 0:ut.isStreaming,se]),l.useEffect(()=>{var te;const F=((te=s.dialog)==null?void 0:te.id)??null;F!==null&&F!==le.current&&(bt("question",se),ts(t("notifyQuestionTitle"),t("notifyQuestionBody"))),le.current=F},[s.dialog,se]),l.useEffect(()=>{const F=[...s.notices].reverse().find(te=>te.level==="error");F&&F.id!==g.current&&(g.current=F.id,bt("error",se),ts(t("notifyErrorTitle"),t("notifyErrorBody")))},[s.notices,se]);const ue=(F,te,he,Ce=!1,Te)=>{const We=`${F}|${he}|${Te?`${Te.start}-${Te.end}`:""}`;o(Me=>Me.some(Je=>`${Je.path}|${Je.mode}|${Je.lines?`${Je.lines.start}-${Je.lines.end}`:""}`===We)?Me:[...Me,{path:F,name:te,mode:he,isDir:Ce,...Te?{lines:Te}:{}}])},ye=F=>o(te=>te.filter(he=>he.key?he.key!==F:he.path!==F)),fe=l.useCallback(F=>(!F.type.startsWith("list_")&&!F.type.startsWith("get_")&&Z(null),n(F)),[n]),ke=l.useRef(0),Le=l.useRef(0),ae=F=>{var Ce;const te=Date.now();(Ce=s.state)!=null&&Ce.model&&!s.state.model.vision&&te-Le.current>1e4&&(Le.current=te,c("warning",t("imageNotSupported")));const he=`paste-${++ke.current}`;o(Te=>[...Te,{path:"",key:he,name:F.name,mode:"inline",imageData:F.data,mimeType:F.mimeType}])},De=async F=>{for(const te of F){const he=await Kn(te);if(!he){c("error",t("imageLoadFailed",{name:te.name}));continue}ae(he)}},Ae=20*1024*1024,qe=l.useRef(0),ze=async F=>{if(F.size>Ae){c("warning",t("fileTooLarge",{name:F.name,size:Ae/1024/1024}));return}let te;try{te=(await new Promise((Te,We)=>{const Me=new FileReader;Me.onload=()=>Te(Me.result),Me.onerror=()=>We(Me.error??new Error("read failed")),Me.readAsDataURL(F)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",t("fileLoadFailed",{name:F.name}));return}const he=`upload-${++qe.current}`;o(Ce=>[...Ce,{path:"",key:he,name:F.name,mode:"inline",fileData:te,size:F.size,mimeType:F.type||void 0}])},P=async F=>{for(const te of F)Ge(te.type)?await De([te]):await ze(te)},xe=l.useCallback((F,te,he)=>{n({type:"edit_message",messageId:F,text:te,attachments:he})},[n]),pe=l.useCallback((F,te)=>{n({type:"queue_remove",kind:F,text:te})},[n]),Se=l.useCallback(()=>q(!0),[]),ve=l.useCallback(()=>o([]),[]),S=l.useCallback(ye,[]),B=l.useCallback(De,[De]),oe=l.useCallback(P,[P]),ce=(pt=s.state)==null?void 0:pt.model,je=(mt=s.state)==null?void 0:mt.thinkingLevel,we=(ht=s.state)==null?void 0:ht.availableThinkingLevels,Ie=l.useMemo(()=>ce?{model:ce,thinkingLevel:je??"off",availableThinkingLevels:we??[]}:null,[ce,je,we]),Oe=l.useCallback(()=>{var F,te;return!s.ready||s.terminals.length!==0?!1:(i.create({id:Qe(),conversationId:s.activeConversationId||((F=s.state)==null?void 0:F.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((te=s.state)==null?void 0:te.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,(gt=s.state)==null?void 0:gt.cwd,s.terminals.length,t,i]);return l.useEffect(()=>{if(O.current){if(f!=="terminal"||s.terminals.length!==0){O.current=!1;return}Oe()&&(O.current=!1)}},[s.terminals.length,Oe,f]),e.jsxs("div",{className:"app",onDragOver:F=>{var te;Array.from(((te=F.dataTransfer)==null?void 0:te.types)??[]).includes("Files")&&(F.preventDefault(),x(!0))},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||x(!1)},onDrop:F=>{var Te,We;if(x(!1),!Array.from(((Te=F.dataTransfer)==null?void 0:Te.types)??[]).includes("Files"))return;F.preventDefault();const te=Array.from(((We=F.dataTransfer)==null?void 0:We.files)??[]);if(te.length===0){c("warning",t("foldersNotSupported"));return}const he=te.filter(Me=>Ge(Me.type)),Ce=te.filter(Me=>!Ge(Me.type));he.length>0&&De(he),Ce.length>0&&P(Ce)},children:[y&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(xa,{chat:s,send:n,terminal:i,view:f,plugins:T,onViewChange:F=>{O.current=F==="terminal"&&s.terminals.length===0,O.current&&Oe()&&(O.current=!1),b(F),Z(null)},onOpenPanel:Z,onOpenSettings:()=>v(!0),onOpenBgTasks:()=>E(!0),onOpenGlobalSearch:()=>A(!0),sound:se,onSoundChange:X,onSoundPreview:F=>bt(F,se),themes:ge,theme:Ne,onThemeChange:de}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(F=>e.jsx(po,{notice:F,onDismiss:r},F.id))}),e.jsx(nl,{send:n,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${N}px`,"--right-w":`${Q}px`},children:[_&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>Z(null)}),e.jsxs("div",{className:`view-pane ${f==="chat"?"":"hidden"}`,children:[!z&&W&&e.jsx(bn,{side:"left",onClick:M}),e.jsx("div",{className:`panel-drawer drawer-left ${_==="left"?"open":""}${z?"":W?" hidden":""}`,children:e.jsx(wa,{collapsible:!z,onToggleCollapse:M,send:fe,active:!z||_==="left",ready:s.ready,status:s.status,cwd:((p=s.state)==null?void 0:p.cwd)??"",sessionFile:((re=s.state)==null?void 0:re.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!z&&e.jsx(vn,{side:"left",width:N,onResize:J}),e.jsxs("main",{className:L?"main wide-chat":"main",children:[s.state?e.jsx(cl,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:xe,onKillBash:()=>n({type:"abort_bash"}),onRemoveQueued:pe,thinkingWrap:((Pe=s.settings)==null?void 0:Pe.thinkingWrap)??!0,toolsWrap:((_e=s.settings)==null?void 0:_e.toolsWrap)??!0,jumpTarget:ee,onJumpDone:()=>Y(null)},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(Nl,{send:n,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId,engine:s.engine}),s.dialog&&e.jsx(Il,{dialog:s.dialog,send:n}),s.question&&e.jsx(Rl,{question:s.question,send:n}),e.jsx(wl,{send:n,ready:s.ready,streaming:((Be=s.state)==null?void 0:Be.isStreaming)??!1,messages:((ft=s.state)==null?void 0:ft.messages)??mo,slashCommands:s.slashCommands,modelState:Ie,models:s.models,modelsLoading:s.modelsLoading,providerKeys:s.providerKeys,attachments:a,onRemoveAttachment:S,onAddImageFiles:B,onAddLocalFiles:oe,onNotice:c,onManageModels:Se,onSent:ve})]}),!z&&e.jsx(vn,{side:"right",width:Q,onResize:U}),e.jsx("div",{className:`panel-drawer drawer-right ${_==="right"?"open":""}${z?"":G?" hidden":""}`,children:e.jsx(Ja,{collapsible:!z,onToggleCollapse:k,send:fe,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((xt=s.state)==null?void 0:xt.cwd)??"",onAttach:(F,te,he,Ce)=>{Z(null),ue(F,te,he,Ce)},onPreview:(F,te)=>{Z(null),m({path:F,name:te})},onNotice:(F,te)=>c(F,te)})}),!z&&G&&e.jsx(bn,{side:"right",onClick:k})]}),e.jsx("div",{className:`view-pane ${f==="terminal"?"":"hidden"}`,children:e.jsx(l.Suspense,{fallback:null,children:e.jsx(uo,{chat:s,send:n,terminal:i})})}),e.jsx("div",{className:`view-pane ${f==="git"?"":"hidden"}`,children:e.jsx(Dl,{chat:s,send:n,terminal:i,active:f==="git",onSwitchToTerminal:()=>b("terminal")})}),D.map(F=>{const te=`plugin:${F.info.id}`;return e.jsx("div",{className:`view-pane ${f===te?"":"hidden"}`,children:e.jsx(Al,{entry:F,send:n})},F.info.id)})]})}),e.jsx(Pl,{chat:s,send:n}),u&&e.jsx(Jl,{file:u,content:s.fileContent,send:n,onAddLines:(F,te,he,Ce)=>ue(F,te,"lines",!1,{start:he,end:Ce}),onAttach:(F,te,he)=>ue(F,te,he),onClose:()=>m(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!R&&!$&&e.jsx(_l,{send:n,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>w(!0)}),$&&e.jsx($l,{send:n,providers:s.modelsConfig,providerStatus:s.providers,providerKeys:s.providerKeys,fetchModelsResult:s.fetchModelsResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>q(!1)}),ie&&e.jsx(zl,{chat:s,send:n,terminal:i,onSwitchToTerminal:()=>b("terminal"),onClose:()=>v(!1)}),d&&e.jsx(Gl,{servers:s.bgServers,send:n,onClose:()=>E(!1)}),e.jsx(Yl,{open:h,send:n,projects:s.projects,cwd:((Mt=s.state)==null?void 0:Mt.cwd)??"",fileSearch:s.fileSearch,sessionSearch:s.sessionSearch,onClose:()=>A(!1),onSwitchSession:(F,te)=>{n({type:"switch_session",path:F});const he=te&&te[0];Y(he?{path:F,role:he.role,timestamp:he.timestamp}:null)},onSwitchProject:F=>{n({type:"set_cwd",path:F})},onPreviewFile:(F,te)=>{m({path:F,name:te})}})]})}Na();fi(gi());Ci.createRoot(document.getElementById("root")).render(e.jsx(l.StrictMode,{children:e.jsx(ua,{children:e.jsx(ho,{})})}));"serviceWorker"in navigator&&window.addEventListener("load",()=>{const t=An();navigator.serviceWorker.register(`${t}sw.js`,{scope:t}).catch(s=>{console.warn("Service worker registration failed:",s)})});export{rt as F,fn as T,be as a,yo as b,Ke as c,xo as d,Kt as e,He as f,zi as g,ot as h,Re as i,Qe as r,Pt as u};
|
|
323
|
+
`),de=(g=!1)=>{var ue,ye,fe,ke,Le;const O=U.trim(),me=m.some(ae=>ae.imageData||ae.fileData);if(!(!se||!O&&!me)){if(O==="/help"){const ae=(ye=(ue=w.current)==null?void 0:ue.closest(".inputbox"))==null?void 0:ye.getBoundingClientRect();R(ae==null?void 0:ae.width),z(!0),W(""),(fe=w.current)==null||fe.focus();return}if(O==="/copy"){W(""),(ke=w.current)==null||ke.focus(),h();return}if(u({type:"prompt",text:O,queue:g,attachments:m.map(ae=>ae.imageData?{path:"",imageData:ae.imageData,mimeType:ae.mimeType,name:ae.name}:ae.fileData?{path:"",fileData:ae.fileData,mimeType:ae.mimeType,name:ae.name,size:ae.size}:{path:ae.path,mode:ae.mode,...ae.lines?{lines:ae.lines}:{}})})){O&&kl(O),ie.current=-1,v.current="",W(""),T();const ae=i==null?void 0:i.model;ae&&xl(`${ae.provider}/${ae.id}`),(Le=w.current)==null||Le.focus()}}},Ee=g=>{if(!g.nativeEvent.isComposing){if(C&&C.length>0)switch(g.key){case"ArrowDown":g.preventDefault(),_(O=>(O+1)%C.length);return;case"ArrowUp":g.preventDefault(),_(O=>(O-1+C.length)%C.length);return;case"Tab":case"Enter":g.preventDefault(),E();return;case"Escape":g.preventDefault(),M(null);return}if(g.key==="ArrowUp"||g.key==="ArrowDown"){if(g.ctrlKey||g.metaKey||g.altKey)return;const O=w.current;if(!O)return;const me=g.key==="ArrowUp";if(me&&!ge(O)||!me&&!Ne(O)||!me&&ie.current===-1)return;const ue=Tt();if(ue.length===0)return;if(g.preventDefault(),me){if(ie.current===-1){v.current=U;const ye=ue.length-1;ie.current=ye;const fe=ue[ye];W(fe),d(fe),requestAnimationFrame(()=>{const ke=w.current;ke&&(ke.selectionStart=ke.selectionEnd=fe.length)})}else if(ie.current>0){const ye=ie.current-1;ie.current=ye;const fe=ue[ye];W(fe),d(fe),requestAnimationFrame(()=>{const ke=w.current;ke&&(ke.selectionStart=ke.selectionEnd=fe.length)})}}else{const ye=ie.current+1;if(ye<ue.length){ie.current=ye;const fe=ue[ye];W(fe),d(fe),requestAnimationFrame(()=>{const ke=w.current;ke&&(ke.selectionStart=ke.selectionEnd=fe.length)})}else{ie.current=-1;const fe=v.current;W(fe),d(fe),requestAnimationFrame(()=>{const ke=w.current;ke&&(ke.selectionStart=ke.selectionEnd=fe.length)})}}return}if(g.key==="Escape"&&ie.current!==-1){g.preventDefault();const O=v.current;ie.current=-1,W(O),d(O),requestAnimationFrame(()=>{const me=w.current;me&&(me.selectionStart=me.selectionEnd=O.length)});return}if(g.key==="Enter"){if(Cl&&!g.shiftKey&&!(g.ctrlKey||g.metaKey))return;g.shiftKey||(g.preventDefault(),de())}}},le=()=>e.jsx("div",{className:"inputbox-actions",children:n?e.jsxs(e.Fragment,{children:[U.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:N("supplementTip"),onClick:()=>de(!0),children:[e.jsx(Cn,{})," ",N("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:N("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(Ot,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:N("sendTip"),disabled:!se||!U.trim()&&!m.some(g=>g.imageData||g.fileData),onClick:()=>de(),children:e.jsx(In,{})})});return e.jsxs("div",{className:`inputbar${K?" drop-active":""}`,onDragOver:g=>{g.preventDefault(),g.stopPropagation(),G(!0)},onDragLeave:g=>{g.currentTarget.contains(g.relatedTarget)||G(!1)},onDrop:g=>{var O;g.preventDefault(),g.stopPropagation(),G(!1),A(((O=g.dataTransfer)==null?void 0:O.files)??null)},children:[K&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",N("dropHereToAttach")]})}),m.length>0&&e.jsxs("div",{className:"attach-row",children:[m.map(g=>e.jsxs("span",{className:`attach-chip ${g.imageData?"image":g.fileData?"file":g.mode}`,title:g.imageData?N("attachImage",{name:g.name}):g.fileData?N("attachFile",{name:g.name}):g.isDir?N("folderRef",{path:g.path}):g.mode==="reference"?N("refOnly",{path:g.path}):g.mode==="lines"&&g.lines?N("attachLines",{path:g.path,start:g.lines.start,end:g.lines.end}):N("attachContent",{path:g.path}),children:[g.imageData?"🖼":g.fileData?"📄":g.isDir?"📁":g.mode==="reference"?"🔗":"📎"," ",g.name,g.mode==="lines"&&g.lines&&e.jsxs("span",{className:"attach-range",children:["L",g.lines.start,"-",g.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:N("removeAttachment"),onClick:()=>f(g.key??g.path),children:"×"})]},g.key??`${g.path}|${g.mode}|${g.lines?`${g.lines.start}-${g.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:N("attachHint")})]}),C&&C.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:q,"aria-label":N("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:N("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>M(null),children:"Esc"})]}),C.map((g,O)=>e.jsxs("button",{type:"button",className:`slash-item${O===k?" active":""}`,onMouseEnter:()=>_(O),onClick:()=>E(g),children:[e.jsxs("span",{className:"slash-name",children:["/",g.name]}),e.jsx("span",{className:`slash-source ${g.source}`,children:L[g.source]}),e.jsxs("span",{className:"slash-desc",children:[V(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:J(g)})]})]},g.name))]}),Z&&e.jsx("div",{className:"modal-backdrop",onClick:()=>z(!1),children:e.jsxs("div",{className:"slash-help",style:I?{width:I}:void 0,onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",N("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>z(!1),children:N("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:N("slashLoading")}):c.map(g=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",g.name]}),e.jsx("span",{className:`slash-source ${g.source}`,children:L[g.source]}),e.jsxs("span",{className:"slash-help-desc",children:[V(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:J(g)})]})]},g.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:$,type:"file",multiple:!0,hidden:!0,onChange:g=>{A(g.target.files),g.target.value=""}}),e.jsx("textarea",{ref:w,value:U,rows:1,placeholder:N(se?n?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!se,onChange:g=>{ie.current=-1,W(g.target.value),d(g.target.value)},onKeyDown:Ee,onPaste:ee}),e.jsxs("div",{className:"composer-tools",children:[e.jsxs("div",{className:"composer-tools-left",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:N("uploadFile"),disabled:!se,onClick:()=>{var g;return(g=$.current)==null?void 0:g.click()},children:e.jsx(Ui,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:N("tpl.openPicker"),onClick:Q,children:e.jsx(Xi,{})}),e.jsx(Nl,{state:i,models:a,modelsLoading:o,send:u,onManageModels:D,providerKeys:H,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:le()})]})]})]})}),Tl=l.memo(function({goal:s,models:n,modelsLoading:r,activeConversationId:c,engine:i,send:a}){var I,R,w,$,q,ie,v;const o=be(),{locale:u}=Mt(),m=u==="en"&&s.statusEn?s.statusEn:s.status||"",f=u==="en"&&((I=s.wizard)!=null&&I.statusEn)?s.wizard.statusEn:((R=s.wizard)==null?void 0:R.status)||"",y=i==="dsh",x=!s.conversationId||s.conversationId===c,b=s.goal!==null&&x,[T,D]=l.useState(""),[H,N]=l.useState(s.reviewModel??""),[j,Q]=l.useState(s.maxRounds),[V,J]=l.useState(s.locked),[U,W]=l.useState(!1),[K,G]=l.useState(!1),[C,M]=l.useState(!0);l.useEffect(()=>{N(s.reviewModel??""),Q(s.maxRounds||0),J(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),l.useEffect(()=>{U&&n.length===0&&!K&&!r&&(G(!0),a({type:"list_models"}))},[U,n.length,K,r,a]),l.useEffect(()=>{n.length>0&&G(!1)},[n.length]);const k=()=>{var L;return H?((L=n.find(d=>d.id===H))==null?void 0:L.name)??H:o("goalBarUseMainModel")},_=()=>{const L=T.trim();L&&(a({type:"set_goal",goal:L,...H?{reviewModel:H}:{},maxRounds:j,locked:V}),D(""),M(!1))},Z=()=>{const L=T.trim();L&&(a({type:"start_goal_wizard",text:L,...H?{wizardModel:H}:{},maxRounds:j,locked:V}),D(""),M(!1))},z=(((w=s.wizard)==null?void 0:w.active)??!1)&&x;return z?e.jsx("div",{className:`goalbar goalbar-active ${z?"wizard":""}`,children:e.jsxs("div",{className:"goalbar-active-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx("span",{className:"goalbar-spin",children:"🔍"})}),e.jsxs("span",{className:"goalbar-text",title:(($=s.wizard)==null?void 0:$.draft)??"",children:[o("goalWizardRunning"),": ",(q=s.wizard)==null?void 0:q.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[o("goalBarRound",{n:(((ie=s.wizard)==null?void 0:ie.step)??0)+1})," / ",((v=s.wizard)==null?void 0:v.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:f||o("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),onClick:()=>{a({type:"clear_goal"}),M(!0)},children:e.jsx(Re,{})})]})}):b?e.jsx("div",{className:`goalbar goalbar-active ${s.reviewing?"reviewing":""}`,children:e.jsxs("div",{className:"goalbar-active-row",children:[e.jsx("span",{className:"goalbar-icon",children:s.reviewing?e.jsx("span",{className:"goalbar-spin",children:"◌"}):"🎯"}),e.jsx("span",{className:"goalbar-text",title:s.goal??"",children:s.goal}),s.reviewing?e.jsxs("span",{className:"goalbar-chip reviewing",children:[o("goalBarReviewing")," ",o("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?o("goalBarPassed"):s.verdict==="fail"?o("goalBarFailed"):`${o("goalBarRound",{n:s.round||1})} · ${s.locked?o("goalBarLocked"):o("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:m}),e.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),disabled:s.reviewing,onClick:()=>{a({type:"clear_goal"}),M(!0)},children:e.jsx(Re,{})})]})}):C?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:o("goalBarPlaceholder"),onClick:()=>M(!1),children:[e.jsx(Hs,{})," ",e.jsx("span",{children:o("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx(Hs,{})}),e.jsx("input",{className:"goalbar-input",value:T,placeholder:o("goalBarPlaceholder"),onChange:L=>D(L.target.value),onKeyDown:L=>{L.key==="Enter"&&_()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!T.trim(),onClick:_,children:o("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!T.trim(),title:o("goalWizardTip"),onClick:Z,children:["🔍 ",o("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o(V?"goalBarLocked":"goalBarUnlocked"),onClick:()=>J(L=>(a({type:"set_goal_prefs",locked:!L}),!L)),children:V?e.jsx(Qi,{}):e.jsx($i,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o("goalBarClear"),onClick:()=>M(!0),children:e.jsx(Et,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[y?e.jsx("p",{className:"goalbar-dsh-note",children:o("dshNoReviewModel")}):e.jsxs(Xe,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[o("goalBarReviewModel"),": ",e.jsx("b",{children:k()})]}),open:U,onOpenChange:W,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("goalBarReviewModel")}),(K||r)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),n.length===0&&!K&&!r&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),e.jsx($e,{active:H==="",onClick:()=>{N(""),W(!1),a({type:"set_goal_prefs",reviewModel:""})},children:o("goalBarUseMainModel")}),n.map(L=>e.jsx($e,{active:H===L.id,onClick:()=>{N(L.id),W(!1),a({type:"set_goal_prefs",reviewModel:L.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:L.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:L.provider})})]})},L.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>a({type:"list_models"}),children:o("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:o("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:o("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:j,placeholder:o("goalBarUnlimitedShort"),onChange:L=>{const d=parseInt(L.target.value,10);if(Number.isNaN(d)||d<0){Q(0);return}Q(d)},onBlur:()=>a({type:"set_goal_prefs",maxRounds:j}),onKeyDown:L=>{L.key==="Enter"&&(a({type:"set_goal_prefs",maxRounds:j}),L.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:o(V?"goalBarLocked":"goalBarUnlocked")})]})]})});function El(t){const s=Math.max(0,t.input??0),n=Math.max(0,t.cacheRead??0),r=Math.max(0,t.cacheWrite??0),c=s+n+r;return{totalInput:c,miss:s,read:n,write:r,hitRate:c>0?Math.min(n/c,1):0,writeRate:c>0?Math.min(r/c,1):0}}const ui=2e3;function Pl(t,s,n=ui){return t.filter(r=>s-r.t<=n)}function Ml(t,s=ui){if(t.length<2)return 0;const n=t[t.length-1],r=t.find(i=>i.t>=n.t-s)??t[0],c=(n.t-r.t)/1e3;return c<=0?0:Math.max(0,(n.out-r.out)/c)}function gn(t){if(!t)return 0;let s=0;for(let r=0;r<t.length;r++){const c=t.charCodeAt(r);(c>=12352&&c<=12543||c>=13312&&c<=19903||c>=19968&&c<=40959||c>=63744&&c<=64255||c>=65280&&c<=65519||c===12288)&&s++}const n=t.length-s;return Math.round(s+n/4)}function Il(t){let s=0;for(const n of t)n.type==="text"&&typeof n.text=="string"&&n.text?s+=gn(n.text):n.type==="thinking"&&typeof n.thinking=="string"&&n.thinking&&(s+=gn(n.thinking));return s}const et="@root";function Rl({chat:t,send:s}){const n=be(),r=t.state,[c,i]=l.useState(!1),[a,o]=l.useState(""),[u,m]=l.useState(""),[f,y]=l.useState(!1),[x,b]=l.useState(""),[T,D]=l.useState(-1),H=l.useRef(null),N=l.useRef(null),j=t.pathCompletions.filter(h=>h.type==="dir"),Q=h=>h.endsWith("/")?h:h+"/",V=h=>{let A=h.endsWith("/")&&h!=="/"?h.slice(0,-1):h;if(A===et||A==="/")return null;const ee=A.lastIndexOf("/");if(ee<0)return/^[A-Za-z]:$/.test(A)?et:null;if(ee===0)return"/";const Y=A.slice(0,ee);return/^[A-Za-z]:$/.test(Y)?Y+"/":Y};l.useEffect(()=>{if(!c)return;const h=setTimeout(()=>{s({type:"complete_path",path:Q(a)})},60);return()=>clearTimeout(h)},[a,c,s]),l.useEffect(()=>{if(!c||u===a)return;const h=setTimeout(()=>{s({type:"complete_path",path:u})},150);return()=>clearTimeout(h)},[u,a,c,s]);const J=l.useRef([]),U=(r==null?void 0:r.isStreaming)??!1,W=r!=null&&r.streamingMessage?Il(r.streamingMessage.content):0;if(l.useEffect(()=>{if(!U){J.current=[];return}const h=Date.now(),A=J.current,ee=A[A.length-1];ee&&h-ee.t<250||(J.current=Pl([...A,{t:h,out:W}],h))},[U,W]),!r)return null;const K=r.stats,G=El(K.tokens),C=G.hitRate*100,M=G.totalInput===0?"":G.hitRate>=.7?"ok":G.hitRate>=.4?"mid":"warn",k=G.totalInput>0?`${C.toFixed(1)}%`:"—",_=U?Ml(J.current):0,Z=t.ready?"ok":"busy",z=t.ready?n("connected"):n("connecting"),I=K.contextUsage,R=I.tokens!==null&&I.percent!==null?`${it(I.tokens)} / ${it(I.contextWindow)}`:"—",w=I.percent??null,$=w===null?"":w>=80?"warn":w>=50?"mid":"ok",q=r.queue.steering.length+r.queue.followUp.length,ie=()=>{m(r.cwd),o(r.cwd),y(!1),b(""),i(!0)},v=h=>{const A=h.trim();A!==et&&(A&&A!==r.cwd&&s({type:"set_cwd",path:A}),i(!1))},L=()=>{const h=x.trim();h&&(s({type:"make_dir",path:`${Q(a)}${h}`}),setTimeout(()=>{s({type:"complete_path",path:Q(a)})},80),b(""),y(!1))},d=h=>{if(h.key==="Escape")h.stopPropagation(),i(!1);else if(h.key==="Enter"&&!h.nativeEvent.isComposing)v(u);else if(h.key==="Tab"){if(j.length===0)return;h.preventDefault();const A=T>=0?(T+1)%j.length:0;D(A),m(j[A].path),o(j[A].path)}},E=V(a);return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${Z}`,title:z}),e.jsx("span",{className:"status-item",children:z}),e.jsx("span",{className:"status-sep",children:"·"}),t.engine&&t.engine!=="pi"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`status-item engine-badge engine-${t.engine}`,title:`${n("engineBadge")}: ${t.engine}`,children:t.engine==="dsh"?"DSH":t.engine}),e.jsx("span",{className:"status-sep",children:"·"})]}),e.jsxs("span",{className:"status-item status-ctx",title:n("contextUsage"),children:[n("context"),e.jsx("span",{className:`ctx-bar ${$}`,children:w!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(w,100)}%`}})}),R]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("cumulativeCost"),children:["$",Ll(K.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-cache",title:n("cacheHitTip",{read:it(G.read),write:it(G.write),miss:it(G.miss),input:it(G.totalInput)}),children:[n("cacheHit"),e.jsx("b",{className:`cache-pct ${M}`,children:k})]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("sessionMessages"),children:[n("messages")," ",K.totalMessages]}),t.statuses.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsx("span",{className:"status-item ext-status",title:n("pluginStatus"),children:t.statuses.map(h=>h.text).join(" · ")})]}),r.isStreaming&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item working",children:[e.jsx("span",{className:"working-spin"}),n("working"),q>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",q," ",n("queued")]})]}),e.jsx("span",{className:"status-item status-rate",title:n("rateTip"),children:_>0?`${Math.round(_)}${n("tps")}`:"…"})]}),c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"status-cwd-backdrop",onClick:()=>i(!1)}),e.jsxs("div",{className:"cwd-picker",children:[e.jsxs("div",{className:"cwd-picker-head",children:[e.jsxs("span",{className:"cwd-picker-title",title:a===et?n("computer"):a,children:[a===et?"💻":e.jsx(st,{}),e.jsx("span",{children:a===et?n("computer"):a})]}),e.jsxs("button",{type:"button",className:"cwd-up",disabled:!E,title:n("cwdGoUp"),onClick:()=>{E&&(o(E),m(E),D(-1))},children:["↑ ",n("cwdGoUp")]})]}),e.jsxs("div",{className:"cwd-picker-row",children:[e.jsx("input",{ref:H,className:"status-cwd-input cwd-picker-input",value:u,placeholder:n("enterPath"),spellCheck:!1,onChange:h=>{m(h.target.value),D(-1)},onKeyDown:d}),e.jsx("button",{type:"button",className:"cwd-choose-btn primary",title:n("cwdPickCurrent"),disabled:a===et,onClick:()=>v(a),children:n("cwdPickCurrent")})]}),e.jsxs("div",{className:"cwd-list",children:[j.length===0&&e.jsx("div",{className:"cwd-empty",children:n("cwdEmpty")}),j.map(h=>e.jsxs("div",{className:"cwd-item",children:[e.jsxs("button",{type:"button",className:"cwd-enter",title:`${n("cwdEnter")} ${h.path}`,onClick:()=>{o(h.path),m(h.path),D(-1)},children:[e.jsx(st,{}),e.jsx("span",{className:"cwd-name",children:h.name})]}),e.jsx("button",{type:"button",className:"cwd-choose-btn",title:n("cwdChoose"),onClick:()=>v(h.path),children:n("cwdChoose")})]},h.path))]}),e.jsx("div",{className:"cwd-picker-foot",children:f?e.jsxs("div",{className:"cwd-newrow",children:[e.jsx("input",{ref:N,value:x,autoFocus:!0,spellCheck:!1,placeholder:n("cwdNewName"),onChange:h=>b(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.nativeEvent.isComposing?(h.preventDefault(),L()):h.key==="Escape"&&(h.stopPropagation(),y(!1),b(""))}}),e.jsx("button",{type:"button",className:"cwd-choose-btn primary",onClick:L,children:n("cwdCreate")}),e.jsx("button",{type:"button",className:"cwd-choose-btn",onClick:()=>{y(!1),b("")},children:n("cwdCancel")})]}):e.jsxs("button",{type:"button",className:"cwd-newbtn",onClick:()=>y(!0),children:["+ ",n("cwdNewFolder")]})})]})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:n("cwdTip",{path:r.cwd}),onClick:ie,children:["📁 ",r.cwd]})]})}function it(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function Ll(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function Dl({dialog:t,send:s}){const n=be(),[r,c]=l.useState(""),[i,a]=l.useState(0),o=f=>{s({type:"dialog_response",id:t.id,value:f})};l.useEffect(()=>{c(""),a(0);const f=y=>{y.key==="Escape"&&o(null)};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t.id]);const u=Array.isArray(t.args[0])?t.args[0]:[],m=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("pluginRequest")}),t.title&&t.title!==n("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>o(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[u.map((f,y)=>e.jsx("button",{type:"button",className:`dialog-option ${y===i?"sel":""}`,onMouseEnter:()=>a(y),onClick:()=>o(f),children:f},y)),u.length===0&&e.jsx("div",{className:"dialog-hint",children:n("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:m}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(!1),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(!0),children:n("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:r,placeholder:m||n("inputPlaceholder"),autoFocus:!0,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.nativeEvent.isComposing&&o(r)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(null),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(r),children:n("ok")})]})]})]})}function Al({question:t,send:s}){const n=be(),[r,c]=l.useState({}),[i,a]=l.useState({}),[o,u]=l.useState(()=>t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1);l.useEffect(()=>{c({}),a({}),u(t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1)},[t.id,t.deadline]),l.useEffect(()=>{if(!t.deadline)return;const x=setInterval(()=>{u(b=>{const T=Math.max(0,Math.ceil((t.deadline-Date.now())/1e3));return T<=0&&b>0&&s({type:"question_answer",id:t.id,answers:[],cancelled:!0}),T})},1e3);return()=>clearInterval(x)},[t.id,t.deadline]);const m=x=>{if(x){s({type:"question_answer",id:t.id,answers:[],cancelled:!0});return}const b=t.questions.map(T=>{const D=r[T.id]??[],H=(i[T.id]??"").trim();return{id:T.id,selected:D,...H?{custom:H}:{}}});s({type:"question_answer",id:t.id,answers:b})};l.useEffect(()=>{const x=b=>{b.key==="Escape"&&m(!0)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t.id]);const f=(x,b,T)=>{c(D=>{const H=D[x]??[];return T?{...D,[x]:H.includes(b)?H.filter(N=>N!==b):[...H,b]}:{...D,[x]:[b]}})},y=t.questions.every(x=>{var b;return(((b=r[x.id])==null?void 0:b.length)??0)>0||(i[x.id]??"").trim()!==""});return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":"select",children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("modelQuestion")}),o>=0&&e.jsx("span",{className:"question-timer",children:o>0?n("questionTimeout",{s:o}):n("questionTimeoutExpired")}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>m(!0),children:"✕"})]}),t.questions.map((x,b)=>{var T;return e.jsxs("div",{className:"set-section",children:[e.jsx("div",{className:"set-section-title",children:x.header??`${n("modelQuestion")} ${b+1}`}),e.jsx("p",{className:"set-row-desc",children:x.question}),x.detail&&e.jsx("p",{className:"set-hint",children:x.detail}),(((T=x.options)==null?void 0:T.length)??0)>0&&e.jsx("div",{className:"set-list",children:x.options.map(D=>{const H=(r[x.id]??[]).includes(D.label);return e.jsxs("button",{type:"button",className:`set-row question-option${H?" active":""}`,onClick:()=>f(x.id,D.label,!!x.multiSelect),children:[e.jsxs("span",{className:"set-row-name",children:[x.multiSelect?H?"☑ ":"☐ ":H?"● ":"○ ",D.label]}),D.description&&e.jsx("span",{className:"set-row-desc",children:D.description})]},D.label)})}),e.jsx("input",{className:"set-prompt-input question-custom",placeholder:n("modelQuestionCustom"),value:i[x.id]??"",onChange:D=>a(H=>({...H,[x.id]:D.target.value}))})]},x.id)}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"dialog-submit",disabled:!y,onClick:()=>m(!1),children:n("modelQuestionSubmit")}),e.jsx("button",{type:"button",className:"dialog-dismiss-inline",onClick:()=>m(!0),children:n("cancel")})]})]})}const fn=t=>`'${t.replace(/'/g,"'\\''")}'`;function _l(t){if(t.x==="?"&&t.y==="?")return"untracked";const s=t.x!==" "&&t.x!=="?",n=t.y!==" "&&t.y!=="?";return s&&n?"both":s?"staged":"unstaged"}function Bl({chat:t,send:s,terminal:n,active:r,onSwitchToTerminal:c}){var qe,ze;const i=be(),[a,o]=l.useState(null),[u,m]=l.useState([]),[f,y]=l.useState(""),[x,b]=l.useState(new Map),[T,D]=l.useState("changes"),[H,N]=l.useState([]),[j,Q]=l.useState(null),[V,J]=l.useState(""),[U,W]=l.useState(!1),[K,G]=l.useState(null),[C,M]=l.useState(null),[k,_]=l.useState(!1),[Z,z]=l.useState(!1),[I,R]=l.useState(!1),[w,$]=l.useState(null),[q,ie]=l.useState(!1),[v,L]=l.useState(""),d=l.useRef(0),E=l.useRef(-1),h=l.useRef(-1),A=l.useRef(-1),ee=l.useRef(-1),Y=l.useRef(void 0),se=l.useRef(null),X=l.useRef([]),ge=l.useCallback(P=>{if(P.reqId===E.current){if(E.current=-1,z(!1),$(null),!P.ok){$(P.error??i("scmQueryFailedShort"));return}if(P.notRepo){ie(!0),o(null),m([]),b(new Map),N([]),Q(null),J(""),M(null);return}ie(!1);const xe={branch:P.branch??"",detached:!!P.detached,upstream:P.upstream??null,ahead:P.ahead??0,behind:P.behind??0,upstreamGone:!!P.upstreamGone,files:(P.files??[]).map(ve=>({...ve}))},pe=(P.branches??[]).map(ve=>({...ve})),Se=new Map;for(const[ve,S]of Object.entries(P.stats??{}))Se.set(ve,{add:S[0],del:S[1]});o(xe),m(pe),b(Se),y(ve=>{var S;return xe.detached?ve||"":xe.branch&&pe.some(B=>B.name===xe.branch)?xe.branch:ve&&pe.some(B=>B.name===ve)?ve:((S=pe[0])==null?void 0:S.name)??""}),M(ve=>ve&&!xe.files.some(S=>S.path===ve.file.path)?null:ve)}else if(P.reqId===h.current){if(h.current=-1,_(!1),!P.ok){$(P.error??i("scmQueryFailedShort"));return}const xe=se.current;if(!xe)return;M({file:xe,staged:P.stagedText??"",worktree:P.worktreeText??"",untracked:!1})}else if(P.reqId===ee.current){if(ee.current=-1,R(!1),!P.ok){$(P.error??i("scmQueryFailedShort"));return}N((P.history??[]).map(xe=>({...xe})))}else if(P.reqId===A.current){if(A.current=-1,W(!1),!P.ok){$(P.error??i("scmQueryFailedShort"));return}J(P.text??"")}},[]);l.useEffect(()=>{const P=t.scmData;P&&P.type==="scm_data"&&ge(P)},[t.scmData,ge]);const Ne=l.useCallback((P,xe)=>{if(!t.ready||t.status!=="open")return!1;const pe=++d.current;return s({...P,reqId:pe})?(xe.current=pe,!0):(d.current-=1,!1)},[t.ready,t.status,s]),de=l.useCallback((P=!1,xe=!1)=>{var pe;!t.ready||t.status!=="open"||(pe=t.state)!=null&&pe.cwd&&(Y.current!==void 0&&Y.current!==t.state.cwd&&(o(null),m([]),b(new Map),N([]),R(!1),ee.current=-1,Q(null),J(""),M(null),G(null)),Y.current=t.state.cwd,$(null),Ne({type:"scm_status"},E)&&(xe||z(!0)))},[t.ready,(qe=t.state)==null?void 0:qe.cwd,t.status,Ne]),Ee=l.useCallback(P=>{if(G(P),Q(null),se.current=P,P.x==="?"&&P.y==="?"){M({file:P,staged:"",worktree:"",untracked:!0});return}_(!0),$(null),Ne({type:"scm_filediff",path:P.path},h)||_(!1)},[Ne]),le=l.useCallback(P=>{Q(P),G(null),M(null),J(""),W(!0),$(null),Ne({type:"scm_commit",hash:P.hash},A)||W(!1)},[Ne]),g=l.useCallback((P,xe)=>{var S,B;if(!t.ready)return;const pe={name:P,command:xe,cwd:"${pwd}"};let Se;const ve=t.terminals.find(oe=>oe.title===P);ve?(n.restart(ve.id),s({type:"run_command",terminalId:ve.id,conversationId:ve.conversationId,command:pe,cols:80,rows:24}),Se=ve.id):(Se=Qe(),n.create({id:Se,conversationId:t.activeConversationId||((S=t.state)==null?void 0:S.conversationId)||"",title:P,cwd:((B=t.state)==null?void 0:B.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:pe})),n.select(Se),c()},[t.ready,(ze=t.state)==null?void 0:ze.cwd,t.terminals,c,s,n]),O=l.useCallback(()=>{const P=v.trim();if(!P||q)return;const xe=P.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");g("git commit",`git commit -m "${xe}"`),L("")},[v,q,g]),me=l.useCallback(()=>{const P=v.trim();if(!P||q)return;const xe=P.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");g("git commit",`git add -A && git commit -m "${xe}"`),L("")},[v,q,g]),ue=l.useCallback(P=>{q||g("git add",`git add -- ${fn(P.path)}`)},[q,g]),ye=l.useCallback(P=>{q||g("git reset",`git reset HEAD -- ${fn(P.path)}`)},[q,g]),fe=l.useCallback(()=>{if(!f||q)return;const P=u.find(xe=>xe.name===f);if(P!=null&&P.remote&&typeof P.remote=="string"){const xe=f.slice(P.remote.length+1);g("git checkout",`git checkout -b ${xe} ${f} || git checkout ${f}`)}else g("git checkout",`git checkout ${f}`)},[f,u,q,g]),ke=l.useCallback(()=>g("git push","git push"),[g]),Le=l.useCallback(()=>g("git pull","git pull"),[g]),ae=l.useCallback(()=>{Ne({type:"scm_history"},ee)||(ee.current=-1)},[Ne]);l.useEffect(()=>{r&&de()},[r,de]),l.useEffect(()=>{T==="history"&&a&&ae()},[T,a,ae]),l.useEffect(()=>{t.scmDirty>0&&r&&de(!1,!0)},[t.scmDirty]),l.useEffect(()=>{if(!r||!t.ready||t.status!=="open")return;const P=setInterval(()=>{document.visibilityState!=="hidden"&&de(!1,!0)},3e4);return()=>clearInterval(P)},[r,t.ready,t.status,de]),l.useEffect(()=>{const P=X.current;if(X.current=t.terminals,!r)return;t.terminals.some(pe=>{var ve;return pe.running!==!1?!1:((ve=P.find(S=>S.id===pe.id))==null?void 0:ve.running)===!0&&pe.title.startsWith("git ")})&&t.ready&&t.status==="open"&&(de(!1,!0),T==="history"&&a&&ae())},[t.terminals,r,t.ready,t.status,de,T,a,ae]);const De={staged:i("scmStaged"),unstaged:i("scmUnstaged"),untracked:i("scmUntracked"),both:i("scmStagedUnstaged")},Ae=P=>{const xe=P.split(`
|
|
324
|
+
`);return e.jsx("pre",{className:"scm-diff-pre",children:xe.map((pe,Se)=>{let ve="";return pe.startsWith("diff --git")||pe.startsWith("index ")||pe.startsWith("new file")||pe.startsWith("deleted file")||pe.startsWith("old mode")||pe.startsWith("new mode")||pe.startsWith("similarity index")||pe.startsWith("rename ")||pe.startsWith("copy ")||pe.startsWith("Binary files")||pe.startsWith("---")||pe.startsWith("+++")?ve="hdr":pe.startsWith("@@")?ve="hunk":pe.startsWith("+")?ve="add":pe.startsWith("-")&&(ve="del"),e.jsx("div",{className:`scm-diff-line ${ve}`,children:pe||" "},Se)})})};return e.jsxs("div",{className:"scm-view",children:[e.jsxs("div",{className:"scm-header",children:[e.jsxs("div",{className:"scm-title-row",children:[e.jsxs("span",{className:"scm-title",children:[e.jsx(_t,{}),i("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":T==="changes",className:T==="changes"?"active":"",onClick:()=>{D("changes"),$(null)},children:i("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":T==="history",className:T==="history"?"active":"",onClick:()=>{D("history"),$(null)},children:i("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:i("scmRefreshTip"),disabled:Z,onClick:()=>de(!0),children:e.jsx(lt,{className:Z?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:i("scmCurrentBranch"),children:[e.jsx(_t,{}),a?a.detached?i("scmDetached"):a.branch:"…",(a==null?void 0:a.upstream)&&e.jsx("span",{className:"scm-upstream",children:a.upstreamGone?i("scmUpstreamGone"):a.ahead>0||a.behind>0?i("scmAheadBehind",{ahead:a.ahead,behind:a.behind}):a.upstream})]}),e.jsxs("select",{className:"scm-select",value:f,disabled:q||u.length===0,title:i("scmSwitchBranch"),onChange:P=>y(P.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:i("scmSelectBranch")}),u.filter(P=>!P.remote).map(P=>e.jsx("option",{value:P.name,children:P.current?`* ${P.name}`:P.name},P.name)),u.some(P=>P.remote)&&e.jsx("optgroup",{label:i("scmRemoteBranches"),children:u.filter(P=>P.remote).map(P=>e.jsx("option",{value:P.name,children:P.name},P.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!f||f===(a==null?void 0:a.branch)||q,title:i("scmSwitchBranchTip",{branch:f}),onClick:fe,children:[e.jsx(_t,{}),i("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!a||a.detached||q,title:i("scmPushTip"),onClick:ke,children:[e.jsx(In,{}),i("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!a||a.detached||q,title:i("scmPullTip"),onClick:Le,children:[e.jsx(Rn,{}),i("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:v,placeholder:i("scmCommitPlaceholder"),disabled:q,onChange:P=>L(P.target.value),onKeyDown:P=>{P.key==="Enter"&&!P.nativeEvent.isComposing&&O()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!v.trim()||q,title:i("scmCommitTip"),onClick:O,children:[e.jsx(Pt,{}),i("scmCommit")]}),e.jsx("button",{type:"button",className:"btn",disabled:!v.trim()||q,title:i("scmCommitAllTip"),onClick:me,children:i("scmCommitAll")})]})]}),e.jsxs("div",{className:"scm-body",children:[T==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmHistory")}),H.length>0&&e.jsx("span",{className:"scm-files-count",children:H.length})]}),e.jsx("div",{className:"scm-history-list",children:q?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):!a||I?e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")}):H.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoHistory")}):H.map(P=>e.jsxs("button",{type:"button",className:`scm-commit ${(j==null?void 0:j.hash)===P.hash?"active":""}`,onClick:()=>le(P),title:P.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:P.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:P.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[P.shortHash," · ",P.author," · ",P.date]}),P.decorations&&e.jsx("span",{className:"scm-commit-refs",children:P.decorations})]})]},P.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmChanges")}),a&&a.files.length>0&&e.jsx("span",{className:"scm-files-count",children:a.files.length})]}),e.jsx("div",{className:"scm-files-list",children:q?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):a?a.files.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoChanges")}):a.files.map(P=>{const xe=_l(P),pe=x.get(P.path);return e.jsxs("div",{className:`scm-file ${(K==null?void 0:K.path)===P.path?"active":""}`,title:De[xe],onClick:()=>Ee(P),children:[e.jsx("span",{className:`scm-file-xy ${xe==="untracked"?"q":"x"}`,children:P.x!==" "?P.x:" "}),e.jsx("span",{className:`scm-file-xy ${xe==="untracked"?"q":"y"}`,children:P.y!==" "?P.y:" "}),e.jsx("span",{className:"scm-file-path",children:P.path}),pe&&(pe.add>0||pe.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[pe.add>0&&e.jsxs("span",{className:"add",children:["+",pe.add]}),pe.del>0&&e.jsxs("span",{className:"del",children:["-",pe.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(P.y!==" "||xe==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:i("scmStageTip",{path:P.path}),onClick:Se=>{Se.stopPropagation(),ue(P)},children:"+"}),xe==="staged"||xe==="both"?e.jsx("button",{type:"button",className:"scm-act",title:i("scmUnstageTip",{path:P.path}),onClick:Se=>{Se.stopPropagation(),ye(P)},children:"−"}):null]})]},P.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:T==="history"?j?`${j.shortHash} ${j.subject}`:i("scmCommitDetail"):K?K.path:i("scmDiff")}),(T==="history"?U:k)&&e.jsx("span",{className:"scm-diff-loading",children:i("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:T==="history"?e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{className:"scm-error",children:w}),!j&&!w&&e.jsx("div",{className:"scm-empty",children:i("scmSelectCommitHint")}),j&&U&&!w&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),j&&!U&&!w&&V?Ae(V):null]}):e.jsxs(e.Fragment,{children:[w&&e.jsx("div",{className:"scm-error",children:w}),!K&&!w&&e.jsx("div",{className:"scm-empty",children:i("scmSelectFileHint")}),K&&!C&&!w&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),K&&C&&C.untracked&&e.jsx("div",{className:"scm-empty",children:i("scmUntrackedNote")}),K&&C&&!C.untracked&&e.jsxs(e.Fragment,{children:[C.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmStaged")}),Ae(C.staged)]}),C.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmUnstaged")}),Ae(C.worktree)]}),!C.staged&&!C.worktree&&e.jsx("div",{className:"scm-empty",children:i("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(ct,{}),e.jsx("span",{children:i("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:c,children:i("scmViewTerminal")})]})]})}function Fl({entry:t,send:s}){const n=l.useRef(null),r=be();return l.useEffect(()=>{const c=n.current;if(!c)return;let i;try{i=t.module.mount(c,Ra(t.info.id,a=>s(a)))}catch(a){console.error(`[plugin:${t.info.id}] mount failed:`,a),c.textContent=r("pluginMountFailed",{name:t.info.name})}return()=>{if(typeof i=="function")try{i()}catch(a){console.error(`[plugin:${t.info.id}] cleanup failed:`,a)}c.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:n})}function $l({send:t,piConfigured:s,piAgentInstalled:n,providers:r,installResult:c,onClose:i}){const a=be(),[o,u]=l.useState(!1),[m,f]=l.useState(""),[y,x]=l.useState(""),[b,T]=l.useState(!1);l.useEffect(()=>{t({type:"list_providers"})},[t]),l.useEffect(()=>{s&&i()},[s,i]),l.useEffect(()=>{c&&u(!1)},[c]),l.useEffect(()=>{var V;!m&&r.length>0&&f(((V=r.find(J=>!J.configured))==null?void 0:V.id)??r[0].id)},[r,m]);const D=()=>{o||(u(!0),t({type:"install_pi_agent"}))},H=()=>{!y.trim()||b||(T(!0),t({type:"set_provider_api_key",provider:m.trim(),apiKey:y.trim()}),setTimeout(()=>T(!1),3e3))},N=()=>{t({type:"get_state"}),t({type:"list_providers"})},j=r.find(V=>V.id===m),Q=c!==null&&!c.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":a("close"),onClick:i,children:e.jsx(Re,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(Nt,{className:"modal-head-icon"}),e.jsx("h2",{children:a("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:a("setupDesc")}),Q?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:a("installFailed")}),e.jsx("pre",{className:"setup-detail",children:c.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:D,children:a("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:a("skip")})]})]}):n||c!=null&&c.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:c!=null&&c.ok?a("installDone"):a("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:a("provider")}),e.jsxs("select",{value:m,onChange:V=>f(V.target.value),children:[r.length===0&&e.jsx("option",{value:"",children:a("loading")}),r.map(V=>e.jsxs("option",{value:V.id,children:[V.name,"(",V.id,")",V.configured?` · ${a("configured")}`:""]},V.id))]}),(j==null?void 0:j.configured)&&e.jsx("div",{className:"field-hint",children:a("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:a("apiKey")}),e.jsx("input",{type:"password",value:y,onChange:V=>x(V.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!y.trim()||b||!m,onClick:H,children:a(b?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:N,children:[e.jsx(lt,{})," ",a("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:D,children:a(o?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:a("skip")})]})]})})}const Hl=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],Ls=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),Ol=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[Ls()]});function ds(t){return{providerId:t.providerId,name:t.name??"",api:t.api??"openai-completions",baseUrl:t.baseUrl??"",apiKey:t.apiKey??"",authHeader:t.authHeader??!1,models:(t.models.length?t.models:[Ls()]).map(s=>{var n;return{id:s.id,name:s.name??"",reasoning:s.reasoning??!1,input:(n=s.input)!=null&&n.includes("image")?"text-image":"text",contextWindow:s.contextWindow?String(s.contextWindow):"",maxTokens:s.maxTokens?String(s.maxTokens):""}})}}function Wl({send:t,providers:s,providerStatus:n,providerKeys:r,fetchModelsResult:c,cloneProviderResult:i,onClose:a}){const o=be(),[u,m]=l.useState(null),[f,y]=l.useState({}),[x,b]=l.useState({}),[T,D]=l.useState(null),[H,N]=l.useState(!1),[j,Q]=l.useState(0),[V,J]=l.useState(null),U=l.useRef(0),[W,K]=l.useState(null),[G,C]=l.useState(""),[M,k]=l.useState(null);l.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"}),t({type:"list_provider_keys"})},[t]);const _=()=>{if(!u)return;const v=u.baseUrl.trim();if(!v){J({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(H)return;N(!0),J(null);const L=j+1;Q(L),t({type:"fetch_models",reqId:L,baseUrl:v,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};l.useEffect(()=>{var v;if(!(!c||c.reqId===U.current))if(U.current=c.reqId,N(!1),c.ok&&((v=c.models)!=null&&v.length)){const L=c.models;m(d=>{if(!d)return d;const E=d.models.map(Y=>{var ge;if(!Y.id.trim())return Y;const se=L.find(Ne=>Ne.id===Y.id.trim());if(!se)return Y;const X={...Y};return!X.name&&se.name&&(X.name=se.name),!X.contextWindow&&se.contextWindow&&(X.contextWindow=String(se.contextWindow)),!X.maxTokens&&se.maxTokens&&(X.maxTokens=String(se.maxTokens)),X.input==="text"&&((ge=se.input)!=null&&ge.includes("image"))&&(X.input="text-image"),!X.reasoning&&se.reasoning&&(X.reasoning=!0),X}),h=new Set(E.map(Y=>Y.id.trim()).filter(Boolean)),A=L.filter(Y=>!h.has(Y.id)).map(Y=>{var se;return{id:Y.id,name:Y.name??"",reasoning:Y.reasoning??!1,input:(se=Y.input)!=null&&se.includes("image")?"text-image":"text",contextWindow:Y.contextWindow?String(Y.contextWindow):"",maxTokens:Y.maxTokens?String(Y.maxTokens):""}}),ee=[...E,...A];return ee.some(Y=>Y.id.trim())?{...d,models:ee.filter(Y=>Y.id.trim())}:d}),J({ok:!0,text:o("fetchModelsOk",{n:L.length})})}else J({ok:!1,text:c.error||o("fetchModelsEmpty")})},[c]);const Z=v=>{const L=(f[v.id]??"").trim();!L||T||(D(v.id),t({type:"add_provider_key",provider:v.id,apiKey:L,name:(x[v.id]??"").trim()||void 0}),setTimeout(()=>{D(null),y(d=>({...d,[v.id]:""})),b(d=>({...d,[v.id]:""})),t({type:"list_providers"}),t({type:"list_provider_keys"})},1500))},z=(v,L)=>{t({type:"activate_provider_key",provider:v,keyName:L}),t({type:"list_provider_keys"})},I=(v,L)=>{window.confirm(o("removeKeyConfirm"))&&(t({type:"remove_provider_key",provider:v,keyName:L}),t({type:"list_provider_keys"}))},R=()=>{if(!M)return;const v=M.providerId.trim();if(!v||!M.apiKey.trim())return;const L=M.models.filter(E=>E.id.trim()).map(E=>({id:E.id.trim(),name:E.name.trim()||void 0,reasoning:E.reasoning||void 0,input:E.input==="text-image"?["text","image"]:void 0,contextWindow:E.contextWindow?Number(E.contextWindow):void 0,maxTokens:E.maxTokens?Number(E.maxTokens):void 0})),d={providerId:v,name:M.name.trim()||void 0,api:M.api.trim()||void 0,baseUrl:M.baseUrl.trim()||void 0,apiKey:M.apiKey.trim()||void 0,authHeader:M.authHeader||void 0,models:L};t({type:"save_model_config",providerId:v,config:d}),k(null),a()},w=()=>{if(!u)return;const v=u.providerId.trim(),L=u.models.filter(E=>E.id.trim()).map(E=>({id:E.id.trim(),name:E.name.trim()||void 0,reasoning:E.reasoning||void 0,input:E.input==="text-image"?["text","image"]:void 0,contextWindow:E.contextWindow?Number(E.contextWindow):void 0,maxTokens:E.maxTokens?Number(E.maxTokens):void 0})),d={providerId:v,name:u.name.trim()||void 0,api:u.api.trim()||void 0,baseUrl:u.baseUrl.trim()||void 0,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader||void 0,models:L};t({type:"save_model_config",providerId:v,config:d}),a()};l.useEffect(()=>{if(i&&i.ok){const v=i.configs;if(v&&v.length>1){K(v.map(L=>ds({...L,apiKey:""}))),C("");return}if(i.config){k(ds({...i.config,apiKey:""}));return}}},[i]);const $=v=>{window.confirm(o("clearKeyConfirm",{id:v}))&&t({type:"clear_provider_api_key",provider:v})},q=v=>{window.confirm(o("deleteProviderConfirm",{id:v.providerId,n:v.models.length}))&&t({type:"delete_model_config",providerId:v.providerId})},ie=(v,L)=>{u&&m({...u,models:u.models.map((d,E)=>E===v?{...d,...L}:d)})};return e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"modal model-modal",onClick:v=>v.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:a,children:e.jsx(Re,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:M?o("addKey"):W?o("batchCreateProviders",{n:W.length}):o(u?"editProvider":"manageModelsTitle")})}),M?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:o("secondKeyTitle",{api:M.api,baseUrl:M.baseUrl||o("noBaseUrlShort"),n:M.models.length})}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[o("providerNameLabel")," ",e.jsx("em",{children:o("providerNameHint")})]}),e.jsx("input",{type:"text",value:M.providerId,onChange:v=>k({...M,providerId:v.target.value}),placeholder:"opencode-2"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKeyLabel")}),e.jsx("input",{type:"password",value:M.apiKey,onChange:v=>k({...M,apiKey:v.target.value}),placeholder:o("secondKeyPlaceholder")})]})]}),e.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:8},children:[M.models.slice(0,5).map(v=>v.id).join(", "),M.models.length>5?` … +${M.models.length-5}`:""]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>k(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn",onClick:()=>{const v=M;k(null),m(v)},children:o("advancedEdit")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!M.providerId.trim()||!M.apiKey.trim(),onClick:R,children:o("save")})]})]}):W?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:o("batchDesc",{apis:W.map(v=>v.api).join("、"),n:W.length})}),e.jsxs("label",{className:"field",style:{marginBottom:16},children:[e.jsx("span",{className:"field-label",children:o("batchKeyLabel",{n:W.length})}),e.jsx("input",{type:"password",value:G,onChange:v=>C(v.target.value),placeholder:o("secondKeyPlaceholder")})]}),e.jsx("div",{className:"provider-list",style:{marginBottom:16},children:W.map((v,L)=>e.jsxs("div",{className:"provider-row",style:{flexDirection:"column",alignItems:"stretch",gap:6},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[e.jsx("strong",{children:v.providerId}),e.jsx("span",{style:{opacity:.7},children:v.api})]}),e.jsxs("div",{className:"provider-sub",style:{fontSize:12,opacity:.7},children:[v.baseUrl||o("noBaseUrlShort")," · ",o("modelsCountShort",{n:v.models.length}),v.models.slice(0,3).map(d=>d.id).join(", "),v.models.length>3?` … +${v.models.length-3}`:""]}),e.jsx("input",{type:"text",value:v.providerId,onChange:d=>K(E=>E.map((h,A)=>A===L?{...h,providerId:d.target.value}:h)),placeholder:o("providerIdPlaceholder"),style:{fontSize:12}}),e.jsx("input",{type:"text",value:v.baseUrl,onChange:d=>K(E=>E.map((h,A)=>A===L?{...h,baseUrl:d.target.value}:h)),placeholder:o("baseUrlExamplePh"),style:{fontSize:12}})]},L))})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>K(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!G.trim(),onClick:()=>{for(const v of W){const L=v.providerId.trim();if(!L)continue;const d=v.models.filter(h=>h.id.trim()).map(h=>({id:h.id.trim(),name:h.name.trim()||void 0,reasoning:h.reasoning||void 0,input:h.input==="text-image"?["text","image"]:void 0,contextWindow:h.contextWindow?Number(h.contextWindow):void 0,maxTokens:h.maxTokens?Number(h.maxTokens):void 0})),E={providerId:L,name:v.name.trim()||void 0,api:v.api.trim()||void 0,baseUrl:v.baseUrl.trim()||void 0,apiKey:G.trim()||void 0,authHeader:v.authHeader||void 0,models:d};t({type:"save_model_config",providerId:L,config:E})}K(null),a()},children:o("saveAllBatch",{n:W.length})})]})]}):u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[o("providerId")," ",e.jsx("em",{children:o("providerIdHint")})]}),e.jsx("input",{type:"text",value:u.providerId,disabled:s.some(v=>v.providerId===u.providerId),onChange:v=>m({...u,providerId:v.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("displayName")}),e.jsx("input",{type:"text",value:u.name,onChange:v=>m({...u,name:v.target.value}),placeholder:o("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiType")}),e.jsx("select",{value:u.api,onChange:v=>m({...u,api:v.target.value}),children:Hl.map(v=>e.jsx("option",{value:v,children:v},v))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:o("baseUrlHint")})]}),e.jsx("input",{type:"text",value:u.baseUrl,onChange:v=>m({...u,baseUrl:v.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKey")}),e.jsx("input",{type:"password",value:u.apiKey,onChange:v=>m({...u,apiKey:v.target.value}),placeholder:o("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:v=>m({...u,authHeader:v.target.checked})}),e.jsx("span",{children:o("authHeader")})]})]}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:o("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[V&&e.jsx("span",{className:`fetch-msg ${V.ok?"ok":"err"}`,title:V.text,children:V.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:H||!u.baseUrl.trim(),title:o("fetchModelsHint"),onClick:_,children:[e.jsx(Vt,{})," ",o(H?"fetchingModels":"fetchModels")]})]})]}),u.models.map((v,L)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:v.id,onChange:d=>ie(L,{id:d.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:v.name,onChange:d=>ie(L,{name:d.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:v.input,onChange:d=>ie(L,{input:d.target.value}),children:[e.jsx("option",{value:"text",children:o("text")}),e.jsx("option",{value:"text-image",children:o("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:v.reasoning,onChange:d=>ie(L,{reasoning:d.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:v.contextWindow,onChange:d=>ie(L,{contextWindow:d.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:v.maxTokens,onChange:d=>ie(L,{maxTokens:d.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>m({...u,models:u.models.filter((d,E)=>E!==L)}),children:e.jsx(He,{})})]},L)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>m({...u,models:[...u.models,Ls()]}),children:[e.jsx(Ke,{})," ",o("addModel")]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>m(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(v=>v.id.trim()),onClick:w,children:o("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-fixed-hint",children:e.jsxs("div",{className:"form-section-title",children:[o("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:o("hintKeyOnly")})]})}),e.jsxs("div",{className:"model-modal-body",children:[e.jsxs("div",{className:"provider-list",children:[n.length===0&&e.jsx("div",{className:"dd-loading",children:o("loading")}),n.map(v=>{const L=r[v.id]??[];return e.jsxs("div",{className:"provider-row provider-key-row",children:[e.jsxs("div",{className:"provider-key-head",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:v.name}),e.jsxs("span",{className:"provider-sub",children:[v.id,v.configured&&e.jsx("span",{className:"auth-badge",children:o("configuredBadge")}),v.source&&!v.configured&&e.jsx("span",{className:"auth-badge dim",children:v.source})]})]}),v.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>$(v.id),children:[e.jsx(He,{})," ",o("clearKey")]})]}),e.jsxs("div",{className:"provider-keys",children:[L.length===0&&e.jsx("div",{className:"provider-key-empty",children:o("noKeyYet")}),L.map(d=>e.jsxs("div",{className:`provider-key-item ${d.active?"active":""}`,children:[e.jsx("span",{className:"provider-key-dot",children:d.active?"●":"○"}),e.jsx("span",{className:"provider-key-label",children:d.name}),!d.active&&e.jsx("button",{type:"button",className:"iconbtn",title:o("activateKey"),onClick:()=>z(v.id,d.name),children:e.jsx(Pt,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeKey"),onClick:()=>I(v.id,d.name),children:e.jsx(He,{})})]},d.name)),e.jsxs("div",{className:"provider-add-key",children:[e.jsx("input",{type:"text",className:"key-input key-input-name",placeholder:o("keyNamePh"),value:x[v.id]??"",onChange:d=>b(E=>({...E,[v.id]:d.target.value}))}),e.jsx("input",{type:"password",className:"key-input key-input-value",placeholder:o("addKeyPlaceholder"),value:f[v.id]??"",onChange:d=>y(E=>({...E,[v.id]:d.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(f[v.id]??"").trim()||T===v.id,onClick:()=>Z(v),children:[e.jsx(Ke,{})," ",T===v.id?o("savingKey"):o("addKey")]})]})]})]},v.id)})]}),e.jsx("div",{className:"form-section-title",children:o("customProviders")}),e.jsx("p",{className:"modal-desc",children:o("customDesc")}),s.length===0&&e.jsx("div",{className:"dd-loading",children:o("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:s.map(v=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:v.providerId}),e.jsxs("span",{className:"provider-sub",children:[v.api??"—",v.baseUrl?` · ${v.baseUrl}`:"",v.models.length>0&&` · ${o("modelsCount",{n:v.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:o("edit"),onClick:()=>m(ds(v)),children:e.jsx(qt,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>q(v),children:e.jsx(He,{})})]})]},v.providerId))})]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>m(Ol()),children:[e.jsx(Ke,{})," ",o("addProvider")]})})]})]})})}function Ul({plugin:t,send:s}){const n=be(),r=t.settingsSchema??[],[c,i]=l.useState(()=>({...t.settingsValues})),[a,o]=l.useState(!1);if(r.length===0)return null;const u=(x,b)=>i(T=>({...T,[x]:b})),m=r.some(x=>{var b;return c[x.key]!==((b=t.settingsValues)==null?void 0:b[x.key])}),f=()=>{o(!0),s({type:"plugin_settings",pluginId:t.id,values:c}),setTimeout(()=>o(!1),800)},y=()=>i({...t.settingsValues});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:r.map(x=>e.jsxs("label",{className:"plugin-settings-field",title:x.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:x.label}),x.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!c[x.key],onChange:b=>u(x.key,b.target.checked)}):x.type==="select"?e.jsx("select",{value:String(c[x.key]??""),onChange:b=>u(x.key,b.target.value),children:(x.options??[]).map(b=>e.jsx("option",{value:b,children:b},b))}):e.jsx("input",{type:x.type==="password"?"password":x.type==="number"?"number":"text",value:String(c[x.key]??""),min:x.min,max:x.max,onChange:b=>u(x.key,x.type==="number"?Number(b.target.value):b.target.value)})]},x.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!m||a,onClick:f,children:n(a?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:y,children:n("pluginSettingsReset")})]})]})}const pi="pi-web-ui:wide-chat",zt={wide:!1};function mi(t){if(!t||typeof t!="object")return{...zt};const s=t;return{wide:typeof s.wide=="boolean"?s.wide:zt.wide}}function Kl(){try{const t=localStorage.getItem(pi);return t?mi(JSON.parse(t)):{...zt}}catch{return{...zt}}}function ql(t){const s=mi(t);try{localStorage.setItem(pi,JSON.stringify(s))}catch{}Ft=s;for(const n of Ss)n()}let Ft=null;const Ss=new Set;function zl(t){return Ss.add(t),()=>{Ss.delete(t)}}function Vl(){return Ft||(Ft=Kl()),Ft.wide}function hi(){return l.useSyncExternalStore(zl,Vl)}function Gl(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Ve({text:t}){const s=l.useRef(null),[n,r]=l.useState(!1),c=()=>{var a;const i=(a=s.current)==null?void 0:a.getBoundingClientRect();i&&r(window.innerWidth-i.right<340)};return e.jsxs("span",{ref:s,className:`set-tip${n?" flip":""}`,tabIndex:0,"aria-label":t,onMouseEnter:c,onFocus:c,children:["?",e.jsx("span",{className:"set-tip-bubble",role:"tooltip",children:t})]})}function Fe({title:t,subtitle:s,tip:n,enabled:r,onToggle:c,action:i}){const a=be();return e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[t,n&&e.jsx(Ve,{text:n})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),i,e.jsx("button",{type:"button",className:`set-switch ${r?"on":""}`,role:"switch","aria-checked":r,title:a(r?"settingsEnabled":"settingsDisabled"),onClick:c,children:e.jsx("span",{className:"set-switch-knob"})})]})}function Ql({chat:t,send:s,terminal:n,onSwitchToTerminal:r,onClose:c}){var ut,pt,mt,ht,gt,ft;const i=be(),a=t.settings,o=t.engine==="dsh",[u,m]=l.useState("prompt"),f=l.useRef(null);l.useEffect(()=>{var p;(p=f.current)==null||p.scrollTo({top:0})},[u]),l.useEffect(()=>{u==="plugins"&&t.engine==="dsh"&&s({type:"dsh_patches_list"})},[u,t.engine,s]);const[y,x]=l.useState(""),[b,T]=l.useState("append"),D=l.useRef(!1),[H,N]=l.useState(""),[j,Q]=l.useState("append"),V=l.useRef(!1),[J,U]=l.useState(""),W=l.useRef(!1),[K,G]=l.useState(""),[C,M]=l.useState(null),[k,_]=l.useState(null),[Z,z]=l.useState(!1),I=hi(),[R,w]=l.useState(()=>ci()),[$,q]=l.useState(()=>{try{return Tt().length}catch{return 0}}),[ie,v]=l.useState(!1),L=()=>{try{q(Tt().length)}catch{q(0)}};l.useEffect(()=>{u==="prompt-history"&&L()},[u]),l.useEffect(()=>{if(!ie)return;const p=window.setTimeout(()=>v(!1),3e3);return()=>window.clearTimeout(p)},[ie]);const[d,E]=l.useState(null),[h,A]=l.useState(null),[ee,Y]=l.useState(""),[se,X]=l.useState(""),[ge,Ne]=l.useState(""),[de,Ee]=l.useState(""),[le,g]=l.useState(""),[O,me]=l.useState(!1);l.useEffect(()=>{a&&(T(a.promptMode),!D.current&&(x(b==="append"||a.customSystemPrompt?a.customSystemPrompt:a.defaultSystemPrompt||""),Q(a.visionBridgePromptMode),!V.current&&(N(j==="append"||a.visionBridgePrompt?a.visionBridgePrompt:a.visionBridgeDefaultPrompt||""),W.current||U(a.reviewPrompt))))},[a,b,j]);const[ue,ye]=l.useState(String((a==null?void 0:a.terminalBashIdleMs)??15e3));if(l.useEffect(()=>{ye(String((a==null?void 0:a.terminalBashIdleMs)??15e3))},[a==null?void 0:a.terminalBashIdleMs]),!a)return null;const fe=[{id:"prompt",icon:e.jsx(Tn,{}),label:i("settingsSystemPrompt")},{id:"prompt-history",icon:e.jsx(Us,{}),label:i("settingsPromptHistory"),count:$},{id:"terminal",icon:e.jsx(ct,{}),label:i("settingsTerminalTools")},{id:"display",icon:e.jsx(dt,{}),label:i("settingsMessageDisplay")},{id:"markers",icon:e.jsx(Os,{}),label:i("settingsMarkers"),count:((ut=a.markers)==null?void 0:ut.length)??0},{id:"skills",icon:e.jsx(Nt,{}),label:i("settingsSkills"),count:a.skills.length},{id:"extensions",icon:e.jsx(Xt,{}),label:i("settingsExtensions"),count:a.extensions.length},{id:"plugins",icon:e.jsx(Zt,{}),label:i("settingsUiPlugins"),count:t.plugins.length},{id:"review",icon:e.jsx(At,{}),label:i("settingsReview"),count:a.reviewSkills.length},...o?[]:[{id:"vision",icon:e.jsx(hs,{}),label:i("settingsVisionBridge")}],{id:"presets",icon:e.jsx(Oi,{}),label:i("settingsPresets"),count:a.presets.length},...o?[]:[{id:"subagent-templates",icon:e.jsx($s,{}),label:i("settingsSubagentTemplates"),count:a.subagentTemplates.length}]],ke=new Set(a.disabledSkills),Le=new Set(a.disabledExtensions),ae=p=>s({type:"set_settings",...p}),De=p=>{const re=new Set(ke);re.has(p.name)?re.delete(p.name):re.add(p.name),ae({disabledSkills:[...re]})},Ae=new Set(a.disabledPlugins??[]),qe=new Set(t.plugins.map(p=>p.id)),ze=p=>{const re=new Set(Ae);re.has(p.id)?re.delete(p.id):re.add(p.id),ae({disabledPlugins:[...re]})},P=p=>{const re=new Set(Le);re.has(p.id)?re.delete(p.id):re.add(p.id),ae({disabledExtensions:[...re]})},xe=a.markersEnabled??!0,pe=new Set(a.disabledMarkers??[]),Se=p=>{const re=new Set(pe),Pe=p==="conv"||p==="rename"||p==="title"?["conv","rename","title"]:[p],_e=!Pe.some(Be=>re.has(Be));for(const Be of Pe)_e?re.add(Be):re.delete(Be);ae({disabledMarkers:[...re]})},ve=(p,re)=>{var xt,yt;const Pe={name:p,command:re,cwd:"${pwd}"};let _e;const Be=t.terminals.find(It=>It.title===p);Be?(n.restart(Be.id),s({type:"run_command",terminalId:Be.id,conversationId:Be.conversationId,command:Pe,cols:80,rows:24}),_e=Be.id):(_e=Qe(),n.create({id:_e,conversationId:t.activeConversationId||((xt=t.state)==null?void 0:xt.conversationId)||"",title:p,cwd:((yt=t.state)==null?void 0:yt.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Pe})),n.select(_e),r(),c()},S=p=>{E(null),ve(`${i("uninstallTitle")} ${p}`,`pi remove npm:${p}`)},B=p=>{A(null),ve(`${i("uninstallTitle")} ${p}`,`pi-web-ui uninstall ${p}`)},oe=(p,re)=>{ve(`${i("pluginUpdate")} ${p}`,`pi-web-ui install ${re} --name ${p} --force`)},ce=p=>{ve(`${i("pluginInstall")} ${p.id}`,`pi-web-ui install ${p.source} --name ${p.id}`)},je=p=>{s({type:"plugin_catalog_remove",id:p})},we=()=>{const p=ee.trim();p&&(s({type:"plugin_catalog_add",entry:{source:p,...se.trim()?{id:se.trim()}:{},...ge.trim()?{name:ge.trim()}:{},...de.trim()?{description:de.trim()}:{},...le.trim()?{icon:le.trim()}:{}}}),Y(""),X(""),Ne(""),Ee(""),g(""),me(!1))},Ie=p=>{const re=new Set(a.reviewSkills.filter(Pe=>!Pe.enabled).map(Pe=>Pe.name));re.has(p.name)?re.delete(p.name):re.add(p.name),ae({reviewDisabledSkills:[...re]})},Oe=()=>{const p=b==="replace"&&a.defaultSystemPrompt&&y===a.defaultSystemPrompt?"":y;ae({promptMode:b,customSystemPrompt:p})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal settings-modal",onClick:p=>p.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:c,children:e.jsx(Re,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(Wt,{className:"modal-head-icon"}),e.jsx("h2",{children:i("settingsTitle")}),e.jsx(Ve,{text:i("settingsDesc")})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-rail","aria-label":i("settingsTitle"),children:fe.map(p=>e.jsxs("button",{type:"button",className:`settings-tab${u===p.id?" active":""}`,"aria-current":u===p.id?"true":void 0,title:p.label,onClick:()=>m(p.id),children:[e.jsx("span",{className:"settings-tab-icon",children:p.icon}),e.jsx("span",{className:"settings-tab-label",children:p.label}),p.count!==void 0&&e.jsx("span",{className:"set-count",children:p.count})]},p.id))}),e.jsxs("div",{className:"modal-body",ref:f,children:[u==="prompt"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(At,{className:"set-section-icon"}),i("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:b,onChange:p=>{const re=p.target.value;T(re),ae({promptMode:re})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]}),e.jsx(Ve,{text:i(b==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:i("promptPlaceholder"),value:y,onFocus:()=>D.current=!0,onBlur:()=>{D.current=!1,Oe()},onChange:p=>x(p.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":Z,onClick:()=>z(p=>!p),children:[i("settingsViewPrompt")," ",Z?"▴":"▾"]}),Z&&e.jsxs("div",{className:"set-prompt-view",children:[e.jsxs("div",{className:"set-prompt-view-head",children:[e.jsx("span",{children:i("settingsViewPromptHint")}),e.jsx(Ps,{text:a.effectiveSystemPrompt})]}),a.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:a.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:i("settingsViewPromptEmpty")})]})]}),u==="prompt-history"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Us,{className:"set-section-icon"}),i("settingsPromptHistory"),e.jsx(Ve,{text:i("settingsPromptHistoryDesc")}),e.jsx("span",{className:"set-count",children:i("promptHistoryCount",{n:String($)})})]}),$===0?e.jsx("p",{className:"set-empty",children:i("promptHistoryEmpty")}):e.jsx("p",{className:"set-hint",children:i("promptHistoryCount",{n:String($)})}),e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"ph-max",children:i("promptHistoryMax")}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("input",{id:"ph-max",className:"set-input",type:"number",min:1,max:500,step:1,value:String(R.maxEntries),onChange:p=>{const re=Math.floor(Number(p.target.value)||0),Pe={...R,maxEntries:re};w(Pe)},onBlur:()=>{const p={...R};(!Number.isFinite(p.maxEntries)||p.maxEntries<1)&&(p.maxEntries=1),p.maxEntries>500&&(p.maxEntries=500),p.maxEntries=Math.floor(p.maxEntries),w(p),cs(p),L()}}),e.jsx(Ve,{text:i("promptHistoryMaxHint")})]})]}),e.jsx(Fe,{title:i("promptHistoryCharLimit"),tip:i("promptHistoryCharLimitHint"),enabled:R.charLimitEnabled,onToggle:()=>{const p={...R,charLimitEnabled:!R.charLimitEnabled};w(p),cs(p),L()}}),R.charLimitEnabled&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"ph-char-limit",children:i("promptHistoryCharLimit")}),e.jsx("input",{id:"ph-char-limit",className:"set-input",type:"number",min:100,max:2e4,step:100,placeholder:i("promptHistoryCharLimitPlaceholder"),value:String(R.charLimit),onChange:p=>{const re=Math.floor(Number(p.target.value)||0);w({...R,charLimit:re})},onBlur:()=>{let p=Math.floor(Number(R.charLimit)||0);(!Number.isFinite(p)||p<100)&&(p=100),p>2e4&&(p=2e4);const re={...R,charLimit:p};w(re),cs(re),L()}})]}),e.jsxs("div",{className:"set-field",style:{marginTop:12},children:[e.jsxs("button",{type:"button",className:`set-uninstall${ie?" confirm":""}`,disabled:$===0,title:i($===0?"promptHistoryEmpty":"promptHistoryClear"),onClick:()=>{if(!ie){v(!0);return}jl(),v(!1),L()},children:[e.jsx(He,{})," ",i(ie?"promptHistoryClearConfirm":"promptHistoryClear")]}),$>0&&e.jsx("span",{className:"set-hint",style:{marginLeft:8},children:i("promptHistoryCount",{n:String($)})})]}),e.jsxs("p",{className:"set-hint",children:[e.jsx(ra,{style:{verticalAlign:"-2px",marginRight:4}}),i("settingsPromptHistoryDesc")]})]}),u==="terminal"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ct,{className:"set-section-icon"}),i("settingsTerminalTools")]}),e.jsx(Fe,{title:i("terminalToolsEnabled"),tip:i("settingsTerminalToolsDesc"),enabled:a.terminalToolsEnabled,onToggle:()=>ae({terminalToolsEnabled:!a.terminalToolsEnabled})}),!a.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:i("terminalToolsOffHint")}),e.jsx(Fe,{title:i("terminalBashTakeover"),tip:i("terminalBashTakeoverDesc"),enabled:a.terminalBash,onToggle:()=>ae({terminalBash:!a.terminalBash})}),a.terminalBash&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:i("terminalBashIdleMs")}),e.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:ue,onChange:p=>ye(p.target.value),onBlur:()=>{const p=Math.max(0,Math.floor(Number(ue)||0));ye(String(p)),p!==a.terminalBashIdleMs&&ae({terminalBashIdleMs:p})}})]})]}),u==="display"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(dt,{className:"set-section-icon"}),i("settingsMessageDisplay")]}),e.jsx(Fe,{title:i("thinkingWrap"),tip:i("thinkingWrapDesc"),enabled:a.thinkingWrap??!0,onToggle:()=>ae({thinkingWrap:!(a.thinkingWrap??!0)})}),e.jsx(Fe,{title:i("toolsWrap"),tip:i("toolsWrapDesc"),enabled:a.toolsWrap??!0,onToggle:()=>ae({toolsWrap:!(a.toolsWrap??!0)})}),e.jsx("hr",{className:"set-sep"}),e.jsx(Fe,{title:i("wideChat"),tip:i("wideChatDesc"),enabled:I,onToggle:()=>ql({wide:!I})})]}),u==="markers"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Os,{className:"set-section-icon"}),i("settingsMarkers"),e.jsx(Ve,{text:i("settingsMarkersDesc")}),e.jsx("span",{className:"set-count",children:((pt=a.markers)==null?void 0:pt.length)??0})]}),e.jsx(Fe,{title:i("markersEnabled"),tip:i("markersEnabledDesc"),enabled:xe,onToggle:()=>ae({markersEnabled:!xe})}),!xe&&e.jsx("p",{className:"set-hint",children:i("markersOffHint")}),xe&&(((mt=a.markers)==null?void 0:mt.length)??0)===0&&e.jsxs("p",{className:"set-empty",children:[i("loading"),"..."]}),xe&&a.markers&&a.markers.length>0&&e.jsx("div",{className:"set-list",children:a.markers.map(p=>e.jsx(Fe,{title:p.name==="todo"?i("markerGroupTodo"):p.name==="svc"?i("markerGroupSvc"):p.name==="notify"?i("markerGroupNotify"):p.name==="conv"||p.name==="rename"||p.name==="title"?i("markerGroupRename"):p.name,subtitle:(p.guidance[0]??"").slice(0,120),tip:p.guidance.join(`
|
|
325
|
+
`),enabled:p.enabled,onToggle:()=>Se(p.name)},p.name))}),xe&&e.jsx("p",{className:"set-hint",children:i("markerRenameTip")})]}),u==="skills"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Nt,{className:"set-section-icon"}),i("settingsSkills"),e.jsx("span",{className:"set-count",children:a.skills.length})]}),a.skills.length===0?e.jsx("p",{className:"set-empty",children:i(o?"dshSkillsNote":"noSkills")}):e.jsx("div",{className:"set-list",children:a.skills.map(p=>e.jsx(Fe,{title:p.name,subtitle:p.description,enabled:p.enabled,onToggle:()=>De(p)},p.name))})]}),u==="extensions"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Xt,{className:"set-section-icon"}),i("settingsExtensions"),e.jsx("span",{className:"set-count",children:a.extensions.length})]}),a.extensions.length===0?e.jsx("p",{className:"set-empty",children:i(o?"dshExtensionsNote":"noExtensions")}):e.jsx("div",{className:"set-list",children:a.extensions.map(p=>{const re=p.id.startsWith("npm:")?p.id.slice(4):null;return e.jsx(Fe,{title:p.name,subtitle:p.path,enabled:p.enabled,onToggle:()=>P(p),action:re?d===p.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>S(re),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("uninstallHint"),onClick:()=>E(p.id),children:[e.jsx(He,{}),i("uninstallExt")]}):void 0},p.id)})})]}),u==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Xt,{className:"set-section-icon"}),i("pluginMarket"),e.jsx("span",{className:"set-count",children:t.pluginCatalog.length}),e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginCatalogAddHint"),onClick:()=>me(p=>!p),children:[e.jsx(Ke,{}),i("pluginCatalogAdd")]})]}),O&&e.jsxs("div",{className:"set-catalog-add",children:[e.jsx("input",{className:"set-input",placeholder:i("pluginCatalogSource"),value:ee,onChange:p=>Y(p.target.value)}),e.jsx("input",{className:"set-input",placeholder:i("pluginCatalogId"),value:se,onChange:p=>X(p.target.value)}),e.jsx("input",{className:"set-input",placeholder:i("pluginCatalogName"),value:ge,onChange:p=>Ne(p.target.value)}),e.jsx("input",{className:"set-input",placeholder:i("pluginCatalogIcon"),value:le,onChange:p=>g(p.target.value)}),e.jsx("textarea",{className:"set-input",rows:2,placeholder:i("pluginCatalogDesc"),value:de,onChange:p=>Ee(p.target.value)}),e.jsxs("div",{className:"set-catalog-add-actions",children:[e.jsx("button",{type:"button",className:"set-uninstall confirm",disabled:!ee.trim(),onClick:we,children:i("pluginCatalogAddSubmit")}),e.jsx("button",{type:"button",className:"set-uninstall",onClick:()=>me(!1),children:i("cancel")})]})]}),t.pluginCatalog.length===0?e.jsx("p",{className:"set-empty",children:i("noPluginCatalog")}):e.jsx("div",{className:"set-list",children:t.pluginCatalog.map(p=>{const re=qe.has(p.id);return e.jsxs("div",{className:"set-catalog-row",children:[e.jsxs("div",{className:"set-catalog-main",children:[e.jsxs("div",{className:"set-catalog-title",children:[e.jsxs("span",{children:[p.icon?`${p.icon} `:"",p.name]}),re&&e.jsx("span",{className:"set-catalog-installed",children:i("pluginInstalled")}),!p.builtin&&e.jsx("span",{className:"set-catalog-custom",children:i("pluginCatalogCustom")})]}),p.description&&e.jsx("div",{className:"set-catalog-desc",children:p.description}),e.jsx("div",{className:"set-catalog-source",children:p.source})]}),e.jsxs("div",{className:"set-row-actions",children:[re?e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>oe(p.id,p.source),children:[e.jsx(lt,{}),i("pluginUpdate")]}),h===p.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>B(p.id),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>A(p.id),children:[e.jsx(He,{}),i("uninstallExt")]})]}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginInstallHint"),onClick:()=>ce(p),children:[e.jsx(Vt,{}),i("pluginInstall")]}),!p.builtin&&e.jsx("button",{type:"button",className:"set-uninstall",title:i("pluginCatalogRemoveHint"),onClick:()=>je(p.id),children:e.jsx(Re,{})})]})]},p.id)})})]}),u==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Zt,{className:"set-section-icon"}),i("settingsUiPlugins"),e.jsx("span",{className:"set-count",children:t.plugins.length})]}),t.plugins.length===0?e.jsx("p",{className:"set-empty",children:i("noUiPlugins")}):e.jsx("div",{className:"set-list",children:t.plugins.map(p=>{var re;return e.jsxs(e.Fragment,{children:[e.jsx(Fe,{title:`${p.icon?`${p.icon} `:""}${p.name}`,subtitle:(p.error?`${p.id} · ${p.error}`:p.source?`${p.id} · ${p.source}`:`${p.id} · ${i("uiPluginNoSource")}`)+((re=p.permissions)!=null&&re.length?` · ${i("uiPluginPerms")}: ${p.permissions.join(", ")}`:""),enabled:!Ae.has(p.id)&&!p.error,onToggle:()=>!p.error&&ze(p),action:e.jsxs("div",{className:"set-row-actions",children:[p.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>oe(p.id,p.source),children:[e.jsx(lt,{}),i("pluginUpdate")]}),h===p.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>B(p.id),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>A(p.id),children:[e.jsx(He,{}),i("uninstallExt")]})]})},p.id),p.settingsSchema&&p.settingsSchema.length>0&&e.jsx(Ul,{plugin:p,send:s})]})})})]}),u==="plugins"&&t.engine==="dsh"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Zt,{className:"set-section-icon"}),i("dshPatches"),e.jsx(Ve,{text:i("dshPatchesDesc")}),e.jsx("span",{className:"set-count",children:((ht=t.dshPatches)==null?void 0:ht.files.length)??0}),e.jsxs("button",{type:"button",className:"set-uninstall",title:i("dshPatchesRescanHint"),onClick:()=>s({type:"dsh_patches_rescan"}),children:[e.jsx(lt,{}),i("dshPatchesRescan")]})]}),(((gt=t.dshPatches)==null?void 0:gt.files.length)??0)===0?e.jsx("p",{className:"set-empty",children:i("dshPatchesEmpty")}):e.jsx("div",{className:"set-list",children:t.dshPatches.files.map(p=>e.jsx("div",{className:"set-row",children:e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:p.name}),e.jsxs("div",{className:"set-row-desc",children:[Gl(p.size)," · ",new Date(p.mtimeMs).toLocaleString()]})]})},p.name))}),e.jsxs("p",{className:"set-hint",children:[i("dshPatchesPath")," ",((ft=t.dshPatches)==null?void 0:ft.patchDir)??""]})]}),u==="review"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(At,{className:"set-section-icon"}),i("settingsReview"),e.jsx(Ve,{text:i("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:a.reviewSkills.length})]}),o&&e.jsx("p",{className:"set-hint",children:i("dshReviewPromptNote")}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:i("reviewPromptPlaceholder"),value:J,onFocus:()=>W.current=!0,onBlur:()=>{W.current=!1,ae({reviewPrompt:J})},onChange:p=>U(p.target.value)}),e.jsx("div",{className:"set-field-label",children:i("settingsReviewSkills")}),a.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:a.reviewSkills.map(p=>e.jsx(Fe,{title:p.name,subtitle:p.description,enabled:p.enabled,onToggle:()=>Ie(p)},`review-${p.name}`))})]}),u==="vision"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(hs,{className:"set-section-icon"}),i("settingsVisionBridge")]}),e.jsx(Fe,{title:i("visionBridgeEnabled"),tip:i("settingsVisionBridgeDesc"),enabled:a.visionBridgeEnabled,onToggle:()=>ae({visionBridgeEnabled:!a.visionBridgeEnabled})}),!a.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:i("visionBridgeOffHint")}),a.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:a.visionBridgeModel??"",onChange:p=>ae({visionBridgeModel:p.target.value||null}),children:[e.jsx("option",{value:"",children:i("visionBridgeAuto")}),a.visionModels.map(p=>e.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.id}`))]})]}),a.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:j,onChange:p=>{const re=p.target.value;Q(re),ae({visionBridgePromptMode:re})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]})]}),a.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:i("visionBridgePromptPlaceholder"),value:H,onFocus:()=>V.current=!0,onBlur:()=>{V.current=!1;const p=j==="replace"&&a.visionBridgeDefaultPrompt&&H===a.visionBridgeDefaultPrompt?"":H;ae({visionBridgePromptMode:j,visionBridgePrompt:p})},onChange:p=>N(p.target.value)}),a.visionBridgeEnabled&&(a.visionModels.length===0?e.jsx("p",{className:"set-hint",children:i("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:i("visionBridgeCurrent",{model:a.visionBridgeModel??i("visionBridgeAuto")})}))]}),u==="presets"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Wt,{className:"set-section-icon"}),i("settingsPresets"),e.jsx("span",{className:"set-count",children:a.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:i("presetNamePlaceholder"),value:K,onChange:p=>G(p.target.value),onKeyDown:p=>{p.key==="Enter"&&K.trim()&&(s({type:"save_preset",name:K.trim()}),G(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!K.trim(),onClick:()=>{s({type:"save_preset",name:K.trim()}),G("")},children:[e.jsx(Ke,{})," ",i("saveAsPreset")]})]}),a.presets.length===0?e.jsx("p",{className:"set-empty",children:i("noPresets")}):e.jsx("div",{className:"set-list",children:a.presets.map(p=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:p.name}),e.jsxs("div",{className:"set-row-desc",children:[p.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend"),p.disabledSkills.length>0&&` · ${i("settingsSkills")} ${p.disabledSkills.length}`,p.disabledExtensions.length>0&&` · ${i("settingsExtensions")} ${p.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:p.name}),children:i("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("deletePreset"),onClick:()=>s({type:"delete_preset",name:p.name}),children:e.jsx(He,{})})]})]},p.name))})]}),u==="subagent-templates"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx($s,{className:"set-section-icon"}),i("settingsSubagentTemplates"),e.jsx(Ve,{text:i("settingsSubagentTemplatesDesc")}),e.jsx("span",{className:"set-count",children:a.subagentTemplates.length}),e.jsxs("button",{type:"button",className:"set-save-btn",title:i("subagentTemplateNew"),onClick:()=>M({name:"",description:"",promptMode:"replace",systemPrompt:"",enabledSkills:[],enabledExtensions:[],model:"",enabled:!0}),children:[e.jsx(Ke,{})," ",i("subagentTemplateNew")]})]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("subagentDefaultModelLabel")}),e.jsxs("select",{className:"set-select",value:a.subagentDefaultModel??"",onChange:p=>ae({subagentDefaultModel:p.target.value||null}),children:[e.jsx("option",{value:"",children:i("subagentFollowMain")}),a.subagentModels.map(p=>e.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.id}`))]})]}),a.subagentModels.length===0?e.jsx("p",{className:"set-hint",children:i("subagentNoModels")}):e.jsx("p",{className:"set-hint",children:i("subagentDefaultModelHint")}),C&&e.jsxs("div",{className:"tpl-editor",children:[e.jsxs("div",{className:"tpl-fields",children:[e.jsx("input",{className:"set-input",placeholder:i("tplNamePlaceholder"),value:C.name,onChange:p=>M({...C,name:p.target.value})}),e.jsx("input",{className:"set-input",placeholder:i("tplDescriptionPlaceholder"),value:C.description,onChange:p=>M({...C,description:p.target.value})})]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("tplPromptModeLabel")}),e.jsxs("select",{className:"set-select",value:C.promptMode,onChange:p=>M({...C,promptMode:p.target.value}),children:[e.jsx("option",{value:"replace",children:i("promptModeReplace")}),e.jsx("option",{value:"append",children:i("promptModeAppend")})]})]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("tplModelLabel")}),e.jsxs("select",{className:"set-select",value:C.model??"",onChange:p=>M({...C,model:p.target.value}),children:[e.jsx("option",{value:"",children:i("subagentFollowMain")}),a.subagentModels.map(p=>e.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.id}`))]})]}),e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:`${i("tplSystemPromptLabel")}:${i("tplSystemPromptPlaceholder")}`,value:C.systemPrompt,onChange:p=>M({...C,systemPrompt:p.target.value})}),e.jsxs("div",{className:"tpl-pick-block",children:[e.jsx("div",{className:"tpl-pick-head",children:e.jsxs("span",{children:[i("tplSkillsLabel")," · ",i("tplWhitelistHint")]})}),a.skills.length===0?e.jsx("p",{className:"set-hint",children:i("noSkills")}):e.jsx("div",{className:"tpl-pick",children:a.skills.map(p=>e.jsxs("label",{className:`tpl-chip${C.enabledSkills.includes(p.name)?" on":""}`,children:[e.jsx("input",{type:"checkbox",checked:C.enabledSkills.includes(p.name),onChange:re=>{const Pe=re.target.checked;M({...C,enabledSkills:Pe?[...C.enabledSkills,p.name]:C.enabledSkills.filter(_e=>_e!==p.name)})}}),p.name]},p.name))})]}),e.jsxs("div",{className:"tpl-pick-block",children:[e.jsx("div",{className:"tpl-pick-head",children:e.jsxs("span",{children:[i("tplExtensionsLabel")," · ",i("tplWhitelistHint")]})}),a.extensions.length===0?e.jsx("p",{className:"set-hint",children:i("noExtensions")}):e.jsx("div",{className:"tpl-pick",children:a.extensions.map(p=>e.jsxs("label",{className:`tpl-chip${C.enabledExtensions.includes(p.id)?" on":""}`,children:[e.jsx("input",{type:"checkbox",checked:C.enabledExtensions.includes(p.id),onChange:re=>{const Pe=re.target.checked;M({...C,enabledExtensions:Pe?[...C.enabledExtensions,p.id]:C.enabledExtensions.filter(_e=>_e!==p.id)})}}),p.name]},p.id))})]}),e.jsxs("div",{className:"tpl-actions",children:[e.jsx("button",{type:"button",className:"set-save-btn",disabled:!C.name.trim(),onClick:()=>{s({type:"save_subagent_template",template:{...C,name:C.name.trim()}}),M(null)},children:i("tplSave")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>M(null),children:i("tplCancel")})]})]}),a.subagentTemplates.length===0?e.jsx("p",{className:"set-empty",children:i("noSubagentTemplates")}):e.jsx("div",{className:"set-list",children:a.subagentTemplates.map(p=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[p.name,a.subagentDefaultTemplates.includes(p.name)&&e.jsx("span",{className:"tpl-badge default",children:i("tplDefaultBadge")}),!p.enabled&&e.jsx("span",{className:"tpl-badge",children:i("subagentTemplateClosed")})]}),e.jsxs("div",{className:"set-row-desc",children:[p.description||`${p.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend")}`,p.model?` · ${i("tplModelLabel")} ${p.model}`:` · ${i("subagentFollowMain")}`,p.enabledSkills.length>0&&` · ${i("tplSkillsLabel")} ${p.enabledSkills.length}`,p.enabledExtensions.length>0&&` · ${i("tplExtensionsLabel")} ${p.enabledExtensions.length}`,!p.description&&p.enabledSkills.length===0&&p.enabledExtensions.length===0&&` · ${i("tplInherit")}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:`set-switch${p.enabled?" on":""}`,role:"switch","aria-checked":p.enabled,title:`${p.enabled?i("subagentTemplateDisable"):i("subagentTemplateEnable")} · ${i("subagentTemplateOffHint")}`,onClick:()=>s({type:"save_subagent_template",template:{...p,enabled:!p.enabled}}),children:e.jsx("span",{className:"set-switch-knob"})}),e.jsx("button",{type:"button",className:"dd-refresh",title:i("subagentTemplateEdit"),onClick:()=>M({...p}),children:i("subagentTemplateEdit")}),k===p.name?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>{s({type:"delete_subagent_template",name:p.name}),_(null)},children:i("uninstallConfirm")}):e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("tplDelete"),onClick:()=>_(p.name),children:e.jsx(He,{})})]})]},p.name))})]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:c,children:i("close")})})]})})}function Yl(t,s){const n=Math.max(0,Date.now()-t),r=Math.floor(n/6e4);if(r<1)return s("bgTaskJustNow");if(r<60)return s("bgTaskMinutes",{n:r});const c=Math.floor(r/60);return c<24?s("bgTaskHours",{n:c}):s("bgTaskDays",{n:Math.floor(c/24)})}function Jl({servers:t,send:s,onClose:n}){const r=be(),[c,i]=l.useState(new Set),a=o=>i(u=>{const m=new Set(u);return m.has(o)?m.delete(o):m.add(o),m});return l.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"bg-task-modal",onClick:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(Kt,{})," ",r("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:r("close"),onClick:n,children:e.jsx(Re,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(Kt,{}),e.jsx("span",{children:r("bgTasksEmpty")}),e.jsx("small",{children:r("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(o=>{const u=!!o.taskId,m=o.taskId??String(o.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:u?o.plugin:r("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[u?e.jsxs("span",{className:"bg-task-port",title:o.taskId,children:["🧩 ",o.plugin]}):e.jsxs("span",{className:"bg-task-port",children:[":",o.port]}),o.name&&e.jsx("span",{className:"bg-task-name",children:o.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[!u&&e.jsxs("span",{children:[r("bgTaskPid")," ",o.pid]}),e.jsxs("span",{children:[r("bgTaskSince")," ",Yl(o.since,r)]}),u&&o.status&&e.jsx("span",{className:"bg-task-status",children:o.status})]}),o.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${c.has(m)?"open":""}`,title:`${r("bgTaskCommand")}: ${o.command}`,onClick:()=>a(m),children:[e.jsx(ct,{}),e.jsx("code",{children:o.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:r("bgTaskStop"),onClick:()=>s(u?{type:"kill_background_server",taskId:o.taskId}:{type:"kill_background_server",port:o.port}),children:[e.jsx(Ot,{}),e.jsx("span",{children:r("bgTaskStop")})]})]},m)})}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:r("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(lt,{}),e.jsx("span",{children:r("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:r("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(Ot,{}),e.jsx("span",{children:r("bgTaskStopAll")})]})]})]})})}function Xl(t,s){return t.toLowerCase().includes(s)}function Zl({open:t,send:s,projects:n,cwd:r,fileSearch:c,sessionSearch:i,onClose:a,onSwitchSession:o,onSwitchProject:u,onPreviewFile:m}){const f=be(),y=l.useRef(null),[x,b]=l.useState(""),T=l.useDeferredValue(x),[D,H]=l.useState(0),N=l.useRef(1),j=l.useRef(0),Q=l.useRef(null);l.useEffect(()=>{if(!t)return;s({type:"list_sessions"}),s({type:"list_projects"});const I=x.trim();if(I){const R=++N.current;j.current=R,J(!0),s({type:"search_files",reqId:R,query:I}),s({type:"search_sessions",reqId:R,query:I})}requestAnimationFrame(()=>{var R;return(R=y.current)==null?void 0:R.select()})},[t]);const[V,J]=l.useState(!1);l.useEffect(()=>{Q.current&&clearTimeout(Q.current);const I=T.trim();if(!I){J(!1);return}return Q.current=setTimeout(()=>{const R=++N.current;j.current=R,J(!0),s({type:"search_files",reqId:R,query:I}),s({type:"search_sessions",reqId:R,query:I})},300),()=>{Q.current&&clearTimeout(Q.current)}},[T]);const U=T.trim().toLowerCase(),W=l.useMemo(()=>!U||!i||i.reqId!==j.current||!i.ok?[]:i.results,[i,U]),K=l.useMemo(()=>U?n.filter(I=>Xl(I.path,U)).slice(0,10):[],[n,U]),G=l.useMemo(()=>!U||!c||c.reqId!==j.current||!c.ok?[]:c.results,[c,U]);l.useEffect(()=>{c&&c.reqId===j.current&&i&&i.reqId===j.current&&j.current!==0&&J(!1)},[c,i]);const C=!!c&&c.ok&&c.truncated,M=l.useMemo(()=>[...W.map(I=>({kind:"session",path:I.path,anchors:I.anchors})),...K.map(I=>({kind:"project",path:I.path})),...G.filter(I=>I.type==="file").map(I=>({kind:"file",path:I.path,name:I.name}))],[W,K,G]);l.useEffect(()=>{H(0)},[T]);const k=l.useCallback(I=>{if(I)if(I.kind==="session")o(I.path,I.anchors),a();else if(I.kind==="project"){u(I.path),s({type:"list_sessions"}),s({type:"list_projects"});const R=T.trim();if(R){const w=++N.current;j.current=w,J(!0),s({type:"search_files",reqId:w,query:R}),s({type:"search_sessions",reqId:w,query:R})}}else m(I.path,I.name)},[o,u,m,s,T]);l.useEffect(()=>{if(!t)return;const I=R=>{R.key==="Escape"?(R.preventDefault(),R.stopPropagation(),a()):R.key==="ArrowDown"?(R.preventDefault(),H(w=>Math.min(w+1,M.length-1))):R.key==="ArrowUp"?(R.preventDefault(),H(w=>Math.max(w-1,0))):R.key==="Enter"&&(R.preventDefault(),k(M[D]))};return window.addEventListener("keydown",I,!0),()=>window.removeEventListener("keydown",I,!0)},[M,D,k,a,t]);const _=W.length+K.length+G.length,Z=(I,R,w)=>e.jsxs("div",{className:"gs-section-head",children:[w,e.jsx("span",{children:I}),e.jsx("em",{children:R})]});let z=-1;return t?e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:a,children:e.jsxs("div",{className:"gs-modal",onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(Ut,{}),e.jsx("input",{ref:y,type:"text",value:x,placeholder:f("gsPlaceholder"),onChange:I=>b(I.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:f("close"),onClick:a,children:e.jsx(Re,{})})]}),e.jsxs("div",{className:"gs-results",children:[!U&&e.jsx("div",{className:"gs-empty",children:f("gsHint")}),U&&_===0&&!C&&e.jsx("div",{className:"gs-empty",children:f(V?"gsSearching":"gsNoResults")}),W.length>0&&e.jsxs("div",{className:"gs-section",children:[Z(f("gsSessions"),W.length,e.jsx(dt,{})),W.map(I=>{z++;const R=z;return e.jsxs("button",{type:"button",className:R===D?"gs-item active":"gs-item",onMouseEnter:()=>H(R),onClick:()=>k({kind:"session",path:I.path,anchors:I.anchors}),children:[e.jsxs("span",{className:"gs-item-title",children:[I.name||I.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:I.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:I.firstMessage})]},I.path)})]}),K.length>0&&e.jsxs("div",{className:"gs-section",children:[Z(f("gsProjects"),K.length,e.jsx(st,{})),K.map(I=>{z++;const R=z,w=r&&I.path===r;return e.jsxs("button",{type:"button",className:R===D?"gs-item active":"gs-item",onMouseEnter:()=>H(R),onClick:()=>k({kind:"project",path:I.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[I.path.split(/[\\/]/).pop(),w&&e.jsx("em",{className:"gs-item-meta",children:f("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:I.path})]},I.path)})]}),(G.length>0||U&&C)&&e.jsxs("div",{className:"gs-section",children:[Z(f("gsFiles"),G.length,e.jsx(Tn,{})),G.map(I=>{z++;const R=z;return e.jsxs("button",{type:"button",className:R===D?"gs-item active":"gs-item",disabled:I.type==="dir",title:I.type==="dir"?void 0:f("gsOpenPreview"),onMouseEnter:()=>H(R),onClick:()=>{I.type==="file"&&k({kind:"file",path:I.path,name:I.name})},children:[e.jsx("span",{className:"gs-item-title",children:I.name}),e.jsx("span",{className:"gs-item-sub",children:I.path})]},`${I.type}:${I.path}`)}),C&&e.jsx("div",{className:"gs-truncated",children:f("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",f("gsNavigate")]}),e.jsxs("span",{children:["Enter ",f("gsOpen")]}),e.jsxs("span",{children:["Esc ",f("gsCloseHint")]})]})]})}):null}const us=5e3;function eo({file:t,content:s,send:n,onAddLines:r,onAttach:c,onClose:i}){const a=be(),[o,u]=l.useState(null),[m,f]=l.useState(!1),[y,x]=l.useState(null),[b,T]=l.useState(!1),[D,H]=l.useState(!1),[N,j]=l.useState(!1),[Q,V]=l.useState(""),[J,U]=l.useState(!0),W=l.useRef(!1),[K,G]=l.useState(!0),[C,M]=l.useState(!1),[k,_]=l.useState(100),Z=l.useRef(0),z=l.useRef(!1),I=l.useRef(null);l.useEffect(()=>{f(!0),u(null),x(null),j(!1),V(""),U(!0),W.current=!1,n({type:"read_file",path:t.path})},[t.path,n]),l.useEffect(()=>{s&&s.path===t.path&&(u(s),N||V(s.text),f(!1))},[s,N,t.path]),l.useEffect(()=>{const le=g=>{if(g.key==="Escape"){A();return}if((g.ctrlKey||g.metaKey)&&g.key.toLowerCase()==="s"&&N){g.preventDefault(),h();return}const O=g.target,me=O&&(O.tagName==="INPUT"||O.tagName==="TEXTAREA"||O.isContentEditable);(g.ctrlKey||g.metaKey)&&g.key.toLowerCase()==="a"&&!me&&(g.preventDefault(),ie())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[i,o,N,Q]),l.useEffect(()=>{const le=()=>{z.current=!1,T(!1)};return window.addEventListener("mouseup",le),()=>window.removeEventListener("mouseup",le)},[]);const R=l.useMemo(()=>{if(!o)return[];const le=o.text.split(`
|
|
326
|
+
`);return le.length>0&&le[le.length-1]===""&&le.pop(),le.slice(0,us)},[o]),w=(o==null?void 0:o.lines)??0,$=w>us,q=(le,g)=>{if(g){const O=Z.current>0?Z.current:le;x({start:Math.min(O,le),end:Math.max(O,le)})}else Z.current=le,x({start:le,end:le})},ie=()=>{R.length!==0&&(Z.current=1,x({start:1,end:R.length}))},v=()=>{y&&(r(t.path,t.name,y.start,y.end),H(!0),I.current&&clearTimeout(I.current),I.current=setTimeout(()=>H(!1),1400))},L=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,d=()=>{V((o==null?void 0:o.text)??""),j(!1),W.current&&U(!0)},E=()=>{if(N){if(Q!==((o==null?void 0:o.text)??"")&&!window.confirm(a("discardFileChanges")))return;d();return}!L||!o||(W.current=ps(t.name)&&J,ps(t.name)&&U(!1),x(null),V(o.text),j(!0))},h=()=>{!N||!o||!L||n({type:"write_file",path:t.path,text:Q})&&(j(!1),W.current&&U(!0),x(null))},A=()=>{N&&Q!==((o==null?void 0:o.text)??"")&&!window.confirm(a("discardFileChanges"))||i()},ee=le=>{_(Math.min(200,Math.max(50,le)))},Y=y?y.end-y.start+1:0,se=(o==null?void 0:o.binary)??!1,X=(o==null?void 0:o.truncated)??!1,ge=(o==null?void 0:o.kind)??"text",Ne=ps(t.name),de=Ne&&J&&!N&&ge==="text"&&!se,Ee=le=>Qt(Ye(`/api/file?clientId=${encodeURIComponent(Es())}&path=${encodeURIComponent(le)}`));return e.jsx("div",{className:`fp-overlay ${C?"fullscreen":""}`,onMouseDown:le=>{le.target===le.currentTarget&&A()},children:e.jsxs("div",{className:`fp ${C?"fullscreen":""}`,style:{"--fp-zoom":k/100},children:[e.jsxs("div",{className:"fp-head",children:[e.jsx("span",{className:"fp-name",title:t.path,children:t.name}),e.jsx("span",{className:"fp-path",children:t.path}),e.jsxs("span",{className:"fp-meta",children:[o&&ge==="text"&&!se&&a("fileLines",{n:w}),o&&` · ${to(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[Ne&&ge==="text"&&!se&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${J?"on":""}`,"data-tip":a(J?"showMarkdownSource":"showMarkdownPreview"),disabled:N,onClick:()=>U(le=>!le),children:J?e.jsx(hs,{}):e.jsx(sa,{})}),ge==="text"&&!se&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${N?"on":""}`,"data-tip":a(X?"fileEditTruncated":N?"exitEditFile":"editFile"),disabled:!L&&!N,onClick:E,children:e.jsx(gs,{})}),ge==="text"&&!se&&!de&&e.jsx("button",{type:"button",className:`fp-attach wrap ${K?"on":""}`,"data-tip":a(K?"disableWrap":"enableWrap"),onClick:()=>G(le=>!le),children:e.jsx(ta,{})}),ge==="text"&&o&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":a("zoomOut"),disabled:k<=50,onClick:()=>ee(k-10),children:e.jsx(_i,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:a("resetZoom"),onClick:()=>_(100),children:[k,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":a("zoomIn"),disabled:k>=200,onClick:()=>ee(k+10),children:e.jsx(Bi,{})})]}),ge!=="video"&&ge!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":a("attachInlineTip"),onClick:()=>c(t.path,t.name,"inline"),children:e.jsx(Ke,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":a("referenceTip"),onClick:()=>c(t.path,t.name,"reference"),children:e.jsx(ms,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${C?"on":""}`,"data-tip":a(C?"exitFullscreen":"fullscreen"),onClick:()=>M(le=>!le),children:C?e.jsx(qi,{}):e.jsx(Vi,{})}),e.jsx("button",{type:"button",className:"fp-close",title:a("close"),onClick:A,children:e.jsx(Re,{})})]})]}),X&&ge==="text"&&!se&&e.jsx("div",{className:"fp-notice",children:a("previewTruncated")}),m&&!o&&e.jsx("div",{className:"fp-empty",children:a("loading")}),!m&&ge==="none"&&!se&&e.jsx("div",{className:"fp-empty",children:a("previewNotSupported")}),!m&&ge==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:Ee(t.path),alt:t.name})}),!m&&ge==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:Ee(t.path),controls:!0,preload:"metadata"})}),!m&&de&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(Yt,{text:o.text})})}),!m&&se&&ge!=="image"&&ge!=="video"&&o&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[a("binaryFile"),o.truncated&&a("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:o.text})]}),!m&&N&&ge==="text"&&!se&&o&&e.jsx("textarea",{className:`fp-editor ${K?"":"no-wrap"}`,value:Q,onChange:le=>V(le.target.value),wrap:K?"soft":"off",spellCheck:!1,autoFocus:!0}),!m&&!de&&!N&&ge==="text"&&!se&&o&&R.length===0&&e.jsx("div",{className:"fp-empty",children:a("emptyFile")}),!m&&!de&&!N&&ge==="text"&&!se&&R.length>0&&e.jsxs("div",{className:`fp-code ${b?"dragging":""} ${K?"":"no-wrap"}`,onMouseDown:le=>{le.button===0&&le.preventDefault()},children:[R.map((le,g)=>{const O=g+1,me=y!==null&&O>=y.start&&O<=y.end;return e.jsxs("div",{className:`fp-line ${me?"sel":""}`,onMouseDown:ue=>{ue.button===0&&(q(O,ue.shiftKey),z.current=!0,T(!0))},onMouseEnter:()=>{z.current&&q(O,!0)},children:[e.jsx("span",{className:"fp-num",children:O}),e.jsx("span",{className:"fp-code-text",children:le})]},O)}),$&&e.jsx("div",{className:"fp-lines-note",children:a("previewLinesTruncated",{n:us})})]}),e.jsx("div",{className:"fp-foot",children:N?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:a("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:E,children:a("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:Q===((o==null?void 0:o.text)??""),onClick:h,children:[e.jsx(Wi,{})," ",a("saveFile")]})]})]}):!de&&ge==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:y?a("selectedRange",{n:Y,start:y.start,end:y.end}):a("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:R.length===0,onClick:ie,children:a("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!y,onClick:()=>x(null),children:a("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!y||se,onClick:v,children:[D?e.jsx(Pt,{}):null,a(D?"addedToChat":"addToChat")]})]})]})})]})})}function ps(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function to(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const gi="pi-web-sounds",vt={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function fi(){try{const t=localStorage.getItem(gi);if(!t)return{...vt};const s=JSON.parse(t),n={...vt,...s};for(const r of["enabled","question","done","start","error"])typeof n[r]!="boolean"&&(n[r]=vt[r]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=vt.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...vt}}}function so(t){try{localStorage.setItem(gi,JSON.stringify(t))}catch{}}let bt=null;function no(){try{if(!bt){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;bt=new t}return bt.state==="suspended"&&bt.resume(),bt}catch{return null}}const io=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],ao=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],ro=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],lo=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],oo={question:io,done:ao,start:ro,error:lo};function co(t,s,n){const r=t.createOscillator(),c=t.createGain();r.type=s.type,r.frequency.value=s.freq;const i=t.currentTime+s.start,a=Math.max(1e-4,s.peak*n);c.gain.setValueAtTime(1e-4,i),c.gain.exponentialRampToValueAtTime(a,i+.012),c.gain.exponentialRampToValueAtTime(1e-4,i+s.dur),r.connect(c),c.connect(t.destination),r.start(i),r.stop(i+s.dur+.05)}function kt(t,s=fi()){if(!s.enabled||!s[t])return;const n=no();if(!n)return;const r=Math.max(0,Math.min(1,s.volume/100));for(const c of oo[t])co(n,c,r)}const uo=l.lazy(()=>Ei(()=>import("./TerminalPanel-Bu0PEPj5.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function po({notice:t,onDismiss:s}){const n=be(),{locale:r}=Mt(),c=r==="en"&&t.textEn?t.textEn:t.text,[i,a]=l.useState(!1);l.useEffect(()=>{if(i)return;const u=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(u)},[i,t.id,t.level,s]);const o=t.level==="error"?oa:t.level==="warning"?la:Yi;return e.jsxs("div",{className:`notice notice-${t.level}${i?" paused":""}`,role:"status",onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[e.jsx(o,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:c}),e.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>s(t.id),children:e.jsx(Re,{})})]})}const mo=[],xi=180,yi=520,vi=240,bi=t=>`pi-web-ui:${t}-panel-width`;function xn(t){const s=Number(localStorage.getItem(bi(t)));return Number.isFinite(s)&&s>=xi&&s<=yi?s:vi}const Ts=t=>`pi-web-ui:${t}-panel-collapsed`;function yn(t){return localStorage.getItem(Ts(t))==="1"}function vn({side:t,width:s,onResize:n}){const r=be(),c=l.useCallback(i=>{i.preventDefault();const a=i.clientX,o=s;let u=o;const m=y=>{const x=t==="left"?y.clientX-a:a-y.clientX;u=Math.min(yi,Math.max(xi,Math.round(o+x))),n(u)},f=()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",f),document.body.classList.remove("panel-resizing"),localStorage.setItem(bi(t),String(u))};window.addEventListener("pointermove",m),window.addEventListener("pointerup",f),document.body.classList.add("panel-resizing")},[t,s,n]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:r("dragToResize"),onPointerDown:c,onDoubleClick:()=>n(vi)})}function bn({side:t,onClick:s}){const n=be();return e.jsx("button",{type:"button",className:`panel-rail panel-rail-${t}`,title:n("expandPanel"),onClick:s,children:t==="left"?e.jsx(Pn,{}):e.jsx(Mn,{})})}function ho(){var ut,pt,mt,ht,gt,ft,p,re,Pe,_e,Be,xt,yt,It;const t=be(),{chat:s,send:n,dismissNotice:r,pushNotice:c,terminal:i}=Wa(),[a,o]=l.useState([]),[u,m]=l.useState(null),[f,y]=l.useState(!1),[x,b]=l.useState("chat"),T=l.useMemo(()=>s.plugins.filter(F=>{var te,he;return!((he=(te=s.settings)==null?void 0:te.disabledPlugins)!=null&&he.includes(F.id))}),[s.plugins,(ut=s.settings)==null?void 0:ut.disabledPlugins]),[D,H]=l.useState([]);l.useEffect(()=>Ma(H),[]),l.useEffect(()=>{ar(n),rr(T,s.pluginsEpoch),Ia(T,s.pluginsEpoch)},[T,s.pluginsEpoch,n]);const[N,j]=l.useState(()=>xn("left")),[Q,V]=l.useState(()=>xn("right")),J=l.useCallback(F=>j(F),[]),U=l.useCallback(F=>V(F),[]),[W,K]=l.useState(()=>yn("left")),[G,C]=l.useState(()=>yn("right")),M=l.useCallback(()=>{K(F=>(localStorage.setItem(Ts("left"),F?"0":"1"),!F))},[]),k=l.useCallback(()=>{C(F=>(localStorage.setItem(Ts("right"),F?"0":"1"),!F))},[]),[_,Z]=l.useState(null),[z,I]=l.useState(()=>window.matchMedia("(max-width: 768px)").matches);l.useEffect(()=>{const F=window.matchMedia("(max-width: 768px)"),te=he=>I(he.matches);return F.addEventListener("change",te),()=>F.removeEventListener("change",te)},[]);const[R,w]=l.useState(!1),[$,q]=l.useState(!1),[ie,v]=l.useState(!1),L=hi(),[d,E]=l.useState(!1),[h,A]=l.useState(!1),[ee,Y]=l.useState(null);l.useEffect(()=>{if(!ee)return;const F=setTimeout(()=>Y(null),15e3);return()=>clearTimeout(F)},[ee]),l.useEffect(()=>{const F=te=>{var Je,Ds;const he=te.detail,Ce=(he==null?void 0:he.title)||t("pluginCommandFallback"),Te=he==null?void 0:he.command;if(!Te||!s.ready)return;const We={name:Ce,command:Te,cwd:"${pwd}"},Me=s.terminals.find(Jt=>Jt.title===Ce);if(Me)i.restart(Me.id),n({type:"run_command",terminalId:Me.id,conversationId:Me.conversationId,command:We,cols:80,rows:24});else{const Jt=Qe();i.create({id:Jt,conversationId:s.activeConversationId||((Je=s.state)==null?void 0:Je.conversationId)||"",title:Ce,cwd:((Ds=s.state)==null?void 0:Ds.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:We})}b("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",F),()=>window.removeEventListener("pi-web-ui:plugin-run-command",F)},[s,i,n]),l.useEffect(()=>{const F=te=>{!(te.ctrlKey||te.metaKey)||te.key.toLowerCase()!=="k"||(te.preventDefault(),A(he=>!he))};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[]);const[se,X]=l.useState(fi),{themes:ge,theme:Ne,switchTheme:de}=ur(),Ee=l.useRef(null),le=l.useRef(null),g=l.useRef(0),O=l.useRef(!1),me=l.useRef(s.terminals);l.useEffect(()=>{so(se)},[se]),l.useEffect(()=>{var te;const F=me.current;me.current=s.terminals;for(const he of s.terminals){const Ce=((te=he.command)==null?void 0:te.command)??"",Te=F.find(We=>We.id===he.id);!(Te!=null&&Te.running)||he.running||(Ce.startsWith("pi remove ")?n({type:"extensions_reload"}):Ce.startsWith("pi-web-ui install ")||Ce.startsWith("pi-web-ui uninstall ")?n({type:"plugins_reload"}):Ce.startsWith("npm i -g ")&&(n({type:"extensions_reload"}),n({type:"plugins_reload"}),n({type:"check_updates_all",force:!0})))}},[s.terminals,n]),l.useEffect(()=>{var he;const F=((he=s.state)==null?void 0:he.isStreaming)??!1,te=Ee.current;Ee.current=F,te!==null&&(!te&&F?kt("start",se):te&&!F&&(kt("done",se),ss(t("notifyDoneTitle"),t("notifyDoneBody"))))},[(pt=s.state)==null?void 0:pt.isStreaming,se]),l.useEffect(()=>{var te;const F=((te=s.dialog)==null?void 0:te.id)??null;F!==null&&F!==le.current&&(kt("question",se),ss(t("notifyQuestionTitle"),t("notifyQuestionBody"))),le.current=F},[s.dialog,se]),l.useEffect(()=>{const F=[...s.notices].reverse().find(te=>te.level==="error");F&&F.id!==g.current&&(g.current=F.id,kt("error",se),ss(t("notifyErrorTitle"),t("notifyErrorBody")))},[s.notices,se]);const ue=(F,te,he,Ce=!1,Te)=>{const We=`${F}|${he}|${Te?`${Te.start}-${Te.end}`:""}`;o(Me=>Me.some(Je=>`${Je.path}|${Je.mode}|${Je.lines?`${Je.lines.start}-${Je.lines.end}`:""}`===We)?Me:[...Me,{path:F,name:te,mode:he,isDir:Ce,...Te?{lines:Te}:{}}])},ye=F=>o(te=>te.filter(he=>he.key?he.key!==F:he.path!==F)),fe=l.useCallback(F=>(!F.type.startsWith("list_")&&!F.type.startsWith("get_")&&Z(null),n(F)),[n]),ke=l.useRef(0),Le=l.useRef(0),ae=F=>{var Ce;const te=Date.now();(Ce=s.state)!=null&&Ce.model&&!s.state.model.vision&&te-Le.current>1e4&&(Le.current=te,c("warning",t("imageNotSupported")));const he=`paste-${++ke.current}`;o(Te=>[...Te,{path:"",key:he,name:F.name,mode:"inline",imageData:F.data,mimeType:F.mimeType}])},De=async F=>{for(const te of F){const he=await Vn(te);if(!he){c("error",t("imageLoadFailed",{name:te.name}));continue}ae(he)}},Ae=20*1024*1024,qe=l.useRef(0),ze=async F=>{if(F.size>Ae){c("warning",t("fileTooLarge",{name:F.name,size:Ae/1024/1024}));return}let te;try{te=(await new Promise((Te,We)=>{const Me=new FileReader;Me.onload=()=>Te(Me.result),Me.onerror=()=>We(Me.error??new Error("read failed")),Me.readAsDataURL(F)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",t("fileLoadFailed",{name:F.name}));return}const he=`upload-${++qe.current}`;o(Ce=>[...Ce,{path:"",key:he,name:F.name,mode:"inline",fileData:te,size:F.size,mimeType:F.type||void 0}])},P=async F=>{for(const te of F)Ge(te.type)?await De([te]):await ze(te)},xe=l.useCallback((F,te,he)=>{n({type:"edit_message",messageId:F,text:te,attachments:he})},[n]),pe=l.useCallback((F,te)=>{n({type:"queue_remove",kind:F,text:te})},[n]),Se=l.useCallback(()=>q(!0),[]),ve=l.useCallback(()=>o([]),[]),S=l.useCallback(ye,[]),B=l.useCallback(De,[De]),oe=l.useCallback(P,[P]),ce=(mt=s.state)==null?void 0:mt.model,je=(ht=s.state)==null?void 0:ht.thinkingLevel,we=(gt=s.state)==null?void 0:gt.availableThinkingLevels,Ie=l.useMemo(()=>ce?{model:ce,thinkingLevel:je??"off",availableThinkingLevels:we??[]}:null,[ce,je,we]),Oe=l.useCallback(()=>{var F,te;return!s.ready||s.terminals.length!==0?!1:(i.create({id:Qe(),conversationId:s.activeConversationId||((F=s.state)==null?void 0:F.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((te=s.state)==null?void 0:te.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,(ft=s.state)==null?void 0:ft.cwd,s.terminals.length,t,i]);return l.useEffect(()=>{if(O.current){if(x!=="terminal"||s.terminals.length!==0){O.current=!1;return}Oe()&&(O.current=!1)}},[s.terminals.length,Oe,x]),e.jsxs("div",{className:"app",onDragOver:F=>{var te;Array.from(((te=F.dataTransfer)==null?void 0:te.types)??[]).includes("Files")&&(F.preventDefault(),y(!0))},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||y(!1)},onDrop:F=>{var Te,We;if(y(!1),!Array.from(((Te=F.dataTransfer)==null?void 0:Te.types)??[]).includes("Files"))return;F.preventDefault();const te=Array.from(((We=F.dataTransfer)==null?void 0:We.files)??[]);if(te.length===0){c("warning",t("foldersNotSupported"));return}const he=te.filter(Me=>Ge(Me.type)),Ce=te.filter(Me=>!Ge(Me.type));he.length>0&&De(he),Ce.length>0&&P(Ce)},children:[f&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(xa,{chat:s,send:n,terminal:i,view:x,plugins:T,onViewChange:F=>{O.current=F==="terminal"&&s.terminals.length===0,O.current&&Oe()&&(O.current=!1),b(F),Z(null)},onOpenPanel:Z,onOpenSettings:()=>v(!0),onOpenBgTasks:()=>E(!0),onOpenGlobalSearch:()=>A(!0),sound:se,onSoundChange:X,onSoundPreview:F=>kt(F,se),themes:ge,theme:Ne,onThemeChange:de}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(F=>e.jsx(po,{notice:F,onDismiss:r},F.id))}),e.jsx(rl,{send:n,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${N}px`,"--right-w":`${Q}px`},children:[_&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>Z(null)}),e.jsxs("div",{className:`view-pane ${x==="chat"?"":"hidden"}`,children:[!z&&W&&e.jsx(bn,{side:"left",onClick:M}),e.jsx("div",{className:`panel-drawer drawer-left ${_==="left"?"open":""}${z?"":W?" hidden":""}`,children:e.jsx(wa,{collapsible:!z,onToggleCollapse:M,send:fe,active:!z||_==="left",ready:s.ready,status:s.status,cwd:((p=s.state)==null?void 0:p.cwd)??"",sessionFile:((re=s.state)==null?void 0:re.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!z&&e.jsx(vn,{side:"left",width:N,onResize:J}),e.jsxs("main",{className:L?"main wide-chat":"main",children:[s.state?e.jsx(pl,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:xe,onKillBash:()=>n({type:"abort_bash"}),onRemoveQueued:pe,thinkingWrap:((Pe=s.settings)==null?void 0:Pe.thinkingWrap)??!0,toolsWrap:((_e=s.settings)==null?void 0:_e.toolsWrap)??!0,jumpTarget:ee,onJumpDone:()=>Y(null)},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(Tl,{send:n,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId,engine:s.engine}),s.dialog&&e.jsx(Dl,{dialog:s.dialog,send:n}),s.question&&e.jsx(Al,{question:s.question,send:n}),e.jsx(Sl,{send:n,ready:s.ready,streaming:((Be=s.state)==null?void 0:Be.isStreaming)??!1,messages:((xt=s.state)==null?void 0:xt.messages)??mo,slashCommands:s.slashCommands,modelState:Ie,models:s.models,modelsLoading:s.modelsLoading,providerKeys:s.providerKeys,attachments:a,onRemoveAttachment:S,onAddImageFiles:B,onAddLocalFiles:oe,onNotice:c,onManageModels:Se,onSent:ve})]}),!z&&e.jsx(vn,{side:"right",width:Q,onResize:U}),e.jsx("div",{className:`panel-drawer drawer-right ${_==="right"?"open":""}${z?"":G?" hidden":""}`,children:e.jsx(Ja,{collapsible:!z,onToggleCollapse:k,send:fe,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((yt=s.state)==null?void 0:yt.cwd)??"",onAttach:(F,te,he,Ce)=>{Z(null),ue(F,te,he,Ce)},onPreview:(F,te)=>{Z(null),m({path:F,name:te})},onNotice:(F,te)=>c(F,te)})}),!z&&G&&e.jsx(bn,{side:"right",onClick:k})]}),e.jsx("div",{className:`view-pane ${x==="terminal"?"":"hidden"}`,children:e.jsx(l.Suspense,{fallback:null,children:e.jsx(uo,{chat:s,send:n,terminal:i})})}),e.jsx("div",{className:`view-pane ${x==="git"?"":"hidden"}`,children:e.jsx(Bl,{chat:s,send:n,terminal:i,active:x==="git",onSwitchToTerminal:()=>b("terminal")})}),D.map(F=>{const te=`plugin:${F.info.id}`;return e.jsx("div",{className:`view-pane ${x===te?"":"hidden"}`,children:e.jsx(Fl,{entry:F,send:n})},F.info.id)})]})}),e.jsx(Rl,{chat:s,send:n}),u&&e.jsx(eo,{file:u,content:s.fileContent,send:n,onAddLines:(F,te,he,Ce)=>ue(F,te,"lines",!1,{start:he,end:Ce}),onAttach:(F,te,he)=>ue(F,te,he),onClose:()=>m(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!R&&!$&&e.jsx($l,{send:n,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>w(!0)}),$&&e.jsx(Wl,{send:n,providers:s.modelsConfig,providerStatus:s.providers,providerKeys:s.providerKeys,fetchModelsResult:s.fetchModelsResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>q(!1)}),ie&&e.jsx(Ql,{chat:s,send:n,terminal:i,onSwitchToTerminal:()=>b("terminal"),onClose:()=>v(!1)}),d&&e.jsx(Jl,{servers:s.bgServers,send:n,onClose:()=>E(!1)}),e.jsx(Zl,{open:h,send:n,projects:s.projects,cwd:((It=s.state)==null?void 0:It.cwd)??"",fileSearch:s.fileSearch,sessionSearch:s.sessionSearch,onClose:()=>A(!1),onSwitchSession:(F,te)=>{n({type:"switch_session",path:F});const he=te&&te[0];Y(he?{path:F,role:he.role,timestamp:he.timestamp}:null)},onSwitchProject:F=>{n({type:"set_cwd",path:F})},onPreviewFile:(F,te)=>{m({path:F,name:te})}})]})}Na();zn(qn());Ci.createRoot(document.getElementById("root")).render(e.jsx(l.StrictMode,{children:e.jsx(ua,{children:e.jsx(ho,{})})}));"serviceWorker"in navigator&&window.addEventListener("load",()=>{const t=An();navigator.serviceWorker.register(`${t}sw.js`,{scope:t}).catch(s=>{console.warn("Service worker registration failed:",s)})});export{lt as F,rt as T,be as a,yo as b,Ke as c,xo as d,qt as e,He as f,zi as g,ct as h,Re as i,Qe as r,Mt as u};
|