pi-web-ui 0.36.0 → 0.44.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.
@@ -1,19 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-BxezvWth.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 De,a as i,j as e,M as js,b as sn,c as nn}from"./markdown-DRBrS2Nf.js";import{r as ks}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"]'))o(c);new MutationObserver(c=>{for(const a of c)if(a.type==="childList")for(const r of a.addedNodes)r.tagName==="LINK"&&r.rel==="modulepreload"&&o(r)}).observe(document,{childList:!0,subtree:!0});function n(c){const a={};return c.integrity&&(a.integrity=c.integrity),c.referrerPolicy&&(a.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?a.credentials="include":c.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function o(c){if(c.ep)return;c.ep=!0;const a=n(c);fetch(c.href,a)}})();var Qe={},qt;function an(){if(qt)return Qe;qt=1;var t=ks();return Qe.createRoot=t.createRoot,Qe.hydrateRoot=t.hydrateRoot,Qe}var rn=an();const on="modulepreload",ln=function(t){return"/"+t},zt={},ws=function(s,n,o){let c=Promise.resolve();if(n&&n.length>0){let r=function(m){return Promise.all(m.map(f=>Promise.resolve(f).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));c=r(n.map(m=>{if(m=ln(m),m in zt)return;zt[m]=!0;const f=m.endsWith(".css"),h=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${h}`))return;const k=document.createElement("link");if(k.rel=f?"stylesheet":on,f||(k.as="script"),k.crossOrigin="",k.href=m,u&&k.setAttribute("nonce",u),document.head.appendChild(k),f)return new Promise((M,N)=>{k.addEventListener("load",M),k.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${m}`)))})}))}function a(r){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=r,window.dispatchEvent(l),!l.defaultPrevented)throw r}return c.then(r=>{for(const l of r||[])l.status==="rejected"&&a(l.reason);return s().catch(a)})};var Ns={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Kt=De.createContext&&De.createContext(Ns),cn=["attr","size","title"];function dn(t,s){if(t==null)return{};var n,o,c=un(t,s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(o=0;o<a.length;o++)n=a[o],s.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(c[n]=t[n])}return c}function un(t,s){if(t==null)return{};var n={};for(var o in t)if({}.hasOwnProperty.call(t,o)){if(s.indexOf(o)!==-1)continue;n[o]=t[o]}return n}function Ze(){return Ze=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var o in n)({}).hasOwnProperty.call(n,o)&&(t[o]=n[o])}return t},Ze.apply(null,arguments)}function Vt(t,s){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);s&&(o=o.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),n.push.apply(n,o)}return n}function et(t){for(var s=1;s<arguments.length;s++){var n=arguments[s]!=null?arguments[s]:{};s%2?Vt(Object(n),!0).forEach(function(o){mn(t,o,n[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Vt(Object(n)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(n,o))})}return t}function mn(t,s,n){return(s=pn(s))in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function pn(t){var s=hn(t,"string");return typeof s=="symbol"?s:s+""}function hn(t,s){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var o=n.call(t,s);if(typeof o!="object")return o;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Cs(t){return t&&t.map((s,n)=>De.createElement(s.tag,et({key:n},s.attr),Cs(s.child)))}function z(t){return s=>De.createElement(gn,Ze({attr:et({},t.attr)},s),Cs(t.child))}function gn(t){var s=n=>{var o=t.attr,c=t.size,a=t.title,r=dn(t,cn),l=c||n.size||"1em",u;return n.className&&(u=n.className),t.className&&(u=(u?u+" ":"")+t.className),De.createElement("svg",Ze({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,o,r,{className:u,style:et(et({color:t.color||n.color},n.style),t.style),height:l,width:l,xmlns:"http://www.w3.org/2000/svg"}),a&&De.createElement("title",null,a),t.children)};return Kt!==void 0?De.createElement(Kt.Consumer,null,n=>s(n)):s(Ns)}function fn(t){return z({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 xn(t){return z({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 bt(t){return z({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 Ce(t){return z({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 Ss(t){return z({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 vn(t){return z({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 $e(t){return z({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 Je(t){return z({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 Gt(t){return z({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 yn(t){return z({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 tt(t){return z({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 st(t){return z({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 bn(t){return z({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 nt(t){return z({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 jn(t){return z({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 ot(t){return z({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 Ue(t){return z({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 _i(t){return z({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 Jt(t){return z({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 kn(t){return z({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 wn(t){return z({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 Nn(t){return z({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 at(t){return z({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 Cn(t){return z({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 Sn(t){return z({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 Tn(t){return z({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 En(t){return z({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 jt(t){return z({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 it(t){return z({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 Mn(t){return z({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"},child:[]}]})(t)}function Rn(t){return z({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 In(t){return z({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 Ln(t){return z({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 Qt(t){return z({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 Xe(t){return z({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 qe(t){return z({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 Ts(t){return z({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 Pn(t){return z({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 Es(t){return z({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 kt(t){return z({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 Yt(t){return z({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 Mt(t){return z({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 lt(t){return z({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 Bn(t){return z({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 Rt(t){return z({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 Dn(t){return z({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 ct(t){return z({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 dt(t){return z({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 Fe(t){return z({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 ut(t){return z({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 $n(t){return z({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 Ms(t){return z({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 _n(t){return z({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 Rs(t){return z({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 Is(t){return z({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 Fn(t){return z({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 An(t){return z({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 _e(){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 Le({trigger:t,open:s,onOpenChange:n,children:o,align:c="right",fit:a=!1,direction:r="down",menuClassName:l}){const u=i.useRef(null);return i.useEffect(()=>{if(!s)return;const m=h=>{u.current&&!u.current.contains(h.target)&&n(!1)},f=h=>{h.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",m),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("keydown",f)}},[s,n]),e.jsxs("div",{className:`dropdown ${c} ${a?"fit":""} ${r==="up"?"dd-up":""}`,ref:u,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!s),"aria-expanded":s,children:[t,e.jsx(Fe,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${l??""}`,children:o})]})}function Ne({active:t,disabled:s=!1,title:n,onClick:o,children:c}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:n,onClick:o,children:c})}const Ls="pi-web-ui:lang",On={cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",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:"插件状态",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",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:"排队",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editImageHint:"原图已保留,可粘贴/拖入新图片 · ⌘/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)。",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",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:"插件请求",noOptions:"(无选项)",inputPlaceholder:"输入内容",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量","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 密钥即可开始对话:",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":"上下文已压缩",welcomeTitle:"pi 编码智能体",welcomeSub:"检查、编辑、运行 —— 随时待命",directory:"目录",clickToFill:"点击填入输入框",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:同时搜索历史对话、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索文件…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","ex.understand":"了解这个项目","ex.understand.prompt":"介绍一下这个项目:整体结构、主要模块和如何运行?","ex.debug":"排查一个问题","ex.debug.prompt":"帮我排查一个 bug,请先说明问题现象,我会补充细节。","ex.test":"编写测试","ex.test.prompt":"为项目的核心模块编写单元测试。","ex.review":"代码审查","ex.review.prompt":"审查最近改动的代码,指出潜在问题和改进建议。",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})",closeTerminal:"关闭终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",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 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}",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"只需填入 API 密钥",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",cloneProvider:"复制为自定义",cloning:"复制中",cloneProviderTitle:"复制该内置供应商(baseUrl + 模型列表)为自定义供应商,填入另一个 API 密钥即可双 key 并存",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",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:"系统提示词",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:"转写提示词",settingsTerminalTools:"终端工具",terminalToolsEnabled:"启用持久终端工具",settingsTerminalToolsDesc:"让 AI 在交互式程序(REPL/vim)、长驻服务、需要持续观察输出或你要求在可见终端操作时,使用内置终端;普通命令仍走一次性 bash 工具",terminalToolsOffHint:"已关闭:AI 无法使用 terminal_* 工具,也不会收到相关使用引导",terminalBashTakeover:"终端接管 bash",terminalBashTakeoverDesc:"bash 命令改在持久可见终端里执行:完整输出自动返回、shell 状态跨调用保留(cd/venv/ssh);命令静默超时自动转后台并在结束后主动通知 AI",terminalBashIdleMs:"静默转后台阈值(毫秒)",terminalBashIdleMsDesc:"命令连续无输出达到该时长即不再阻塞等待,转入后台继续运行并通知 AI;0 = 一直等到命令结束(默认 15000)",visionBridgePromptPlaceholder:"输入自定义转写提示词…(留空 = 使用内置默认提示词,失焦后自动应用)",visionBridgePromptAppendHint:"追加模式:自定义内容拼接到内置转写提示词末尾(推荐,保留默认的逐字转写约束)。",visionBridgePromptReplaceHint:"替换模式:完全用自定义内容替换内置转写提示词。切换后输入框会显示内置默认提示词,可直接修改;不改动失焦则仍使用默认。",uninstallExt:"卸载",uninstallConfirm:"确认卸载?",uninstallConfirmHint:"再次点击确认,将在终端执行 pi remove",uninstallHint:"通过可见终端执行 pi remove 卸载此包,完成后自动刷新列表",uninstallTitle:"卸载",pluginUpdate:"更新",pluginUpdateHint:"从安装来源重新拉取并覆盖安装(保留 config.json 配置),完成后自动重载插件列表",pluginUninstallHint:"在可见终端执行 pi-web-ui uninstall 卸载此插件(再次点击确认),完成后自动刷新列表",settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",settingsPresets:"预设",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},Hn={cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",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",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",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",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",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",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",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",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",editImageHint:"Original images kept — paste/drop to add more · ⌘/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).",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}",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",noOptions:"(no options)",inputPlaceholder:"Enter content",soundHeader:"Sound notifications",enableSound:"Enable sound",preview:"Preview",volume:"Volume","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:",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",welcomeTitle:"pi coding agent",welcomeSub:"Inspect, edit, run — always ready",directory:"Directory",clickToFill:"Click to fill input",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",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search session history, recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching files…",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","ex.understand":"Understand this project","ex.understand.prompt":"Introduce this project: overall structure, main modules, and how to run it?","ex.debug":"Debug an issue","ex.debug.prompt":"Help me debug a bug — describe the symptom first, and I'll add details.","ex.test":"Write tests","ex.test.prompt":"Write unit tests for the core modules.","ex.review":"Code review","ex.review.prompt":"Review the recently changed code and point out potential issues and improvements.",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})",closeTerminal:"Close terminal",rerun:"Reload .pi/commands.json",terminalTitle:"Terminal {n}",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 add -A && git commit -m "…" in the terminal (commits all changes incl. untracked)',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 — not shown in diff, included on commit",scmQueryFailed:"Git query failed: {error}",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:"Clone as custom",cloning:"Cloning",cloneProviderTitle:"Copy this built-in provider (baseUrl + model catalog) into a custom provider — paste another API key to run both keys side by side",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",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",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",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",terminalBashTakeover:"Terminal-backed bash",terminalBashTakeoverDesc:"Run bash commands inside the persistent visible terminal: full output returned automatically, shell state retained across calls (cd/venv/ssh); silent commands move to the background and notify the AI when they finish",terminalBashIdleMs:"Silence-to-background threshold (ms)",terminalBashIdleMsDesc:"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",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/)",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",settingsPresets:"Presets",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…"},Ps=i.createContext(null);function Wn(){try{const t=localStorage.getItem(Ls);if(t==="zh"||t==="en")return t}catch{}return"zh"}function Un({children:t}){const[s,n]=i.useState(Wn),o=i.useCallback(r=>{n(r);try{localStorage.setItem(Ls,r)}catch{}},[]),c=i.useCallback((r,l)=>{let u=Hn[r];if(s==="zh"&&(u=On[r]),l)for(const[m,f]of Object.entries(l))u=u.replaceAll(`{${m}}`,String(f));return u},[s]);i.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en"},[s]);const a=i.useMemo(()=>({locale:s,setLocale:o,t:c}),[s,o,c]);return e.jsx(Ps.Provider,{value:a,children:t})}function It(){const t=i.useContext(Ps);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function he(){return It().t}const qn=["off","minimal","low","medium","high","xhigh","max"],Bs=i.memo(function({state:s,models:n,modelsLoading:o,send:c,onManageModels:a,compact:r=!1}){const l=he(),u=s==null?void 0:s.model,m=u?`${u.provider}/${u.id}`:null,[f,h]=i.useState(!1),[k,M]=i.useState(!1),[N,D]=i.useState("");i.useEffect(()=>{f||D("")},[f]);const R=i.useMemo(()=>{const y=N.trim().toLowerCase();return y?n.filter(w=>w.name.toLowerCase().includes(y)||w.provider.toLowerCase().includes(y)||w.id.toLowerCase().includes(y)):n},[n,N]),[P,A]=i.useState(!1),p=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,E=qn.map(y=>({value:y,label:l(`thinking.${y}`),supported:p?p.has(y):!0})),I=y=>{var w;return((w=E.find(d=>d.value===y))==null?void 0:w.label)??y};return i.useEffect(()=>{f&&n.length===0&&!P&&!o&&(A(!0),c({type:"list_models"}))},[f,n.length,P,o,c]),i.useEffect(()=>{n.length>0&&A(!1)},[n.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(lt,{}),e.jsx("span",{className:"chip-model",children:u?u.name:l("selectModel")}),!r&&(u==null?void 0:u.vision)&&e.jsx("span",{className:"chip-vision",title:l("vision"),children:"🖼"}),!r&&u&&e.jsx("span",{className:"chip-sub",children:u.provider})]}),open:f,onOpenChange:h,menuClassName:"dd-menu-model",children:[e.jsx("div",{className:"dd-header",children:l("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(nt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:l("searchModels"),value:N,onChange:y=>D(y.target.value)})]}),e.jsxs("div",{className:"dd-model-scroll",children:[(P||o)&&e.jsx("div",{className:"dd-loading",children:l("loading")}),n.length===0&&!P&&!o&&e.jsx("div",{className:"dd-loading",children:l("noModels")}),R.length===0&&n.length>0&&e.jsx("div",{className:"dd-loading",children:l("noModelMatches")}),R.map(y=>e.jsx(Ne,{active:m===y.id,onClick:()=>{m!==y.id&&c({type:"set_model",modelId:y.id}),h(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:y.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:y.provider}),(y.reasoning||y.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[y.reasoning&&e.jsx("span",{className:"dd-model-badge",children:l("reasoning")}),y.vision&&e.jsx("span",{className:"dd-model-badge",children:l("vision")})]})]})]})},y.id))]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>c({type:"list_models"}),children:l("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{h(!1),a()},children:l("manageModels")})]})]}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(bt,{}),e.jsx("span",{className:"chip-sub",children:l("thinkingChip",{level:s?I(s.thinkingLevel):"—"})})]}),open:k,onOpenChange:M,children:[e.jsx("div",{className:"dd-header",children:l("thinkingLevel")}),E.map(y=>e.jsx(Ne,{active:(s==null?void 0:s.thinkingLevel)===y.value,disabled:!y.supported,title:y.supported?void 0:l("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==y.value&&c({type:"set_thinking",level:y.value}),M(!1)},children:y.label},y.value))]})]})}),zn=[{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 Xt({settings:t,onChange:s,onPreview:n}){const o=he(),c=a=>s({...t,...a});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:o("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Ss,{className:"sound-icon"}),e.jsx("span",{children:o("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:a=>c({enabled:a.target.checked})})]}),zn.map(({kind:a,labelKey:r,descKey:l})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:o(r)}),e.jsx("span",{className:"sound-desc",children:o(l)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:o("preview"),disabled:!t.enabled,onClick:u=>{u.preventDefault(),n(a)},children:o("preview")}),e.jsx("input",{type:"checkbox",checked:t[a],disabled:!t.enabled,onChange:u=>c({[a]:u.target.checked})})]})]},a)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:o("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:a=>c({volume:Number(a.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}function Kn({chat:t,send:s,terminal:n,view:o,plugins:c,onViewChange:a,onOpenPanel:r,onManageModels:l,onOpenSettings:u,onOpenBgTasks:m,onOpenGlobalSearch:f,sound:h,onSoundChange:k,onSoundPreview:M,themes:N,theme:D,onThemeChange:R}){var V;const{locale:P,setLocale:A,t:p}=It(),[E,I]=i.useState(!1),[y,w]=i.useState(!1),[d,S]=i.useState(!1),[W,K]=i.useState(!1),[oe,ne]=i.useState(!1),le=[{value:"zh",label:p("langZh")},{value:"en",label:p("langEn")}],L=t.ready?p("connected"):t.status==="closed"?p("reconnecting"):p("connecting"),F=t.ready?"ok":"busy",H=()=>{var Q,de;if(!t.ready)return;const T=p("updateTabTitle"),b={name:T,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},U=t.terminals.find(fe=>fe.title===T);U?(n.restart(U.id),s({type:"run_command",terminalId:U.id,conversationId:U.conversationId,command:b,cols:80,rows:24})):n.create({id:_e(),conversationId:t.activeConversationId||((Q=t.state)==null?void 0:Q.conversationId)||"",title:T,cwd:((de=t.state)==null?void 0:de.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:b}),K(!1),ne(!1),a("terminal")},$=()=>{var T,b;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dd-update",children:[e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:p("currentVersion")}),e.jsxs("b",{children:["v",((T=t.update)==null?void 0:T.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:p("latestVersion")}),e.jsx("b",{children:t.update===null?p("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:p("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:p("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:p("updateAvailable",{version:t.update.latest})}),((b=t.update)==null?void 0:b.latestPublishedAt)&&Date.now()-new Date(t.update.latestPublishedAt).getTime()<30*6e4&&e.jsx("div",{className:"dd-note warn",children:p("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:p("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?p("checkingUpdate"):p("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:H,children:p("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:p("openHistory"),onClick:()=>r("left"),children:e.jsx(Cn,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${F}`,title:L}),e.jsx("span",{className:"conn-label",children:L})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":p("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":o==="chat",className:o==="chat"?"active":"",onClick:()=>a("chat"),children:[e.jsx(at,{}),e.jsx("span",{children:p("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":o==="terminal",className:o==="terminal"?"active":"",onClick:()=>a("terminal"),children:[e.jsx(Je,{}),e.jsx("span",{children:p("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":o==="git",className:o==="git"?"active":"",onClick:()=>a("git"),children:[e.jsx(Xe,{}),e.jsx("span",{children:p("scmTab")})]}),c.map(T=>{const b=T.error?`${T.name}: ${T.error}`:T.description?`${T.name} — ${T.description}`:T.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":o===`plugin:${T.id}`,className:`plugin-tab${o===`plugin:${T.id}`?" active":""}${T.error?" broken":""}`,title:b,onClick:()=>a(`plugin:${T.id}`),children:[T.icon?e.jsx("span",{"aria-hidden":!0,children:T.icon}):e.jsx(Ms,{}),e.jsx("span",{children:T.name})]},T.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:p("searchGlobalTip"),onClick:f,children:[e.jsx(nt,{}),e.jsx("span",{className:"chip-sub",children:p("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":p("bgTasksTip"),onClick:m,children:[e.jsx(it,{}),e.jsx("span",{className:"chip-sub",children:p("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(Bs,{state:t.state?{model:t.state.model,thinkingLevel:t.state.thinkingLevel,availableThinkingLevels:t.state.availableThinkingLevels}:null,models:t.models,modelsLoading:t.modelsLoading,send:s,onManageModels:l}),e.jsxs("button",{type:"button",className:"chip",title:p("settingsTitle"),onClick:u,children:[e.jsx(st,{}),e.jsx("span",{className:"chip-sub",children:p("settings")})]}),e.jsx(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ss,{}),e.jsx("span",{className:"chip-sub",children:p("sound")})]}),open:E,onOpenChange:I,children:e.jsx(Xt,{settings:h,onChange:k,onPreview:M})}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ln,{}),e.jsx("span",{className:"chip-sub",children:P==="zh"?p("langZh"):"EN"})]}),open:y,onOpenChange:w,children:[e.jsx("div",{className:"dd-header",children:p("language")}),le.map(T=>e.jsx(Ne,{active:P===T.value,onClick:()=>{A(T.value),w(!1)},children:T.label},T.value))]}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(yn,{}),e.jsx("span",{className:"chip-sub",children:p("theme")})]}),open:d,onOpenChange:S,children:[e.jsx("div",{className:"dd-header",children:p("theme")}),e.jsx(Ne,{active:D===null,onClick:()=>{R(null),S(!1)},children:p("themeDefault")}),N.map(T=>e.jsx(Ne,{active:D===T.id,onClick:()=>{R(T.id),S(!1)},children:T.name},T.id))]}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Mt,{}),e.jsxs("span",{className:"chip-sub",children:["v",((V=t.update)==null?void 0:V.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:p("updateAvailable",{version:t.update.latest??""})})]}),open:W,onOpenChange:T=>{K(T),T&&s({type:"check_update"})},fit:!0,children:[e.jsx("div",{className:"dd-header",children:p("update")}),$()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:p("githubRepo"),children:e.jsx(Qt,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":p("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(Ue,{}),e.jsx("span",{children:p("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(wn,{}),e.jsx("span",{className:"chip-sub",children:p("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:oe,onOpenChange:T=>{ne(T),T&&s({type:"check_update"})},children:[e.jsx("div",{className:"dd-header",children:p("sound")}),e.jsx("div",{className:"dd-header",children:p("settings")}),e.jsxs(Ne,{onClick:()=>{ne(!1),u()},children:[e.jsx(st,{})," ",p("settingsTitle")]}),e.jsxs(Ne,{onClick:()=>{ne(!1),f()},children:[e.jsx(nt,{})," ",p("searchGlobal")]}),e.jsxs(Ne,{onClick:()=>{ne(!1),m()},children:[e.jsx(it,{})," ",p("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(Xt,{settings:h,onChange:k,onPreview:M}),e.jsx("div",{className:"dd-header",children:p("language")}),le.map(T=>e.jsx(Ne,{active:P===T.value,onClick:()=>A(T.value),children:T.label},T.value)),e.jsx("div",{className:"dd-header",children:p("theme")}),e.jsx(Ne,{active:D===null,onClick:()=>{R(null),ne(!1)},children:p("themeDefault")}),N.map(T=>e.jsx(Ne,{active:D===T.id,onClick:()=>{R(T.id),ne(!1)},children:T.name},T.id)),e.jsx("div",{className:"dd-header",children:p("update")}),$(),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(Qt,{})," ",p("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:p("openFiles"),onClick:()=>r("right"),children:e.jsx(qe,{})})]})]})}function Zt(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()}`}const Vn=i.memo(function({ready:s,status:n,cwd:o,sessionFile:c,conversations:a,sessions:r,projects:l,activeConversationId:u,send:m,active:f}){const h=he(),k=c,M=o,[N,D]=i.useState(null);i.useEffect(()=>{!f||!s||n!=="open"||o&&(m({type:"list_sessions"}),m({type:"list_projects"}))},[f,s,n,o,m]);const R=p=>{const E=p.name||p.firstMessage.trim();return E.length>0?E:h("emptyChat")},P=p=>p.split(/[\\/]/).pop()||p,A=(p,E,I,y)=>{const w=N===p;return e.jsx("button",{type:"button",className:`lp-del ${w?"confirm":""}`,title:w?I:E,onClick:d=>{d.stopPropagation(),w?(D(null),y()):D(p)},children:w?e.jsx(ut,{}):e.jsx($e,{})})};return e.jsxs("aside",{className:"panel panel-left",children:[l.length>0&&e.jsxs("div",{className:"panel-projects",children:[e.jsx("div",{className:"panel-section-title",children:h("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:l.map(p=>{const E=M===p.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>D(I=>I===`proj:${p.path}`?null:I),children:[e.jsxs("button",{type:"button",className:`project-item ${E?"active":""}`,title:p.path,onClick:()=>{E||m({type:"set_cwd",path:p.path})},children:[e.jsx(qe,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:P(p.path)}),e.jsx("span",{className:"project-path",children:p.path})]}),e.jsx("span",{className:"project-time",children:Zt(p.lastUsed)})]}),A(`proj:${p.path}`,h("deleteProject"),h("deleteProjectConfirm"),()=>m({type:"remove_project",path:p.path}))]},p.path)})})]}),a.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:h("runningConversations")}),a.map(p=>{const E=u===p.id;return e.jsxs("button",{type:"button",className:`session-item ${E?"active":""}`,title:p.title,onClick:()=>{E||m({type:"switch_conversation",id:p.id})},children:[e.jsx(at,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:p.title}),e.jsx("span",{className:"session-sub",children:E?h("current"):h("messageCount",{n:p.messageCount})})]}),p.isStreaming&&e.jsx("span",{className:"conv-streaming",title:h("streaming")})]},p.id)}),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:h("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[r.length===0&&e.jsx("div",{className:"panel-empty",children:h("noHistory")}),r.map(p=>{const E=k===p.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>D(I=>I===`sess:${p.path}`?null:I),children:[e.jsxs("button",{type:"button",className:`session-item ${E?"active":""}`,title:p.path,onClick:()=>{E||m({type:"switch_session",path:p.path})},children:[e.jsx(at,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:R(p)}),e.jsxs("span",{className:"session-sub",children:[E?h("current"):h("messageCount",{n:p.messageCount}),p.source==="tui"&&e.jsx("span",{className:"session-src",title:h("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:Zt(p.modified)})]}),A(`sess:${p.path}`,h("deleteSession"),h("deleteSessionConfirm"),()=>m({type:"delete_session",path:p.path}))]},p.path)})]})]})]})}),Ds="pi-web-ui:token";function Gn(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem(Ds,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function Jn(){try{return localStorage.getItem(Ds)??""}catch{return""}}function mt(t){const s=Jn();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}function Qn(t,s){const n=s.assistantMessageEvent,o=t.stats.tokens,c=s.usage!==null?{...o,...s.usage}:o,a=c===o?t.stats:{...t.stats,tokens:c};if(n.type!=="text_delta"&&n.type!=="thinking_delta")return a===t.stats?t:{...t,stats:a};const r=n.delta??"";if(!r)return a===t.stats?t:{...t,stats:a};const l=t.streamingMessage??null,u=l&&l.id===s.messageId?l:{id:s.messageId,content:[]},m=[...u.content],f=n.type==="thinking_delta"?"thinking":"text",h=n.contentIndex??m.length-1;return h>=0&&h<m.length&&m[h].type===f?m[h]=f==="thinking"?{type:"thinking",thinking:(m[h].thinking??"")+r}:{type:"text",text:(m[h].text??"")+r}:m.push(f==="thinking"?{type:"thinking",thinking:r}:{type:"text",text:r}),{...t,stats:a,streamingMessage:{...u,id:s.messageId,content:m}}}const wt="pi-web-ui:plugin-data";function Yn(t,s){window.dispatchEvent(new CustomEvent(wt,{detail:{pluginId:t,payload:s}}))}function Xn(t){const s=n=>{const o=n.detail;t(o.pluginId,o.payload)};return window.addEventListener(wt,s),()=>window.removeEventListener(wt,s)}const We=new Map,Nt=new Set,Oe=new Set;let es=-1;function $s(){return[...We.values()]}function Zn(){const t=$s();for(const s of Nt)s(t)}function ea(t){return Nt.add(t),t($s()),()=>Nt.delete(t)}async function ta(t,s){s!==es&&(es=s,We.clear(),Oe.clear());const n=new Set(t.map(o=>o.id));for(const o of[...We.keys()])n.has(o)||We.delete(o);for(const o of[...Oe])n.has(o)||Oe.delete(o);await Promise.all(t.filter(o=>o.hasClient&&!o.error&&!We.has(o.id)&&!Oe.has(o.id)).map(async o=>{try{const a=(await ws(()=>import(`/plugins/${encodeURIComponent(o.id)}/client/entry.mjs?e=${s}`),[])).default;a&&typeof a.mount=="function"?We.set(o.id,{info:o,module:a}):(Oe.add(o.id),console.error(`[plugin:${o.id}] entry.mjs 缺少 default.mount`))}catch(c){Oe.add(o.id),console.error(`[plugin:${o.id}] 客户端加载失败:`,c)}})),Zn()}function sa(t,s){return{pluginId:t,send:n=>s({type:"plugin_message",pluginId:t,payload:n}),onData:n=>Xn((o,c)=>{o===t&&n(c)})}}const na=9,gt=2e5,aa=2e5,ia={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 ra(){const t=new Map,s=new Map,n=(o,c)=>`${o}:${c}`;return{write(o,c,a){const r=n(o,c),l=t.get(r);if(l&&l.size>0){for(const f of l)try{f.write(a)}catch{}return}const u=s.get(r)??"",m=u.length+a.length>aa?a:u+a;s.set(r,m)},register(o,c,a){const r=n(o,c);let l=t.get(r);l||(l=new Set,t.set(r,l)),l.add(a);const u=s.get(r);if(u){try{a.write(u)}catch{}s.delete(r)}return()=>{const m=t.get(r);m&&(m.delete(a),m.size===0&&t.delete(r)),s.delete(r)}},clear(){t.clear(),s.clear()}}}function ts(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 o=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),o=!0);return o?new Map(t):t}function ss(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 o=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),o=!0);return o?new Map(t):t}function oa(t,s){var n,o,c,a;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,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==na};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:ts(t.liveOutputs,s.state),toolStatuses:ss(t.toolStatuses,s.state)};case"snapshot_delta":{const r=t.state,l=s.msg;if(!r||r.conversationId!==l.conversationId||r.rev!==l.baseRev)return t;const u={...r,...l.state,messages:l.appended.length>0?[...r.messages,...l.appended]:r.messages};return{...t,ready:!0,state:u,activeConversationId:u.conversationId,liveOutputs:ts(t.liveOutputs,u),toolStatuses:ss(t.toolStatuses,u)}}case"tool_delta":{const r=t.liveOutputs.get(s.toolCallId),l=((r==null?void 0:r.text)??"")+s.delta,u=l.length>gt?`…[前 ${l.length-gt} 字符已省略]…
3
- `+l.slice(l.length-gt):l,m=new Map(t.liveOutputs);return m.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:m}}case"message_delta":{const r=t.state;return!r||r.conversationId!==s.msg.conversationId?t:{...t,state:Qn(r,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(r=>r.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"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"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"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};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"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(r=>r.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(n=t.state)!=null&&n.conversationId)&&s.conversationId!==(t.activeConversationId||((o=t.state)==null?void 0:o.conversationId))?t:{...t,terminals:t.terminals.map(r=>r.id===s.terminalId?{...r,running:!1,exitCode:s.exitCode}:r)};case"terminal_restart":return{...t,terminals:t.terminals.map(r=>r.id===s.terminalId?{...r,running:!0,exitCode:null}:r)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(c=t.state)!=null&&c.conversationId)&&s.conversationId!==(t.activeConversationId||((a=t.state)==null?void 0:a.conversationId))?t:{...t,terminals:s.terminals.map(r=>{var l;return{...r,conversationId:s.conversationId??((l=t.state)==null?void 0:l.conversationId)??""}})};default:return t}}const ns="pi-web-client-id";let ft=null;function Lt(){if(ft)return ft;let t=null;try{t=sessionStorage.getItem(ns),t||(t=_e(),sessionStorage.setItem(ns,t))}catch{t=t??_e()}return ft=t,t}function la(){const t=location.protocol==="https:"?"wss:":"ws:";return mt(`${t}//${location.host}/ws`)}function ca(){const[t,s]=i.useReducer(oa,{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:[],installResult:null,pathCompletions:[],update:null,widgets:[],statuses:[],dialog:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],goal:ia,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,protocolMismatch:!1}),n=i.useRef(null),o=i.useRef(ra()),c=i.useRef(0),a=i.useRef(null),r=i.useRef(!0),l=i.useRef(0),u=i.useRef(0),m=i.useRef(new Map),f=i.useRef(null),h=()=>{f.current||(f.current=setTimeout(()=>{f.current=null;const y=n.current;y&&y.readyState===WebSocket.OPEN&&y.send(JSON.stringify({type:"get_state"}))},300))},k=(y,w)=>{var W;const d=m.current,S=d.get(y);if(S!==void 0&&w!==S+1){const K=I.current.chat,oe=K.activeConversationId||((W=K.state)==null?void 0:W.conversationId);y===oe&&h()}d.set(y,w)},M=i.useCallback((y,w)=>{const d=++u.current;s({type:"notice",notice:{id:d,level:y,text:w}})},[]),N=i.useCallback(y=>{const w=n.current;return w&&w.readyState===WebSocket.OPEN?(w.send(JSON.stringify(y)),!0):!1},[]),D=i.useCallback(()=>{if(!r.current)return;s({type:"status",status:"connecting"});const y=new WebSocket(la());n.current=y,y.onopen=()=>{n.current===y&&(s({type:"status",status:"open"}),c.current=0,l.current=Date.now(),y.send(JSON.stringify({type:"hello",clientId:Lt()})))},y.onmessage=w=>{if(n.current!==y)return;l.current=Date.now();let d;try{d=JSON.parse(w.data)}catch{return}switch(d.type){case"ready":s({type:"ready",serverVersion:d.serverVersion,protocolVersion:d.protocolVersion}),y.send(JSON.stringify({type:"get_state"})),y.send(JSON.stringify({type:"list_files"})),y.send(JSON.stringify({type:"list_models"})),y.send(JSON.stringify({type:"list_commands"})),y.send(JSON.stringify({type:"get_commands"})),y.send(JSON.stringify({type:"check_update"}));break;case"snapshot":m.current=new Map,s({type:"snapshot",state:d.state});break;case"snapshot_delta":{const S=I.current.chat.state;(!S||S.conversationId!==d.conversationId||S.rev!==d.baseRev)&&h(),s({type:"snapshot_delta",msg:d});break}case"tool_delta":k(d.conversationId,d.seq),s({type:"tool_delta",toolCallId:d.toolCallId,toolName:d.toolName,delta:d.delta});break;case"tool_status":s({type:"tool_status",status:d});break;case"message_delta":{k(d.conversationId,d.seq),s({type:"message_delta",msg:d});break}case"notice":{const S=++u.current;s({type:"notice",notice:{id:S,level:d.level,text:d.text}});break}case"sessions":s({type:"sessions",sessions:d.sessions});break;case"conversations":s({type:"conversations",conversations:d.conversations,activeId:d.activeId});break;case"projects":s({type:"projects",projects:d.projects});break;case"files":s({type:"files",files:d});break;case"file_changed":s({type:"file_changed",path:d.path});break;case"file_content":s({type:"file_content",content:d});break;case"models":s({type:"models",models:d.models,loading:!1});break;case"models_config":s({type:"models_config",providers:d.providers});break;case"providers_status":s({type:"providers_status",providers:d.providers});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:d.reqId,ok:d.ok,models:d.models,error:d.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:d.reqId,ok:d.ok,added:d.added,total:d.total,error:d.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:d.reqId,ok:d.ok,config:d.config,error:d.error}});break;case"scm_data":s({type:"scm_data",data:d});break;case"search_files_result":s({type:"file_search_result",result:{reqId:d.reqId,ok:d.ok,results:d.results,truncated:d.truncated}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:d});break;case"path_completions":s({type:"path_completions",completions:d.completions});break;case"update_status":s({type:"update_status",status:d});break;case"widgets":s({type:"widgets",widgets:d.widgets});break;case"statuses":s({type:"statuses",statuses:d.statuses});break;case"dialog":s({type:"dialog",dialog:{id:d.id,kind:d.kind,title:d.title,args:d.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"terminal_output":o.current.write(d.conversationId??I.current.chat.activeConversationId,d.terminalId,d.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:d.conversationId,terminalId:d.terminalId,exitCode:d.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:d.conversationId,terminals:d.terminals});break;case"commands":s({type:"commands",commands:d.commands,path:d.path});break;case"slash_commands":s({type:"slash_commands",commands:d.commands});break;case"goal_status":s({type:"goal_status",status:d.status});break;case"settings_state":s({type:"settings",settings:d.settings});break;case"bg_servers":s({type:"bg_servers",servers:d.servers});break;case"plugins":s({type:"plugins",plugins:d.plugins,epoch:d.epoch});break;case"plugin_data":Yn(d.pluginId,d.payload);break}},y.onclose=()=>{if(n.current===y&&(n.current=null),o.current.clear(),!r.current||n.current&&n.current!==y)return;s({type:"status",status:"closed"});const w=Math.min(1e3*2**c.current,1e4);c.current+=1,a.current=setTimeout(()=>{a.current=null,D()},w)},y.onerror=()=>{}},[]);i.useEffect(()=>{r.current=!0,D();const y=setInterval(()=>{if(!r.current)return;const w=n.current;w&&w.readyState===WebSocket.OPEN&&Date.now()-l.current>3e4&&w.close()},5e3);return()=>{var w;r.current=!1,clearInterval(y),a.current&&(clearTimeout(a.current),a.current=null),(w=n.current)==null||w.close(),n.current=null}},[D]);const R=i.useCallback(y=>s({type:"dismiss_notice",id:y}),[]),P=i.useCallback(y=>s({type:"terminal_add",meta:y}),[]),A=i.useCallback(y=>s({type:"terminal_remove",id:y}),[]),p=i.useCallback(y=>s({type:"terminal_restart",terminalId:y}),[]),E=i.useCallback((y,w,d)=>o.current.register(y,w,d),[]),I=i.useRef({chat:t,send:N,pushNotice:M,dismissNotice:R,terminal:{create:P,close:A,register:E,restart:p}});return I.current={chat:t,send:N,pushNotice:M,dismissNotice:R,terminal:{create:P,close:A,register:E,restart:p}},I.current}const da=200*1024*1024,ua=/windows/i.test(navigator.userAgent),ma=/[<>:"/\\|?*\u0000-\u001f]/g,pa=/[. ]+$/,ha=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function ga(t){const s=t.replace(ma,"_").replace(pa,"");return s?ha.test(s)?`_${s}`:s:"_"}function as(t,s=!0){const n=new URLSearchParams({clientId:Lt(),path:t,...s?{download:"1"}:{}});return mt(`/api/file?${n}`)}async function fa(t,s){const n=ua?ga(s):s;try{const o=await fetch(as(t));if(!o.ok)return{ok:!1,cancelled:!1,error:await o.text().catch(()=>"")||(o.status===404?"文件不存在":`HTTP ${o.status}`)};if(Number(o.headers.get("content-length")??"0")>da)return window.location.assign(as(t)),{ok:!0};const a=await o.blob();return window.showSaveFilePicker&&window.isSecureContext?xa(a,n):Ct(a,n)}catch(o){return{ok:!1,cancelled:!1,error:o instanceof Error?o.message:String(o)}}}async function xa(t,s){let n;const o=window.showSaveFilePicker;if(!o)return Ct(t,s);try{n=await o({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:Ct(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 Ct(t,s){const n=URL.createObjectURL(t),o=document.createElement("a");return o.href=n,o.download=s,document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}const va=i.memo(function({files:s,fileChanged:n,widgets:o,cwd:c,send:a,onAttach:r,onPreview:l,onNotice:u}){const m=he(),[f,h]=i.useState(""),[k,M]=i.useState(null),[N,D]=i.useState(!1),R=1e4,P=i.useRef(0),A=i.useRef(void 0),p=i.useCallback((w,d)=>{const S=++P.current;h(w),d!=null&&d.silent||D(!0),a({type:"list_files",path:w===""?void 0:w})||P.current===S&&D(!1)},[a]);i.useEffect(()=>{s&&s.path===f&&D(!1)},[s,f]),i.useEffect(()=>{if(c!==A.current){A.current=c,p("",{silent:!0});return}const w=setInterval(()=>{document.visibilityState!=="hidden"&&p(f,{silent:!0})},R);return()=>clearInterval(w)},[c,f,p]),i.useEffect(()=>{n&&n.path===f&&p(f,{silent:!0})},[n,f,p]);const E=w=>p(w),I=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&p(s.parent)},y=f.split("/").filter(Boolean);return e.jsxs("aside",{className:"panel panel-right",children:[e.jsxs("div",{className:"panel-crumbs",children:[e.jsx("button",{type:"button",className:`crumb ${f===""?"active":""}`,onClick:()=>p(""),children:m("rootDir")}),y.map((w,d)=>{const S=y.slice(0,d+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(dt,{}),e.jsx("button",{type:"button",className:`crumb ${S===f?"active":""}`,onClick:()=>p(S),children:w})]},S)})]}),e.jsxs("div",{className:"panel-body",children:[N&&e.jsx("div",{className:"panel-empty",children:m("loading")}),!N&&s&&s.path===f&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:I,children:[e.jsx(qe,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(w=>w.type==="dir"?e.jsxs("div",{className:"file-item dir",children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>E(w.path),children:[e.jsx(qe,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:w.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":m("linkFolderTip"),onClick:()=>r(w.path,w.name,"reference",!0),children:e.jsx(jt,{})})]},w.path):e.jsxs("div",{className:"file-item file",children:[e.jsxs("button",{type:"button",className:"file-name",title:`${w.path} — ${m("previewFile")}`,onClick:()=>l(w.path,w.name),children:[e.jsx(Ts,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:w.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":m("downloadFile"),onClick:()=>{fa(w.path,w.name).then(d=>{d.ok||d.cancelled||u("error",m("downloadFailed",{error:d.error}))})},children:e.jsx(Mt,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":m("attachInlineTip"),onClick:()=>r(w.path,w.name,"inline"),children:e.jsx(Ue,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":m("referenceTip"),onClick:()=>r(w.path,w.name,"reference"),children:e.jsx(jt,{})})]},w.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:m("filesTruncated")})]}),!N&&!s&&e.jsx("div",{className:"panel-empty",children:m("noFiles")})]}),o.filter(w=>w.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:o.filter(w=>w.lines.length>0).map(w=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:m("widgetExpand"),onClick:()=>M(w.key),children:[e.jsx("span",{children:w.key}),e.jsx(Tn,{})]}),e.jsx("pre",{className:"widget-lines",children:w.lines.join(`
4
- `)})]},w.key))}),k&&(()=>{const w=o.find(d=>d.key===k);return w?e.jsx("div",{className:"modal-backdrop",onClick:()=>M(null),children:e.jsxs("div",{className:"widget-expand",onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"widget-expand-head",children:[e.jsx("span",{className:"widget-expand-title",children:w.key}),e.jsx("button",{type:"button",className:"btn",title:m("close"),onClick:()=>M(null),children:e.jsx(Ce,{})})]}),e.jsx("pre",{className:"widget-expand-lines",children:w.lines.join(`
5
- `)})]})}):null})()]})});var is=ks();const _s=i.memo(function({text:s}){const n=he(),[o,c]=i.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:o?e.jsx(ut,{}):e.jsx(Rt,{})}):null}),Fs=[nn],As=[[sn,{detect:!0,ignoreMissing:!0}]];function Os({text:t}){return e.jsx(js,{remarkPlugins:Fs,rehypePlugins:As,components:{pre:ya},children:t})}const pt=i.memo(function({text:s}){return e.jsx("div",{className:"md",children:e.jsx(Os,{text:s})})});function ya({children:t,...s}){return e.jsxs("div",{className:"codeblock",children:[e.jsx(_s,{text:St(t)}),e.jsx("pre",{...s,children:t})]})}function St(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(St).join("");if(t&&typeof t=="object"&&"props"in t){const s=t.props;return St(s==null?void 0:s.children)}return""}const ba=/^\s{0,3}(`{3,}|~{3,})/,ja=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function xt(t){return t.trim()===""}function rs(t){const s=ba.exec(t);return s?s[1]:null}function ka(t){const s=t.split(`
6
- `),n=[];let o=[],c=null;for(let a=0;a<s.length;a++){const r=s[a];if(c!==null){const u=rs(r);u&&u[0]===c[0]&&u.length>=c.length&&(c=null),o.push(r);continue}const l=rs(r);if(l&&!xt(r)){c=l,o.push(r);continue}if(xt(r)){let u=a;for(;u<s.length&&xt(s[u]);)u++;if(!(u<s.length&&ja.test(s[u]))&&o.length>0){n.push(o.join(`
7
- `)),o=[];continue}o.push(r);continue}o.push(r)}return{frozen:n,active:o.join(`
8
- `),inFence:c!==null}}const wa=i.memo(function({text:s}){return e.jsx(js,{remarkPlugins:Fs,rehypePlugins:As,children:s})}),os=200;function Na({text:t,inFence:s}){const[n,o]=i.useState(t),c=i.useRef(0),a=i.useRef(null);return i.useEffect(()=>{if(s)return;const r=Date.now()-c.current,l=()=>{c.current=Date.now(),o(t)};if(r>=os){l();return}return a.current=setTimeout(l,os-r),()=>{a.current&&clearTimeout(a.current)}},[t,s]),s?e.jsx("div",{className:"codeblock",children:e.jsx("pre",{children:e.jsx("code",{children:t})})}):e.jsx(Os,{text:n})}const Ca=i.memo(function({text:s}){const{frozen:n,active:o,inFence:c}=i.useMemo(()=>ka(s),[s]);return e.jsxs("div",{className:"md",children:[n.map((a,r)=>e.jsx(wa,{text:a},r)),o.length>0&&e.jsx(Na,{text:o,inFence:c},n.length)]})});function Sa({thinking:t,streaming:s}){const n=he(),[o,c]=i.useState(s),a=t.split(`
9
- `)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${o?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>c(r=>!r),children:[o?e.jsx(Fe,{}):e.jsx(dt,{}),e.jsx(lt,{className:"thinking-icon"}),e.jsx("span",{className:"thinking-label",children:s?e.jsxs("span",{className:"thinking-live-label",children:[n("thinkingNow"),e.jsx("span",{className:"dots"})]}):o?n("thinking"):n("thinkingPreview",{preview:a})})]}),o&&e.jsx("div",{className:"thinking-body",children:t})]})}const Ta={bash:"$",read:"📄",write:"✍️",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function Ea(t){return Ta[t]??"🛠"}const Ma=i.memo(function({block:s,view:n,onKillBash:o}){var E,I,y,w;const c=he(),[a,r]=i.useState(!0),[l,u]=i.useState(!1),m=!n.result&&n.streaming&&!n.status,f=s.name==="bash"&&m,h=n.result!==void 0,k=!n.result&&!!n.status,M=((E=n.result)==null?void 0:E.isError)??((I=n.status)==null?void 0:I.isError)??!1,N=n.result?n.result.content.map(d=>d.type==="text"?d.text:"").join(""):n.liveOutput??"",D=M?"err":h?"ok":m||k?"run":"idle";let R=c(M?"error":h?"done":m?"running":k?"toolDoneWaitingModel":"toolQueued");const P=k&&((y=n.status)==null?void 0:y.durationMs)!==void 0?Ia(n.status.durationMs):"";k&&P&&(R=`${R} · ${P}`);const A=k&&((w=n.status)==null?void 0:w.exitCode)!==void 0?`exit ${n.status.exitCode}`:"",p=()=>{s.argumentsText&&(navigator.clipboard.writeText(s.argumentsText),u(!0),setTimeout(()=>u(!1),1200))};return e.jsxs("div",{className:`toolcall ${D}`,children:[e.jsxs("div",{className:"toolcall-head",children:[e.jsx("span",{className:"toolcall-icon",children:Ea(s.name)}),e.jsx("span",{className:"toolcall-name",children:s.name}),e.jsxs("span",{className:"toolcall-status",children:[R,A&&e.jsx("em",{className:"toolcall-exit",children:A})]}),e.jsx("span",{className:"toolcall-spacer"}),f&&o&&e.jsxs("button",{type:"button",className:"toolcall-kill",title:c("stopBashTip"),onClick:o,children:[e.jsx(tt,{}),e.jsx("span",{children:c("stopBash")})]}),e.jsx("button",{type:"button",className:"toolcall-copy",title:c("copyArgs"),onClick:p,children:l?e.jsx($n,{}):e.jsx(Rt,{})}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>r(d=>!d),children:a?e.jsx(Fe,{}):e.jsx(dt,{})})]}),a&&e.jsxs("div",{className:"toolcall-body",children:[s.argumentsText&&e.jsx("div",{className:"toolcall-args",children:s.name==="bash"&&s.argumentsText.startsWith("{")?e.jsx(Ra,{args:s.argumentsText}):e.jsx("pre",{children:s.argumentsText})}),N.length>0&&e.jsxs("div",{className:"toolcall-output",children:[e.jsxs("div",{className:"toolcall-output-label",children:[c(M?"errorOutput":"output"),(m||k)&&e.jsx("span",{className:"cursor"})]}),e.jsx("pre",{children:N})]}),m&&N.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",c("waitingOutput")]}),k&&N.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",c("waitingModel")]})]})]})});function Ra({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(Je,{className:"termline-icon"}),e.jsx("code",{children:s.command}),typeof s.timeout=="number"&&e.jsxs("span",{className:"termline-timeout",children:["⏱ ",s.timeout,"s"]})]})}function Ia(t){if(t===void 0)return"";const s=t/1e3;if(s<60)return`${s.toFixed(1)}s`;const n=Math.floor(s/60),o=Math.round(s%60);return`${n}m ${String(o).padStart(2,"0")}s`}const La=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function Pt(t){var n;const s=t.match(La);return s?{name:s[1],location:s[2],content:s[3],userMessage:((n=s[4])==null?void 0:n.trim())||void 0}:null}const Pa=1568,Ba=2*1024*1024;function Pe(t){return t.startsWith("image/")&&t!=="image/svg+xml"&&t!=="image/svg"}async function Hs(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,Pa/Math.max(s.width,s.height)),o=Math.max(1,Math.round(s.width*n)),c=Math.max(1,Math.round(s.height*n)),a=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 r=null;for(const[l,u]of a){const m=document.createElement("canvas");m.width=o,m.height=c;const f=m.getContext("2d");if(!f)continue;l!=="image/png"&&(f.fillStyle="#ffffff",f.fillRect(0,0,o,c)),f.drawImage(s,0,0,o,c);const h=m.toDataURL(l,u),k=h.match(/^data:([^;]+);base64,/),M=k?k[1]:l,N=h.replace(/^data:[^;]*;base64,/,""),D=Math.floor(N.length*3/4);if(r={data:N,mimeType:M,name:t.name,size:D},D<=Ba)return r}return r}finally{s.close()}}function Ge(t){return t.type==="text"&&typeof t.text=="string"?t:null}function Ws(t){return t.type==="thinking"&&typeof t.thinking=="string"?t:null}function Us(t){return t.type==="toolCall"&&typeof t.id=="string"&&typeof t.name=="string"?t:null}function rt(t){return t.type==="image"&&typeof t.dataUrl=="string"?t:null}function qs(t){return t.type==="bash"&&typeof t.command=="string"?t:null}const ls=i.memo(function({message:s,toolResults:n,liveOutputs:o,toolStatuses:c,streaming:a,isLast:r,onEdit:l,onKillBash:u,onCollapse:m,questionImages:f,qnIndex:h,qnActive:k,onJump:M}){const N=he(),[D,R]=i.useState(!1),[P,A]=i.useState(""),[p,E]=i.useState([]),[I,y]=i.useState(!1);if(s.role==="toolResult")return null;const w=s.role==="custom"&&s.customType==="file",d=s.content.map($=>{var V;return((V=Ge($))==null?void 0:V.text)??""}).filter(Boolean).join(`
10
- `),S=s.role==="user"?Pt(d):null,W=S?S.userMessage??`skill:${S.name}`:d.split(`
11
- `).join(" ").trim(),K=a&&r&&s.content.length===0,oe=s.role==="user"&&!a&&!K&&!!l,ne=async $=>{const V=[];for(const T of $){if(!Pe(T.type))continue;const b=await Hs(T);b&&V.push({path:"",imageData:b.data,mimeType:b.mimeType,name:b.name})}V.length>0&&E(T=>[...T,...V])},le=()=>{A(S?`/skill:${S.name}${S.userMessage?` ${S.userMessage}`:""}`:s.content.map($=>{var V;return((V=Ge($))==null?void 0:V.text)??""}).filter(Boolean).join(`
12
- `)),E(f??[]),R(!0)},L=()=>{const $=P.trim();$&&(l==null||l(s.id,$,p.length>0?p:void 0),R(!1))},F=s.role==="custom"&&(s.customType==="goal-review"||s.customType==="goal-wizard"),H=s.role==="custom"&&s.customType==="goal-wizard";return e.jsxs("div",{className:`msg msg-${s.role}${F?" 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"?H?N("goalWizardCard"):F?N("goalBarTitle"):s.customType==="file"?N("attachment"):`${N("plugin")} · ${s.customType??N("unknown")}`:zs(s.role,N)}),s.model&&e.jsx("span",{className:"msg-model",children:s.model}),s.timestamp&&e.jsx("span",{className:"msg-time",children:Fa(s.timestamp)}),m&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:N("collapseMsg"),onClick:()=>m(s.id),children:[e.jsx(ct,{})," ",N("collapseMsg")]}),h!==void 0&&M&&e.jsxs("button",{type:"button",className:`qn-tag ${k?"active":""}`,title:`${h+1}. ${W}`,"aria-label":`${h+1}. ${W}`,onClick:()=>M(s.id),children:[e.jsx("span",{className:"qn-tag-bar"}),e.jsx("span",{className:"qn-tag-idx",children:h+1})]})]}),e.jsx("div",{className:"msg-body",children:D?e.jsxs("div",{className:`msg-editor${I?" drag-over":""}`,onDragOver:$=>{$.preventDefault(),$.stopPropagation(),y(!0)},onDragLeave:$=>{$.currentTarget.contains($.relatedTarget)||y(!1)},onDrop:$=>{var V;$.preventDefault(),$.stopPropagation(),y(!1),ne(Array.from(((V=$.dataTransfer)==null?void 0:V.files)??[]))},children:[p.length>0&&e.jsx("div",{className:"msg-editor-images",children:p.map(($,V)=>e.jsxs("span",{className:"msg-editor-img",children:[e.jsx("img",{src:`data:${$.mimeType??"image/png"};base64,${$.imageData}`,alt:$.name}),e.jsx("button",{type:"button",className:"msg-editor-img-remove",title:N("removeAttachment"),onClick:()=>E(T=>T.filter((b,U)=>U!==V)),children:e.jsx(Ce,{})})]},`${$.name}-${V}`))}),e.jsx("textarea",{className:"msg-editor-input",value:P,autoFocus:!0,placeholder:N("editPlaceholder"),rows:Math.max(2,Math.min(10,P.split(`
13
- `).length+1)),onChange:$=>A($.target.value),onPaste:$=>{var T;const V=[];for(const b of((T=$.clipboardData)==null?void 0:T.items)??[])if(b.kind==="file"&&Pe(b.type)){const U=b.getAsFile();U&&V.push(U)}V.length!==0&&($.preventDefault(),ne(V))},onKeyDown:$=>{$.key==="Enter"&&($.metaKey||$.ctrlKey)?($.preventDefault(),L()):$.key==="Escape"&&R(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(In,{})," ",N("editImageHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>R(!1),children:N("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!P.trim(),title:N("reaskFromHere"),onClick:L,children:[e.jsx(kt,{})," ",N("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),w?e.jsx(Da,{message:s}):S?e.jsxs(e.Fragment,{children:[e.jsx(_a,{block:S}),S.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(pt,{text:S.userMessage})}),s.content.map(($,V)=>$.type==="text"?null:e.jsx(ds,{block:$,toolResults:n,liveOutputs:o,toolStatuses:c,streaming:a,isLast:r,onKillBash:u},`${s.id}-${V}`))]}):s.content.map(($,V)=>e.jsx(ds,{block:$,toolResults:n,liveOutputs:o,toolStatuses:c,streaming:a,isLast:r,onKillBash:u},`${s.id}-${V}`)),K&&e.jsxs("div",{className:"thinking-wait",children:[N("thinkingWait"),e.jsx("span",{className:"dot"})]}),a&&r&&!K&&e.jsx("span",{className:"stream-cursor"})]})}),oe&&!D&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:N("editReaskTip"),onClick:le,children:[e.jsx(kt,{})," ",N("editReask")]})})]})});function Da({message:t}){const s=he(),[n,o]=i.useState(!1),c=t.details??{},a=c.name??c.path??s("attachment"),r=c.type==="folder",l=c.mode==="reference",u=c.mode==="bridged",m=t.content.filter(M=>M.type==="text").map(M=>M.text).join(`
14
- `),f=$a(m),h=t.content.find(M=>M.type==="image"),k=f.split(`
15
- `).length;return e.jsxs("div",{className:`attachcard ${l?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>o(M=>!M),children:[e.jsx("span",{className:"attachcard-icon",children:r?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:a}),c.path&&e.jsx("span",{className:"attachcard-path",children:c.path}),e.jsx("span",{className:`attachcard-mode ${c.mode==="lines"?"lines":l?"ref":u?"bridged":"inline"}`,children:l?r?s("folderRefShort"):`${s("refOnlyShort")} · ${cs(c.size)}`:u?s("bridgedVision"):h?s("image"):c.mode==="lines"?s("inlineLinesRange",{start:c.startLine??1,end:c.endLine??c.lines??1}):s("inlineLines",{n:c.lines??k})}),!l&&(n?e.jsx(Fe,{}):e.jsx(dt,{}))]}),!l&&n&&(u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:s("bridgedVisionDetail")}),(h==null?void 0:h.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:h.dataUrl,alt:a})}),f&&e.jsx("pre",{className:"attachcard-content",children:f})]}):h!=null&&h.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:h.dataUrl,alt:a})}):e.jsx("pre",{className:"attachcard-content",children:f})),l&&e.jsx("div",{className:"attachcard-refnote",children:r?s("folderNotExpanded"):s("fileNotExpanded",{size:cs(c.size)})})]})}function cs(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function $a(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 _a({block:t}){const s=he(),[n,o]=i.useState(!1);return e.jsxs("div",{className:`skillcard${n?" expanded":""}`,children:[e.jsxs("button",{type:"button",className:"skillcard-head",onClick:()=>o(c=>!c),title:t.location,children:[e.jsx("span",{className:"skillcard-icon",children:e.jsx(_n,{})}),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:[n?e.jsx(ct,{}):e.jsx(Fe,{}),s(n?"collapseMsg":"expandMsg")]})]}),n&&e.jsx("div",{className:"skillcard-body",children:e.jsx(pt,{text:t.content})})]})}function ds({block:t,toolResults:s,liveOutputs:n,toolStatuses:o,streaming:c,isLast:a,onKillBash:r}){const l=he(),u=Ge(t);if(u){const M=c&&a;return e.jsxs("div",{className:"msg-text",children:[M?e.jsx(Ca,{text:u.text}):e.jsx(pt,{text:u.text}),u.truncated&&e.jsx("div",{className:"trunc-note",children:l("truncated")})]})}const m=Ws(t);if(m)return e.jsx(Sa,{thinking:m.thinking,streaming:c&&a});const f=Us(t);if(f){const M=s.get(f.id),N=n.get(f.id),D={result:M,liveOutput:N==null?void 0:N.text,streaming:c,status:o.get(f.id)};return e.jsx(Ma,{block:f,view:D,onKillBash:r})}const h=rt(t);if(h&&h.dataUrl)return e.jsx("div",{className:"msg-image",children:e.jsx("img",{src:h.dataUrl,alt:"attachment"})});const k=qs(t);return k?e.jsxs("div",{className:"bashblock",children:[e.jsxs("div",{className:"bashblock-command",children:[e.jsx("span",{className:"bashblock-prompt",children:"$"}),e.jsx("code",{children:k.command}),k.exitCode!==void 0&&e.jsx("span",{className:`bashblock-exit ${k.exitCode===0?"ok":"err"}`,children:l("exitCode",{code:k.exitCode})}),k.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:l("cancelled")})]}),k.output&&e.jsx("pre",{className:"bashblock-output",children:k.output}),k.truncated&&e.jsx("div",{className:"trunc-note",children:l("outputTruncated")})]}):null}function zs(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 Fa(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),o=String(s.getMinutes()).padStart(2,"0");return`${n}:${o}`}const Aa=i.memo(function({message:s,onExpand:n}){const o=he();let c="";for(const h of s.content){const k=Ge(h);if(k&&k.text.trim()){const M=Pt(k.text);M?c=`skill:${M.name}`+(M.userMessage?` · ${M.userMessage.replace(/\s+/g," ").trim()}`:""):c=k.text.replace(/\s+/g," ").trim();break}}if(!c&&s.role==="custom"&&s.customType==="file"){const h=s.details??{};c=h.name??h.path??""}c.length>90&&(c=`${c.slice(0,90)}…`);let r=0,l=0,u=0,m=0;for(const h of s.content)Ws(h)?r++:Us(h)?l++:qs(h)?u++:rt(h)&&m++;const f=[];return r&&f.push(`${o("thinking")} ${r}`),l&&f.push(`${o("toolCalls")} ${l}`),u&&f.push(`${o("bashRuns")} ${u}`),m&&f.push(`${o("images")} ${m}`),e.jsxs("button",{type:"button",className:"msg-collapsed","data-msg-id":s.id,title:`${o("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"?o("attachment"):zs(s.role,o)}),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((h,k)=>e.jsx("span",{className:"msg-collapsed-chip",children:h},k))})]}),s.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:Oa(s.timestamp)}):null,e.jsxs("span",{className:"msg-collapsed-action",children:[e.jsx(Fe,{})," ",o("expandMsg")]})]})});function Oa(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),o=String(s.getMinutes()).padStart(2,"0");return`${n}:${o}`}const Ha=i.memo(function({id:s,show:n,height:o,containerRef:c,onMeasured:a,lazyRef:r,children:l}){const u=i.useRef(null),m=i.useRef(null);return i.useLayoutEffect(()=>{const f=m.current;if(m.current=n,!n||f!==!1)return;const h=u.current,k=c.current;if(!h||!k)return;const M=h.offsetHeight;a==null||a(s,M);const N=M-o;if(N!==0){const D=h.parentElement;D&&D.getBoundingClientRect().bottom<=k.getBoundingClientRect().top&&(k.scrollTop+=N)}},[n]),n?e.jsx("div",{ref:r,"data-lazy-id":s,children:e.jsx("div",{ref:u,children:l})}):e.jsx("div",{ref:r,className:"msg-lazy-ph","data-msg-id":s,"data-lazy-id":s,style:{height:o},"aria-hidden":"true"})});function Wa(t,s,n,o){const c=[],a=[];let r=0;for(const l of t){if(n.has(l.id))continue;l.top<s.bottom&&l.bottom>s.top?o.has(l.id)&&c.push(l.id):o.has(l.id)||(a.push(l.id),l.bottom<=s.top&&(r+=l.bottom-l.top))}return{show:c,hide:a,shrinkAbove:r}}function Ua(t,s){if(s.show.length===0&&s.hide.length===0)return t;const n=new Set(t);for(const o of s.show)n.delete(o);for(const o of s.hide)n.add(o);return n}function qa(t,s,n){const o=new Set;let c=0;for(let a=t.length-1;a>=0&&!(a<t.length-1&&c>=n);a--){const r=t[a];o.add(r.id),c+=s.get(r.id)??Ks(r.role,r.customType)}return o}function Ks(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}}function za(t){if(t.role==="toolResult")return"";const s=[];for(const n of t.content)Ka(n,s);return t.errorMessage&&s.push(t.errorMessage),s.join(`
16
- `)}function Ka(t,s){if(typeof t.text=="string"){s.push(t.text);return}switch(t.type){case"thinking":typeof t.thinking=="string"&&s.push(t.thinking);break;case"toolCall":{typeof t.name=="string"&&s.push(t.name),typeof t.argumentsText=="string"&&s.push(t.argumentsText);break}case"bash":typeof t.command=="string"&&s.push(t.command),typeof t.output=="string"&&s.push(t.output);break}}function Va(t,s){const n=s.trim().toLowerCase();if(!n)return 0;const o=t.toLowerCase();let c=0,a=o.indexOf(n);for(;a!==-1;)c++,a=o.indexOf(n,a+n.length);return c}function Ga(t,s){const n=s.trim().toLowerCase();if(!n)return[];const o=[];for(const c of t){const a=za(c);if(!a)continue;const r=Va(a,n);for(let l=0;l<r;l++)o.push({messageId:c.id,occurrence:l})}return o}function Ja(t,s){var r;const n=new Map,o=[],c=s.toLowerCase();if(!c)return{byMsg:n,all:o};const a=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(l){const u=l.parentElement;return!u||u.closest(".search-bar")?NodeFilter.FILTER_REJECT:(l.textContent??"").toLowerCase().includes(c)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let l=a.nextNode();l;l=a.nextNode()){const u=(l.textContent??"").toLowerCase(),m=(r=l.parentElement)==null?void 0:r.closest("[data-msg-id]");if(!m)continue;const f=m.getAttribute("data-msg-id")??"";let h=u.indexOf(c);for(;h!==-1;){const k=document.createRange();k.setStart(l,h),k.setEnd(l,h+c.length),o.push(k);const M=n.get(f);M?M.push(k):n.set(f,[k]),h=u.indexOf(c,h+c.length)}}return{byMsg:n,all:o}}function He(t,s){const n=CSS;if(!n.highlights)return;if(s.length===0){n.highlights.delete(t);return}const o=window.Highlight;o&&n.highlights.set(t,new o(...s))}function Qa({containerRef:t,messages:s,open:n,onClose:o,onEnsureExpanded:c}){const a=he(),r=i.useRef(null),[l,u]=i.useState(""),[m,f]=i.useState(0),h=i.useDeferredValue(l),k=n?h.trim():"",M=i.useMemo(()=>n?Ga(s,k):[],[s,k,n]),N=i.useRef(M);N.current=M;const D=i.useRef(m);D.current=m,i.useEffect(()=>{n&&(f(0),requestAnimationFrame(()=>{var p;return(p=r.current)==null?void 0:p.select()}))},[n]),i.useEffect(()=>{if(!n)return;const p=E=>{E.key==="Escape"&&(E.preventDefault(),E.stopPropagation(),o())};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,o]),i.useEffect(()=>(n||(He("msg-search",[]),He("msg-search-active",[])),()=>{He("msg-search",[]),He("msg-search-active",[])}),[n]);const R=i.useCallback(p=>{const E=t.current;if(!E)return;const I=E.querySelector(`[data-msg-id="${p}"]`);I&&(I.classList.remove("msg-flash"),I.offsetWidth,I.classList.add("msg-flash"))},[t]);i.useLayoutEffect(()=>{if(!n||!k)return;const p=t.current;if(!p)return;let E=!1,I=0;return I=requestAnimationFrame(()=>{var K;if(E)return;const{byMsg:y,all:w}=Ja(p,k);He("msg-search",w);const d=N.current,S=d[Math.min(D.current,d.length-1)];if(!S)return;const W=(K=y.get(S.messageId))==null?void 0:K[S.occurrence];if(W){He("msg-search-active",[W]);const oe=W.startContainer.parentElement??p.querySelector(`[data-msg-id="${S.messageId}"]`);oe==null||oe.scrollIntoView({block:"center"})}else R(S.messageId)}),()=>{E=!0,cancelAnimationFrame(I)}},[n,k,M,t,R]);const P=i.useCallback(p=>{const E=N.current;if(E.length===0)return;const I=(D.current+p+E.length)%E.length;f(I),c(E[I].messageId)},[c]);if(!n)return null;const A=M.length;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:r,className:"search-input",type:"text",value:l,placeholder:a("searchPlaceholder"),onChange:p=>{u(p.target.value),f(0)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),P(p.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${A===0?"empty":""}`,children:A===0?a("searchNoResults"):`${Math.min(m+1,A)}/${A}`}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchPrev"),disabled:A===0,onClick:()=>P(-1),children:e.jsx(ct,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchNext"),disabled:A===0,onClick:()=>P(1),children:e.jsx(Fe,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchClose"),onClick:o,children:e.jsx(Ce,{})})]})}const us=new Map,Ya=15,ms=30,ps=1200,Xa=1600;function hs(t){return t.content.some(s=>s.type==="toolCall")}const Za=[{key:"ex.understand",icon:"🔍"},{key:"ex.debug",icon:"🐛"},{key:"ex.test",icon:"🧪"},{key:"ex.review",icon:"🧹"}];function ei(t){return Za.map(({key:s,icon:n})=>({icon:n,text:t(s),prompt:t(`${s}.prompt`)}))}function ti({state:t,liveOutputs:s,toolStatuses:n,onEdit:o,onKillBash:c}){const a=he(),r=i.useRef(null),[l,u]=i.useState(!0),m=i.useRef(!0),f=i.useRef(0),h=i.useRef(!1),[k,M]=i.useState(()=>new Set),[N,D]=i.useState(!1),R=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,P=i.useMemo(()=>{const j=new Map;for(const B of t.messages)B.role==="toolResult"&&B.toolCallId&&j.set(B.toolCallId,B);return j},[t.messages]),A=i.useMemo(()=>{var B,Z;const j=new Map;for(let X=0;X<t.messages.length;X++){const ce=t.messages[X];if(ce.role!=="user")continue;const ue=[];for(const ge of ce.content){const v=rt(ge);if(!((B=v==null?void 0:v.dataUrl)!=null&&B.startsWith("data:")))continue;const ie=v.dataUrl.match(/^data:([^;]*);base64,(.+)$/);ie&&ue.push({path:"",imageData:ie[2],mimeType:ie[1]||"image/png"})}for(let ge=X+1;ge<t.messages.length&&t.messages[ge].role==="custom"&&t.messages[ge].customType==="file";ge++){const v=t.messages[ge].details??{};if(v.mode!=="reference")for(const ie of t.messages[ge].content){const J=rt(ie);if(!((Z=J==null?void 0:J.dataUrl)!=null&&Z.startsWith("data:")))continue;const xe=J.dataUrl.match(/^data:([^;]*);base64,(.+)$/);xe&&ue.push({path:"",imageData:xe[2],mimeType:xe[1]||"image/png",name:v.name??`image.${(xe[1]||"image/png").split("/")[1]??"png"}`})}}ue.length>0&&j.set(ce.id,ue)}return j},[t.messages]),p=R.length>0?R[R.length-1].id:null,E=t.messages.length>ms?Math.max(0,t.messages.length-Ya):0,[I,y]=i.useState(()=>new Set),[w,d]=i.useState(()=>new Set),S=i.useRef(new Map),W=i.useRef(new Map),K=i.useRef(0),oe=i.useRef(I);oe.current=I;const ne=t.messages.length>ms&&!N,le=i.useRef(ne);le.current=ne;const L=qa(t.messages,S.current,Xa),F=i.useRef(L);F.current=L;const H=i.useCallback(()=>{const j=r.current;if(!j)return;if(!le.current){y(ue=>ue.size?new Set:ue);return}const B=j.getBoundingClientRect(),Z={top:B.top-ps,bottom:B.bottom+ps},X=[];for(const[ue,ge]of W.current){const v=ge.getBoundingClientRect();X.push({id:ue,top:v.top,bottom:v.bottom}),oe.current.has(ue)||S.current.set(ue,v.bottom-v.top)}const ce=Wa(X,Z,F.current,oe.current);for(const ue of ce.hide){const ge=W.current.get(ue);ge&&S.current.set(ue,ge.offsetHeight)}y(ue=>Ua(ue,ce))},[]),$=i.useCallback(()=>{K.current||(K.current=requestAnimationFrame(()=>{K.current=0,H()}))},[H]);i.useLayoutEffect(()=>{H()},[H]);const V=i.useRef(N);i.useLayoutEffect(()=>{V.current&&!N&&H(),V.current=N},[N,H]);const T=i.useCallback((j,B)=>{S.current.set(j,B)},[]),b=i.useCallback(j=>{j&&W.current.set(j.dataset.lazyId??"",j)},[]);i.useEffect(()=>{const j=new Set(t.messages.map(B=>B.id));for(const[B,Z]of W.current)j.has(B)||(W.current.delete(B),S.current.delete(B));y(B=>{let Z=!1;const X=new Set;for(const ce of B)j.has(ce)?X.add(ce):Z=!0;return Z?X:B})},[t.messages,k]),i.useEffect(()=>()=>cancelAnimationFrame(K.current),[]);const U=i.useMemo(()=>{const j=[];for(const B of t.messages){if(B.role!=="user")continue;const Z=B.content.map(ue=>{var ge;return((ge=Ge(ue))==null?void 0:ge.text)??""}).filter(Boolean).join(" "),X=Pt(Z),ce=X?X.userMessage??`skill:${X.name}`:Z.trim();ce&&j.push({id:B.id,text:ce})}return j},[t.messages]),Q=i.useMemo(()=>{const j=new Map;return U.forEach((B,Z)=>j.set(B.id,Z)),j},[U]),[de,fe]=i.useState(-1),ye=i.useRef(-1),x=i.useRef(U);i.useEffect(()=>{x.current=U},[U]);const _=i.useCallback(()=>{const j=r.current,B=x.current;if(!j||B.length===0)return;const Z=j.getBoundingClientRect().top,X=140;let ce=-1;for(let ue=0;ue<B.length;ue++){const ge=j.querySelector(`[data-msg-id="${B[ue].id}"]`);if(ge)if(ge.getBoundingClientRect().top<=Z+X)ce=ue;else break}ce!==ye.current&&(ye.current=ce,fe(ce))},[]);i.useEffect(()=>{_()},[U,_]);const ae=i.useCallback(j=>{M(B=>B.has(j)?B:new Set(B).add(j))},[]),g=i.useCallback(j=>{const B=t.messages.findIndex(Z=>Z.id===j);B>=0&&B<E&&!k.has(j)&&is.flushSync(()=>ae(j))},[t.messages,E,k,ae]);i.useEffect(()=>{const j=B=>{if(!(B.ctrlKey||B.metaKey)||B.key.toLowerCase()!=="f")return;const Z=B.target;Z&&(Z.tagName==="INPUT"||Z.tagName==="TEXTAREA"||Z.isContentEditable)||(B.preventDefault(),D(!0))};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[]);const q=i.useCallback(j=>{M(B=>{if(!B.has(j))return B;const Z=new Set(B);return Z.delete(j),Z})},[]),G=i.useCallback(j=>{const B=t.messages.findIndex(X=>X.id===j);is.flushSync(()=>{B>=0&&B<E&&!k.has(j)&&ae(j),d(X=>X.has(j)?X:new Set(X).add(j))});const Z=x.current.findIndex(X=>X.id===j);ye.current=Z,fe(Z),requestAnimationFrame(()=>{var ce,ue,ge;const X=(ce=r.current)==null?void 0:ce.querySelector(`[data-msg-id="${j}"]`);X&&((ue=r.current)==null||ue.querySelectorAll(".msg-flash").forEach(v=>v.classList.remove("msg-flash")),X.scrollIntoView({block:"start"}),X.classList.remove("msg-flash"),X.offsetWidth,X.classList.add("msg-flash"),X!==((ge=r.current)==null?void 0:ge.lastElementChild)&&(h.current=!0))})},[t.messages,E,k,ae]),te=i.useCallback(()=>{const j=r.current;if(!j)return;const B=j.scrollTop-f.current;f.current=j.scrollTop;const Z=j.scrollHeight-j.scrollTop-j.clientHeight<80;B<-4&&B>-500?h.current=!0:Z&&B>=0&&(h.current=!1),m.current=Z&&!h.current,u(m.current),_(),$()},[_,$]),me=i.useRef(!1);i.useEffect(()=>{const j=me.current;if(me.current=!!t.isStreaming,j&&!t.isStreaming&&!h.current){const B=()=>{const X=r.current;X&&!h.current&&(X.scrollTop=X.scrollHeight,m.current=!0,u(!0))};requestAnimationFrame(()=>requestAnimationFrame(B));const Z=setTimeout(B,180);return()=>clearTimeout(Z)}},[t.isStreaming]),i.useEffect(()=>{const j=r.current;j&&m.current&&(j.scrollTop=j.scrollHeight)},[R,t.isStreaming,s]);const je=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");i.useEffect(()=>{const j=r.current;j&&m.current&&(j.scrollTop=j.scrollHeight)},[je]);const Y=i.useCallback(()=>{const j=r.current;j&&(j.scrollTop=j.scrollHeight),m.current=!0,h.current=!1,u(!0)},[]),re=i.useRef(null);i.useEffect(()=>{const j=re.current,B=r.current;if(!j||!B)return;const Z=X=>{X.preventDefault();const ce=j.querySelector(".qn-list");if(ce&&ce.contains(X.target)&&ce.scrollHeight>ce.clientHeight){ce.scrollTop+=X.deltaY;return}B.scrollTop+=X.deltaY};return j.addEventListener("wheel",Z,{passive:!1}),()=>j.removeEventListener("wheel",Z)},[]);const[se,Te]=i.useState(0);i.useEffect(()=>{const j=()=>{var B;Te(((B=r.current)==null?void 0:B.clientHeight)??0),$()};return j(),window.addEventListener("resize",j),()=>window.removeEventListener("resize",j)},[$]);const Ee=U.length,Re=i.useMemo(()=>Ee===0?27:Math.max(4,Math.min(27,Math.floor(((se||600)-16)/Ee)-3)),[Ee,se]),Ae=Re<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:"messages",ref:r,onScroll:te,children:[t.messages.length===0&&!t.streamingMessage&&e.jsxs("div",{className:"empty-state",children:[e.jsx("div",{className:"empty-logo-wrap",children:e.jsx("div",{className:"empty-logo",children:"π"})}),e.jsx("h2",{className:"empty-title",children:a("welcomeTitle")}),e.jsx("p",{className:"empty-sub",children:a("welcomeSub")}),e.jsxs("div",{className:"empty-cwd",children:[e.jsx("span",{className:"empty-cwd-label",children:a("directory")}),e.jsx("span",{className:"empty-cwd-path",children:t.cwd})]}),e.jsx("div",{className:"empty-examples",children:ei(a).map(j=>e.jsxs("button",{type:"button",className:"empty-example",title:a("clickToFill"),onClick:()=>window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:j.prompt})),children:[e.jsx("span",{className:"empty-example-icon",children:j.icon}),e.jsx("span",{className:"empty-example-text",children:j.text})]},j.prompt))})]}),t.messages.map((j,B)=>{const Z=B<E,X=Z&&k.has(j.id);if(Z&&!X)return j.role==="toolResult"?null:e.jsx(Aa,{message:j,onExpand:ae},j.id);const ce=j.role==="user"?Q.get(j.id):void 0,ue=!ne||L.has(j.id)||w.has(j.id)||!I.has(j.id);return e.jsx(Ha,{id:j.id,show:ue,height:S.current.get(j.id)??Ks(j.role,j.customType),containerRef:r,onMeasured:T,lazyRef:b,children:e.jsx(ls,{message:j,qnIndex:ce,qnActive:ce!==void 0?ce===de:void 0,onJump:G,toolResults:P,liveOutputs:hs(j)?s:us,toolStatuses:n,streaming:t.isStreaming,onKillBash:c,isLast:j.id===p,onEdit:o,questionImages:A.get(j.id),onCollapse:X?q:void 0},j.id)},j.id)}),t.streamingMessage&&e.jsx(ls,{message:t.streamingMessage,toolResults:P,liveOutputs:hs(t.streamingMessage)?s:us,toolStatuses:n,streaming:!0,isLast:!0,onEdit:o,onKillBash:c},t.streamingMessage.id),t.isStreaming&&R.length===0&&e.jsx("div",{className:"streaming-wait",children:a("waitingResponse")}),t.queue.steering.map((j,B)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:a("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:j})]})},`q-steer-${B}`)),t.queue.followUp.map((j,B)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:a("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:j})]})},`q-fu-${B}`))]}),!l&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Y,children:[e.jsx(Is,{})," ",a("backToBottom")]}),e.jsx(Qa,{containerRef:r,messages:R,open:N,onClose:()=>D(!1),onEnsureExpanded:g}),U.length>0&&e.jsxs("div",{className:`qn-rail ${Ae?"many":""}`,ref:re,"aria-label":a("questionNavTitle"),style:{"--rail-gap":`${Re}px`},children:[U.map((j,B)=>e.jsx("button",{type:"button",className:`qn-bar ${B===de?"active":""}`,"aria-label":`${B+1}. ${j.text}`,onClick:()=>G(j.id),children:e.jsxs("span",{className:"qn-bar-text",children:[B+1,". ",j.text]})},j.id)),Ae&&e.jsx("div",{className:"qn-list",children:U.map((j,B)=>e.jsxs("button",{type:"button",className:`qn-list-item ${B===de?"active":""}`,"aria-label":`${B+1}. ${j.text}`,onClick:()=>G(j.id),children:[e.jsx("span",{className:"qn-list-idx",children:B+1}),e.jsx("span",{className:"qn-list-text",children:j.text})]},j.id))})]})]})}const si=i.memo(function({ready:s,streaming:n,messages:o,slashCommands:c,modelState:a,models:r,modelsLoading:l,send:u,attachments:m,onRemoveAttachment:f,onAddImageFiles:h,onAddLocalFiles:k,onNotice:M,onSent:N,onManageModels:D}){const R=he(),{locale:P}=It(),A=g=>P==="en"&&g.descriptionEn?g.descriptionEn:g.description??"",p=g=>P==="en"&&g.argumentHintEn?g.argumentHintEn:g.argumentHint??"",[E,I]=i.useState(""),[y,w]=i.useState(!1),[d,S]=i.useState(null),[W,K]=i.useState(0),[oe,ne]=i.useState(!1),[le,L]=i.useState(void 0),F=i.useRef(null),H=i.useRef(null),$=i.useRef(null),V={builtin:R("slashBuiltin"),extension:R("slashExtension"),prompt:R("slashPrompt"),skill:R("slashSkill")},T=g=>{const q=g.match(/^\/([^\s]*)$/);if(q&&s){const G=q[1].toLowerCase(),te=c.filter(me=>me.name.toLowerCase().startsWith(G));S(te.length>0?te:null),K(0)}else S(null)};i.useEffect(()=>{var q;const g=(q=$.current)==null?void 0:q.querySelector(".slash-item.active");g==null||g.scrollIntoView({block:"nearest"})},[W,d]);const b=g=>{var je;const q=d??[],G=g??q[W%Math.max(q.length,1)];if(!G){S(null);return}const te=E.match(/^\/([^\s]*)([\s\S]*)$/),me=te?te[2]:"";I(`/${G.name} ${me}`),S(null),(je=F.current)==null||je.focus()},U=async()=>{const q=[...o].reverse().find(te=>te.role==="assistant"&&te.content.some(me=>me.type==="text"&&me.text)),G=q==null?void 0:q.content.filter(te=>te.type==="text").map(te=>te.text).join(`
17
- `);if(!G){M("warning",R("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(G),M("info",R("slashCopied"))}catch{M("error",R("slashCopyFailed"))}},Q=g=>{if(!g||g.length===0){M("warning",R("foldersNotSupported"));return}const q=Array.from(g).filter(te=>Pe(te.type)),G=Array.from(g).filter(te=>!Pe(te.type));q.length>0&&h(q),G.length>0&&k(G)},de=g=>{var te;const q=(te=g.clipboardData)==null?void 0:te.items;if(!q)return;const G=[];for(const me of q)if(me.kind==="file"&&Pe(me.type)){const je=me.getAsFile();je&&G.push(je)}G.length!==0&&(g.preventDefault(),h(G))},fe=s,ye=i.useRef(E);i.useEffect(()=>{ye.current=E},[E]),i.useEffect(()=>{T(ye.current)},[c]),i.useEffect(()=>{const g=q=>{var te;const G=q.detail;I(G),(te=F.current)==null||te.focus()};return window.addEventListener("pi-web:fill",g),()=>window.removeEventListener("pi-web:fill",g)},[]),i.useEffect(()=>{if(!oe)return;const g=q=>{q.key==="Escape"&&ne(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[oe]),i.useEffect(()=>{const g=F.current;if(!g)return;g.style.height="auto";const q=g.scrollHeight>220;g.style.height=`${Math.min(g.scrollHeight,220)}px`,g.style.overflowY=q?"auto":"hidden"},[E]);const x=(g=!1)=>{var te,me,je,Y,re;const q=E.trim(),G=m.some(se=>se.imageData||se.fileData);if(!(!fe||!q&&!G)){if(q==="/help"){const se=(me=(te=F.current)==null?void 0:te.closest(".inputbox"))==null?void 0:me.getBoundingClientRect();L(se==null?void 0:se.width),ne(!0),I(""),(je=F.current)==null||je.focus();return}if(q==="/copy"){I(""),(Y=F.current)==null||Y.focus(),U();return}u({type:"prompt",text:q,queue:g,attachments:m.map(se=>se.imageData?{path:"",imageData:se.imageData,mimeType:se.mimeType,name:se.name}:se.fileData?{path:"",fileData:se.fileData,mimeType:se.mimeType,name:se.name,size:se.size}:{path:se.path,mode:se.mode,...se.lines?{lines:se.lines}:{}})})&&(I(""),N(),(re=F.current)==null||re.focus())}},_=g=>{if(!g.nativeEvent.isComposing){if(d&&d.length>0)switch(g.key){case"ArrowDown":g.preventDefault(),K(q=>(q+1)%d.length);return;case"ArrowUp":g.preventDefault(),K(q=>(q-1+d.length)%d.length);return;case"Tab":case"Enter":g.preventDefault(),b();return;case"Escape":g.preventDefault(),S(null);return}g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),x())}},ae=()=>e.jsx("div",{className:"inputbox-actions",children:n?e.jsxs(e.Fragment,{children:[E.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:R("supplementTip"),onClick:()=>x(!0),children:[e.jsx(bn,{})," ",R("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:R("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(tt,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:R("sendTip"),disabled:!fe||!E.trim()&&!m.some(g=>g.imageData||g.fileData),onClick:()=>x(),children:e.jsx(Rs,{})})});return e.jsxs("div",{className:`inputbar${y?" drop-active":""}`,onDragOver:g=>{g.preventDefault(),g.stopPropagation(),w(!0)},onDragLeave:g=>{g.currentTarget.contains(g.relatedTarget)||w(!1)},onDrop:g=>{var q;g.preventDefault(),g.stopPropagation(),w(!1),Q(((q=g.dataTransfer)==null?void 0:q.files)??null)},children:[y&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",R("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?R("attachImage",{name:g.name}):g.fileData?R("attachFile",{name:g.name}):g.isDir?R("folderRef",{path:g.path}):g.mode==="reference"?R("refOnly",{path:g.path}):g.mode==="lines"&&g.lines?R("attachLines",{path:g.path,start:g.lines.start,end:g.lines.end}):R("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:R("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:R("attachHint")})]}),d&&d.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:$,"aria-label":R("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:R("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>S(null),children:"Esc"})]}),d.map((g,q)=>e.jsxs("button",{type:"button",className:`slash-item${q===W?" active":""}`,onMouseEnter:()=>K(q),onClick:()=>b(g),children:[e.jsxs("span",{className:"slash-name",children:["/",g.name]}),e.jsx("span",{className:`slash-source ${g.source}`,children:V[g.source]}),e.jsxs("span",{className:"slash-desc",children:[A(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:p(g)})]})]},g.name))]}),oe&&e.jsx("div",{className:"modal-backdrop",onClick:()=>ne(!1),children:e.jsxs("div",{className:"slash-help",style:le?{width:le}:void 0,onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",R("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>ne(!1),children:R("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:R("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:V[g.source]}),e.jsxs("span",{className:"slash-help-desc",children:[A(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:p(g)})]})]},g.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:H,type:"file",multiple:!0,hidden:!0,onChange:g=>{Q(g.target.files),g.target.value=""}}),e.jsxs("div",{className:"inputbox-row",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:R("uploadFile"),disabled:!fe,onClick:()=>{var g;return(g=H.current)==null?void 0:g.click()},children:e.jsx(Jt,{})}),e.jsx("textarea",{ref:F,value:E,rows:1,placeholder:R(fe?n?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!fe,onChange:g=>{I(g.target.value),T(g.target.value)},onKeyDown:_,onPaste:de}),ae()]}),e.jsxs("div",{className:"input-tools",children:[e.jsx("div",{className:"input-tools-left",children:e.jsx(Bs,{state:a,models:r,modelsLoading:l,send:u,onManageModels:D,compact:!0})}),e.jsxs("div",{className:"input-tools-right",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:R("uploadFile"),disabled:!fe,onClick:()=>{var g;return(g=H.current)==null?void 0:g.click()},children:e.jsx(Jt,{})}),ae()]})]})]})]})}),ni=i.memo(function({goal:s,models:n,modelsLoading:o,activeConversationId:c,send:a}){var K,oe,ne,le,L,F;const r=he(),l=!s.conversationId||s.conversationId===c,u=s.goal!==null&&l,[m,f]=i.useState(""),[h,k]=i.useState(s.reviewModel??""),[M,N]=i.useState(s.maxRounds),[D,R]=i.useState(s.locked),[P,A]=i.useState(!1),[p,E]=i.useState(!1),[I,y]=i.useState(!0);i.useEffect(()=>{k(s.reviewModel??""),N(s.maxRounds||0),R(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),i.useEffect(()=>{P&&n.length===0&&!p&&!o&&(E(!0),a({type:"list_models"}))},[P,n.length,p,o,a]),i.useEffect(()=>{n.length>0&&E(!1)},[n.length]);const w=()=>{var H;return h?((H=n.find($=>$.id===h))==null?void 0:H.name)??h:r("goalBarUseMainModel")},d=()=>{const H=m.trim();H&&(a({type:"set_goal",goal:H,...h?{reviewModel:h}:{},maxRounds:M,locked:D}),f(""),y(!1))},S=()=>{const H=m.trim();H&&(a({type:"start_goal_wizard",text:H,...h?{wizardModel:h}:{},maxRounds:M,locked:D}),f(""),y(!1))},W=(((K=s.wizard)==null?void 0:K.active)??!1)&&l;return W?e.jsx("div",{className:`goalbar goalbar-active ${W?"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:((oe=s.wizard)==null?void 0:oe.draft)??"",children:[r("goalWizardRunning"),": ",(ne=s.wizard)==null?void 0:ne.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[r("goalBarRound",{n:(((le=s.wizard)==null?void 0:le.step)??0)+1})," ","/ ",((L=s.wizard)==null?void 0:L.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((F=s.wizard)==null?void 0:F.status)||r("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:r("goalBarClear"),onClick:()=>{a({type:"clear_goal"}),y(!0)},children:e.jsx(Ce,{})})]})}):u?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:[r("goalBarReviewing")," ",r("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?r("goalBarPassed"):s.verdict==="fail"?r("goalBarFailed"):`${r("goalBarRound",{n:s.round||1})} · ${s.locked?r("goalBarLocked"):r("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:s.status}),e.jsx("button",{type:"button",className:"goalbar-x",title:r("goalBarClear"),disabled:s.reviewing,onClick:()=>{a({type:"clear_goal"}),y(!0)},children:e.jsx(Ce,{})})]})}):I?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:r("goalBarPlaceholder"),onClick:()=>y(!1),children:[e.jsx(Gt,{})," ",e.jsx("span",{children:r("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx(Gt,{})}),e.jsx("input",{className:"goalbar-input",value:m,placeholder:r("goalBarPlaceholder"),onChange:H=>f(H.target.value),onKeyDown:H=>{H.key==="Enter"&&d()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!m.trim(),onClick:d,children:r("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!m.trim(),title:r("goalWizardTip"),onClick:S,children:["🔍 ",r("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:r(D?"goalBarLocked":"goalBarUnlocked"),onClick:()=>R(H=>(a({type:"set_goal_prefs",locked:!H}),!H)),children:D?e.jsx(En,{}):e.jsx(vn,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:r("goalBarClear"),onClick:()=>y(!0),children:e.jsx(ct,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[e.jsxs(Le,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[r("goalBarReviewModel"),": ",e.jsx("b",{children:w()})]}),open:P,onOpenChange:A,direction:"up",children:[e.jsx("div",{className:"dd-header",children:r("goalBarReviewModel")}),(p||o)&&e.jsx("div",{className:"dd-loading",children:r("loading")}),n.length===0&&!p&&!o&&e.jsx("div",{className:"dd-loading",children:r("noModels")}),e.jsx(Ne,{active:h==="",onClick:()=>{k(""),A(!1),a({type:"set_goal_prefs",reviewModel:""})},children:r("goalBarUseMainModel")}),n.map(H=>e.jsx(Ne,{active:h===H.id,onClick:()=>{k(H.id),A(!1),a({type:"set_goal_prefs",reviewModel:H.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:H.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:H.provider})})]})},H.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>a({type:"list_models"}),children:r("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:r("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:r("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:M,placeholder:r("goalBarUnlimitedShort"),onChange:H=>{const $=parseInt(H.target.value,10);if(Number.isNaN($)||$<0){N(0);return}N($)},onBlur:()=>a({type:"set_goal_prefs",maxRounds:M}),onKeyDown:H=>{H.key==="Enter"&&(a({type:"set_goal_prefs",maxRounds:M}),H.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:r(D?"goalBarLocked":"goalBarUnlocked")})]})]})});function ai({chat:t,send:s}){const n=he(),o=t.state,[c,a]=i.useState(!1),[r,l]=i.useState(""),[u,m]=i.useState(0),f=i.useRef(null),h=t.pathCompletions;if(i.useEffect(()=>{if(!c)return;const d=setTimeout(()=>{s({type:"complete_path",path:r})},150);return()=>clearTimeout(d)},[r,c,s]),i.useEffect(()=>m(0),[h]),i.useEffect(()=>{const d=document.querySelector(`.status-completions .pc-item[data-idx="${u}"]`);d==null||d.scrollIntoView({block:"nearest"})},[u]),!o)return null;const k=o.stats,M=t.ready?"ok":"busy",N=t.ready?n("connected"):n("connecting"),D=k.contextUsage,R=D.tokens!==null&&D.percent!==null?`${gs(D.tokens)} / ${gs(D.contextWindow)}`:"—",P=D.percent??null,A=P===null?"":P>=80?"warn":P>=50?"mid":"ok",p=o.queue.steering.length+o.queue.followUp.length,E=()=>{l(o.cwd),a(!0)},I=(d,S)=>{var K;const W=d.includes("\\")?"\\":"/";l(S?`${d}${W}`:d),m(0),(K=f.current)==null||K.focus()},y=d=>{const S=d.trim();S&&S!==o.cwd&&s({type:"set_cwd",path:S}),a(!1)},w=d=>{if(d.key==="ArrowDown")d.preventDefault(),m(S=>Math.min(S+1,h.length-1));else if(d.key==="ArrowUp")d.preventDefault(),m(S=>Math.max(S-1,0));else if(d.key==="Tab"&&h.length>0){d.preventDefault();const S=h[Math.min(u,h.length-1)];I(S.path,S.type==="dir")}else if(d.key==="Enter"&&!d.nativeEvent.isComposing){const S=r.trim();if(S.endsWith("/")||S.endsWith("\\"))y(S);else if(h.some(W=>W.path===S))y(S);else if(h.length>0&&h[u]){d.preventDefault();const W=h[u];I(W.path,W.type==="dir")}else y(S)}else d.key==="Escape"&&(h.length>0?(d.stopPropagation(),s({type:"complete_path",path:""})):a(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${M}`,title:N}),e.jsx("span",{className:"status-item",children:N}),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 ${A}`,children:P!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(P,100)}%`}})}),R]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("cumulativeCost"),children:["$",ii(k.cost)]}),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(d=>d.text).join(" · ")})]}),o.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"),p>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",p," ",n("queued")]})]})]}),c?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:f,className:"status-cwd-input",value:r,autoFocus:!0,placeholder:n("enterPath"),onChange:d=>l(d.target.value),onKeyDown:w,onBlur:()=>a(!1)}),h.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:d=>d.preventDefault(),children:h.map((d,S)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":S,className:`pc-item ${S===u?"sel":""}`,onMouseEnter:()=>m(S),onClick:()=>I(d.path,d.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:d.type==="dir"?e.jsx(qe,{}):e.jsx(Ts,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:d.name}),e.jsx("span",{className:"pc-path",children:d.path})]})]})},d.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:n("cwdTip",{path:o.cwd}),onClick:E,children:["📁 ",o.cwd]})]})}function gs(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function ii(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function ri({dialog:t,send:s}){const n=he(),[o,c]=i.useState(""),[a,r]=i.useState(0),l=f=>{s({type:"dialog_response",id:t.id,value:f})};i.useEffect(()=>{c(""),r(0);const f=h=>{h.key==="Escape"&&l(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:()=>l(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[u.map((f,h)=>e.jsx("button",{type:"button",className:`dialog-option ${h===a?"sel":""}`,onMouseEnter:()=>r(h),onClick:()=>l(f),children:f},h)),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:()=>l(!1),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>l(!0),children:n("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:o,placeholder:m||n("inputPlaceholder"),autoFocus:!0,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.nativeEvent.isComposing&&l(o)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>l(null),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>l(o),children:n("ok")})]})]})]})}function oi(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 li({chat:t,send:s,terminal:n,active:o,onSwitchToTerminal:c}){var ue,ge;const a=he(),[r,l]=i.useState(null),[u,m]=i.useState([]),[f,h]=i.useState(""),[k,M]=i.useState(new Map),[N,D]=i.useState("changes"),[R,P]=i.useState([]),[A,p]=i.useState(null),[E,I]=i.useState(""),[y,w]=i.useState(!1),[d,S]=i.useState(null),[W,K]=i.useState(null),[oe,ne]=i.useState(!1),[le,L]=i.useState(!1),[F,H]=i.useState(!1),[$,V]=i.useState(null),[T,b]=i.useState(!1),[U,Q]=i.useState(""),de=i.useRef(0),fe=i.useRef(-1),ye=i.useRef(-1),x=i.useRef(-1),_=i.useRef(-1),ae=i.useRef(void 0),g=i.useRef(null),q=i.useRef([]),G=i.useCallback(v=>{if(v.reqId===fe.current){if(fe.current=-1,L(!1),V(null),!v.ok){V(v.error??"查询失败");return}if(v.notRepo){b(!0),l(null),m([]),M(new Map),P([]),p(null),I(""),K(null);return}b(!1);const ie={branch:v.branch??"",detached:!!v.detached,upstream:v.upstream??null,ahead:v.ahead??0,behind:v.behind??0,upstreamGone:!!v.upstreamGone,files:(v.files??[]).map(pe=>({...pe}))},J=(v.branches??[]).map(pe=>({...pe})),xe=new Map;for(const[pe,we]of Object.entries(v.stats??{}))xe.set(pe,{add:we[0],del:we[1]});l(ie),m(J),M(xe),h(pe=>{var we;return ie.detached?pe||"":ie.branch&&J.some(Me=>Me.name===ie.branch)?ie.branch:pe&&J.some(Me=>Me.name===pe)?pe:((we=J[0])==null?void 0:we.name)??""}),K(pe=>pe&&!ie.files.some(we=>we.path===pe.file.path)?null:pe)}else if(v.reqId===ye.current){if(ye.current=-1,ne(!1),!v.ok){V(v.error??"查询失败");return}const ie=g.current;if(!ie)return;K({file:ie,staged:v.stagedText??"",worktree:v.worktreeText??"",untracked:!1})}else if(v.reqId===_.current){if(_.current=-1,H(!1),!v.ok){V(v.error??"查询失败");return}P((v.history??[]).map(ie=>({...ie})))}else if(v.reqId===x.current){if(x.current=-1,w(!1),!v.ok){V(v.error??"查询失败");return}I(v.text??"")}},[]);i.useEffect(()=>{const v=t.scmData;v&&v.type==="scm_data"&&G(v)},[t.scmData,G]);const te=i.useCallback((v,ie)=>{if(!t.ready||t.status!=="open")return!1;const J=++de.current;return s({...v,reqId:J})?(ie.current=J,!0):(de.current-=1,!1)},[t.ready,t.status,s]),me=i.useCallback((v=!1,ie=!1)=>{var J;!t.ready||t.status!=="open"||(J=t.state)!=null&&J.cwd&&(ae.current!==void 0&&ae.current!==t.state.cwd&&(l(null),m([]),M(new Map),P([]),H(!1),_.current=-1,p(null),I(""),K(null),S(null)),ae.current=t.state.cwd,V(null),te({type:"scm_status"},fe)&&(ie||L(!0)))},[t.ready,(ue=t.state)==null?void 0:ue.cwd,t.status,te]),je=i.useCallback(v=>{if(S(v),p(null),g.current=v,v.x==="?"&&v.y==="?"){K({file:v,staged:"",worktree:"",untracked:!0});return}ne(!0),V(null),te({type:"scm_filediff",path:v.path},ye)||ne(!1)},[te]),Y=i.useCallback(v=>{p(v),S(null),K(null),I(""),w(!0),V(null),te({type:"scm_commit",hash:v.hash},x)||w(!1)},[te]),re=i.useCallback((v,ie)=>{var pe,we;if(!t.ready)return;const J={name:v,command:ie,cwd:"${pwd}"},xe=t.terminals.find(Me=>Me.title===v);if(xe)n.restart(xe.id),s({type:"run_command",terminalId:xe.id,conversationId:xe.conversationId,command:J,cols:80,rows:24});else{const Me=_e();n.create({id:Me,conversationId:t.activeConversationId||((pe=t.state)==null?void 0:pe.conversationId)||"",title:v,cwd:((we=t.state)==null?void 0:we.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:J})}c()},[t.ready,(ge=t.state)==null?void 0:ge.cwd,t.terminals,c,s,n]),se=i.useCallback(()=>{const v=U.trim();if(!v||T)return;const ie=v.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");re("git commit",`git add -A && git commit -m "${ie}"`),Q("")},[U,T,re]),Te=v=>`'${v.replace(/'/g,"'\\''")}`,Ee=i.useCallback(v=>{T||re("git add",`git add -- ${Te(v.path)}`)},[T,re]),Re=i.useCallback(v=>{T||re("git reset",`git reset HEAD -- ${Te(v.path)}`)},[T,re]),Ae=i.useCallback(()=>{if(!f||T)return;const v=u.find(ie=>ie.name===f);if(v!=null&&v.remote&&typeof v.remote=="string"){const ie=f.slice(v.remote.length+1);re("git checkout",`git checkout -b ${ie} ${f} || git checkout ${f}`)}else re("git checkout",`git checkout ${f}`)},[f,u,T,re]),j=i.useCallback(()=>re("git push","git push"),[re]),B=i.useCallback(()=>re("git pull","git pull"),[re]),Z=i.useCallback(()=>{te({type:"scm_history"},_)||(_.current=-1)},[te]);i.useEffect(()=>{o&&me()},[o,me]),i.useEffect(()=>{N==="history"&&r&&Z()},[N,r,Z]),i.useEffect(()=>{t.scmDirty>0&&o&&me(!1,!0)},[t.scmDirty]),i.useEffect(()=>{if(!o||!t.ready||t.status!=="open")return;const v=setInterval(()=>{document.visibilityState!=="hidden"&&me(!1,!0)},3e4);return()=>clearInterval(v)},[o,t.ready,t.status,me]),i.useEffect(()=>{const v=q.current;if(q.current=t.terminals,!o)return;t.terminals.some(J=>{var pe;return J.running!==!1?!1:((pe=v.find(we=>we.id===J.id))==null?void 0:pe.running)===!0&&/^git /.test(J.title)})&&t.ready&&t.status==="open"&&(me(!1,!0),N==="history"&&r&&Z())},[t.terminals,o,t.ready,t.status,me,N,r,Z]);const X={staged:a("scmStaged"),unstaged:a("scmUnstaged"),untracked:a("scmUntracked"),both:a("scmStagedUnstaged")},ce=v=>{const ie=v.split(`
18
- `);return e.jsx("pre",{className:"scm-diff-pre",children:ie.map((J,xe)=>{let pe="";return J.startsWith("diff --git")||J.startsWith("index ")||J.startsWith("new file")||J.startsWith("deleted file")||J.startsWith("old mode")||J.startsWith("new mode")||J.startsWith("similarity index")||J.startsWith("rename ")||J.startsWith("copy ")||J.startsWith("Binary files")||J.startsWith("---")||J.startsWith("+++")?pe="hdr":J.startsWith("@@")?pe="hunk":J.startsWith("+")?pe="add":J.startsWith("-")&&(pe="del"),e.jsx("div",{className:`scm-diff-line ${pe}`,children:J||" "},xe)})})};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(Xe,{}),a("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":N==="changes",className:N==="changes"?"active":"",onClick:()=>{D("changes"),V(null)},children:a("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":N==="history",className:N==="history"?"active":"",onClick:()=>{D("history"),V(null)},children:a("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:a("scmRefreshTip"),disabled:le,onClick:()=>me(!0),children:e.jsx(ot,{className:le?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:a("scmCurrentBranch"),children:[e.jsx(Xe,{}),r?r.detached?a("scmDetached"):r.branch:"…",(r==null?void 0:r.upstream)&&e.jsx("span",{className:"scm-upstream",children:r.upstreamGone?a("scmUpstreamGone"):r.ahead>0||r.behind>0?a("scmAheadBehind",{ahead:r.ahead,behind:r.behind}):r.upstream})]}),e.jsxs("select",{className:"scm-select",value:f,disabled:T||u.length===0,title:a("scmSwitchBranch"),onChange:v=>h(v.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:a("scmSelectBranch")}),u.filter(v=>!v.remote).map(v=>e.jsx("option",{value:v.name,children:v.current?`* ${v.name}`:v.name},v.name)),u.some(v=>v.remote)&&e.jsx("optgroup",{label:a("scmRemoteBranches"),children:u.filter(v=>v.remote).map(v=>e.jsx("option",{value:v.name,children:v.name},v.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!f||f===(r==null?void 0:r.branch)||T,title:a("scmSwitchBranchTip",{branch:f}),onClick:Ae,children:[e.jsx(Xe,{}),a("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!r||r.detached||T,title:a("scmPushTip"),onClick:j,children:[e.jsx(Rs,{}),a("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!r||r.detached||T,title:a("scmPullTip"),onClick:B,children:[e.jsx(Is,{}),a("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:U,placeholder:a("scmCommitPlaceholder"),disabled:T,onChange:v=>Q(v.target.value),onKeyDown:v=>{v.key==="Enter"&&!v.nativeEvent.isComposing&&se()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!U.trim()||T,title:a("scmCommitTip"),onClick:se,children:[e.jsx(ut,{}),a("scmCommit")]})]})]}),e.jsxs("div",{className:"scm-body",children:[N==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:a("scmHistory")}),R.length>0&&e.jsx("span",{className:"scm-files-count",children:R.length})]}),e.jsx("div",{className:"scm-history-list",children:T?e.jsx("div",{className:"scm-empty",children:a("scmNotGitRepo")}):!r||F?e.jsx("div",{className:"scm-empty",children:t.status==="open"?a("scmLoading"):a("scmConnecting")}):R.length===0?e.jsx("div",{className:"scm-empty",children:a("scmNoHistory")}):R.map(v=>e.jsxs("button",{type:"button",className:`scm-commit ${(A==null?void 0:A.hash)===v.hash?"active":""}`,onClick:()=>Y(v),title:v.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:v.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:v.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[v.shortHash," · ",v.author," · ",v.date]}),v.decorations&&e.jsx("span",{className:"scm-commit-refs",children:v.decorations})]})]},v.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:a("scmChanges")}),r&&r.files.length>0&&e.jsx("span",{className:"scm-files-count",children:r.files.length})]}),e.jsx("div",{className:"scm-files-list",children:T?e.jsx("div",{className:"scm-empty",children:a("scmNotGitRepo")}):r?r.files.length===0?e.jsx("div",{className:"scm-empty",children:a("scmNoChanges")}):r.files.map(v=>{const ie=oi(v),J=k.get(v.path);return e.jsxs("div",{className:`scm-file ${(d==null?void 0:d.path)===v.path?"active":""}`,title:X[ie],onClick:()=>je(v),children:[e.jsx("span",{className:`scm-file-xy ${ie==="untracked"?"q":"x"}`,children:v.x!==" "?v.x:" "}),e.jsx("span",{className:`scm-file-xy ${ie==="untracked"?"q":"y"}`,children:v.y!==" "?v.y:" "}),e.jsx("span",{className:"scm-file-path",children:v.path}),J&&(J.add>0||J.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[J.add>0&&e.jsxs("span",{className:"add",children:["+",J.add]}),J.del>0&&e.jsxs("span",{className:"del",children:["-",J.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(v.y!==" "||ie==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:a("scmStageTip",{path:v.path}),onClick:xe=>{xe.stopPropagation(),Ee(v)},children:"+"}),ie==="staged"||ie==="both"?e.jsx("button",{type:"button",className:"scm-act",title:a("scmUnstageTip",{path:v.path}),onClick:xe=>{xe.stopPropagation(),Re(v)},children:"−"}):null]})]},v.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?a("scmLoading"):a("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:N==="history"?A?`${A.shortHash} ${A.subject}`:a("scmCommitDetail"):d?d.path:a("scmDiff")}),(N==="history"?y:oe)&&e.jsx("span",{className:"scm-diff-loading",children:a("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:N==="history"?e.jsxs(e.Fragment,{children:[$&&e.jsx("div",{className:"scm-error",children:$}),!A&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmSelectCommitHint")}),A&&y&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmLoading")}),A&&!y&&!$&&E?ce(E):null]}):e.jsxs(e.Fragment,{children:[$&&e.jsx("div",{className:"scm-error",children:$}),!d&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmSelectFileHint")}),d&&!W&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmLoading")}),d&&W&&W.untracked&&e.jsx("div",{className:"scm-empty",children:a("scmUntrackedNote")}),d&&W&&!W.untracked&&e.jsxs(e.Fragment,{children:[W.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:a("scmStaged")}),ce(W.staged)]}),W.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:a("scmUnstaged")}),ce(W.worktree)]}),!W.staged&&!W.worktree&&e.jsx("div",{className:"scm-empty",children:a("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(Je,{}),e.jsx("span",{children:a("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:c,children:a("scmViewTerminal")})]})]})}function ci({entry:t,send:s}){const n=i.useRef(null);return i.useEffect(()=>{const o=n.current;if(!o)return;let c;try{c=t.module.mount(o,sa(t.info.id,a=>s(a)))}catch(a){console.error(`[plugin:${t.info.id}] mount failed:`,a),o.textContent=`插件 ${t.info.name} 挂载失败`}return()=>{if(typeof c=="function")try{c()}catch(a){console.error(`[plugin:${t.info.id}] cleanup failed:`,a)}o.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:n})}function di({send:t,piConfigured:s,providers:n,installResult:o,onClose:c}){const a=he(),[r,l]=i.useState(!1),[u,m]=i.useState(""),[f,h]=i.useState(""),[k,M]=i.useState(!1);i.useEffect(()=>{t({type:"list_providers"})},[t]),i.useEffect(()=>{s&&c()},[s,c]),i.useEffect(()=>{o&&l(!1)},[o]),i.useEffect(()=>{var p;!u&&n.length>0&&m(((p=n.find(E=>!E.configured))==null?void 0:p.id)??n[0].id)},[n,u]);const N=()=>{r||(l(!0),t({type:"install_pi_agent"}))},D=()=>{!f.trim()||k||(M(!0),t({type:"set_provider_api_key",provider:u.trim(),apiKey:f.trim()}),setTimeout(()=>M(!1),3e3))},R=()=>{t({type:"get_state"}),t({type:"list_providers"})},P=n.find(p=>p.id===u),A=o!==null&&!o.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:c,children:e.jsx(Ce,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(lt,{className:"modal-head-icon"}),e.jsx("h2",{children:a("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:a("setupDesc")}),A?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:a("installFailed")}),e.jsx("pre",{className:"setup-detail",children:o.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:r,onClick:N,children:a("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:c,children:a("skip")})]})]}):o!=null&&o.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:a("installDone")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:a("provider")}),e.jsxs("select",{value:u,onChange:p=>m(p.target.value),children:[n.length===0&&e.jsx("option",{value:"",children:a("loading")}),n.map(p=>e.jsxs("option",{value:p.id,children:[p.name,"(",p.id,")",p.configured?` · ${a("configured")}`:""]},p.id))]}),(P==null?void 0:P.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:f,onChange:p=>h(p.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!f.trim()||k||!u,onClick:D,children:a(k?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:R,children:[e.jsx(ot,{})," ",a("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:r,onClick:N,children:a(r?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:c,children:a("skip")})]})]})})}const ui=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],Bt=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),mi=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[Bt()]});function fs(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:[Bt()]).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 pi({send:t,providers:s,providerStatus:n,fetchModelsResult:o,refreshProviderResult:c,cloneProviderResult:a,onClose:r}){const l=he(),[u,m]=i.useState(null),[f,h]=i.useState({}),[k,M]=i.useState(null),[N,D]=i.useState({}),[R,P]=i.useState(!1),[A,p]=i.useState(0),[E,I]=i.useState(null),y=i.useRef(0),[w,d]=i.useState({});i.useRef(0);const S=i.useRef(0),[W,K]=i.useState(null),oe=i.useRef(0),ne=i.useRef(0);i.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const le=()=>{if(!u)return;const b=u.baseUrl.trim();if(!b){I({ok:!1,text:l("fetchModelsNeedBaseUrl")});return}if(R)return;P(!0),I(null);const U=A+1;p(U),t({type:"fetch_models",reqId:U,baseUrl:b,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};i.useEffect(()=>{var b;if(!(!o||o.reqId===y.current))if(y.current=o.reqId,P(!1),o.ok&&((b=o.models)!=null&&b.length)){const U=o.models;m(Q=>{if(!Q)return Q;const de=Q.models.map(_=>{var q;if(!_.id.trim())return _;const ae=U.find(G=>G.id===_.id.trim());if(!ae)return _;const g={..._};return!g.name&&ae.name&&(g.name=ae.name),!g.contextWindow&&ae.contextWindow&&(g.contextWindow=String(ae.contextWindow)),!g.maxTokens&&ae.maxTokens&&(g.maxTokens=String(ae.maxTokens)),g.input==="text"&&((q=ae.input)!=null&&q.includes("image"))&&(g.input="text-image"),!g.reasoning&&ae.reasoning&&(g.reasoning=!0),g}),fe=new Set(de.map(_=>_.id.trim()).filter(Boolean)),ye=U.filter(_=>!fe.has(_.id)).map(_=>{var ae;return{id:_.id,name:_.name??"",reasoning:_.reasoning??!1,input:(ae=_.input)!=null&&ae.includes("image")?"text-image":"text",contextWindow:_.contextWindow?String(_.contextWindow):"",maxTokens:_.maxTokens?String(_.maxTokens):""}}),x=[...de,...ye];return x.some(_=>_.id.trim())?{...Q,models:x.filter(_=>_.id.trim())}:Q}),I({ok:!0,text:l("fetchModelsOk",{n:U.length})})}else I({ok:!1,text:o.error||l("fetchModelsEmpty")})},[o]);const L=b=>{const U=(f[b.id]??"").trim();!U||k||(M(b.id),t({type:"set_provider_api_key",provider:b.id,apiKey:U}),setTimeout(()=>{M(null),h(Q=>({...Q,[b.id]:""})),D(Q=>({...Q,[b.id]:!1})),t({type:"list_providers"})},1500))},F=()=>{if(!u)return;const b=u.providerId.trim(),U=u.models.filter(de=>de.id.trim()).map(de=>({id:de.id.trim(),name:de.name.trim()||void 0,reasoning:de.reasoning||void 0,input:de.input==="text-image"?["text","image"]:void 0,contextWindow:de.contextWindow?Number(de.contextWindow):void 0,maxTokens:de.maxTokens?Number(de.maxTokens):void 0})),Q={providerId:b,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:U};t({type:"save_model_config",providerId:b,config:Q}),r()};i.useEffect(()=>{!c||c.reqId===S.current||(S.current=c.reqId,d({}))},[c]);const H=b=>{if(W)return;K(b.id);const U=++oe.current+Date.now();t({type:"clone_provider",provider:b.id,reqId:U})};i.useEffect(()=>{!a||a.reqId===ne.current||(ne.current=a.reqId,K(null),a.ok&&a.config&&m(fs({...a.config,apiKey:""})))},[a]);const $=b=>{window.confirm(l("clearKeyConfirm",{id:b}))&&t({type:"clear_provider_api_key",provider:b})},V=b=>{window.confirm(l("deleteProviderConfirm",{id:b.providerId,n:b.models.length}))&&t({type:"delete_model_config",providerId:b.providerId})},T=(b,U)=>{u&&m({...u,models:u.models.map((Q,de)=>de===b?{...Q,...U}:Q)})};return e.jsx("div",{className:"modal-backdrop",onClick:r,children:e.jsxs("div",{className:"modal model-modal",onClick:b=>b.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":l("close"),onClick:r,children:e.jsx(Ce,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:l(u?"editProvider":"manageModelsTitle")})}),u?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:[l("providerId")," ",e.jsx("em",{children:l("providerIdHint")})]}),e.jsx("input",{type:"text",value:u.providerId,disabled:s.some(b=>b.providerId===u.providerId),onChange:b=>m({...u,providerId:b.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:l("displayName")}),e.jsx("input",{type:"text",value:u.name,onChange:b=>m({...u,name:b.target.value}),placeholder:l("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:l("apiType")}),e.jsx("select",{value:u.api,onChange:b=>m({...u,api:b.target.value}),children:ui.map(b=>e.jsx("option",{value:b,children:b},b))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:l("baseUrlHint")})]}),e.jsx("input",{type:"text",value:u.baseUrl,onChange:b=>m({...u,baseUrl:b.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:l("apiKey")}),e.jsx("input",{type:"password",value:u.apiKey,onChange:b=>m({...u,apiKey:b.target.value}),placeholder:l("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:b=>m({...u,authHeader:b.target.checked})}),e.jsx("span",{children:l("authHeader")})]})]}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:l("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[E&&e.jsx("span",{className:`fetch-msg ${E.ok?"ok":"err"}`,title:E.text,children:E.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:R||!u.baseUrl.trim(),title:l("fetchModelsHint"),onClick:le,children:[e.jsx(Mt,{})," ",l(R?"fetchingModels":"fetchModels")]})]})]}),u.models.map((b,U)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:b.id,onChange:Q=>T(U,{id:Q.target.value}),placeholder:l("modelIdReq")}),e.jsx("input",{type:"text",value:b.name,onChange:Q=>T(U,{name:Q.target.value}),placeholder:l("displayName")}),e.jsxs("select",{value:b.input,onChange:Q=>T(U,{input:Q.target.value}),children:[e.jsx("option",{value:"text",children:l("text")}),e.jsx("option",{value:"text-image",children:l("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:b.reasoning,onChange:Q=>T(U,{reasoning:Q.target.checked})}),e.jsx("span",{children:l("reasoning")})]}),e.jsx("input",{type:"number",value:b.contextWindow,onChange:Q=>T(U,{contextWindow:Q.target.value}),placeholder:l("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:b.maxTokens,onChange:Q=>T(U,{maxTokens:Q.target.value}),placeholder:l("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:l("removeModel"),onClick:()=>m({...u,models:u.models.filter((Q,de)=>de!==U)}),children:e.jsx($e,{})})]},U)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>m({...u,models:[...u.models,Bt()]}),children:[e.jsx(Ue,{})," ",l("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>m(null),children:l("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(b=>b.id.trim()),onClick:F,children:l("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-section-title",children:[l("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:l("hintKeyOnly")})]}),e.jsxs("div",{className:"provider-list",children:[n.length===0&&e.jsx("div",{className:"dd-loading",children:l("loading")}),n.map(b=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:b.name}),e.jsxs("span",{className:"provider-sub",children:[b.id,b.configured&&e.jsx("span",{className:"auth-badge",children:l("configuredBadge")}),b.source&&!b.configured&&e.jsx("span",{className:"auth-badge dim",children:b.source})]})]}),e.jsxs("div",{className:"provider-actions",children:[b.configured&&!N[b.id]?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"auth-badge",children:l("keyReady")}),e.jsxs("button",{type:"button",className:"btn sm",title:l("replaceKeyTitle"),onClick:()=>D(U=>({...U,[b.id]:!0})),children:[e.jsx(Yt,{})," ",l("replaceKey")]}),b.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:l("clearKeyTitle"),onClick:()=>$(b.id),children:[e.jsx($e,{})," ",l("clearKey")]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"password",className:"key-input",placeholder:l("pasteKey"),value:f[b.id]??"",onChange:U=>h(Q=>({...Q,[b.id]:U.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(f[b.id]??"").trim()||k===b.id,onClick:()=>L(b),children:[e.jsx(Mn,{})," ",k===b.id?l("savingKey"):l("saveKey")]})]}),e.jsxs("button",{type:"button",className:"btn sm",disabled:W!==null,title:l("cloneProviderTitle"),onClick:()=>H(b),children:[e.jsx(Rt,{})," ",W===b.id?l("cloning"):l("cloneProvider")]})]})]},b.id))]}),e.jsx("div",{className:"form-section-title",children:l("customProviders")}),e.jsx("p",{className:"modal-desc",children:l("customDesc")}),s.length===0&&e.jsx("div",{className:"dd-loading",children:l("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:s.map(b=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:b.providerId}),e.jsxs("span",{className:"provider-sub",children:[b.api??"—",b.baseUrl?` · ${b.baseUrl}`:"",b.models.length>0&&` · ${l("modelsCount",{n:b.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:l("edit"),onClick:()=>m(fs(b)),children:e.jsx(Yt,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:l("delete"),onClick:()=>V(b),children:e.jsx($e,{})})]})]},b.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>m(mi()),children:[e.jsx(Ue,{})," ",l("addProvider")]})})]})]})})}function Tt({text:t}){const s=i.useRef(null),[n,o]=i.useState(!1),c=()=>{var r;const a=(r=s.current)==null?void 0:r.getBoundingClientRect();a&&o(window.innerWidth-a.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 Be({title:t,subtitle:s,tip:n,enabled:o,onToggle:c,action:a}){const r=he();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(Tt,{text:n})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),a,e.jsx("button",{type:"button",className:`set-switch ${o?"on":""}`,role:"switch","aria-checked":o,title:r(o?"settingsEnabled":"settingsDisabled"),onClick:c,children:e.jsx("span",{className:"set-switch-knob"})})]})}function hi({chat:t,send:s,terminal:n,onSwitchToTerminal:o,onClose:c}){const a=he(),r=t.settings,[l,u]=i.useState(""),[m,f]=i.useState("append"),h=i.useRef(!1),[k,M]=i.useState(""),[N,D]=i.useState("append"),R=i.useRef(!1),[P,A]=i.useState(""),p=i.useRef(!1),[E,I]=i.useState(""),[y,w]=i.useState(!1),[d,S]=i.useState(null),[W,K]=i.useState(null);i.useEffect(()=>{r&&(f(r.promptMode),!h.current&&(u(m==="append"||r.customSystemPrompt?r.customSystemPrompt:r.defaultSystemPrompt||""),D(r.visionBridgePromptMode),!R.current&&(M(N==="append"||r.visionBridgePrompt?r.visionBridgePrompt:r.visionBridgeDefaultPrompt||""),p.current||A(r.reviewPrompt))))},[r,m,N]);const[oe,ne]=i.useState(String((r==null?void 0:r.terminalBashIdleMs)??15e3));if(i.useEffect(()=>{ne(String((r==null?void 0:r.terminalBashIdleMs)??15e3))},[r==null?void 0:r.terminalBashIdleMs]),!r)return null;const le=new Set(r.disabledSkills),L=new Set(r.disabledExtensions),F=x=>s({type:"set_settings",...x}),H=x=>{const _=new Set(le);_.has(x.name)?_.delete(x.name):_.add(x.name),F({disabledSkills:[..._]})},$=new Set(r.disabledPlugins??[]),V=x=>{const _=new Set($);_.has(x.id)?_.delete(x.id):_.add(x.id),F({disabledPlugins:[..._]})},T=x=>{const _=new Set(L);_.has(x.id)?_.delete(x.id):_.add(x.id),F({disabledExtensions:[..._]})},b=(x,_)=>{var q,G;const ae={name:x,command:_,cwd:"${pwd}"},g=t.terminals.find(te=>te.title===x);g?(n.restart(g.id),s({type:"run_command",terminalId:g.id,conversationId:g.conversationId,command:ae,cols:80,rows:24})):n.create({id:_e(),conversationId:t.activeConversationId||((q=t.state)==null?void 0:q.conversationId)||"",title:x,cwd:((G=t.state)==null?void 0:G.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:ae}),o(),c()},U=x=>{S(null),b(`${a("uninstallTitle")} ${x}`,`pi remove npm:${x}`)},Q=x=>{K(null),b(`${a("uninstallTitle")} ${x}`,`pi-web-ui uninstall ${x}`)},de=(x,_)=>{b(`${a("pluginUpdate")} ${x}`,`pi-web-ui install ${_} --name ${x} --force`)},fe=x=>{const _=new Set(r.reviewSkills.filter(ae=>!ae.enabled).map(ae=>ae.name));_.has(x.name)?_.delete(x.name):_.add(x.name),F({reviewDisabledSkills:[..._]})},ye=()=>{const x=m==="replace"&&r.defaultSystemPrompt&&l===r.defaultSystemPrompt?"":l;F({promptMode:m,customSystemPrompt:x})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal settings-modal",onClick:x=>x.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":a("close"),onClick:c,children:e.jsx(Ce,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(st,{className:"modal-head-icon"}),e.jsx("h2",{children:a("settingsTitle")})]}),e.jsx("p",{className:"modal-desc",children:a("settingsDesc")}),e.jsxs("div",{className:"modal-body",children:[e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(bt,{className:"set-section-icon"}),a("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:a("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:m,onChange:x=>{const _=x.target.value;f(_),F({promptMode:_})},children:[e.jsx("option",{value:"append",children:a("promptModeAppend")}),e.jsx("option",{value:"replace",children:a("promptModeReplace")})]}),e.jsx(Tt,{text:a(m==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:a("promptPlaceholder"),value:l,onFocus:()=>h.current=!0,onBlur:()=>{h.current=!1,ye()},onChange:x=>u(x.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":y,onClick:()=>w(x=>!x),children:[a("settingsViewPrompt")," ",y?"▴":"▾"]}),y&&e.jsxs("div",{className:"set-prompt-view",children:[e.jsxs("div",{className:"set-prompt-view-head",children:[e.jsx("span",{children:a("settingsViewPromptHint")}),e.jsx(_s,{text:r.effectiveSystemPrompt})]}),r.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:r.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:a("settingsViewPromptEmpty")})]})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Je,{className:"set-section-icon"}),a("settingsTerminalTools")]}),e.jsx(Be,{title:a("terminalToolsEnabled"),tip:a("settingsTerminalToolsDesc"),enabled:r.terminalToolsEnabled,onToggle:()=>F({terminalToolsEnabled:!r.terminalToolsEnabled})}),!r.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:a("terminalToolsOffHint")}),e.jsx(Be,{title:a("terminalBashTakeover"),tip:a("terminalBashTakeoverDesc"),enabled:r.terminalBash,onToggle:()=>F({terminalBash:!r.terminalBash})}),r.terminalBash&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:a("terminalBashIdleMs")}),e.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:oe,onChange:x=>ne(x.target.value),onBlur:()=>{const x=Math.max(0,Math.floor(Number(oe)||0));ne(String(x)),x!==r.terminalBashIdleMs&&F({terminalBashIdleMs:x})}})]})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(lt,{className:"set-section-icon"}),a("settingsSkills"),e.jsx("span",{className:"set-count",children:r.skills.length})]}),r.skills.length===0?e.jsx("p",{className:"set-empty",children:a("noSkills")}):e.jsx("div",{className:"set-list",children:r.skills.map(x=>e.jsx(Be,{title:x.name,subtitle:x.description,enabled:x.enabled,onToggle:()=>H(x)},x.name))})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(kn,{className:"set-section-icon"}),a("settingsExtensions"),e.jsx("span",{className:"set-count",children:r.extensions.length})]}),r.extensions.length===0?e.jsx("p",{className:"set-empty",children:a("noExtensions")}):e.jsx("div",{className:"set-list",children:r.extensions.map(x=>{const _=x.id.startsWith("npm:")?x.id.slice(4):null;return e.jsx(Be,{title:x.name,subtitle:x.path,enabled:x.enabled,onToggle:()=>T(x),action:_?d===x.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("uninstallConfirmHint"),onClick:()=>U(_),children:a("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:a("uninstallHint"),onClick:()=>S(x.id),children:[e.jsx($e,{}),a("uninstallExt")]}):void 0},x.id)})})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ms,{className:"set-section-icon"}),a("settingsUiPlugins"),e.jsx("span",{className:"set-count",children:t.plugins.length})]}),t.plugins.length===0?e.jsx("p",{className:"set-empty",children:a("noUiPlugins")}):e.jsx("div",{className:"set-list",children:t.plugins.map(x=>e.jsx(Be,{title:`${x.icon?`${x.icon} `:""}${x.name}`,subtitle:x.error?`${x.id} · ${x.error}`:x.source?`${x.id} · ${x.source}`:`${x.id} · ${a("uiPluginNoSource")}`,enabled:!$.has(x.id)&&!x.error,onToggle:()=>!x.error&&V(x),action:e.jsxs("div",{className:"set-row-actions",children:[x.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUpdateHint"),onClick:()=>de(x.id,x.source),children:[e.jsx(ot,{}),a("pluginUpdate")]}),W===x.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("pluginUninstallHint"),onClick:()=>Q(x.id),children:a("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUninstallHint"),onClick:()=>K(x.id),children:[e.jsx($e,{}),a("uninstallExt")]})]})},x.id))})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(bt,{className:"set-section-icon"}),a("settingsReview"),e.jsx(Tt,{text:a("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:r.reviewSkills.length})]}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:a("reviewPromptPlaceholder"),value:P,onFocus:()=>p.current=!0,onBlur:()=>{p.current=!1,F({reviewPrompt:P})},onChange:x=>A(x.target.value)}),e.jsx("div",{className:"set-field-label",children:a("settingsReviewSkills")}),r.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:a("noSkills")}):e.jsx("div",{className:"set-list",children:r.reviewSkills.map(x=>e.jsx(Be,{title:x.name,subtitle:x.description,enabled:x.enabled,onToggle:()=>fe(x)},`review-${x.name}`))})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Es,{className:"set-section-icon"}),a("settingsVisionBridge")]}),e.jsx(Be,{title:a("visionBridgeEnabled"),tip:a("settingsVisionBridgeDesc"),enabled:r.visionBridgeEnabled,onToggle:()=>F({visionBridgeEnabled:!r.visionBridgeEnabled})}),!r.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:a("visionBridgeOffHint")}),r.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:a("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:r.visionBridgeModel??"",onChange:x=>F({visionBridgeModel:x.target.value||null}),children:[e.jsx("option",{value:"",children:a("visionBridgeAuto")}),r.visionModels.map(x=>e.jsx("option",{value:`${x.provider}/${x.id}`,children:x.label},`${x.provider}/${x.id}`))]})]}),r.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:a("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:N,onChange:x=>{const _=x.target.value;D(_),F({visionBridgePromptMode:_})},children:[e.jsx("option",{value:"append",children:a("promptModeAppend")}),e.jsx("option",{value:"replace",children:a("promptModeReplace")})]})]}),r.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:a("visionBridgePromptPlaceholder"),value:k,onFocus:()=>R.current=!0,onBlur:()=>{R.current=!1;const x=N==="replace"&&r.visionBridgeDefaultPrompt&&k===r.visionBridgeDefaultPrompt?"":k;F({visionBridgePromptMode:N,visionBridgePrompt:x})},onChange:x=>M(x.target.value)}),r.visionBridgeEnabled&&(r.visionModels.length===0?e.jsx("p",{className:"set-hint",children:a("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:a("visionBridgeCurrent",{model:r.visionBridgeModel??a("visionBridgeAuto")})}))]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(st,{className:"set-section-icon"}),a("settingsPresets"),e.jsx("span",{className:"set-count",children:r.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:a("presetNamePlaceholder"),value:E,onChange:x=>I(x.target.value),onKeyDown:x=>{x.key==="Enter"&&E.trim()&&(s({type:"save_preset",name:E.trim()}),I(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!E.trim(),onClick:()=>{s({type:"save_preset",name:E.trim()}),I("")},children:[e.jsx(Ue,{})," ",a("saveAsPreset")]})]}),r.presets.length===0?e.jsx("p",{className:"set-empty",children:a("noPresets")}):e.jsx("div",{className:"set-list",children:r.presets.map(x=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:x.name}),e.jsxs("div",{className:"set-row-desc",children:[x.promptMode==="replace"?a("promptModeReplace"):a("promptModeAppend"),x.disabledSkills.length>0&&` · ${a("settingsSkills")} ${x.disabledSkills.length}`,x.disabledExtensions.length>0&&` · ${a("settingsExtensions")} ${x.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:x.name}),children:a("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:a("deletePreset"),onClick:()=>s({type:"delete_preset",name:x.name}),children:e.jsx($e,{})})]})]},x.name))})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:c,children:a("close")})})]})})}function gi(t,s){const n=Math.max(0,Date.now()-t),o=Math.floor(n/6e4);if(o<1)return s("bgTaskJustNow");if(o<60)return s("bgTaskMinutes",{n:o});const c=Math.floor(o/60);return c<24?s("bgTaskHours",{n:c}):s("bgTaskDays",{n:Math.floor(c/24)})}function fi({servers:t,send:s,onClose:n}){const o=he(),[c,a]=i.useState(new Set),r=l=>a(u=>{const m=new Set(u);return m.has(l)?m.delete(l):m.add(l),m});return i.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"bg-task-modal",onClick:l=>l.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(it,{})," ",o("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:o("close"),onClick:n,children:e.jsx(Ce,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(it,{}),e.jsx("span",{children:o("bgTasksEmpty")}),e.jsx("small",{children:o("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(l=>e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:o("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[e.jsxs("span",{className:"bg-task-port",children:[":",l.port]}),l.name&&e.jsx("span",{className:"bg-task-name",children:l.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[e.jsxs("span",{children:[o("bgTaskPid")," ",l.pid]}),e.jsxs("span",{children:[o("bgTaskSince")," ",gi(l.since,o)]})]}),l.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${c.has(l.port)?"open":""}`,title:`${o("bgTaskCommand")}: ${l.command}`,onClick:()=>r(l.port),children:[e.jsx(Je,{}),e.jsx("code",{children:l.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:o("bgTaskStop"),onClick:()=>s({type:"kill_background_server",port:l.port}),children:[e.jsx(tt,{}),e.jsx("span",{children:o("bgTaskStop")})]})]},l.port))}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:o("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(ot,{}),e.jsx("span",{children:o("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:o("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(tt,{}),e.jsx("span",{children:o("bgTaskStopAll")})]})]})]})})}function Ye(t,s){return t.toLowerCase().includes(s)}function xi({send:t,sessions:s,projects:n,cwd:o,fileSearch:c,onClose:a,onSwitchSession:r,onSwitchProject:l,onPreviewFile:u}){const m=he(),f=i.useRef(null),[h,k]=i.useState(""),M=i.useDeferredValue(h),[N,D]=i.useState(0),R=i.useRef(1),P=i.useRef(0),A=i.useRef(null);i.useEffect(()=>{t({type:"list_sessions"}),t({type:"list_projects"}),requestAnimationFrame(()=>{var L;return(L=f.current)==null?void 0:L.focus()})},[]);const[p,E]=i.useState(!1);i.useEffect(()=>{A.current&&clearTimeout(A.current);const L=M.trim();if(L)return A.current=setTimeout(()=>{const F=++R.current;P.current=F,E(!0),t({type:"search_files",reqId:F,query:L})},300),()=>{A.current&&clearTimeout(A.current)}},[M]);const I=M.trim().toLowerCase(),y=i.useMemo(()=>I?s.filter(L=>Ye(L.firstMessage??"",I)||Ye(L.name??"",I)||Ye(L.path.split(/[\\/]/).pop()??"",I)).slice(0,20):[],[s,I]),w=i.useMemo(()=>I?n.filter(L=>Ye(L.path,I)).slice(0,10):[],[n,I]),d=i.useMemo(()=>!I||!c||c.reqId!==P.current||!c.ok?[]:c.results,[c,I]);i.useEffect(()=>{c&&c.reqId===P.current&&P.current!==0&&E(!1)},[c]);const S=!!c&&c.ok&&c.truncated,W=i.useMemo(()=>[...y.map(L=>({kind:"session",path:L.path})),...w.map(L=>({kind:"project",path:L.path})),...d.filter(L=>L.type==="file").map(L=>({kind:"file",path:L.path,name:L.name}))],[y,w,d]);i.useEffect(()=>{D(0)},[M]);const K=i.useCallback(L=>{L&&(L.kind==="session"?r(L.path):L.kind==="project"?l(L.path):u(L.path,L.name),a())},[r,l,u,a]);i.useEffect(()=>{const L=F=>{F.key==="Escape"?(F.preventDefault(),F.stopPropagation(),a()):F.key==="ArrowDown"?(F.preventDefault(),D(H=>Math.min(H+1,W.length-1))):F.key==="ArrowUp"?(F.preventDefault(),D(H=>Math.max(H-1,0))):F.key==="Enter"&&(F.preventDefault(),K(W[N]))};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[W,N,K,a]);const oe=y.length+w.length+d.length,ne=(L,F,H)=>e.jsxs("div",{className:"gs-section-head",children:[H,e.jsx("span",{children:L}),e.jsx("em",{children:F})]});let le=-1;return e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:a,children:e.jsxs("div",{className:"gs-modal",onClick:L=>L.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(nt,{}),e.jsx("input",{ref:f,type:"text",value:h,placeholder:m("gsPlaceholder"),onChange:L=>k(L.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:m("close"),onClick:a,children:e.jsx(Ce,{})})]}),e.jsxs("div",{className:"gs-results",children:[!I&&e.jsx("div",{className:"gs-empty",children:m("gsHint")}),I&&oe===0&&!S&&e.jsx("div",{className:"gs-empty",children:m(p?"gsSearching":"gsNoResults")}),y.length>0&&e.jsxs("div",{className:"gs-section",children:[ne(m("gsSessions"),y.length,e.jsx(at,{})),y.map(L=>{le++;const F=le;return e.jsxs("button",{type:"button",className:F===N?"gs-item active":"gs-item",onMouseEnter:()=>D(F),onClick:()=>K({kind:"session",path:L.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[L.name||L.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:L.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:L.firstMessage})]},L.path)})]}),w.length>0&&e.jsxs("div",{className:"gs-section",children:[ne(m("gsProjects"),w.length,e.jsx(qe,{})),w.map(L=>{le++;const F=le,H=o&&L.path===o;return e.jsxs("button",{type:"button",className:F===N?"gs-item active":"gs-item",onMouseEnter:()=>D(F),onClick:()=>K({kind:"project",path:L.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[L.path.split(/[\\/]/).pop(),H&&e.jsx("em",{className:"gs-item-meta",children:m("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:L.path})]},L.path)})]}),(d.length>0||I&&S)&&e.jsxs("div",{className:"gs-section",children:[ne(m("gsFiles"),d.length,e.jsx(Pn,{})),d.map(L=>{le++;const F=le;return e.jsxs("button",{type:"button",className:F===N?"gs-item active":"gs-item",disabled:L.type==="dir",title:L.type==="dir"?void 0:m("gsOpenPreview"),onMouseEnter:()=>D(F),onClick:()=>{L.type==="file"&&K({kind:"file",path:L.path,name:L.name})},children:[e.jsx("span",{className:"gs-item-title",children:L.name}),e.jsx("span",{className:"gs-item-sub",children:L.path})]},`${L.type}:${L.path}`)}),S&&e.jsx("div",{className:"gs-truncated",children:m("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",m("gsNavigate")]}),e.jsxs("span",{children:["Enter ",m("gsOpen")]}),e.jsxs("span",{children:["Esc ",m("gsCloseHint")]})]})]})})}const vt=5e3;function vi({file:t,content:s,send:n,onAddLines:o,onAttach:c,onClose:a}){const r=he(),[l,u]=i.useState(null),[m,f]=i.useState(!1),[h,k]=i.useState(null),[M,N]=i.useState(!1),[D,R]=i.useState(!1),[P,A]=i.useState(!1),[p,E]=i.useState(""),[I,y]=i.useState(!0),w=i.useRef(!1),[d,S]=i.useState(!0),[W,K]=i.useState(!1),[oe,ne]=i.useState(100),le=i.useRef(0),L=i.useRef(!1),F=i.useRef(null);i.useEffect(()=>{f(!0),u(null),k(null),A(!1),E(""),y(!0),w.current=!1,n({type:"read_file",path:t.path})},[t.path,n]),i.useEffect(()=>{s&&s.path===t.path&&(u(s),P||E(s.text),f(!1))},[s,P,t.path]),i.useEffect(()=>{const Y=re=>{if(re.key==="Escape"){x();return}if((re.ctrlKey||re.metaKey)&&re.key.toLowerCase()==="s"&&P){re.preventDefault(),ye();return}const se=re.target,Te=se&&(se.tagName==="INPUT"||se.tagName==="TEXTAREA"||se.isContentEditable);(re.ctrlKey||re.metaKey)&&re.key.toLowerCase()==="a"&&!Te&&(re.preventDefault(),b())};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[a,l,P,p]),i.useEffect(()=>{const Y=()=>{L.current=!1,N(!1)};return window.addEventListener("mouseup",Y),()=>window.removeEventListener("mouseup",Y)},[]);const H=i.useMemo(()=>{if(!l)return[];const Y=l.text.split(`
19
- `);return Y.length>0&&Y[Y.length-1]===""&&Y.pop(),Y.slice(0,vt)},[l]),$=(l==null?void 0:l.lines)??0,V=$>vt,T=(Y,re)=>{if(re){const se=le.current>0?le.current:Y;k({start:Math.min(se,Y),end:Math.max(se,Y)})}else le.current=Y,k({start:Y,end:Y})},b=()=>{H.length!==0&&(le.current=1,k({start:1,end:H.length}))},U=()=>{h&&(o(t.path,t.name,h.start,h.end),R(!0),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>R(!1),1400))},Q=l!==null&&l.kind==="text"&&!l.binary&&!l.truncated,de=()=>{E((l==null?void 0:l.text)??""),A(!1),w.current&&y(!0)},fe=()=>{if(P){if(p!==((l==null?void 0:l.text)??"")&&!window.confirm(r("discardFileChanges")))return;de();return}!Q||!l||(w.current=yt(t.name)&&I,yt(t.name)&&y(!1),k(null),E(l.text),A(!0))},ye=()=>{!P||!l||!Q||n({type:"write_file",path:t.path,text:p})&&(A(!1),w.current&&y(!0),k(null))},x=()=>{P&&p!==((l==null?void 0:l.text)??"")&&!window.confirm(r("discardFileChanges"))||a()},_=Y=>{ne(Math.min(200,Math.max(50,Y)))},ae=h?h.end-h.start+1:0,g=(l==null?void 0:l.binary)??!1,q=(l==null?void 0:l.truncated)??!1,G=(l==null?void 0:l.kind)??"text",te=yt(t.name),me=te&&I&&!P&&G==="text"&&!g,je=Y=>mt(`/api/file?clientId=${encodeURIComponent(Lt())}&path=${encodeURIComponent(Y)}`);return e.jsx("div",{className:`fp-overlay ${W?"fullscreen":""}`,onMouseDown:Y=>{Y.target===Y.currentTarget&&x()},children:e.jsxs("div",{className:`fp ${W?"fullscreen":""}`,style:{"--fp-zoom":oe/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:[l&&G==="text"&&!g&&r("fileLines",{n:$}),l&&` · ${yi(l.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[te&&G==="text"&&!g&&l&&e.jsx("button",{type:"button",className:`fp-attach markdown ${I?"on":""}`,"data-tip":r(I?"showMarkdownSource":"showMarkdownPreview"),disabled:P,onClick:()=>y(Y=>!Y),children:I?e.jsx(Es,{}):e.jsx(Dn,{})}),G==="text"&&!g&&l&&e.jsx("button",{type:"button",className:`fp-attach edit ${P?"on":""}`,"data-tip":r(q?"fileEditTruncated":P?"exitEditFile":"editFile"),disabled:!Q&&!P,onClick:fe,children:e.jsx(kt,{})}),G==="text"&&!g&&!me&&e.jsx("button",{type:"button",className:`fp-attach wrap ${d?"on":""}`,"data-tip":r(d?"disableWrap":"enableWrap"),onClick:()=>S(Y=>!Y),children:e.jsx(Bn,{})}),G==="text"&&l&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":r("zoomOut"),disabled:oe<=50,onClick:()=>_(oe-10),children:e.jsx(fn,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:r("resetZoom"),onClick:()=>ne(100),children:[oe,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":r("zoomIn"),disabled:oe>=200,onClick:()=>_(oe+10),children:e.jsx(xn,{})})]}),G!=="video"&&G!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":r("attachInlineTip"),onClick:()=>c(t.path,t.name,"inline"),children:e.jsx(Ue,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":r("referenceTip"),onClick:()=>c(t.path,t.name,"reference"),children:e.jsx(jt,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${W?"on":""}`,"data-tip":r(W?"exitFullscreen":"fullscreen"),onClick:()=>K(Y=>!Y),children:W?e.jsx(Nn,{}):e.jsx(Sn,{})}),e.jsx("button",{type:"button",className:"fp-close",title:r("close"),onClick:x,children:e.jsx(Ce,{})})]})]}),q&&G==="text"&&!g&&e.jsx("div",{className:"fp-notice",children:r("previewTruncated")}),m&&!l&&e.jsx("div",{className:"fp-empty",children:r("loading")}),!m&&G==="none"&&!g&&e.jsx("div",{className:"fp-empty",children:r("previewNotSupported")}),!m&&G==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:je(t.path),alt:t.name})}),!m&&G==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:je(t.path),controls:!0,preload:"metadata"})}),!m&&me&&l&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(pt,{text:l.text})})}),!m&&g&&G!=="image"&&G!=="video"&&l&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[r("binaryFile"),l.truncated&&r("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:l.text})]}),!m&&P&&G==="text"&&!g&&l&&e.jsx("textarea",{className:`fp-editor ${d?"":"no-wrap"}`,value:p,onChange:Y=>E(Y.target.value),wrap:d?"soft":"off",spellCheck:!1,autoFocus:!0}),!m&&!me&&!P&&G==="text"&&!g&&l&&H.length===0&&e.jsx("div",{className:"fp-empty",children:r("emptyFile")}),!m&&!me&&!P&&G==="text"&&!g&&H.length>0&&e.jsxs("div",{className:`fp-code ${M?"dragging":""} ${d?"":"no-wrap"}`,onMouseDown:Y=>{Y.button===0&&Y.preventDefault()},children:[H.map((Y,re)=>{const se=re+1,Te=h!==null&&se>=h.start&&se<=h.end;return e.jsxs("div",{className:`fp-line ${Te?"sel":""}`,onMouseDown:Ee=>{Ee.button===0&&(T(se,Ee.shiftKey),L.current=!0,N(!0))},onMouseEnter:()=>{L.current&&T(se,!0)},children:[e.jsx("span",{className:"fp-num",children:se}),e.jsx("span",{className:"fp-code-text",children:Y})]},se)}),V&&e.jsx("div",{className:"fp-lines-note",children:r("previewLinesTruncated",{n:vt})})]}),e.jsx("div",{className:"fp-foot",children:P?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:r("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:fe,children:r("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:p===((l==null?void 0:l.text)??""),onClick:ye,children:[e.jsx(jn,{})," ",r("saveFile")]})]})]}):!me&&G==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:h?r("selectedRange",{n:ae,start:h.start,end:h.end}):r("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:H.length===0,onClick:b,children:r("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!h,onClick:()=>k(null),children:r("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!h||g,onClick:U,children:[D?e.jsx(ut,{}):null,r(D?"addedToChat":"addToChat")]})]})]})})]})})}function yt(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function yi(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const Vs="pi-web-sounds",ze={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function Gs(){try{const t=localStorage.getItem(Vs);if(!t)return{...ze};const s=JSON.parse(t),n={...ze,...s};for(const o of["enabled","question","done","start","error"])typeof n[o]!="boolean"&&(n[o]=ze[o]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=ze.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...ze}}}function bi(t){try{localStorage.setItem(Vs,JSON.stringify(t))}catch{}}let Ke=null;function ji(){try{if(!Ke){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;Ke=new t}return Ke.state==="suspended"&&Ke.resume(),Ke}catch{return null}}const ki=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],wi=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],Ni=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],Ci=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],Si={question:ki,done:wi,start:Ni,error:Ci};function Ti(t,s,n){const o=t.createOscillator(),c=t.createGain();o.type=s.type,o.frequency.value=s.freq;const a=t.currentTime+s.start,r=Math.max(1e-4,s.peak*n);c.gain.setValueAtTime(1e-4,a),c.gain.exponentialRampToValueAtTime(r,a+.012),c.gain.exponentialRampToValueAtTime(1e-4,a+s.dur),o.connect(c),c.connect(t.destination),o.start(a),o.stop(a+s.dur+.05)}function Ve(t,s=Gs()){if(!s.enabled||!s[t])return;const n=ji();if(!n)return;const o=Math.max(0,Math.min(1,s.volume/100));for(const c of Si[t])Ti(n,c,o)}const Et="pi-web-ui:theme",Js="dark",xs="theme-stylesheet",vs="pi-web-ui:theme-change";function Qs(){try{const t=localStorage.getItem(Et);if(t&&t!==Js)return t}catch{}return null}function Ei(t){try{t?localStorage.setItem(Et,t):localStorage.removeItem(Et)}catch{}}function Ys(t){let s=document.getElementById(xs);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(vs));return}s||(s=document.createElement("link"),s.id=xs,s.rel="stylesheet",document.head.appendChild(s)),s.href=`/themes/${encodeURIComponent(t)}.css`,s.onload=()=>window.dispatchEvent(new CustomEvent(vs))}async function Mi(){try{const t=await fetch(mt("/api/themes"));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function Ri(){const[t,s]=i.useState([]),[n,o]=i.useState(()=>Qs());return i.useEffect(()=>{let a=!1;return Mi().then(r=>{a||s(r)}),()=>{a=!0}},[]),i.useEffect(()=>{Ys(n),Ei(n)},[n]),{themes:t,theme:n,switchTheme:a=>o(a===Js?null:a)}}function Fi(){const t=getComputedStyle(document.documentElement),s=(n,o)=>t.getPropertyValue(n).trim()||o;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 Ii=i.lazy(()=>ws(()=>import("./TerminalPanel-BxezvWth.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function Li({notice:t,onDismiss:s}){const n=he(),[o,c]=i.useState(!1);i.useEffect(()=>{if(o)return;const r=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(r)},[o,t.id,t.level,s]);const a=t.level==="error"?An:t.level==="warning"?Fn:Rn;return e.jsxs("div",{className:`notice notice-${t.level}${o?" paused":""}`,role:"status",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[e.jsx(a,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:t.text}),e.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>s(t.id),children:e.jsx(Ce,{})})]})}const Pi=[],Xs=180,Zs=520,en=240,tn=t=>`pi-web-ui:${t}-panel-width`;function ys(t){const s=Number(localStorage.getItem(tn(t)));return Number.isFinite(s)&&s>=Xs&&s<=Zs?s:en}function bs({side:t,width:s,onResize:n}){const o=he(),c=i.useCallback(a=>{a.preventDefault();const r=a.clientX,l=s;let u=l;const m=h=>{const k=t==="left"?h.clientX-r:r-h.clientX;u=Math.min(Zs,Math.max(Xs,Math.round(l+k))),n(u)},f=()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",f),document.body.classList.remove("panel-resizing"),localStorage.setItem(tn(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:o("dragToResize"),onPointerDown:c,onDoubleClick:()=>n(en)})}function Bi(){var xe,pe,we,Me,Dt,$t,_t,Ft,At,Ot,Ht,Wt;const t=he(),{chat:s,send:n,dismissNotice:o,pushNotice:c,terminal:a}=ca(),[r,l]=i.useState([]),[u,m]=i.useState(null),[f,h]=i.useState(!1),[k,M]=i.useState("chat"),N=i.useMemo(()=>s.plugins.filter(C=>{var O,ee;return!((ee=(O=s.settings)==null?void 0:O.disabledPlugins)!=null&&ee.includes(C.id))}),[s.plugins,(xe=s.settings)==null?void 0:xe.disabledPlugins]),[D,R]=i.useState([]);i.useEffect(()=>ea(R),[]),i.useEffect(()=>{ta(N,s.pluginsEpoch)},[N,s.pluginsEpoch]);const[P,A]=i.useState(()=>ys("left")),[p,E]=i.useState(()=>ys("right")),I=i.useCallback(C=>A(C),[]),y=i.useCallback(C=>E(C),[]),[w,d]=i.useState(null),[S,W]=i.useState(()=>window.matchMedia("(max-width: 768px)").matches);i.useEffect(()=>{const C=window.matchMedia("(max-width: 768px)"),O=ee=>W(ee.matches);return C.addEventListener("change",O),()=>C.removeEventListener("change",O)},[]);const[K,oe]=i.useState(!1),[ne,le]=i.useState(!1),[L,F]=i.useState(!1),[H,$]=i.useState(!1),[V,T]=i.useState(!1);i.useEffect(()=>{const C=O=>{var Ie,Ut;const ee=O.detail,ve=(ee==null?void 0:ee.title)||"插件命令",be=ee==null?void 0:ee.command;if(!be||!s.ready)return;const Se={name:ve,command:be,cwd:"${pwd}"},ke=s.terminals.find(ht=>ht.title===ve);if(ke)a.restart(ke.id),n({type:"run_command",terminalId:ke.id,conversationId:ke.conversationId,command:Se,cols:80,rows:24});else{const ht=_e();a.create({id:ht,conversationId:s.activeConversationId||((Ie=s.state)==null?void 0:Ie.conversationId)||"",title:ve,cwd:((Ut=s.state)==null?void 0:Ut.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Se})}M("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",C),()=>window.removeEventListener("pi-web-ui:plugin-run-command",C)},[s,a,n]),i.useEffect(()=>{const C=O=>{!(O.ctrlKey||O.metaKey)||O.key.toLowerCase()!=="k"||(O.preventDefault(),T(ee=>!ee))};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[]);const[b,U]=i.useState(Gs),{themes:Q,theme:de,switchTheme:fe}=Ri(),ye=i.useRef(null),x=i.useRef(null),_=i.useRef(0),ae=i.useRef(!1),g=i.useRef(s.terminals);i.useEffect(()=>{bi(b)},[b]),i.useEffect(()=>{var O;const C=g.current;g.current=s.terminals;for(const ee of s.terminals){const ve=((O=ee.command)==null?void 0:O.command)??"",be=C.find(Se=>Se.id===ee.id);!(be!=null&&be.running)||ee.running||(ve.startsWith("pi remove ")?n({type:"extensions_reload"}):(ve.startsWith("pi-web-ui install ")||ve.startsWith("pi-web-ui uninstall "))&&n({type:"plugins_reload"}))}},[s.terminals,n]),i.useEffect(()=>{var ee;const C=((ee=s.state)==null?void 0:ee.isStreaming)??!1,O=ye.current;ye.current=C,O!==null&&(!O&&C?Ve("start",b):O&&!C&&Ve("done",b))},[(pe=s.state)==null?void 0:pe.isStreaming,b]),i.useEffect(()=>{var O;const C=((O=s.dialog)==null?void 0:O.id)??null;C!==null&&C!==x.current&&Ve("question",b),x.current=C},[s.dialog,b]),i.useEffect(()=>{const C=[...s.notices].reverse().find(O=>O.level==="error");C&&C.id!==_.current&&(_.current=C.id,Ve("error",b))},[s.notices,b]);const q=(C,O,ee,ve=!1,be)=>{const Se=`${C}|${ee}|${be?`${be.start}-${be.end}`:""}`;l(ke=>ke.some(Ie=>`${Ie.path}|${Ie.mode}|${Ie.lines?`${Ie.lines.start}-${Ie.lines.end}`:""}`===Se)?ke:[...ke,{path:C,name:O,mode:ee,isDir:ve,...be?{lines:be}:{}}])},G=C=>l(O=>O.filter(ee=>ee.key?ee.key!==C:ee.path!==C)),te=i.useCallback(C=>(!C.type.startsWith("list_")&&!C.type.startsWith("get_")&&d(null),n(C)),[n]),me=i.useRef(0),je=i.useRef(0),Y=C=>{var ve;const O=Date.now();(ve=s.state)!=null&&ve.model&&!s.state.model.vision&&O-je.current>1e4&&(je.current=O,c("warning",t("imageNotSupported")));const ee=`paste-${++me.current}`;l(be=>[...be,{path:"",key:ee,name:C.name,mode:"inline",imageData:C.data,mimeType:C.mimeType}])},re=async C=>{for(const O of C){const ee=await Hs(O);if(!ee){c("error",t("imageLoadFailed",{name:O.name}));continue}Y(ee)}},se=20*1024*1024,Te=i.useRef(0),Ee=async C=>{if(C.size>se){c("warning",t("fileTooLarge",{name:C.name,size:se/1024/1024}));return}let O;try{O=(await new Promise((be,Se)=>{const ke=new FileReader;ke.onload=()=>be(ke.result),ke.onerror=()=>Se(ke.error??new Error("read failed")),ke.readAsDataURL(C)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",t("fileLoadFailed",{name:C.name}));return}const ee=`upload-${++Te.current}`;l(ve=>[...ve,{path:"",key:ee,name:C.name,mode:"inline",fileData:O,size:C.size,mimeType:C.type||void 0}])},Re=async C=>{for(const O of C)Pe(O.type)?await re([O]):await Ee(O)},Ae=i.useCallback((C,O,ee)=>{n({type:"edit_message",messageId:C,text:O,attachments:ee})},[n]),j=i.useCallback(()=>le(!0),[]),B=i.useCallback(()=>l([]),[]),Z=i.useCallback(G,[]),X=i.useCallback(re,[re]),ce=i.useCallback(Re,[Re]),ue=(we=s.state)==null?void 0:we.model,ge=(Me=s.state)==null?void 0:Me.thinkingLevel,v=(Dt=s.state)==null?void 0:Dt.availableThinkingLevels,ie=i.useMemo(()=>ue?{model:ue,thinkingLevel:ge??"off",availableThinkingLevels:v??[]}:null,[ue,ge,v]),J=i.useCallback(()=>{var C,O;return!s.ready||s.terminals.length!==0?!1:(a.create({id:_e(),conversationId:s.activeConversationId||((C=s.state)==null?void 0:C.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((O=s.state)==null?void 0:O.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,($t=s.state)==null?void 0:$t.cwd,s.terminals.length,t,a]);return i.useEffect(()=>{if(ae.current){if(k!=="terminal"||s.terminals.length!==0){ae.current=!1;return}J()&&(ae.current=!1)}},[s.terminals.length,J,k]),e.jsxs("div",{className:"app",onDragOver:C=>{var O;Array.from(((O=C.dataTransfer)==null?void 0:O.types)??[]).includes("Files")&&(C.preventDefault(),h(!0))},onDragLeave:C=>{C.currentTarget.contains(C.relatedTarget)||h(!1)},onDrop:C=>{var be,Se;if(h(!1),!Array.from(((be=C.dataTransfer)==null?void 0:be.types)??[]).includes("Files"))return;C.preventDefault();const O=Array.from(((Se=C.dataTransfer)==null?void 0:Se.files)??[]);if(O.length===0){c("warning",t("foldersNotSupported"));return}const ee=O.filter(ke=>Pe(ke.type)),ve=O.filter(ke=>!Pe(ke.type));ee.length>0&&re(ee),ve.length>0&&Re(ve)},children:[f&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(Kn,{chat:s,send:n,terminal:a,view:k,plugins:N,onViewChange:C=>{ae.current=C==="terminal"&&s.terminals.length===0,ae.current&&J()&&(ae.current=!1),M(C),d(null)},onOpenPanel:d,onManageModels:()=>le(!0),onOpenSettings:()=>F(!0),onOpenBgTasks:()=>$(!0),onOpenGlobalSearch:()=>T(!0),sound:b,onSoundChange:U,onSoundPreview:C=>Ve(C,b),themes:Q,theme:de,onThemeChange:fe}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(C=>e.jsx(Li,{notice:C,onDismiss:o},C.id))}),e.jsxs("div",{className:"layout",style:{"--left-w":`${P}px`,"--right-w":`${p}px`},children:[w&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>d(null)}),e.jsxs("div",{className:`view-pane ${k==="chat"?"":"hidden"}`,children:[e.jsx("div",{className:`panel-drawer drawer-left ${w==="left"?"open":""}`,children:e.jsx(Vn,{send:te,active:!S||w==="left",ready:s.ready,status:s.status,cwd:((_t=s.state)==null?void 0:_t.cwd)??"",sessionFile:((Ft=s.state)==null?void 0:Ft.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!S&&e.jsx(bs,{side:"left",width:P,onResize:I}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(ti,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:Ae,onKillBash:()=>n({type:"abort_bash"})},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(ni,{send:n,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId}),s.dialog&&e.jsx(ri,{dialog:s.dialog,send:n}),e.jsx(si,{send:n,ready:s.ready,streaming:((At=s.state)==null?void 0:At.isStreaming)??!1,messages:((Ot=s.state)==null?void 0:Ot.messages)??Pi,slashCommands:s.slashCommands,modelState:ie,models:s.models,modelsLoading:s.modelsLoading,attachments:r,onRemoveAttachment:Z,onAddImageFiles:X,onAddLocalFiles:ce,onNotice:c,onManageModels:j,onSent:B})]}),!S&&e.jsx(bs,{side:"right",width:p,onResize:y}),e.jsx("div",{className:`panel-drawer drawer-right ${w==="right"?"open":""}`,children:e.jsx(va,{send:te,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((Ht=s.state)==null?void 0:Ht.cwd)??"",onAttach:(C,O,ee,ve)=>{d(null),q(C,O,ee,ve)},onPreview:(C,O)=>{d(null),m({path:C,name:O})},onNotice:(C,O)=>c(C,O)})})]}),e.jsx("div",{className:`view-pane ${k==="terminal"?"":"hidden"}`,children:e.jsx(i.Suspense,{fallback:null,children:e.jsx(Ii,{chat:s,send:n,terminal:a})})}),e.jsx("div",{className:`view-pane ${k==="git"?"":"hidden"}`,children:e.jsx(li,{chat:s,send:n,terminal:a,active:k==="git",onSwitchToTerminal:()=>M("terminal")})}),D.map(C=>{const O=`plugin:${C.info.id}`;return e.jsx("div",{className:`view-pane ${k===O?"":"hidden"}`,children:e.jsx(ci,{entry:C,send:n})},C.info.id)})]}),e.jsx(ai,{chat:s,send:n}),u&&e.jsx(vi,{file:u,content:s.fileContent,send:n,onAddLines:(C,O,ee,ve)=>q(C,O,"lines",!1,{start:ee,end:ve}),onAttach:(C,O,ee)=>q(C,O,ee),onClose:()=>m(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!K&&!ne&&e.jsx(di,{send:n,piConfigured:s.state.piConfigured,providers:s.providers,installResult:s.installResult,onClose:()=>oe(!0)}),ne&&e.jsx(pi,{send:n,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>le(!1)}),L&&e.jsx(hi,{chat:s,send:n,terminal:a,onSwitchToTerminal:()=>M("terminal"),onClose:()=>F(!1)}),H&&e.jsx(fi,{servers:s.bgServers,send:n,onClose:()=>$(!1)}),V&&e.jsx(xi,{send:n,sessions:s.sessions,projects:s.projects,cwd:((Wt=s.state)==null?void 0:Wt.cwd)??"",fileSearch:s.fileSearch,onClose:()=>T(!1),onSwitchSession:C=>{n({type:"switch_session",path:C})},onSwitchProject:C=>{n({type:"set_cwd",path:C})},onPreviewFile:(C,O)=>{m({path:C,name:O})}})]})}Gn();Ys(Qs());rn.createRoot(document.getElementById("root")).render(e.jsx(i.StrictMode,{children:e.jsx(Un,{children:e.jsx(Bi,{})})}));export{ot as F,vs as T,Ue as a,Fi as b,_i as c,Yt as d,$e as e,Ce as f,Cn as g,Je as h,_e as r,he as u};