pi-web-ui 0.54.0 → 0.55.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,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-
|
|
2
|
-
import{R as We,a as r,j as e,M as Ms,b as yn,c as kn}from"./markdown-DRBrS2Nf.js";import{r as Rs}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"]'))l(c);new MutationObserver(c=>{for(const i of c)if(i.type==="childList")for(const n of i.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&l(n)}).observe(document,{childList:!0,subtree:!0});function a(c){const i={};return c.integrity&&(i.integrity=c.integrity),c.referrerPolicy&&(i.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?i.credentials="include":c.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function l(c){if(c.ep)return;c.ep=!0;const i=a(c);fetch(c.href,i)}})();var nt={},Jt;function bn(){if(Jt)return nt;Jt=1;var t=Rs();return nt.createRoot=t.createRoot,nt.hydrateRoot=t.hydrateRoot,nt}var jn=bn();const wn="modulepreload",Nn=function(t){return"/"+t},Qt={},Ps=function(s,a,l){let c=Promise.resolve();if(a&&a.length>0){let n=function(h){return Promise.all(h.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),u=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));c=n(a.map(h=>{if(h=Nn(h),h in Qt)return;Qt[h]=!0;const p=h.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${g}`))return;const k=document.createElement("link");if(k.rel=p?"stylesheet":wn,p||(k.as="script"),k.crossOrigin="",k.href=h,u&&k.setAttribute("nonce",u),document.head.appendChild(k),p)return new Promise((b,N)=>{k.addEventListener("load",b),k.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${h}`)))})}))}function i(n){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=n,window.dispatchEvent(o),!o.defaultPrevented)throw n}return c.then(n=>{for(const o of n||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};var Is={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Xt=We.createContext&&We.createContext(Is),Cn=["attr","size","title"];function Sn(t,s){if(t==null)return{};var a,l,c=Tn(t,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(l=0;l<i.length;l++)a=i[l],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(c[a]=t[a])}return c}function Tn(t,s){if(t==null)return{};var a={};for(var l in t)if({}.hasOwnProperty.call(t,l)){if(s.indexOf(l)!==-1)continue;a[l]=t[l]}return a}function ot(){return ot=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var l in a)({}).hasOwnProperty.call(a,l)&&(t[l]=a[l])}return t},ot.apply(null,arguments)}function Zt(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);s&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),a.push.apply(a,l)}return a}function ct(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Zt(Object(a),!0).forEach(function(l){En(t,l,a[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):Zt(Object(a)).forEach(function(l){Object.defineProperty(t,l,Object.getOwnPropertyDescriptor(a,l))})}return t}function En(t,s,a){return(s=Mn(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function Mn(t){var s=Rn(t,"string");return typeof s=="symbol"?s:s+""}function Rn(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var l=a.call(t,s);if(typeof l!="object")return l;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Ls(t){return t&&t.map((s,a)=>We.createElement(s.tag,ct({key:a},s.attr),Ls(s.child)))}function G(t){return s=>We.createElement(Pn,ot({attr:ct({},t.attr)},s),Ls(t.child))}function Pn(t){var s=a=>{var l=t.attr,c=t.size,i=t.title,n=Sn(t,Cn),o=c||a.size||"1em",u;return a.className&&(u=a.className),t.className&&(u=(u?u+" ":"")+t.className),We.createElement("svg",ot({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},a.attr,l,n,{className:u,style:ct(ct({color:t.color||a.color},a.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&We.createElement("title",null,i),t.children)};return Xt!==void 0?We.createElement(Xt.Consumer,null,a=>s(a)):s(Is)}function In(t){return G({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 Ln(t){return G({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"11",y1:"8",x2:"11",y2:"14"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(t)}function at(t){return G({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 we(t){return G({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 Ds(t){return G({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 Dn(t){return G({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 Ie(t){return G({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 ze(t){return G({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 es(t){return G({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 Bn(t){return G({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 dt(t){return G({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 An(t){return G({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"4",y1:"21",x2:"4",y2:"14"},child:[]},{tag:"line",attr:{x1:"4",y1:"10",x2:"4",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"20",y1:"21",x2:"20",y2:"16"},child:[]},{tag:"line",attr:{x1:"20",y1:"12",x2:"20",y2:"3"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"7",y2:"14"},child:[]},{tag:"line",attr:{x1:"9",y1:"8",x2:"15",y2:"8"},child:[]},{tag:"line",attr:{x1:"17",y1:"16",x2:"23",y2:"16"},child:[]}]})(t)}function ut(t){return G({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 Bs(t){return G({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 pt(t){return G({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 _n(t){return G({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 As(t){return G({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"1 4 1 10 7 10"},child:[]},{tag:"path",attr:{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"},child:[]}]})(t)}function ht(t){return G({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 _e(t){return G({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 br(t){return G({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 Fn(t){return G({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 ts(t){return G({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 $n(t){return G({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 On(t){return G({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 Ve(t){return G({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 Wn(t){return G({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 qn(t){return G({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 Hn(t){return G({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 Un(t){return G({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 Tt(t){return G({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 mt(t){return G({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 Kn(t){return G({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 zn(t){return G({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 Vn(t){return G({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 Gn(t){return G({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"14",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"3",y:"14",width:"7",height:"7"},child:[]}]})(t)}function Yn(t){return G({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 ss(t){return G({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 rt(t){return G({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 Ge(t){return G({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 _s(t){return G({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 Fs(t){return G({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 Et(t){return G({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 Mt(t){return G({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 Rt(t){return G({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 At(t){return G({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 tt(t){return G({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 Jn(t){return G({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 _t(t){return G({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 Qn(t){return G({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 gt(t){return G({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 ft(t){return G({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 qe(t){return G({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 xt(t){return G({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 Xn(t){return G({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 ns(t){return G({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 Zn(t){return G({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 $s(t){return G({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 Os(t){return G({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 ei(t){return G({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 ti(t){return G({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 si(t){return t.map(s=>s.kind==="package"?`pi update npm:${s.name}`:`npm i -g ${s.name}@latest`).join("; ")}function De(){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 a=0;a<16;a++)t[a]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(a=>a.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 Ae({trigger:t,open:s,onOpenChange:a,children:l,align:c="right",fit:i=!1,direction:n="down",menuClassName:o,menuRef:u,menuStyle:h}){const p=r.useRef(null);return r.useEffect(()=>{if(!s)return;const g=b=>{p.current&&!p.current.contains(b.target)&&a(!1)},k=b=>{b.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",k),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",k)}},[s,a]),e.jsxs("div",{className:`dropdown ${c} ${i?"fit":""} ${n==="up"?"dd-up":""}`,ref:p,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>a(!s),"aria-expanded":s,children:[t,e.jsx(qe,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${o??""}`,ref:u,style:h,children:l})]})}function Ne({active:t,disabled:s=!1,title:a,onClick:l,children:c}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:a,onClick:l,children:c})}const Ws="pi-web-ui:lang",ni={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:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",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:"技能",slashPlugin:"插件",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 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",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 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",directory:"目录",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",modelUsedCount:"已用 {n} 次",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:搜索历史对话全文(含 AI 回复)、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","tpl.title":"提示词模板","tpl.hint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.clickCard":"点击填入输入框","tpl.editTpl":"编辑 / 删除模板","tpl.openPicker":"提示词模板(常用提示词,随时取用)","tpl.pickerTitle":"提示词模板","tpl.pickerHint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.add":"新建模板","tpl.addDesc":"把常用工作流存成模板","tpl.reset":"恢复默认模板","tpl.resetConfirm":"确认恢复默认?","tpl.builtin":"内置","tpl.custom":"自定义","tpl.newTitle":"新建提示词模板","tpl.editTitle":"编辑提示词模板","tpl.fieldIcon":"图标","tpl.fieldTitle":"标题","tpl.fieldTitlePh":"卡片上显示的短标题","tpl.fieldDesc":"说明","tpl.fieldDescPh":"一句话说明,显示在卡片上","tpl.fieldPrompt":"提示词","tpl.fieldPromptPh":"完整提示词 —— 发送给智能体的内容","tpl.required":"标题和提示词不能为空","tpl.save":"保存修改","tpl.fill":"填入输入框","tpl.fillTip":"填入输入框,可再编辑后发送","tpl.sendNow":"直接发送","tpl.sendTip":"立即作为新对话发送","tpl.delete":"删除","tpl.deleteTip":"删除这个自定义模板","tpl.remove":"移出模板库","tpl.removeTip":"把内置模板移出模板库,可在底部「恢复默认模板」找回","tpl.restore":"恢复默认","tpl.restoreTip":"撤掉你的修改,恢复内置默认","tpl.sk.setup":"仓库初始化","tpl.sk.setup.desc":"让仓库了解它的构建与约定","tpl.sk.setup.prompt":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-BQakjBG_.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 We,a as r,j as e,M as Ps,b as kn,c as bn}from"./markdown-DRBrS2Nf.js";import{r as Is}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"]'))l(c);new MutationObserver(c=>{for(const a of c)if(a.type==="childList")for(const n of a.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&l(n)}).observe(document,{childList:!0,subtree:!0});function i(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 l(c){if(c.ep)return;c.ep=!0;const a=i(c);fetch(c.href,a)}})();var it={},Xt;function jn(){if(Xt)return it;Xt=1;var t=Is();return it.createRoot=t.createRoot,it.hydrateRoot=t.hydrateRoot,it}var wn=jn();const Nn="modulepreload",Cn=function(t){return"/"+t},Zt={},Sn=function(s,i,l){let c=Promise.resolve();if(i&&i.length>0){let n=function(h){return Promise.all(h.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),u=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));c=n(i.map(h=>{if(h=Cn(h),h in Zt)return;Zt[h]=!0;const p=h.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${h}"]${g}`))return;const k=document.createElement("link");if(k.rel=p?"stylesheet":Nn,p||(k.as="script"),k.crossOrigin="",k.href=h,u&&k.setAttribute("nonce",u),document.head.appendChild(k),p)return new Promise((b,N)=>{k.addEventListener("load",b),k.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${h}`)))})}))}function a(n){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=n,window.dispatchEvent(o),!o.defaultPrevented)throw n}return c.then(n=>{for(const o of n||[])o.status==="rejected"&&a(o.reason);return s().catch(a)})};var Ls={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},es=We.createContext&&We.createContext(Ls),Tn=["attr","size","title"];function En(t,s){if(t==null)return{};var i,l,c=Mn(t,s);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);for(l=0;l<a.length;l++)i=a[l],s.indexOf(i)===-1&&{}.propertyIsEnumerable.call(t,i)&&(c[i]=t[i])}return c}function Mn(t,s){if(t==null)return{};var i={};for(var l in t)if({}.hasOwnProperty.call(t,l)){if(s.indexOf(l)!==-1)continue;i[l]=t[l]}return i}function ct(){return ct=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var i=arguments[s];for(var l in i)({}).hasOwnProperty.call(i,l)&&(t[l]=i[l])}return t},ct.apply(null,arguments)}function ts(t,s){var i=Object.keys(t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);s&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),i.push.apply(i,l)}return i}function dt(t){for(var s=1;s<arguments.length;s++){var i=arguments[s]!=null?arguments[s]:{};s%2?ts(Object(i),!0).forEach(function(l){Rn(t,l,i[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(i)):ts(Object(i)).forEach(function(l){Object.defineProperty(t,l,Object.getOwnPropertyDescriptor(i,l))})}return t}function Rn(t,s,i){return(s=Pn(s))in t?Object.defineProperty(t,s,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[s]=i,t}function Pn(t){var s=In(t,"string");return typeof s=="symbol"?s:s+""}function In(t,s){if(typeof t!="object"||!t)return t;var i=t[Symbol.toPrimitive];if(i!==void 0){var l=i.call(t,s);if(typeof l!="object")return l;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Bs(t){return t&&t.map((s,i)=>We.createElement(s.tag,dt({key:i},s.attr),Bs(s.child)))}function G(t){return s=>We.createElement(Ln,ct({attr:dt({},t.attr)},s),Bs(t.child))}function Ln(t){var s=i=>{var l=t.attr,c=t.size,a=t.title,n=En(t,Tn),o=c||i.size||"1em",u;return i.className&&(u=i.className),t.className&&(u=(u?u+" ":"")+t.className),We.createElement("svg",ct({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},i.attr,l,n,{className:u,style:dt(dt({color:t.color||i.color},i.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),a&&We.createElement("title",null,a),t.children)};return es!==void 0?We.createElement(es.Consumer,null,i=>s(i)):s(Ls)}function Bn(t){return G({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 Dn(t){return G({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 rt(t){return G({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 we(t){return G({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 Ds(t){return G({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 An(t){return G({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 Ie(t){return G({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 ze(t){return G({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 ss(t){return G({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 _n(t){return G({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 ut(t){return G({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 Fn(t){return G({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"4",y1:"21",x2:"4",y2:"14"},child:[]},{tag:"line",attr:{x1:"4",y1:"10",x2:"4",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"20",y1:"21",x2:"20",y2:"16"},child:[]},{tag:"line",attr:{x1:"20",y1:"12",x2:"20",y2:"3"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"7",y2:"14"},child:[]},{tag:"line",attr:{x1:"9",y1:"8",x2:"15",y2:"8"},child:[]},{tag:"line",attr:{x1:"17",y1:"16",x2:"23",y2:"16"},child:[]}]})(t)}function pt(t){return G({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 As(t){return G({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 mt(t){return G({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 $n(t){return G({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 _s(t){return G({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"1 4 1 10 7 10"},child:[]},{tag:"path",attr:{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"},child:[]}]})(t)}function gt(t){return G({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 _e(t){return G({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 Sr(t){return G({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 On(t){return G({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 ns(t){return G({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 G({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 qn(t){return G({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 Ve(t){return G({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 Un(t){return G({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 Hn(t){return G({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 Kn(t){return G({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 zn(t){return G({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 Mt(t){return G({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 ht(t){return G({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 Vn(t){return G({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 Gn(t){return G({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 Yn(t){return G({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 Jn(t){return G({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"14",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"3",y:"14",width:"7",height:"7"},child:[]}]})(t)}function Qn(t){return G({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 is(t){return G({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 lt(t){return G({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 Ge(t){return G({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 Fs(t){return G({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 $s(t){return G({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 Rt(t){return G({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 Pt(t){return G({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 It(t){return G({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 Ft(t){return G({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 st(t){return G({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 Xn(t){return G({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 $t(t){return G({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 Zn(t){return G({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 ft(t){return G({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 xt(t){return G({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 qe(t){return G({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 vt(t){return G({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 ei(t){return G({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 as(t){return G({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 ti(t){return G({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 Os(t){return G({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 Ws(t){return G({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 si(t){return G({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 ni(t){return G({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 ii(t){return t.map(s=>s.kind==="package"?`pi update npm:${s.name}`:`npm i -g ${s.name}@latest`).join("; ")}function Be(){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 i=0;i<16;i++)t[i]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(i=>i.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 Ae({trigger:t,open:s,onOpenChange:i,children:l,align:c="right",fit:a=!1,direction:n="down",menuClassName:o,menuRef:u,menuStyle:h}){const p=r.useRef(null);return r.useEffect(()=>{if(!s)return;const g=b=>{p.current&&!p.current.contains(b.target)&&i(!1)},k=b=>{b.key==="Escape"&&i(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",k),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",k)}},[s,i]),e.jsxs("div",{className:`dropdown ${c} ${a?"fit":""} ${n==="up"?"dd-up":""}`,ref:p,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>i(!s),"aria-expanded":s,children:[t,e.jsx(qe,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${o??""}`,ref:u,style:h,children:l})]})}function Ne({active:t,disabled:s=!1,title:i,onClick:l,children:c}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:i,onClick:l,children:c})}const qs="pi-web-ui:lang",ai={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:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",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:"技能",slashPlugin:"插件",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 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",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 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",directory:"目录",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",modelUsedCount:"已用 {n} 次",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:搜索历史对话全文(含 AI 回复)、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","tpl.title":"提示词模板","tpl.hint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.clickCard":"点击填入输入框","tpl.editTpl":"编辑 / 删除模板","tpl.openPicker":"提示词模板(常用提示词,随时取用)","tpl.pickerTitle":"提示词模板","tpl.pickerHint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.add":"新建模板","tpl.addDesc":"把常用工作流存成模板","tpl.reset":"恢复默认模板","tpl.resetConfirm":"确认恢复默认?","tpl.builtin":"内置","tpl.custom":"自定义","tpl.newTitle":"新建提示词模板","tpl.editTitle":"编辑提示词模板","tpl.fieldIcon":"图标","tpl.fieldTitle":"标题","tpl.fieldTitlePh":"卡片上显示的短标题","tpl.fieldDesc":"说明","tpl.fieldDescPh":"一句话说明,显示在卡片上","tpl.fieldPrompt":"提示词","tpl.fieldPromptPh":"完整提示词 —— 发送给智能体的内容","tpl.required":"标题和提示词不能为空","tpl.save":"保存修改","tpl.fill":"填入输入框","tpl.fillTip":"填入输入框,可再编辑后发送","tpl.sendNow":"直接发送","tpl.sendTip":"立即作为新对话发送","tpl.delete":"删除","tpl.deleteTip":"删除这个自定义模板","tpl.remove":"移出模板库","tpl.removeTip":"把内置模板移出模板库,可在底部「恢复默认模板」找回","tpl.restore":"恢复默认","tpl.restoreTip":"撤掉你的修改,恢复内置默认","tpl.sk.setup":"仓库初始化","tpl.sk.setup.desc":"让仓库了解它的构建与约定","tpl.sk.setup.prompt":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
|
|
3
3
|
|
|
4
4
|
1. 项目类型、技术栈与目录结构
|
|
5
5
|
2. 构建 / 测试 / 运行 / 格式化的具体命令
|
|
@@ -149,7 +149,7 @@ import{R as We,a as r,j as e,M as Ms,b as yn,c as kn}from"./markdown-DRBrS2Nf.js
|
|
|
149
149
|
2. 用最小实现让测试通过
|
|
150
150
|
3. 重构并保持测试通过
|
|
151
151
|
|
|
152
|
-
避免三种反模式:与实现耦合的测试、空洞断言(永远为真)、横向切片(只测表面)。每步汇报并运行测试。`,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_* 工具,也不会收到相关使用引导",settingsMessageDisplay:"消息显示",thinkingWrap:"完整显示思考",thinkingWrapDesc:"开启:思考内容始终完整展开并自动换行(流式推理过程也实时可见);关闭:折叠成一行摘要,流式中一行实时显示最新文本",toolsWrap:"完整显示工具",toolsWrapDesc:"开启:工具调用始终完整展开显示参数和输出;关闭:默认折叠,点击展开",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:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},ii={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",allProviders:"All",providers:"Providers",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",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",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",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",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-web-ui",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-web-ui",updateTerminalHint:"Clicking runs npm i -g pi-web-ui@latest in a visible terminal; restart the service afterwards to take effect (pi-web-ui server restart).",updatesAllTitle:"Component updates",updatesAllBadge:"{n} updates",updatesAllUpToDate:"All components up to date",kindWebUi:"Web UI",kindPiCore:"Core",kindPackage:"Package",updatesAllRefresh:"Re-check all",updateCheckFailed:"Check failed",updateBtn:"Update",updateAllBtn:"Update all",updatePkgTabTitle:"Update {name}",updateAllTabTitle:"Update all components",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:",cliReadyHint:"✅ pi agent CLI already installed locally. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",directory:"Directory",waitingResponse:"Waiting for model response…",backToBottom:"Back to bottom",questionNavTitle:"Questions",searchPlaceholder:"Search in conversation…",searchNoResults:"No results",searchModels:"Filter models…",noModelMatches:"No matching models",modelUsedCount:"used {n}×",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search full conversation text (AI replies included), recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching…",gsTruncated:"Too many matches — showing a subset",gsCurrentProject:"current",gsOpenPreview:"Open file preview",gsNavigate:"select",gsOpen:"open",gsCloseHint:"close",bgTaskCommand:"Command",searchPrev:"Previous (Shift+Enter)",searchNext:"Next (Enter)",searchClose:"Close (Esc)",questionNavTip:"All questions in this conversation — hover to expand, click to jump","tpl.title":"Prompt templates","tpl.hint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.clickCard":"Click to fill the input","tpl.editTpl":"Edit / delete template","tpl.openPicker":"Prompt templates (reusable prompts, anytime)","tpl.pickerTitle":"Prompt templates","tpl.pickerHint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.add":"New template","tpl.addDesc":"Save a workflow you use often","tpl.reset":"Restore defaults","tpl.resetConfirm":"Restore defaults?","tpl.builtin":"Built-in","tpl.custom":"Custom","tpl.newTitle":"New prompt template","tpl.editTitle":"Edit prompt template","tpl.fieldIcon":"Icon","tpl.fieldTitle":"Title","tpl.fieldTitlePh":"Short title shown on the card","tpl.fieldDesc":"Description","tpl.fieldDescPh":"One-liner shown on the card","tpl.fieldPrompt":"Prompt","tpl.fieldPromptPh":"The full prompt sent to the agent","tpl.required":"Title and prompt are required","tpl.save":"Save","tpl.fill":"Fill input","tpl.fillTip":"Fill the input so you can tweak it before sending","tpl.sendNow":"Send now","tpl.sendTip":"Send immediately as a new conversation","tpl.delete":"Delete","tpl.deleteTip":"Delete this custom template","tpl.remove":"Remove from library","tpl.removeTip":"Remove this built-in template; restore later via “Restore defaults”","tpl.restore":"Restore default","tpl.restoreTip":"Discard your edits and restore the built-in default","tpl.sk.setup":"Repo setup","tpl.sk.setup.desc":"Give the repo a baseline that other workflows can use","tpl.sk.setup.prompt":`Scan this repository and build the baseline context other workflows rely on, then report concisely:
|
|
152
|
+
避免三种反模式:与实现耦合的测试、空洞断言(永远为真)、横向切片(只测表面)。每步汇报并运行测试。`,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_* 工具,也不会收到相关使用引导",settingsMessageDisplay:"消息显示",thinkingWrap:"完整显示思考",thinkingWrapDesc:"开启:思考内容始终完整展开并自动换行(流式推理过程也实时可见);关闭:折叠成一行摘要,流式中一行实时显示最新文本",toolsWrap:"完整显示工具",toolsWrapDesc:"开启:工具调用始终完整展开显示参数和输出;关闭:默认折叠,点击展开",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:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},ri={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",allProviders:"All",providers:"Providers",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",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",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",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",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-web-ui",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-web-ui",updateTerminalHint:"Clicking runs npm i -g pi-web-ui@latest in a visible terminal; restart the service afterwards to take effect (pi-web-ui server restart).",updatesAllTitle:"Component updates",updatesAllBadge:"{n} updates",updatesAllUpToDate:"All components up to date",kindWebUi:"Web UI",kindPiCore:"Core",kindPackage:"Package",updatesAllRefresh:"Re-check all",updateCheckFailed:"Check failed",updateBtn:"Update",updateAllBtn:"Update all",updatePkgTabTitle:"Update {name}",updateAllTabTitle:"Update all components",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:",cliReadyHint:"✅ pi agent CLI already installed locally. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",directory:"Directory",waitingResponse:"Waiting for model response…",backToBottom:"Back to bottom",questionNavTitle:"Questions",searchPlaceholder:"Search in conversation…",searchNoResults:"No results",searchModels:"Filter models…",noModelMatches:"No matching models",modelUsedCount:"used {n}×",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search full conversation text (AI replies included), recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching…",gsTruncated:"Too many matches — showing a subset",gsCurrentProject:"current",gsOpenPreview:"Open file preview",gsNavigate:"select",gsOpen:"open",gsCloseHint:"close",bgTaskCommand:"Command",searchPrev:"Previous (Shift+Enter)",searchNext:"Next (Enter)",searchClose:"Close (Esc)",questionNavTip:"All questions in this conversation — hover to expand, click to jump","tpl.title":"Prompt templates","tpl.hint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.clickCard":"Click to fill the input","tpl.editTpl":"Edit / delete template","tpl.openPicker":"Prompt templates (reusable prompts, anytime)","tpl.pickerTitle":"Prompt templates","tpl.pickerHint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.add":"New template","tpl.addDesc":"Save a workflow you use often","tpl.reset":"Restore defaults","tpl.resetConfirm":"Restore defaults?","tpl.builtin":"Built-in","tpl.custom":"Custom","tpl.newTitle":"New prompt template","tpl.editTitle":"Edit prompt template","tpl.fieldIcon":"Icon","tpl.fieldTitle":"Title","tpl.fieldTitlePh":"Short title shown on the card","tpl.fieldDesc":"Description","tpl.fieldDescPh":"One-liner shown on the card","tpl.fieldPrompt":"Prompt","tpl.fieldPromptPh":"The full prompt sent to the agent","tpl.required":"Title and prompt are required","tpl.save":"Save","tpl.fill":"Fill input","tpl.fillTip":"Fill the input so you can tweak it before sending","tpl.sendNow":"Send now","tpl.sendTip":"Send immediately as a new conversation","tpl.delete":"Delete","tpl.deleteTip":"Delete this custom template","tpl.remove":"Remove from library","tpl.removeTip":"Remove this built-in template; restore later via “Restore defaults”","tpl.restore":"Restore default","tpl.restoreTip":"Discard your edits and restore the built-in default","tpl.sk.setup":"Repo setup","tpl.sk.setup.desc":"Give the repo a baseline that other workflows can use","tpl.sk.setup.prompt":`Scan this repository and build the baseline context other workflows rely on, then report concisely:
|
|
153
153
|
|
|
154
154
|
1. Project type, tech stack and directory layout
|
|
155
155
|
2. Concrete commands for build / test / run / format
|
|
@@ -299,22 +299,22 @@ Keep going until the plan holds up.`,"tpl.sk.tdd":"Test-driven","tpl.sk.tdd.desc
|
|
|
299
299
|
2. Make them pass with the minimal implementation
|
|
300
300
|
3. Refactor while keeping tests green
|
|
301
301
|
|
|
302
|
-
Avoid three test anti-patterns: tests coupled to the implementation, tautological assertions (always true), and horizontal slicing (surface only). Report after each step and run the tests.`,error:"Error",done:"Done",running:"Running…",toolQueued:"Queued",copyArgs:"Copy args",errorOutput:"Error output",output:"Output",waitingOutput:"Waiting for output…",toolDoneWaitingModel:"Done · waiting on model",waitingModel:"Waiting for model response…",thinkingNow:"Thinking",thinkingPreview:"Thinking: {preview}",commands:"Commands",newCommand:"New command",newTerminal:"New terminal",name:"Name",command:"Command",cwdHint:"(${pwd} = current working directory)",noCommands:"No commands yet — click + to add one",clickToRun:"Click to run",edit:"Edit",delete:"Delete",confirmQ:"Confirm?",builtinTerminal:"Built-in terminal",termEmptySub:"Click a command on the left to run it, or + on the right for a new terminal",noTerminal:"No terminals",exited:"(exited{code})",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",settingsMessageDisplay:"Message display",thinkingWrap:"Show full thinking",thinkingWrapDesc:"On: thinking always expands fully and wraps (live reasoning visible while streaming); Off: collapses to a one-line summary with the latest text shown live while streaming",toolsWrap:"Show full tools",toolsWrapDesc:"On: tool calls always expand fully showing arguments and output; Off: collapsed by default, click to expand",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",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",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…"},qs=r.createContext(null);function ai(){try{const t=localStorage.getItem(Ws);if(t==="zh"||t==="en")return t}catch{}return"zh"}function ri({children:t}){const[s,a]=r.useState(ai),l=r.useCallback(n=>{a(n);try{localStorage.setItem(Ws,n)}catch{}},[]),c=r.useCallback((n,o)=>{let u=ii[n];if(s==="zh"&&(u=ni[n]),o)for(const[h,p]of Object.entries(o))u=u.replaceAll(`{${h}}`,String(p));return u},[s]);r.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en"},[s]);const i=r.useMemo(()=>({locale:s,setLocale:l,t:c}),[s,l,c]);return e.jsx(qs.Provider,{value:i,children:t})}function Ft(){const t=r.useContext(qs);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function pe(){return Ft().t}const li=[{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 is({settings:t,onChange:s,onPreview:a}){const l=pe(),c=i=>s({...t,...i});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:l("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Ds,{className:"sound-icon"}),e.jsx("span",{children:l("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:i=>c({enabled:i.target.checked})})]}),li.map(({kind:i,labelKey:n,descKey:o})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:l(n)}),e.jsx("span",{className:"sound-desc",children:l(o)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:l("preview"),disabled:!t.enabled,onClick:u=>{u.preventDefault(),a(i)},children:l("preview")}),e.jsx("input",{type:"checkbox",checked:t[i],disabled:!t.enabled,onChange:u=>c({[i]:u.target.checked})})]})]},i)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:l("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:i=>c({volume:Number(i.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}function oi({chat:t,send:s,terminal:a,view:l,plugins:c,onViewChange:i,onOpenPanel:n,onOpenSettings:o,onOpenBgTasks:u,onOpenGlobalSearch:h,sound:p,onSoundChange:g,onSoundPreview:k,themes:b,theme:N,onThemeChange:B}){var V;const{locale:w,setLocale:_,t:v}=Ft(),[j,I]=r.useState(!1),[A,S]=r.useState(!1),[T,m]=r.useState(!1),[D,O]=r.useState(!1),[Z,Q]=r.useState(!1),H=[{value:"zh",label:v("langZh")},{value:"en",label:v("langEn")}],K=t.ready?v("connected"):t.status==="closed"?v("reconnecting"):v("connecting"),ie=t.ready?"ok":"busy",x=()=>{var te,U;if(!t.ready)return;const M=v("updateTabTitle"),F={name:M,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},q=t.terminals.find(oe=>oe.title===M);q?(a.restart(q.id),s({type:"run_command",terminalId:q.id,conversationId:q.conversationId,command:F,cols:80,rows:24})):a.create({id:De(),conversationId:t.activeConversationId||((te=t.state)==null?void 0:te.conversationId)||"",title:M,cwd:((U=t.state)==null?void 0:U.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:F}),O(!1),Q(!1),i("terminal")},y=(M,F)=>{var U,oe;if(!t.ready||M.length===0)return;const q={name:F,command:si(M),cwd:"${pwd}"},te=t.terminals.find(re=>re.title===F);te?(a.restart(te.id),s({type:"run_command",terminalId:te.id,conversationId:te.conversationId,command:q,cols:80,rows:24})):a.create({id:De(),conversationId:t.activeConversationId||((U=t.state)==null?void 0:U.conversationId)||"",title:F,cwd:((oe=t.state)==null?void 0:oe.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:q}),O(!1),Q(!1),i("terminal")},$=t.updatesAll??[],ge=$.filter(M=>!M.upToDate&&!M.error).length,z=$.filter(M=>!M.upToDate&&!M.error&&M.kind!=="webui"),P=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:v("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:v("checkingUpdate")}):$.length===0?e.jsx("div",{className:"dd-note",children:v("updatesAllUpToDate")}):e.jsx("ul",{className:"dd-all-list",children:$.map(M=>e.jsxs("li",{className:`dd-all-item${M.error?" err":M.upToDate?"":" warn"}`,children:[e.jsx("span",{className:"dd-all-name",title:M.name,children:M.name}),e.jsx("span",{className:"dd-all-kind",children:M.kind==="webui"?v("kindWebUi"):M.kind==="pi-core"?v("kindPiCore"):v("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:M.error?v("updateCheckFailed"):M.upToDate?`v${M.current}`:e.jsxs(e.Fragment,{children:["v",M.current," → v",M.latest]})}),M.kind!=="webui"&&!M.upToDate&&!M.error&&e.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>y([M],v("updatePkgTabTitle",{name:M.name})),children:v("updateBtn")})]},`${M.kind}:${M.name}`))}),e.jsxs("div",{className:"dd-actions",children:[z.length>0&&e.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>y(z,v("updateAllTabTitle")),children:v("updateAllBtn")}),e.jsx("button",{type:"button",className:"dd-refresh",style:z.length>0?{flex:1}:void 0,onClick:()=>s({type:"check_updates_all",force:!0}),children:v("updatesAllRefresh")})]})]}),X=()=>{var M,F;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dd-update",children:[e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:v("currentVersion")}),e.jsxs("b",{children:["v",((M=t.update)==null?void 0:M.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:v("latestVersion")}),e.jsx("b",{children:t.update===null?v("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:v("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:v("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:v("updateAvailable",{version:t.update.latest})}),((F=t.update)==null?void 0:F.latestPublishedAt)&&Date.now()-new Date(t.update.latestPublishedAt).getTime()<30*6e4&&e.jsx("div",{className:"dd-note warn",children:v("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:v("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?v("checkingUpdate"):v("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:x,children:v("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:v("openHistory"),onClick:()=>n("left"),children:e.jsx(Wn,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${ie}`,title:K}),e.jsx("span",{className:"conn-label",children:K})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":v("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="chat",className:l==="chat"?"active":"",onClick:()=>i("chat"),children:[e.jsx(Ve,{}),e.jsx("span",{children:v("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="terminal",className:l==="terminal"?"active":"",onClick:()=>i("terminal"),children:[e.jsx(ze,{}),e.jsx("span",{children:v("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="git",className:l==="git"?"active":"",onClick:()=>i("git"),children:[e.jsx(rt,{}),e.jsx("span",{children:v("scmTab")})]}),c.map(M=>{const F=M.error?`${M.name}: ${M.error}`:M.description?`${M.name} — ${M.description}`:M.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":l===`plugin:${M.id}`,className:`plugin-tab${l===`plugin:${M.id}`?" active":""}${M.error?" broken":""}`,title:F,onClick:()=>i(`plugin:${M.id}`),children:[M.icon?e.jsx("span",{"aria-hidden":!0,children:M.icon}):null,e.jsx("span",{children:M.name})]},M.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:v("searchGlobalTip"),onClick:h,children:[e.jsx(pt,{}),e.jsx("span",{className:"chip-sub",children:v("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":v("bgTasksTip"),onClick:u,children:[e.jsx(mt,{}),e.jsx("span",{className:"chip-sub",children:v("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:v("settingsTitle"),onClick:o,children:[e.jsx(ut,{}),e.jsx("span",{className:"chip-sub",children:v("settings")})]}),e.jsx(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),e.jsx("span",{className:"chip-sub",children:v("sound")})]}),open:j,onOpenChange:I,children:e.jsx(is,{settings:p,onChange:g,onPreview:k})}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Yn,{}),e.jsx("span",{className:"chip-sub",children:w==="zh"?v("langZh"):"EN"})]}),open:A,onOpenChange:S,children:[e.jsx("div",{className:"dd-header",children:v("language")}),H.map(M=>e.jsx(Ne,{active:w===M.value,onClick:()=>{_(M.value),S(!1)},children:M.label},M.value))]}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Bn,{}),e.jsx("span",{className:"chip-sub",children:v("theme")})]}),open:T,onOpenChange:m,children:[e.jsx("div",{className:"dd-header",children:v("theme")}),e.jsx(Ne,{active:N===null,onClick:()=>{B(null),m(!1)},children:v("themeDefault")}),b.map(M=>e.jsx(Ne,{active:N===M.id,onClick:()=>{B(M.id),m(!1)},children:M.name},M.id))]}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(At,{}),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:v("updateAvailable",{version:t.update.latest??""})}),ge>0&&e.jsx("span",{className:"update-badge",children:v("updatesAllBadge",{n:ge})})]}),open:D,onOpenChange:M=>{O(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:v("update")}),X(),P()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:v("githubRepo"),children:e.jsx(ss,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":v("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(_e,{}),e.jsx("span",{children:v("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx($n,{}),e.jsx("span",{className:"chip-sub",children:v("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:Z,onOpenChange:M=>{Q(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:v("sound")}),e.jsx("div",{className:"dd-header",children:v("settings")}),e.jsxs(Ne,{onClick:()=>{Q(!1),o()},children:[e.jsx(ut,{})," ",v("settingsTitle")]}),e.jsxs(Ne,{onClick:()=>{Q(!1),h()},children:[e.jsx(pt,{})," ",v("searchGlobal")]}),e.jsxs(Ne,{onClick:()=>{Q(!1),u()},children:[e.jsx(mt,{})," ",v("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(is,{settings:p,onChange:g,onPreview:k}),e.jsx("div",{className:"dd-header",children:v("language")}),H.map(M=>e.jsx(Ne,{active:w===M.value,onClick:()=>_(M.value),children:M.label},M.value)),e.jsx("div",{className:"dd-header",children:v("theme")}),e.jsx(Ne,{active:N===null,onClick:()=>{B(null),Q(!1)},children:v("themeDefault")}),b.map(M=>e.jsx(Ne,{active:N===M.id,onClick:()=>{B(M.id),Q(!1)},children:M.name},M.id)),e.jsx("div",{className:"dd-header",children:v("update")}),X(),P(),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(ss,{})," ",v("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:v("openFiles"),onClick:()=>n("right"),children:e.jsx(Ge,{})})]})]})}function as(t){const s=new Date(t),a=new Date;return s.toDateString()===a.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function ci(t,s){const a=new Map;for(const c of t){const i=a.get(c.cwd)??[];i.push(c),a.set(c.cwd,i)}const l=[...a.entries()].map(([c,i])=>({cwd:c,isCurrent:c===s,convs:i}));return l.sort((c,i)=>c.isCurrent?-1:i.isCurrent?1:c.cwd<i.cwd?-1:c.cwd>i.cwd?1:0),l}const di=r.memo(function({ready:s,status:a,cwd:l,sessionFile:c,conversations:i,sessions:n,projects:o,activeConversationId:u,send:h,active:p}){const g=pe(),k=c,b=l,[N,B]=r.useState(null);r.useEffect(()=>{!p||!s||a!=="open"||l&&(h({type:"list_sessions"}),h({type:"list_projects"}))},[p,s,a,l,h]);const w=j=>{const I=j.name||j.firstMessage.trim();return I.length>0?I:g("emptyChat")},_=j=>j.split(/[\\/]/).pop()||j,v=(j,I,A,S)=>{const T=N===j;return e.jsx("button",{type:"button",className:`lp-del ${T?"confirm":""}`,title:T?A:I,onClick:m=>{m.stopPropagation(),T?(B(null),S()):B(j)},children:T?e.jsx(xt,{}):e.jsx(Ie,{})})};return e.jsxs("aside",{className:"panel panel-left",children:[o.length>0&&e.jsxs("div",{className:"panel-projects",children:[e.jsx("div",{className:"panel-section-title",children:g("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:o.map(j=>{const I=b===j.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>B(A=>A===`proj:${j.path}`?null:A),children:[e.jsxs("button",{type:"button",className:`project-item ${I?"active":""}`,title:j.path,onClick:()=>{I||h({type:"set_cwd",path:j.path})},children:[e.jsx(Ge,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:_(j.path)}),e.jsx("span",{className:"project-path",children:j.path})]}),e.jsx("span",{className:"project-time",children:as(j.lastUsed)})]}),v(`proj:${j.path}`,g("deleteProject"),g("deleteProjectConfirm"),()=>h({type:"remove_project",path:j.path}))]},j.path)})})]}),i.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:g("runningConversations")}),ci(i,l).map(j=>e.jsxs("div",{className:"panel-conv-group",children:[!j.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:j.cwd,children:_(j.cwd)}),j.convs.map(I=>{const A=u===I.id;return e.jsxs("button",{type:"button",className:`session-item ${A?"active":""}`,title:`${I.title}${j.isCurrent?"":` — ${j.cwd}`}`,onClick:()=>{A||h({type:"switch_conversation",id:I.id})},children:[e.jsx(Ve,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:I.title}),e.jsx("span",{className:"session-sub",children:A?g("current"):g("messageCount",{n:I.messageCount})})]}),I.isStreaming&&e.jsx("span",{className:"conv-streaming",title:g("streaming")})]},I.id)})]},j.cwd)),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:g("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[n.length===0&&e.jsx("div",{className:"panel-empty",children:g("noHistory")}),n.map(j=>{const I=k===j.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>B(A=>A===`sess:${j.path}`?null:A),children:[e.jsxs("button",{type:"button",className:`session-item ${I?"active":""}`,title:j.path,onClick:()=>{I||h({type:"switch_session",path:j.path})},children:[e.jsx(Ve,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:w(j)}),e.jsxs("span",{className:"session-sub",children:[I?g("current"):g("messageCount",{n:j.messageCount}),j.source==="tui"&&e.jsx("span",{className:"session-src",title:g("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:as(j.modified)})]}),v(`sess:${j.path}`,g("deleteSession"),g("deleteSessionConfirm"),()=>h({type:"delete_session",path:j.path}))]},j.path)})]})]})]})}),Hs="pi-web-ui:token";function ui(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem(Hs,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function pi(){try{return localStorage.getItem(Hs)??""}catch{return""}}function vt(t){const s=pi();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}function mi(t,s){const a=s.assistantMessageEvent,l=t.stats.tokens,c=s.usage!==null?{...l,...s.usage}:l,i=c===l?t.stats:{...t.stats,tokens:c};if(a.type!=="text_delta"&&a.type!=="thinking_delta")return i===t.stats?t:{...t,stats:i};const n=a.delta??"";if(!n)return i===t.stats?t:{...t,stats:i};const o=t.streamingMessage??null,u=o&&o.id===s.messageId?o:{id:s.messageId,content:[]},h=[...u.content],p=a.type==="thinking_delta"?"thinking":"text",g=a.contentIndex??h.length-1;return g>=0&&g<h.length&&h[g].type===p?h[g]=p==="thinking"?{type:"thinking",thinking:(h[g].thinking??"")+n}:{type:"text",text:(h[g].text??"")+n}:h.push(p==="thinking"?{type:"thinking",thinking:n}:{type:"text",text:n}),{...t,stats:i,streamingMessage:{...u,id:s.messageId,content:h}}}const Pt="pi-web-ui:plugin-data";function hi(t,s){window.dispatchEvent(new CustomEvent(Pt,{detail:{pluginId:t,payload:s}}))}function gi(t){const s=a=>{const l=a.detail;t(l.pluginId,l.payload)};return window.addEventListener(Pt,s),()=>window.removeEventListener(Pt,s)}const Ke=new Map,It=new Set,He=new Set;let rs=-1;function Us(){return[...Ke.values()]}function fi(){const t=Us();for(const s of It)s(t)}function xi(t){return It.add(t),t(Us()),()=>It.delete(t)}async function vi(t,s){s!==rs&&(rs=s,Ke.clear(),He.clear());const a=new Set(t.map(l=>l.id));for(const l of[...Ke.keys()])a.has(l)||Ke.delete(l);for(const l of[...He])a.has(l)||He.delete(l);await Promise.all(t.filter(l=>l.hasClient&&!l.error&&!Ke.has(l.id)&&!He.has(l.id)).map(async l=>{try{const i=(await Ps(()=>import(`/plugins/${encodeURIComponent(l.id)}/client/entry.mjs?e=${s}`),[])).default;i&&typeof i.mount=="function"?Ke.set(l.id,{info:l,module:i}):(He.add(l.id),console.error(`[plugin:${l.id}] entry.mjs 缺少 default.mount`))}catch(c){He.add(l.id),console.error(`[plugin:${l.id}] 客户端加载失败:`,c)}})),fi()}function yi(t,s){return{pluginId:t,send:a=>s({type:"plugin_message",pluginId:t,payload:a}),onData:a=>gi((l,c)=>{l===t&&a(c)})}}const ki=10,bt=2e5,bi=2e5,ji={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 wi(){const t=new Map,s=new Map,a=(l,c)=>`${l}:${c}`;return{write(l,c,i){const n=a(l,c),o=t.get(n);if(o&&o.size>0){for(const p of o)try{p.write(i)}catch{}return}const u=s.get(n)??"",h=u.length+i.length>bi?i:u+i;s.set(n,h)},register(l,c,i){const n=a(l,c);let o=t.get(n);o||(o=new Set,t.set(n,o)),o.add(i);const u=s.get(n);if(u){try{i.write(u)}catch{}s.delete(n)}return()=>{const h=t.get(n);h&&(h.delete(i),h.size===0&&t.delete(n)),s.delete(n)}},clear(){t.clear(),s.clear()}}}function ls(t,s){const a=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&a.add(c.toolCallId),c.role==="bashExecution"&&a.add(`bash-${c.id}`);let l=!1;for(const c of t.keys())a.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function os(t,s){if(t.size===0)return t;const a=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&a.add(c.toolCallId);let l=!1;for(const c of t.keys())a.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function Ni(t,s){var a,l,c,i;switch(s.type){case"status":return{...t,status:s.status,ready:s.status==="open"?t.ready:!1,terminals:s.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:s.serverVersion,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==ki};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:ls(t.liveOutputs,s.state),toolStatuses:os(t.toolStatuses,s.state)};case"snapshot_delta":{const n=t.state,o=s.msg;if(!n||n.conversationId!==o.conversationId||n.rev!==o.baseRev)return t;const u={...n,...o.state,messages:o.appended.length>0?[...n.messages,...o.appended]:n.messages};return{...t,ready:!0,state:u,activeConversationId:u.conversationId,liveOutputs:ls(t.liveOutputs,u),toolStatuses:os(t.toolStatuses,u)}}case"tool_delta":{const n=t.liveOutputs.get(s.toolCallId),o=((n==null?void 0:n.text)??"")+s.delta,u=o.length>bt?`…[前 ${o.length-bt} 字符已省略]…
|
|
303
|
-
`+o.slice(o.length-bt):o,h=new Map(t.liveOutputs);return h.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:h}}case"message_delta":{const n=t.state;return!n||n.conversationId!==s.msg.conversationId?t:{...t,state:mi(n,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(n=>n.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"session_search_result":return{...t,sessionSearch:s.result};case"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"update_status_all":return{...t,updatesAll:s.items};case"updates_check_started":return{...t,updatesAll:null};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"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(n=>n.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(a=t.state)!=null&&a.conversationId)&&s.conversationId!==(t.activeConversationId||((l=t.state)==null?void 0:l.conversationId))?t:{...t,terminals:t.terminals.map(n=>n.id===s.terminalId?{...n,running:!1,exitCode:s.exitCode}:n)};case"terminal_restart":return{...t,terminals:t.terminals.map(n=>n.id===s.terminalId?{...n,running:!0,exitCode:null}:n)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(c=t.state)!=null&&c.conversationId)&&s.conversationId!==(t.activeConversationId||((i=t.state)==null?void 0:i.conversationId))?t:{...t,terminals:s.terminals.map(n=>{var o;return{...n,conversationId:s.conversationId??((o=t.state)==null?void 0:o.conversationId)??""}})};default:return t}}const cs="pi-web-client-id";let jt=null;function $t(){if(jt)return jt;let t=null;try{t=sessionStorage.getItem(cs),t||(t=De(),sessionStorage.setItem(cs,t))}catch{t=t??De()}return jt=t,t}function Ci(){const t=location.protocol==="https:"?"wss:":"ws:";return vt(`${t}//${location.host}/ws`)}function Si(){const[t,s]=r.useReducer(Ni,{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,updatesAll:null,widgets:[],statuses:[],dialog:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],goal:ji,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,protocolMismatch:!1}),a=r.useRef(null),l=r.useRef(wi()),c=r.useRef(0),i=r.useRef(null),n=r.useRef(!0),o=r.useRef(0),u=r.useRef(0),h=r.useRef(new Map),p=r.useRef(null),g=()=>{p.current||(p.current=setTimeout(()=>{p.current=null;const S=a.current;S&&S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"get_state"}))},300))},k=(S,T)=>{var O;const m=h.current,D=m.get(S);if(D!==void 0&&T!==D+1){const Z=A.current.chat,Q=Z.activeConversationId||((O=Z.state)==null?void 0:O.conversationId);S===Q&&g()}m.set(S,T)},b=r.useCallback((S,T)=>{const m=++u.current;s({type:"notice",notice:{id:m,level:S,text:T}})},[]),N=r.useCallback(S=>{const T=a.current;return T&&T.readyState===WebSocket.OPEN?(S.type==="check_updates_all"&&S.force===!0&&s({type:"updates_check_started"}),T.send(JSON.stringify(S)),!0):!1},[]),B=r.useCallback(()=>{if(!n.current)return;s({type:"status",status:"connecting"});const S=new WebSocket(Ci());a.current=S,S.onopen=()=>{a.current===S&&(s({type:"status",status:"open"}),c.current=0,o.current=Date.now(),S.send(JSON.stringify({type:"hello",clientId:$t()})))},S.onmessage=T=>{if(a.current!==S)return;o.current=Date.now();let m;try{m=JSON.parse(T.data)}catch{return}switch(m.type){case"ready":s({type:"ready",serverVersion:m.serverVersion,protocolVersion:m.protocolVersion}),S.send(JSON.stringify({type:"get_state"})),S.send(JSON.stringify({type:"list_files"})),S.send(JSON.stringify({type:"list_models"})),S.send(JSON.stringify({type:"list_commands"})),S.send(JSON.stringify({type:"get_commands"})),S.send(JSON.stringify({type:"check_update"})),S.send(JSON.stringify({type:"check_updates_all"}));break;case"snapshot":h.current=new Map,s({type:"snapshot",state:m.state});break;case"snapshot_delta":{const D=A.current.chat.state;(!D||D.conversationId!==m.conversationId||D.rev!==m.baseRev)&&g(),s({type:"snapshot_delta",msg:m});break}case"tool_delta":k(m.conversationId,m.seq),s({type:"tool_delta",toolCallId:m.toolCallId,toolName:m.toolName,delta:m.delta});break;case"tool_status":s({type:"tool_status",status:m});break;case"message_delta":{k(m.conversationId,m.seq),s({type:"message_delta",msg:m});break}case"notice":{const D=++u.current;s({type:"notice",notice:{id:D,level:m.level,text:m.text}});break}case"sessions":s({type:"sessions",sessions:m.sessions});break;case"conversations":s({type:"conversations",conversations:m.conversations,activeId:m.activeId});break;case"projects":s({type:"projects",projects:m.projects});break;case"files":s({type:"files",files:m});break;case"file_changed":s({type:"file_changed",path:m.path});break;case"file_content":s({type:"file_content",content:m});break;case"models":s({type:"models",models:m.models,loading:!1});break;case"models_config":s({type:"models_config",providers:m.providers});break;case"providers_status":s({type:"providers_status",providers:m.providers});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:m.reqId,ok:m.ok,models:m.models,error:m.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:m.reqId,ok:m.ok,added:m.added,total:m.total,error:m.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:m.reqId,ok:m.ok,config:m.config,error:m.error}});break;case"scm_data":s({type:"scm_data",data:m});break;case"search_files_result":s({type:"file_search_result",result:{reqId:m.reqId,ok:m.ok,results:m.results,truncated:m.truncated}});break;case"session_search_results":s({type:"session_search_result",result:{reqId:m.reqId,ok:m.ok,results:m.results}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:m});break;case"path_completions":s({type:"path_completions",completions:m.completions});break;case"update_status":s({type:"update_status",status:m});break;case"update_status_all":s({type:"update_status_all",items:m.items});break;case"widgets":s({type:"widgets",widgets:m.widgets});break;case"statuses":s({type:"statuses",statuses:m.statuses});break;case"dialog":s({type:"dialog",dialog:{id:m.id,kind:m.kind,title:m.title,args:m.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"terminal_output":l.current.write(m.conversationId??A.current.chat.activeConversationId,m.terminalId,m.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:m.conversationId,terminalId:m.terminalId,exitCode:m.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:m.conversationId,terminals:m.terminals});break;case"commands":s({type:"commands",commands:m.commands,path:m.path});break;case"slash_commands":s({type:"slash_commands",commands:m.commands});break;case"goal_status":s({type:"goal_status",status:m.status});break;case"settings_state":s({type:"settings",settings:m.settings});break;case"bg_servers":s({type:"bg_servers",servers:m.servers});break;case"plugins":s({type:"plugins",plugins:m.plugins,epoch:m.epoch});break;case"plugin_data":hi(m.pluginId,m.payload);break}},S.onclose=()=>{if(a.current===S&&(a.current=null),l.current.clear(),!n.current||a.current&&a.current!==S)return;s({type:"status",status:"closed"});const T=Math.min(1e3*2**c.current,1e4);c.current+=1,i.current=setTimeout(()=>{i.current=null,B()},T)},S.onerror=()=>{}},[]);r.useEffect(()=>{n.current=!0,B();const S=setInterval(()=>{if(!n.current)return;const T=a.current;T&&T.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&T.close()},5e3);return()=>{var T;n.current=!1,clearInterval(S),i.current&&(clearTimeout(i.current),i.current=null),(T=a.current)==null||T.close(),a.current=null}},[B]);const w=r.useCallback(S=>s({type:"dismiss_notice",id:S}),[]),_=r.useCallback(S=>s({type:"terminal_add",meta:S}),[]),v=r.useCallback(S=>s({type:"terminal_remove",id:S}),[]),j=r.useCallback(S=>s({type:"terminal_restart",terminalId:S}),[]),I=r.useCallback((S,T,m)=>l.current.register(S,T,m),[]),A=r.useRef({chat:t,send:N,pushNotice:b,dismissNotice:w,terminal:{create:_,close:v,register:I,restart:j}});return A.current={chat:t,send:N,pushNotice:b,dismissNotice:w,terminal:{create:_,close:v,register:I,restart:j}},A.current}const Ti=200*1024*1024,Ei=/windows/i.test(navigator.userAgent),Mi=/[<>:"/\\|?*\u0000-\u001f]/g,Ri=/[. ]+$/,Pi=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Ii(t){const s=t.replace(Mi,"_").replace(Ri,"");return s?Pi.test(s)?`_${s}`:s:"_"}function ds(t,s=!0){const a=new URLSearchParams({clientId:$t(),path:t,...s?{download:"1"}:{}});return vt(`/api/file?${a}`)}async function Li(t,s){const a=Ei?Ii(s):s;try{const l=await fetch(ds(t));if(!l.ok)return{ok:!1,cancelled:!1,error:await l.text().catch(()=>"")||(l.status===404?"文件不存在":`HTTP ${l.status}`)};if(Number(l.headers.get("content-length")??"0")>Ti)return window.location.assign(ds(t)),{ok:!0};const i=await l.blob();return window.showSaveFilePicker&&window.isSecureContext?Di(i,a):Lt(i,a)}catch(l){return{ok:!1,cancelled:!1,error:l instanceof Error?l.message:String(l)}}}async function Di(t,s){let a;const l=window.showSaveFilePicker;if(!l)return Lt(t,s);try{a=await l({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:Lt(t,s)}try{const c=await a.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 Lt(t,s){const a=URL.createObjectURL(t),l=document.createElement("a");return l.href=a,l.download=s,document.body.appendChild(l),l.click(),l.remove(),setTimeout(()=>URL.revokeObjectURL(a),1e4),{ok:!0}}const Bi=r.memo(function({files:s,fileChanged:a,widgets:l,cwd:c,send:i,onAttach:n,onPreview:o,onNotice:u}){const h=pe(),[p,g]=r.useState(""),[k,b]=r.useState(null),[N,B]=r.useState(!1),w=1e4,_=r.useRef(0),v=r.useRef(void 0),j=r.useCallback((T,m)=>{const D=++_.current;g(T),m!=null&&m.silent||B(!0),i({type:"list_files",path:T===""?void 0:T})||_.current===D&&B(!1)},[i]);r.useEffect(()=>{s&&s.path===p&&B(!1)},[s,p]),r.useEffect(()=>{if(c!==v.current){v.current=c,j("",{silent:!0});return}const T=setInterval(()=>{document.visibilityState!=="hidden"&&j(p,{silent:!0})},w);return()=>clearInterval(T)},[c,p,j]),r.useEffect(()=>{a&&a.path===p&&j(p,{silent:!0})},[a,p,j]);const I=T=>j(T),A=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&j(s.parent)},S=p.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 ${p===""?"active":""}`,onClick:()=>j(""),children:h("rootDir")}),S.map((T,m)=>{const D=S.slice(0,m+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(ft,{}),e.jsx("button",{type:"button",className:`crumb ${D===p?"active":""}`,onClick:()=>j(D),children:T})]},D)})]}),e.jsxs("div",{className:"panel-body",children:[N&&e.jsx("div",{className:"panel-empty",children:h("loading")}),!N&&s&&s.path===p&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:A,children:[e.jsx(Ge,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(T=>T.type==="dir"?e.jsxs("div",{className:"file-item dir",children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>I(T.path),children:[e.jsx(Ge,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:T.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":h("linkFolderTip"),onClick:()=>n(T.path,T.name,"reference",!0),children:e.jsx(Tt,{})})]},T.path):e.jsxs("div",{className:"file-item file",children:[e.jsxs("button",{type:"button",className:"file-name",title:`${T.path} — ${h("previewFile")}`,onClick:()=>o(T.path,T.name),children:[e.jsx(_s,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:T.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":h("downloadFile"),onClick:()=>{Li(T.path,T.name).then(m=>{m.ok||m.cancelled||u("error",h("downloadFailed",{error:m.error}))})},children:e.jsx(At,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":h("attachInlineTip"),onClick:()=>n(T.path,T.name,"inline"),children:e.jsx(_e,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":h("referenceTip"),onClick:()=>n(T.path,T.name,"reference"),children:e.jsx(Tt,{})})]},T.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:h("filesTruncated")})]}),!N&&!s&&e.jsx("div",{className:"panel-empty",children:h("noFiles")})]}),l.filter(T=>T.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:l.filter(T=>T.lines.length>0).map(T=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:h("widgetExpand"),onClick:()=>b(T.key),children:[e.jsx("span",{children:T.key}),e.jsx(Hn,{})]}),e.jsx("pre",{className:"widget-lines",children:T.lines.join(`
|
|
302
|
+
Avoid three test anti-patterns: tests coupled to the implementation, tautological assertions (always true), and horizontal slicing (surface only). Report after each step and run the tests.`,error:"Error",done:"Done",running:"Running…",toolQueued:"Queued",copyArgs:"Copy args",errorOutput:"Error output",output:"Output",waitingOutput:"Waiting for output…",toolDoneWaitingModel:"Done · waiting on model",waitingModel:"Waiting for model response…",thinkingNow:"Thinking",thinkingPreview:"Thinking: {preview}",commands:"Commands",newCommand:"New command",newTerminal:"New terminal",name:"Name",command:"Command",cwdHint:"(${pwd} = current working directory)",noCommands:"No commands yet — click + to add one",clickToRun:"Click to run",edit:"Edit",delete:"Delete",confirmQ:"Confirm?",builtinTerminal:"Built-in terminal",termEmptySub:"Click a command on the left to run it, or + on the right for a new terminal",noTerminal:"No terminals",exited:"(exited{code})",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",settingsMessageDisplay:"Message display",thinkingWrap:"Show full thinking",thinkingWrapDesc:"On: thinking always expands fully and wraps (live reasoning visible while streaming); Off: collapses to a one-line summary with the latest text shown live while streaming",toolsWrap:"Show full tools",toolsWrapDesc:"On: tool calls always expand fully showing arguments and output; Off: collapsed by default, click to expand",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",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",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…"},Us=r.createContext(null);function li(){try{const t=localStorage.getItem(qs);if(t==="zh"||t==="en")return t}catch{}return"zh"}function oi({children:t}){const[s,i]=r.useState(li),l=r.useCallback(n=>{i(n);try{localStorage.setItem(qs,n)}catch{}},[]),c=r.useCallback((n,o)=>{let u=ri[n];if(s==="zh"&&(u=ai[n]),o)for(const[h,p]of Object.entries(o))u=u.replaceAll(`{${h}}`,String(p));return u},[s]);r.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en"},[s]);const a=r.useMemo(()=>({locale:s,setLocale:l,t:c}),[s,l,c]);return e.jsx(Us.Provider,{value:a,children:t})}function Ot(){const t=r.useContext(Us);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function pe(){return Ot().t}const ci=[{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 rs({settings:t,onChange:s,onPreview:i}){const l=pe(),c=a=>s({...t,...a});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:l("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Ds,{className:"sound-icon"}),e.jsx("span",{children:l("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:a=>c({enabled:a.target.checked})})]}),ci.map(({kind:a,labelKey:n,descKey:o})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:l(n)}),e.jsx("span",{className:"sound-desc",children:l(o)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:l("preview"),disabled:!t.enabled,onClick:u=>{u.preventDefault(),i(a)},children:l("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:l("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 di({chat:t,send:s,terminal:i,view:l,plugins:c,onViewChange:a,onOpenPanel:n,onOpenSettings:o,onOpenBgTasks:u,onOpenGlobalSearch:h,sound:p,onSoundChange:g,onSoundPreview:k,themes:b,theme:N,onThemeChange:D}){var V;const{locale:w,setLocale:_,t:v}=Ot(),[j,I]=r.useState(!1),[A,S]=r.useState(!1),[T,m]=r.useState(!1),[B,O]=r.useState(!1),[Z,Q]=r.useState(!1),U=[{value:"zh",label:v("langZh")},{value:"en",label:v("langEn")}],K=t.ready?v("connected"):t.status==="closed"?v("reconnecting"):v("connecting"),ie=t.ready?"ok":"busy",x=()=>{var te,H;if(!t.ready)return;const M=v("updateTabTitle"),F={name:M,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},q=t.terminals.find(oe=>oe.title===M);q?(i.restart(q.id),s({type:"run_command",terminalId:q.id,conversationId:q.conversationId,command:F,cols:80,rows:24})):i.create({id:Be(),conversationId:t.activeConversationId||((te=t.state)==null?void 0:te.conversationId)||"",title:M,cwd:((H=t.state)==null?void 0:H.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:F}),O(!1),Q(!1),a("terminal")},y=(M,F)=>{var H,oe;if(!t.ready||M.length===0)return;const q={name:F,command:ii(M),cwd:"${pwd}"},te=t.terminals.find(re=>re.title===F);te?(i.restart(te.id),s({type:"run_command",terminalId:te.id,conversationId:te.conversationId,command:q,cols:80,rows:24})):i.create({id:Be(),conversationId:t.activeConversationId||((H=t.state)==null?void 0:H.conversationId)||"",title:F,cwd:((oe=t.state)==null?void 0:oe.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:q}),O(!1),Q(!1),a("terminal")},$=t.updatesAll??[],ge=$.filter(M=>!M.upToDate&&!M.error).length,z=$.filter(M=>!M.upToDate&&!M.error&&M.kind!=="webui"),P=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:v("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:v("checkingUpdate")}):$.length===0?e.jsx("div",{className:"dd-note",children:v("updatesAllUpToDate")}):e.jsx("ul",{className:"dd-all-list",children:$.map(M=>e.jsxs("li",{className:`dd-all-item${M.error?" err":M.upToDate?"":" warn"}`,children:[e.jsx("span",{className:"dd-all-name",title:M.name,children:M.name}),e.jsx("span",{className:"dd-all-kind",children:M.kind==="webui"?v("kindWebUi"):M.kind==="pi-core"?v("kindPiCore"):v("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:M.error?v("updateCheckFailed"):M.upToDate?`v${M.current}`:e.jsxs(e.Fragment,{children:["v",M.current," → v",M.latest]})}),M.kind!=="webui"&&!M.upToDate&&!M.error&&e.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>y([M],v("updatePkgTabTitle",{name:M.name})),children:v("updateBtn")})]},`${M.kind}:${M.name}`))}),e.jsxs("div",{className:"dd-actions",children:[z.length>0&&e.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>y(z,v("updateAllTabTitle")),children:v("updateAllBtn")}),e.jsx("button",{type:"button",className:"dd-refresh",style:z.length>0?{flex:1}:void 0,onClick:()=>s({type:"check_updates_all",force:!0}),children:v("updatesAllRefresh")})]})]}),X=()=>{var M,F;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dd-update",children:[e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:v("currentVersion")}),e.jsxs("b",{children:["v",((M=t.update)==null?void 0:M.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:v("latestVersion")}),e.jsx("b",{children:t.update===null?v("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:v("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:v("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:v("updateAvailable",{version:t.update.latest})}),((F=t.update)==null?void 0:F.latestPublishedAt)&&Date.now()-new Date(t.update.latestPublishedAt).getTime()<30*6e4&&e.jsx("div",{className:"dd-note warn",children:v("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:v("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?v("checkingUpdate"):v("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:x,children:v("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:v("openHistory"),onClick:()=>n("left"),children:e.jsx(Un,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${ie}`,title:K}),e.jsx("span",{className:"conn-label",children:K})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":v("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="chat",className:l==="chat"?"active":"",onClick:()=>a("chat"),children:[e.jsx(Ve,{}),e.jsx("span",{children:v("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="terminal",className:l==="terminal"?"active":"",onClick:()=>a("terminal"),children:[e.jsx(ze,{}),e.jsx("span",{children:v("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="git",className:l==="git"?"active":"",onClick:()=>a("git"),children:[e.jsx(lt,{}),e.jsx("span",{children:v("scmTab")})]}),c.map(M=>{const F=M.error?`${M.name}: ${M.error}`:M.description?`${M.name} — ${M.description}`:M.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":l===`plugin:${M.id}`,className:`plugin-tab${l===`plugin:${M.id}`?" active":""}${M.error?" broken":""}`,title:F,onClick:()=>a(`plugin:${M.id}`),children:[M.icon?e.jsx("span",{"aria-hidden":!0,children:M.icon}):null,e.jsx("span",{children:M.name})]},M.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:v("searchGlobalTip"),onClick:h,children:[e.jsx(mt,{}),e.jsx("span",{className:"chip-sub",children:v("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":v("bgTasksTip"),onClick:u,children:[e.jsx(ht,{}),e.jsx("span",{className:"chip-sub",children:v("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:v("settingsTitle"),onClick:o,children:[e.jsx(pt,{}),e.jsx("span",{className:"chip-sub",children:v("settings")})]}),e.jsx(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ds,{}),e.jsx("span",{className:"chip-sub",children:v("sound")})]}),open:j,onOpenChange:I,children:e.jsx(rs,{settings:p,onChange:g,onPreview:k})}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Qn,{}),e.jsx("span",{className:"chip-sub",children:w==="zh"?v("langZh"):"EN"})]}),open:A,onOpenChange:S,children:[e.jsx("div",{className:"dd-header",children:v("language")}),U.map(M=>e.jsx(Ne,{active:w===M.value,onClick:()=>{_(M.value),S(!1)},children:M.label},M.value))]}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(_n,{}),e.jsx("span",{className:"chip-sub",children:v("theme")})]}),open:T,onOpenChange:m,children:[e.jsx("div",{className:"dd-header",children:v("theme")}),e.jsx(Ne,{active:N===null,onClick:()=>{D(null),m(!1)},children:v("themeDefault")}),b.map(M=>e.jsx(Ne,{active:N===M.id,onClick:()=>{D(M.id),m(!1)},children:M.name},M.id))]}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ft,{}),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:v("updateAvailable",{version:t.update.latest??""})}),ge>0&&e.jsx("span",{className:"update-badge",children:v("updatesAllBadge",{n:ge})})]}),open:B,onOpenChange:M=>{O(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:v("update")}),X(),P()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:v("githubRepo"),children:e.jsx(is,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":v("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(_e,{}),e.jsx("span",{children:v("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Wn,{}),e.jsx("span",{className:"chip-sub",children:v("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:Z,onOpenChange:M=>{Q(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:v("sound")}),e.jsx("div",{className:"dd-header",children:v("settings")}),e.jsxs(Ne,{onClick:()=>{Q(!1),o()},children:[e.jsx(pt,{})," ",v("settingsTitle")]}),e.jsxs(Ne,{onClick:()=>{Q(!1),h()},children:[e.jsx(mt,{})," ",v("searchGlobal")]}),e.jsxs(Ne,{onClick:()=>{Q(!1),u()},children:[e.jsx(ht,{})," ",v("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(rs,{settings:p,onChange:g,onPreview:k}),e.jsx("div",{className:"dd-header",children:v("language")}),U.map(M=>e.jsx(Ne,{active:w===M.value,onClick:()=>_(M.value),children:M.label},M.value)),e.jsx("div",{className:"dd-header",children:v("theme")}),e.jsx(Ne,{active:N===null,onClick:()=>{D(null),Q(!1)},children:v("themeDefault")}),b.map(M=>e.jsx(Ne,{active:N===M.id,onClick:()=>{D(M.id),Q(!1)},children:M.name},M.id)),e.jsx("div",{className:"dd-header",children:v("update")}),X(),P(),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(is,{})," ",v("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:v("openFiles"),onClick:()=>n("right"),children:e.jsx(Ge,{})})]})]})}function ls(t){const s=new Date(t),i=new Date;return s.toDateString()===i.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function ui(t,s){const i=new Map;for(const c of t){const a=i.get(c.cwd)??[];a.push(c),i.set(c.cwd,a)}const l=[...i.entries()].map(([c,a])=>({cwd:c,isCurrent:c===s,convs:a}));return l.sort((c,a)=>c.isCurrent?-1:a.isCurrent?1:c.cwd<a.cwd?-1:c.cwd>a.cwd?1:0),l}const pi=r.memo(function({ready:s,status:i,cwd:l,sessionFile:c,conversations:a,sessions:n,projects:o,activeConversationId:u,send:h,active:p}){const g=pe(),k=c,b=l,[N,D]=r.useState(null);r.useEffect(()=>{!p||!s||i!=="open"||l&&(h({type:"list_sessions"}),h({type:"list_projects"}))},[p,s,i,l,h]);const w=j=>{const I=j.name||j.firstMessage.trim();return I.length>0?I:g("emptyChat")},_=j=>j.split(/[\\/]/).pop()||j,v=(j,I,A,S)=>{const T=N===j;return e.jsx("button",{type:"button",className:`lp-del ${T?"confirm":""}`,title:T?A:I,onClick:m=>{m.stopPropagation(),T?(D(null),S()):D(j)},children:T?e.jsx(vt,{}):e.jsx(Ie,{})})};return e.jsxs("aside",{className:"panel panel-left",children:[o.length>0&&e.jsxs("div",{className:"panel-projects",children:[e.jsx("div",{className:"panel-section-title",children:g("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:o.map(j=>{const I=b===j.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>D(A=>A===`proj:${j.path}`?null:A),children:[e.jsxs("button",{type:"button",className:`project-item ${I?"active":""}`,title:j.path,onClick:()=>{I||h({type:"set_cwd",path:j.path})},children:[e.jsx(Ge,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:_(j.path)}),e.jsx("span",{className:"project-path",children:j.path})]}),e.jsx("span",{className:"project-time",children:ls(j.lastUsed)})]}),v(`proj:${j.path}`,g("deleteProject"),g("deleteProjectConfirm"),()=>h({type:"remove_project",path:j.path}))]},j.path)})})]}),a.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:g("runningConversations")}),ui(a,l).map(j=>e.jsxs("div",{className:"panel-conv-group",children:[!j.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:j.cwd,children:_(j.cwd)}),j.convs.map(I=>{const A=u===I.id;return e.jsxs("button",{type:"button",className:`session-item ${A?"active":""}`,title:`${I.title}${j.isCurrent?"":` — ${j.cwd}`}`,onClick:()=>{A||h({type:"switch_conversation",id:I.id})},children:[e.jsx(Ve,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:I.title}),e.jsx("span",{className:"session-sub",children:A?g("current"):g("messageCount",{n:I.messageCount})})]}),I.isStreaming&&e.jsx("span",{className:"conv-streaming",title:g("streaming")})]},I.id)})]},j.cwd)),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:g("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[n.length===0&&e.jsx("div",{className:"panel-empty",children:g("noHistory")}),n.map(j=>{const I=k===j.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>D(A=>A===`sess:${j.path}`?null:A),children:[e.jsxs("button",{type:"button",className:`session-item ${I?"active":""}`,title:j.path,onClick:()=>{I||h({type:"switch_session",path:j.path})},children:[e.jsx(Ve,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:w(j)}),e.jsxs("span",{className:"session-sub",children:[I?g("current"):g("messageCount",{n:j.messageCount}),j.source==="tui"&&e.jsx("span",{className:"session-src",title:g("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:ls(j.modified)})]}),v(`sess:${j.path}`,g("deleteSession"),g("deleteSessionConfirm"),()=>h({type:"delete_session",path:j.path}))]},j.path)})]})]})]})}),Hs="pi-web-ui:token";function mi(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem(Hs,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function hi(){try{return localStorage.getItem(Hs)??""}catch{return""}}function yt(t){const s=hi();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}let jt=null;function gi(t){if(t===void 0){const i=globalThis.document;if(i&&typeof i.baseURI=="string"&&i.baseURI)try{t=new URL(i.baseURI).pathname}catch{}if(t===void 0)return"/"}if(!t||t==="/")return"/";let s=t.replace(/index\.html$/i,"");return s.endsWith("/")||(s+="/"),s}function fi(){return jt===null&&(jt=gi()),jt}function xi(t,s){return s==="/"?t:s+t.replace(/^\/+/,"")}function Ye(t){return xi(t,fi())}function vi(t,s){const i=s.assistantMessageEvent,l=t.stats.tokens,c=s.usage!==null?{...l,...s.usage}:l,a=c===l?t.stats:{...t.stats,tokens:c};if(i.type!=="text_delta"&&i.type!=="thinking_delta")return a===t.stats?t:{...t,stats:a};const n=i.delta??"";if(!n)return a===t.stats?t:{...t,stats:a};const o=t.streamingMessage??null,u=o&&o.id===s.messageId?o:{id:s.messageId,content:[]},h=[...u.content],p=i.type==="thinking_delta"?"thinking":"text",g=i.contentIndex??h.length-1;return g>=0&&g<h.length&&h[g].type===p?h[g]=p==="thinking"?{type:"thinking",thinking:(h[g].thinking??"")+n}:{type:"text",text:(h[g].text??"")+n}:h.push(p==="thinking"?{type:"thinking",thinking:n}:{type:"text",text:n}),{...t,stats:a,streamingMessage:{...u,id:s.messageId,content:h}}}const Lt="pi-web-ui:plugin-data";function yi(t,s){window.dispatchEvent(new CustomEvent(Lt,{detail:{pluginId:t,payload:s}}))}function ki(t){const s=i=>{const l=i.detail;t(l.pluginId,l.payload)};return window.addEventListener(Lt,s),()=>window.removeEventListener(Lt,s)}const Ke=new Map,Bt=new Set,Ue=new Set;let os=-1;function Ks(){return[...Ke.values()]}function bi(){const t=Ks();for(const s of Bt)s(t)}function ji(t){return Bt.add(t),t(Ks()),()=>Bt.delete(t)}async function wi(t,s){s!==os&&(os=s,Ke.clear(),Ue.clear());const i=new Set(t.map(l=>l.id));for(const l of[...Ke.keys()])i.has(l)||Ke.delete(l);for(const l of[...Ue])i.has(l)||Ue.delete(l);await Promise.all(t.filter(l=>l.hasClient&&!l.error&&!Ke.has(l.id)&&!Ue.has(l.id)).map(async l=>{try{const a=(await import(Ye(`/plugins/${encodeURIComponent(l.id)}/client/entry.mjs?e=${s}`))).default;a&&typeof a.mount=="function"?Ke.set(l.id,{info:l,module:a}):(Ue.add(l.id),console.error(`[plugin:${l.id}] entry.mjs 缺少 default.mount`))}catch(c){Ue.add(l.id),console.error(`[plugin:${l.id}] 客户端加载失败:`,c)}})),bi()}function Ni(t,s){return{pluginId:t,send:i=>s({type:"plugin_message",pluginId:t,payload:i}),onData:i=>ki((l,c)=>{l===t&&i(c)})}}const Ci=10,wt=2e5,Si=2e5,Ti={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 Ei(){const t=new Map,s=new Map,i=(l,c)=>`${l}:${c}`;return{write(l,c,a){const n=i(l,c),o=t.get(n);if(o&&o.size>0){for(const p of o)try{p.write(a)}catch{}return}const u=s.get(n)??"",h=u.length+a.length>Si?a:u+a;s.set(n,h)},register(l,c,a){const n=i(l,c);let o=t.get(n);o||(o=new Set,t.set(n,o)),o.add(a);const u=s.get(n);if(u){try{a.write(u)}catch{}s.delete(n)}return()=>{const h=t.get(n);h&&(h.delete(a),h.size===0&&t.delete(n)),s.delete(n)}},clear(){t.clear(),s.clear()}}}function cs(t,s){const i=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&i.add(c.toolCallId),c.role==="bashExecution"&&i.add(`bash-${c.id}`);let l=!1;for(const c of t.keys())i.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function ds(t,s){if(t.size===0)return t;const i=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&i.add(c.toolCallId);let l=!1;for(const c of t.keys())i.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function Mi(t,s){var i,l,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!==Ci};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:cs(t.liveOutputs,s.state),toolStatuses:ds(t.toolStatuses,s.state)};case"snapshot_delta":{const n=t.state,o=s.msg;if(!n||n.conversationId!==o.conversationId||n.rev!==o.baseRev)return t;const u={...n,...o.state,messages:o.appended.length>0?[...n.messages,...o.appended]:n.messages};return{...t,ready:!0,state:u,activeConversationId:u.conversationId,liveOutputs:cs(t.liveOutputs,u),toolStatuses:ds(t.toolStatuses,u)}}case"tool_delta":{const n=t.liveOutputs.get(s.toolCallId),o=((n==null?void 0:n.text)??"")+s.delta,u=o.length>wt?`…[前 ${o.length-wt} 字符已省略]…
|
|
303
|
+
`+o.slice(o.length-wt):o,h=new Map(t.liveOutputs);return h.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:h}}case"message_delta":{const n=t.state;return!n||n.conversationId!==s.msg.conversationId?t:{...t,state:vi(n,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(n=>n.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"session_search_result":return{...t,sessionSearch:s.result};case"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"update_status_all":return{...t,updatesAll:s.items};case"updates_check_started":return{...t,updatesAll:null};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"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(n=>n.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(i=t.state)!=null&&i.conversationId)&&s.conversationId!==(t.activeConversationId||((l=t.state)==null?void 0:l.conversationId))?t:{...t,terminals:t.terminals.map(n=>n.id===s.terminalId?{...n,running:!1,exitCode:s.exitCode}:n)};case"terminal_restart":return{...t,terminals:t.terminals.map(n=>n.id===s.terminalId?{...n,running:!0,exitCode:null}:n)};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(n=>{var o;return{...n,conversationId:s.conversationId??((o=t.state)==null?void 0:o.conversationId)??""}})};default:return t}}const us="pi-web-client-id";let Nt=null;function Wt(){if(Nt)return Nt;let t=null;try{t=sessionStorage.getItem(us),t||(t=Be(),sessionStorage.setItem(us,t))}catch{t=t??Be()}return Nt=t,t}function Ri(){const t=location.protocol==="https:"?"wss:":"ws:";return yt(`${t}//${location.host}${Ye("/ws")}`)}function Pi(){const[t,s]=r.useReducer(Mi,{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,updatesAll:null,widgets:[],statuses:[],dialog:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],goal:Ti,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,protocolMismatch:!1}),i=r.useRef(null),l=r.useRef(Ei()),c=r.useRef(0),a=r.useRef(null),n=r.useRef(!0),o=r.useRef(0),u=r.useRef(0),h=r.useRef(new Map),p=r.useRef(null),g=()=>{p.current||(p.current=setTimeout(()=>{p.current=null;const S=i.current;S&&S.readyState===WebSocket.OPEN&&S.send(JSON.stringify({type:"get_state"}))},300))},k=(S,T)=>{var O;const m=h.current,B=m.get(S);if(B!==void 0&&T!==B+1){const Z=A.current.chat,Q=Z.activeConversationId||((O=Z.state)==null?void 0:O.conversationId);S===Q&&g()}m.set(S,T)},b=r.useCallback((S,T)=>{const m=++u.current;s({type:"notice",notice:{id:m,level:S,text:T}})},[]),N=r.useCallback(S=>{const T=i.current;return T&&T.readyState===WebSocket.OPEN?(S.type==="check_updates_all"&&S.force===!0&&s({type:"updates_check_started"}),T.send(JSON.stringify(S)),!0):!1},[]),D=r.useCallback(()=>{if(!n.current)return;s({type:"status",status:"connecting"});const S=new WebSocket(Ri());i.current=S,S.onopen=()=>{i.current===S&&(s({type:"status",status:"open"}),c.current=0,o.current=Date.now(),S.send(JSON.stringify({type:"hello",clientId:Wt()})))},S.onmessage=T=>{if(i.current!==S)return;o.current=Date.now();let m;try{m=JSON.parse(T.data)}catch{return}switch(m.type){case"ready":s({type:"ready",serverVersion:m.serverVersion,protocolVersion:m.protocolVersion}),S.send(JSON.stringify({type:"get_state"})),S.send(JSON.stringify({type:"list_files"})),S.send(JSON.stringify({type:"list_models"})),S.send(JSON.stringify({type:"list_commands"})),S.send(JSON.stringify({type:"get_commands"})),S.send(JSON.stringify({type:"check_update"})),S.send(JSON.stringify({type:"check_updates_all"}));break;case"snapshot":h.current=new Map,s({type:"snapshot",state:m.state});break;case"snapshot_delta":{const B=A.current.chat.state;(!B||B.conversationId!==m.conversationId||B.rev!==m.baseRev)&&g(),s({type:"snapshot_delta",msg:m});break}case"tool_delta":k(m.conversationId,m.seq),s({type:"tool_delta",toolCallId:m.toolCallId,toolName:m.toolName,delta:m.delta});break;case"tool_status":s({type:"tool_status",status:m});break;case"message_delta":{k(m.conversationId,m.seq),s({type:"message_delta",msg:m});break}case"notice":{const B=++u.current;s({type:"notice",notice:{id:B,level:m.level,text:m.text}});break}case"sessions":s({type:"sessions",sessions:m.sessions});break;case"conversations":s({type:"conversations",conversations:m.conversations,activeId:m.activeId});break;case"projects":s({type:"projects",projects:m.projects});break;case"files":s({type:"files",files:m});break;case"file_changed":s({type:"file_changed",path:m.path});break;case"file_content":s({type:"file_content",content:m});break;case"models":s({type:"models",models:m.models,loading:!1});break;case"models_config":s({type:"models_config",providers:m.providers});break;case"providers_status":s({type:"providers_status",providers:m.providers});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:m.reqId,ok:m.ok,models:m.models,error:m.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:m.reqId,ok:m.ok,added:m.added,total:m.total,error:m.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:m.reqId,ok:m.ok,config:m.config,error:m.error}});break;case"scm_data":s({type:"scm_data",data:m});break;case"search_files_result":s({type:"file_search_result",result:{reqId:m.reqId,ok:m.ok,results:m.results,truncated:m.truncated}});break;case"session_search_results":s({type:"session_search_result",result:{reqId:m.reqId,ok:m.ok,results:m.results}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:m});break;case"path_completions":s({type:"path_completions",completions:m.completions});break;case"update_status":s({type:"update_status",status:m});break;case"update_status_all":s({type:"update_status_all",items:m.items});break;case"widgets":s({type:"widgets",widgets:m.widgets});break;case"statuses":s({type:"statuses",statuses:m.statuses});break;case"dialog":s({type:"dialog",dialog:{id:m.id,kind:m.kind,title:m.title,args:m.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"terminal_output":l.current.write(m.conversationId??A.current.chat.activeConversationId,m.terminalId,m.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:m.conversationId,terminalId:m.terminalId,exitCode:m.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:m.conversationId,terminals:m.terminals});break;case"commands":s({type:"commands",commands:m.commands,path:m.path});break;case"slash_commands":s({type:"slash_commands",commands:m.commands});break;case"goal_status":s({type:"goal_status",status:m.status});break;case"settings_state":s({type:"settings",settings:m.settings});break;case"bg_servers":s({type:"bg_servers",servers:m.servers});break;case"plugins":s({type:"plugins",plugins:m.plugins,epoch:m.epoch});break;case"plugin_data":yi(m.pluginId,m.payload);break}},S.onclose=()=>{if(i.current===S&&(i.current=null),l.current.clear(),!n.current||i.current&&i.current!==S)return;s({type:"status",status:"closed"});const T=Math.min(1e3*2**c.current,1e4);c.current+=1,a.current=setTimeout(()=>{a.current=null,D()},T)},S.onerror=()=>{}},[]);r.useEffect(()=>{n.current=!0,D();const S=setInterval(()=>{if(!n.current)return;const T=i.current;T&&T.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&T.close()},5e3);return()=>{var T;n.current=!1,clearInterval(S),a.current&&(clearTimeout(a.current),a.current=null),(T=i.current)==null||T.close(),i.current=null}},[D]);const w=r.useCallback(S=>s({type:"dismiss_notice",id:S}),[]),_=r.useCallback(S=>s({type:"terminal_add",meta:S}),[]),v=r.useCallback(S=>s({type:"terminal_remove",id:S}),[]),j=r.useCallback(S=>s({type:"terminal_restart",terminalId:S}),[]),I=r.useCallback((S,T,m)=>l.current.register(S,T,m),[]),A=r.useRef({chat:t,send:N,pushNotice:b,dismissNotice:w,terminal:{create:_,close:v,register:I,restart:j}});return A.current={chat:t,send:N,pushNotice:b,dismissNotice:w,terminal:{create:_,close:v,register:I,restart:j}},A.current}const Ii=200*1024*1024,Li=/windows/i.test(navigator.userAgent),Bi=/[<>:"/\\|?*\u0000-\u001f]/g,Di=/[. ]+$/,Ai=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function _i(t){const s=t.replace(Bi,"_").replace(Di,"");return s?Ai.test(s)?`_${s}`:s:"_"}function ps(t,s=!0){const i=new URLSearchParams({clientId:Wt(),path:t,...s?{download:"1"}:{}});return yt(Ye(`/api/file?${i}`))}async function Fi(t,s){const i=Li?_i(s):s;try{const l=await fetch(ps(t));if(!l.ok)return{ok:!1,cancelled:!1,error:await l.text().catch(()=>"")||(l.status===404?"文件不存在":`HTTP ${l.status}`)};if(Number(l.headers.get("content-length")??"0")>Ii)return window.location.assign(ps(t)),{ok:!0};const a=await l.blob();return window.showSaveFilePicker&&window.isSecureContext?$i(a,i):Dt(a,i)}catch(l){return{ok:!1,cancelled:!1,error:l instanceof Error?l.message:String(l)}}}async function $i(t,s){let i;const l=window.showSaveFilePicker;if(!l)return Dt(t,s);try{i=await l({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:Dt(t,s)}try{const c=await i.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 Dt(t,s){const i=URL.createObjectURL(t),l=document.createElement("a");return l.href=i,l.download=s,document.body.appendChild(l),l.click(),l.remove(),setTimeout(()=>URL.revokeObjectURL(i),1e4),{ok:!0}}const Oi=r.memo(function({files:s,fileChanged:i,widgets:l,cwd:c,send:a,onAttach:n,onPreview:o,onNotice:u}){const h=pe(),[p,g]=r.useState(""),[k,b]=r.useState(null),[N,D]=r.useState(!1),w=1e4,_=r.useRef(0),v=r.useRef(void 0),j=r.useCallback((T,m)=>{const B=++_.current;g(T),m!=null&&m.silent||D(!0),a({type:"list_files",path:T===""?void 0:T})||_.current===B&&D(!1)},[a]);r.useEffect(()=>{s&&s.path===p&&D(!1)},[s,p]),r.useEffect(()=>{if(c!==v.current){v.current=c,j("",{silent:!0});return}const T=setInterval(()=>{document.visibilityState!=="hidden"&&j(p,{silent:!0})},w);return()=>clearInterval(T)},[c,p,j]),r.useEffect(()=>{i&&i.path===p&&j(p,{silent:!0})},[i,p,j]);const I=T=>j(T),A=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&j(s.parent)},S=p.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 ${p===""?"active":""}`,onClick:()=>j(""),children:h("rootDir")}),S.map((T,m)=>{const B=S.slice(0,m+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(xt,{}),e.jsx("button",{type:"button",className:`crumb ${B===p?"active":""}`,onClick:()=>j(B),children:T})]},B)})]}),e.jsxs("div",{className:"panel-body",children:[N&&e.jsx("div",{className:"panel-empty",children:h("loading")}),!N&&s&&s.path===p&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:A,children:[e.jsx(Ge,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(T=>T.type==="dir"?e.jsxs("div",{className:"file-item dir",children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>I(T.path),children:[e.jsx(Ge,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:T.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":h("linkFolderTip"),onClick:()=>n(T.path,T.name,"reference",!0),children:e.jsx(Mt,{})})]},T.path):e.jsxs("div",{className:"file-item file",children:[e.jsxs("button",{type:"button",className:"file-name",title:`${T.path} — ${h("previewFile")}`,onClick:()=>o(T.path,T.name),children:[e.jsx(Fs,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:T.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":h("downloadFile"),onClick:()=>{Fi(T.path,T.name).then(m=>{m.ok||m.cancelled||u("error",h("downloadFailed",{error:m.error}))})},children:e.jsx(Ft,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":h("attachInlineTip"),onClick:()=>n(T.path,T.name,"inline"),children:e.jsx(_e,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":h("referenceTip"),onClick:()=>n(T.path,T.name,"reference"),children:e.jsx(Mt,{})})]},T.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:h("filesTruncated")})]}),!N&&!s&&e.jsx("div",{className:"panel-empty",children:h("noFiles")})]}),l.filter(T=>T.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:l.filter(T=>T.lines.length>0).map(T=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:h("widgetExpand"),onClick:()=>b(T.key),children:[e.jsx("span",{children:T.key}),e.jsx(Kn,{})]}),e.jsx("pre",{className:"widget-lines",children:T.lines.join(`
|
|
304
304
|
`)})]},T.key))}),k&&(()=>{const T=l.find(m=>m.key===k);return T?e.jsx("div",{className:"modal-backdrop",onClick:()=>b(null),children:e.jsxs("div",{className:"widget-expand",onClick:m=>m.stopPropagation(),children:[e.jsxs("div",{className:"widget-expand-head",children:[e.jsx("span",{className:"widget-expand-title",children:T.key}),e.jsx("button",{type:"button",className:"btn",title:h("close"),onClick:()=>b(null),children:e.jsx(we,{})})]}),e.jsx("pre",{className:"widget-expand-lines",children:T.lines.join(`
|
|
305
|
-
`)})]})}):null})()]})});var
|
|
306
|
-
`).map(n=>n===""?[]:[n])}if(Array.isArray(l)){let
|
|
307
|
-
`),
|
|
308
|
-
`)),l=[];continue}l.push(n);continue}l.push(n)}return{frozen:
|
|
309
|
-
`),inFence:c!==null}}const
|
|
310
|
-
`)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${n?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>
|
|
311
|
-
`),K=s.role==="user"?
|
|
312
|
-
`).join(" ").trim(),x=
|
|
313
|
-
`)),S(p??[]),v(!0)},X=()=>{const F=j.trim();F&&(o==null||o(s.id,F,A.length>0?A:void 0),v(!1))},V=s.role==="custom"&&(s.customType==="goal-review"||s.customType==="goal-wizard"),M=s.role==="custom"&&s.customType==="goal-wizard";return e.jsxs("div",{className:`msg msg-${s.role}${V?" 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"?M?w("goalWizardCard"):V?w("goalBarTitle"):s.customType==="file"?w("attachment"):`${w("plugin")} · ${s.customType??w("unknown")}`:
|
|
314
|
-
`).length+1)),onChange:F=>I(F.target.value),onPaste:F=>{var te;const q=[];for(const
|
|
315
|
-
`),p=
|
|
316
|
-
`).length;return e.jsxs("div",{className:`attachcard ${o?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>l(b=>!b),children:[e.jsx("span",{className:"attachcard-icon",children:n?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:
|
|
317
|
-
`)}function xa(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 a=s.trim().toLowerCase();if(!a)return 0;const l=t.toLowerCase();let c=0,i=l.indexOf(a);for(;i!==-1;)c++,i=l.indexOf(a,i+a.length);return c}function ya(t,s){const a=s.trim().toLowerCase();if(!a)return[];const l=[];for(const c of t){const i=fa(c);if(!i)continue;const n=va(i,a);for(let o=0;o<n;o++)l.push({messageId:c.id,occurrence:o})}return l}function ka(t,s){var n;const a=new Map,l=[],c=s.toLowerCase();if(!c)return{byMsg:a,all:l};const i=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(o){const u=o.parentElement;return!u||u.closest(".search-bar")?NodeFilter.FILTER_REJECT:(o.textContent??"").toLowerCase().includes(c)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let o=i.nextNode();o;o=i.nextNode()){const u=(o.textContent??"").toLowerCase(),h=(n=o.parentElement)==null?void 0:n.closest("[data-msg-id]");if(!h)continue;const p=h.getAttribute("data-msg-id")??"";let g=u.indexOf(c);for(;g!==-1;){const k=document.createRange();k.setStart(o,g),k.setEnd(o,g+c.length),l.push(k);const b=a.get(p);b?b.push(k):a.set(p,[k]),g=u.indexOf(c,g+c.length)}}return{byMsg:a,all:l}}function Ue(t,s){const a=CSS;if(!a.highlights)return;if(s.length===0){a.highlights.delete(t);return}const l=window.Highlight;l&&a.highlights.set(t,new l(...s))}function ba({containerRef:t,messages:s,open:a,onClose:l,onEnsureExpanded:c}){const i=pe(),n=r.useRef(null),[o,u]=r.useState(""),[h,p]=r.useState(0),g=r.useDeferredValue(o),k=a?g.trim():"",b=r.useMemo(()=>a?ya(s,k):[],[s,k,a]),N=r.useRef(b);N.current=b;const B=r.useRef(h);B.current=h,r.useEffect(()=>{a&&(p(0),requestAnimationFrame(()=>{var j;return(j=n.current)==null?void 0:j.select()}))},[a]),r.useEffect(()=>{if(!a)return;const j=I=>{I.key==="Escape"&&(I.preventDefault(),I.stopPropagation(),l())};return window.addEventListener("keydown",j,!0),()=>window.removeEventListener("keydown",j,!0)},[a,l]),r.useEffect(()=>(a||(Ue("msg-search",[]),Ue("msg-search-active",[])),()=>{Ue("msg-search",[]),Ue("msg-search-active",[])}),[a]);const w=r.useCallback(j=>{const I=t.current;if(!I)return;const A=I.querySelector(`[data-msg-id="${j}"]`);A&&(A.classList.remove("msg-flash"),A.offsetWidth,A.classList.add("msg-flash"))},[t]);r.useLayoutEffect(()=>{if(!a||!k)return;const j=t.current;if(!j)return;let I=!1,A=0;return A=requestAnimationFrame(()=>{var Z;if(I)return;const{byMsg:S,all:T}=ka(j,k);Ue("msg-search",T);const m=N.current,D=m[Math.min(B.current,m.length-1)];if(!D)return;const O=(Z=S.get(D.messageId))==null?void 0:Z[D.occurrence];if(O){Ue("msg-search-active",[O]);const Q=O.startContainer.parentElement??j.querySelector(`[data-msg-id="${D.messageId}"]`);Q==null||Q.scrollIntoView({block:"center"})}else w(D.messageId)}),()=>{I=!0,cancelAnimationFrame(A)}},[a,k,b,t,w]);const _=r.useCallback(j=>{const I=N.current;if(I.length===0)return;const A=(B.current+j+I.length)%I.length;p(A),c(I[A].messageId)},[c]);if(!a)return null;const v=b.length;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:n,className:"search-input",type:"text",value:o,placeholder:i("searchPlaceholder"),onChange:j=>{u(j.target.value),p(0)},onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),_(j.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${v===0?"empty":""}`,children:v===0?i("searchNoResults"):`${Math.min(h+1,v)}/${v}`}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchPrev"),disabled:v===0,onClick:()=>_(-1),children:e.jsx(gt,{})}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchNext"),disabled:v===0,onClick:()=>_(1),children:e.jsx(qe,{})}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchClose"),onClick:l,children:e.jsx(we,{})})]})}function ja(t){const{dSt:s,dSh:a,escaped:l,graceActive:c,stuck:i}=t;return c?{flipEscape:!1,reassert:!1}:s>=-4||s<=-500?{flipEscape:!1,reassert:!1}:a<0?{flipEscape:!1,reassert:i&&!l}:{flipEscape:!0,reassert:!1}}const sn=[{id:"setup-matt-pocock-skills",icon:"🛠",titleKey:"tpl.sk.setup",descKey:"tpl.sk.setup.desc",promptKey:"tpl.sk.setup.prompt"},{id:"ask-matt",icon:"🧭",titleKey:"tpl.sk.ask",descKey:"tpl.sk.ask.desc",promptKey:"tpl.sk.ask.prompt"},{id:"grill-with-docs",icon:"🗣",titleKey:"tpl.sk.grilldocs",descKey:"tpl.sk.grilldocs.desc",promptKey:"tpl.sk.grilldocs.prompt"},{id:"to-spec",icon:"📝",titleKey:"tpl.sk.tospec",descKey:"tpl.sk.tospec.desc",promptKey:"tpl.sk.tospec.prompt"},{id:"to-tickets",icon:"🎫",titleKey:"tpl.sk.totickets",descKey:"tpl.sk.totickets.desc",promptKey:"tpl.sk.totickets.prompt"},{id:"implement",icon:"🏗",titleKey:"tpl.sk.implement",descKey:"tpl.sk.implement.desc",promptKey:"tpl.sk.implement.prompt"},{id:"code-review",icon:"🧹",titleKey:"tpl.sk.codeview",descKey:"tpl.sk.codeview.desc",promptKey:"tpl.sk.codeview.prompt"},{id:"wayfinder",icon:"🗺",titleKey:"tpl.sk.wayfinder",descKey:"tpl.sk.wayfinder.desc",promptKey:"tpl.sk.wayfinder.prompt"},{id:"prototype",icon:"🔬",titleKey:"tpl.sk.prototype",descKey:"tpl.sk.prototype.desc",promptKey:"tpl.sk.prototype.prompt"},{id:"research",icon:"📚",titleKey:"tpl.sk.research",descKey:"tpl.sk.research.desc",promptKey:"tpl.sk.research.prompt"},{id:"improve-codebase-architecture",icon:"🏛",titleKey:"tpl.sk.arch",descKey:"tpl.sk.arch.desc",promptKey:"tpl.sk.arch.prompt"},{id:"diagnosing-bugs",icon:"🐛",titleKey:"tpl.sk.debug",descKey:"tpl.sk.debug.desc",promptKey:"tpl.sk.debug.prompt"},{id:"resolving-merge-conflicts",icon:"🔀",titleKey:"tpl.sk.merge",descKey:"tpl.sk.merge.desc",promptKey:"tpl.sk.merge.prompt"},{id:"triage",icon:"🗂",titleKey:"tpl.sk.triage",descKey:"tpl.sk.triage.desc",promptKey:"tpl.sk.triage.prompt"},{id:"wizard",icon:"✨",titleKey:"tpl.sk.wizard",descKey:"tpl.sk.wizard.desc",promptKey:"tpl.sk.wizard.prompt"},{id:"grill-me",icon:"🔍",titleKey:"tpl.sk.grillme",descKey:"tpl.sk.grillme.desc",promptKey:"tpl.sk.grillme.prompt"},{id:"handoff",icon:"🤝",titleKey:"tpl.sk.handoff",descKey:"tpl.sk.handoff.desc",promptKey:"tpl.sk.handoff.prompt"},{id:"to-questionnaire",icon:"📋",titleKey:"tpl.sk.questionnaire",descKey:"tpl.sk.questionnaire.desc",promptKey:"tpl.sk.questionnaire.prompt"},{id:"teach",icon:"🎓",titleKey:"tpl.sk.teach",descKey:"tpl.sk.teach.desc",promptKey:"tpl.sk.teach.prompt"},{id:"wait-what",icon:"💬",titleKey:"tpl.sk.ww",descKey:"tpl.sk.ww.desc",promptKey:"tpl.sk.ww.prompt"},{id:"writing-for-agents",icon:"📄",titleKey:"tpl.sk.wfa",descKey:"tpl.sk.wfa.desc",promptKey:"tpl.sk.wfa.prompt"},{id:"codebase-design",icon:"🧱",titleKey:"tpl.sk.codesign",descKey:"tpl.sk.codesign.desc",promptKey:"tpl.sk.codesign.prompt"},{id:"domain-modeling",icon:"🏷",titleKey:"tpl.sk.domain",descKey:"tpl.sk.domain.desc",promptKey:"tpl.sk.domain.prompt"},{id:"grilling",icon:"🔥",titleKey:"tpl.sk.grilling",descKey:"tpl.sk.grilling.desc",promptKey:"tpl.sk.grilling.prompt"},{id:"tdd",icon:"🧪",titleKey:"tpl.sk.tdd",descKey:"tpl.sk.tdd.desc",promptKey:"tpl.sk.tdd.prompt"}],nn="pi-web-ui:prompt-templates";function wa(){try{const t=localStorage.getItem(nn);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(a=>!!a&&typeof a=="object"&&typeof a.id=="string"):[]}catch{return[]}}function vs(t){return sn.some(s=>s.id===t)}function it(t){return typeof t.title=="string"}const an=r.createContext(null);function rn(){const t=r.useContext(an);if(!t)throw new Error("useTemplates must be used within TemplateProvider");return t}function Na({send:t,children:s}){const a=pe(),[l,c]=r.useState(wa),[i,n]=r.useState(!1),[o,u]=r.useState(null),[h,p]=r.useState(!1),[g,k]=r.useState(!1),[b,N]=r.useState(!1);r.useEffect(()=>{try{localStorage.setItem(nn,JSON.stringify(l))}catch{}},[l]);const B=r.useMemo(()=>{const H=new Map,K=new Set;for(const y of l)y.hidden?K.add(y.id):(it(y)&&!vs(y.id)||it(y))&&H.set(y.id,y);const ie=sn.filter(y=>!K.has(y.id)).map(y=>{const $=H.get(y.id);return{id:y.id,icon:($==null?void 0:$.icon)??y.icon,title:($==null?void 0:$.title)??a(y.titleKey),desc:($==null?void 0:$.desc)??a(y.descKey),prompt:($==null?void 0:$.prompt)??a(y.promptKey),builtin:!0}}),x=l.filter(y=>it(y)&&!vs(y.id)).map(y=>({id:y.id,icon:y.icon??"📌",title:y.title??"",desc:y.desc??"",prompt:y.prompt??""}));return[...ie,...x]},[l,a]),w=r.useCallback(()=>n(!0),[]),_=r.useCallback(H=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:H}))},[]),v=r.useCallback((H,K=!1)=>{N(K),H?(p(!1),u({...H})):(p(!0),u({id:De(),icon:"📌",title:"",desc:"",prompt:""}))},[]),j=r.useCallback(()=>{n(!1),u(null),N(!1)},[]),I=r.useCallback(()=>{g?(c([]),k(!1)):(k(!0),setTimeout(()=>k(!1),5e3))},[g]),A=r.useCallback(H=>{n(!1),_(H.prompt)},[_]),S=r.useCallback(H=>{n(!1),v(H,!0)},[v]),T=r.useCallback(()=>{n(!1),v(void 0,!0)},[v]),m=r.useCallback(H=>{c(K=>{const ie=K.findIndex(x=>x.id===H.id);if(ie>=0){const x=[...K];return x[ie]=H,x}return[...K,H]}),u(null),b&&(n(!0),N(!1))},[b]),D=r.useCallback(H=>{c(K=>H.builtin?[...K.filter(x=>x.id!==H.id),{id:H.id,hidden:!0}]:K.filter(ie=>ie.id!==H.id)),u(null),b&&(n(!0),N(!1))},[b]),O=r.useCallback(H=>{c(K=>K.filter(ie=>ie.id!==H.id||ie.hidden)),u(null),b&&(n(!0),N(!1))},[b]),Z=r.useMemo(()=>({templates:B,fill:_,openPicker:w,openEdit:v,resetConfirm:g,toggleReset:I}),[B,_,w,v,g,I]),Q=o?l.some(H=>H.id===o.id&&!H.hidden&&it(H)):!1;return e.jsxs(an.Provider,{value:Z,children:[s,i&&e.jsx(Sa,{templates:B,resetConfirm:g,onFill:A,onEditTpl:S,onNew:T,onResetToggle:I,onClose:j}),o&&e.jsx(Ta,{editing:o,isNew:h,hasOverride:Q,onDraft:u,onSave:m,onRestore:()=>O(o),onRemove:()=>D(o),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:o.prompt})),j()},onSend:()=>{const H=o.prompt.trim();H&&t({type:"prompt",text:H,queue:!1})&&j()},onClose:j})]})}function Ca(){const t=pe(),{templates:s,fill:a,openEdit:l,toggleReset:c,resetConfirm:i}=rn();return e.jsxs("div",{className:"empty-templates",children:[e.jsxs("div",{className:"empty-templates-head",children:[e.jsx("span",{className:"empty-templates-title",children:t("tpl.title")}),e.jsx("span",{className:"empty-templates-hint",children:t("tpl.hint")})]}),e.jsxs("div",{className:"empty-templates-grid",children:[s.map(n=>e.jsx(ln,{tpl:n,title:t("tpl.clickCard"),onFill:()=>a(n.prompt),onEdit:()=>l(n),editTitle:t("tpl.editTpl")},n.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>l(),title:t("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(_e,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:t("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"empty-templates-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:c,children:[e.jsx(As,{}),t(i?"tpl.resetConfirm":"tpl.reset")]})})]})}function ln({tpl:t,title:s,onFill:a,onEdit:l,editTitle:c}){const i=pe();return e.jsxs("button",{type:"button",className:"empty-template",title:s,onClick:a,children:[e.jsx("span",{className:"empty-template-icon",children:t.icon}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t.title}),e.jsx("span",{className:"empty-template-desc",children:t.desc})]}),e.jsx("span",{className:"template-card-ops",role:"button",title:c??i("tpl.editTpl"),onClick:n=>{n.stopPropagation(),l()},children:e.jsx(Rt,{})})]})}function Sa({templates:t,resetConfirm:s,onFill:a,onEditTpl:l,onNew:c,onResetToggle:i,onClose:n}){const o=pe();return r.useEffect(()=>{const u=h=>{h.key==="Escape"&&n()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n]),e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"modal template-picker",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"template-picker-head",children:[e.jsx("span",{className:"template-picker-title",children:o("tpl.pickerTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:o("close"),onClick:n,children:e.jsx(we,{})})]}),e.jsx("div",{className:"template-picker-hint",children:o("tpl.pickerHint")}),e.jsxs("div",{className:"template-picker-grid",children:[t.map(u=>e.jsx(ln,{tpl:u,title:o("tpl.clickCard"),onFill:()=>a(u),onEdit:()=>l(u),editTitle:o("tpl.editTpl")},u.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:c,title:o("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(_e,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:o("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:o("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"template-picker-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:i,children:[e.jsx(As,{}),o(s?"tpl.resetConfirm":"tpl.reset")]})})]})})}function Ta({editing:t,isNew:s,hasOverride:a,onDraft:l,onSave:c,onRestore:i,onRemove:n,onFill:o,onSend:u,onClose:h}){const p=pe(),g=r.useRef(null);r.useEffect(()=>{const N=B=>{B.key==="Escape"&&h()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[h]),r.useEffect(()=>{const N=g.current;if(!N)return;N.style.height="auto";const B=N.scrollHeight>300;N.style.height=`${Math.min(N.scrollHeight,300)}px`,N.style.overflowY=B?"auto":"hidden"},[t.prompt]);const k=()=>{const N=t.title.trim(),B=t.prompt.trim();if(!N||!B){l({...t,error:p("tpl.required")});return}c({id:t.id,icon:t.icon.trim()||"📌",title:N,desc:t.desc.trim(),prompt:B})},b=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:h,children:e.jsxs("div",{className:"modal template-modal",onClick:N=>N.stopPropagation(),children:[e.jsxs("div",{className:"template-modal-head",children:[e.jsx("span",{className:"template-modal-icon",children:t.icon}),e.jsx("span",{className:"template-modal-badge",children:p(b?"tpl.builtin":"tpl.custom")}),e.jsx("span",{className:"template-modal-title",children:p(s?"tpl.newTitle":"tpl.editTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:p("close"),onClick:h,children:e.jsx(we,{})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:p("tpl.fieldIcon")}),e.jsx("input",{className:"template-field-input icon",value:t.icon,maxLength:4,onChange:N=>l({...t,icon:N.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:p("tpl.fieldTitle")}),e.jsx("input",{className:"template-field-input",value:t.title,placeholder:p("tpl.fieldTitlePh"),onChange:N=>l({...t,title:N.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:p("tpl.fieldDesc")}),e.jsx("input",{className:"template-field-input",value:t.desc,placeholder:p("tpl.fieldDescPh"),onChange:N=>l({...t,desc:N.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:p("tpl.fieldPrompt")}),e.jsx("textarea",{ref:g,className:"template-field-prompt",value:t.prompt,placeholder:p("tpl.fieldPromptPh"),onChange:N=>l({...t,prompt:N.target.value})})]}),t.error&&e.jsx("div",{className:"template-error",children:t.error}),e.jsxs("div",{className:"template-modal-actions",children:[e.jsxs("div",{className:"template-modal-actions-left",children:[!s&&b&&a&&e.jsx("button",{type:"button",className:"btn template-btn ghost",title:p("tpl.restoreTip"),onClick:i,children:p("tpl.restore")}),!s&&b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:p("tpl.removeTip"),onClick:n,children:[e.jsx(Ie,{})," ",p("tpl.remove")]}),!s&&!b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:p("tpl.deleteTip"),onClick:n,children:[e.jsx(Ie,{})," ",p("tpl.delete")]})]}),e.jsxs("div",{className:"template-modal-actions-right",children:[e.jsx("button",{type:"button",className:"btn template-btn",onClick:k,children:p("tpl.save")}),e.jsx("button",{type:"button",className:"btn template-btn fill",onClick:o,title:p("tpl.fillTip"),children:p("tpl.fill")}),e.jsxs("button",{type:"button",className:"btn template-btn send",onClick:u,title:p("tpl.sendTip"),children:[e.jsx(Bs,{})," ",p("tpl.sendNow")]})]})]})]})})}const ys=new Map,Ea=15,ks=30,Nt=250,bs=1200,Ma=1600;function js(t){return t.content.some(s=>s.type==="toolCall")}function Ra({state:t,liveOutputs:s,toolStatuses:a,onEdit:l,onKillBash:c,thinkingWrap:i,toolsWrap:n,jumpTarget:o,onJumpDone:u}){const h=pe(),p=r.useRef(null),[g,k]=r.useState(!0),b=r.useRef(!0),N=r.useRef(0),B=r.useRef(0),w=r.useRef(!1),_=r.useRef(0),[v,j]=r.useState(()=>new Set),[I,A]=r.useState(!1),S=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,T=r.useMemo(()=>{const f=new Map;for(const E of t.messages)E.role==="toolResult"&&E.toolCallId&&f.set(E.toolCallId,E);return f},[t.messages]),m=r.useMemo(()=>ra(t.messages),[t.messages]),D=S.length>0?S[S.length-1].id:null,O=t.messages.length>ks?Math.max(0,t.messages.length-Ea):0,[Z,Q]=r.useState(()=>new Set),[H,K]=r.useState(()=>new Set),ie=r.useRef(new Map),x=r.useRef(new Map),y=r.useRef(new Map),$=r.useRef(0),ge=r.useMemo(()=>{const f=new Map;for(const E of t.messages)f.set(E.id,ha(E));return f},[t.messages]),z=r.useRef(ge);z.current=ge;const P=r.useRef(Z);P.current=Z;const X=t.messages.length>ks&&!I,V=r.useRef(X);V.current=X;const M=pa(t.messages,ie.current,Ma),F=r.useRef(M);F.current=M;const q=r.useCallback(()=>{const f=p.current;if(!f)return;if(!V.current){Q(he=>he.size?new Set:he);return}const E=f.getBoundingClientRect(),J={top:E.top-bs,bottom:E.bottom+bs},se=[];for(const[he,je]of y.current){const Re=je.getBoundingClientRect();se.push({id:he,top:Re.top,bottom:Re.bottom}),P.current.has(he)||oe(he,Re.bottom-Re.top,z.current.get(he))}const me=da(se,J,F.current,P.current);for(const he of me.hide){const je=y.current.get(he);je&&oe(he,je.offsetHeight,z.current.get(he))}Q(he=>ua(he,me))},[]),te=r.useCallback(()=>{$.current||($.current=requestAnimationFrame(()=>{$.current=0,q()}))},[q]);r.useLayoutEffect(()=>{q()},[q]);const U=r.useRef(I);r.useLayoutEffect(()=>{U.current&&!I&&q(),U.current=I},[I,q]);const oe=r.useCallback((f,E,J)=>{J!==void 0&&(x.current.set(f,{h:E,len:J}),ie.current.set(f,E))},[]),re=r.useCallback((f,E)=>{oe(f,E,z.current.get(f))},[oe]),d=r.useCallback(f=>{f&&y.current.set(f.dataset.lazyId??"",f)},[]);r.useEffect(()=>{const f=new Set(t.messages.map(E=>E.id));for(const[E,J]of y.current)f.has(E)||(y.current.delete(E),ie.current.delete(E),x.current.delete(E));Q(E=>{let J=!1;const se=new Set;for(const me of E)f.has(me)?se.add(me):J=!0;return J?se:E})},[t.messages,v]),r.useEffect(()=>()=>cancelAnimationFrame($.current),[]);const R=r.useMemo(()=>{const f=[];for(const E of t.messages){if(E.role!=="user")continue;const J=E.content.map(he=>{var je;return((je=st(he))==null?void 0:je.text)??""}).filter(Boolean).join(" "),se=Ot(J),me=se?se.userMessage??`skill:${se.name}`:J.trim();me&&f.push({id:E.id,text:me})}return f},[t.messages]),le=r.useMemo(()=>{const f=new Map;return R.forEach((E,J)=>f.set(E.id,J)),f},[R]),[ee,fe]=r.useState(-1),Y=r.useRef(-1),de=r.useRef(R);r.useEffect(()=>{de.current=R},[R]);const xe=r.useCallback(()=>{const f=p.current,E=de.current;if(!f||E.length===0)return;const J=f.getBoundingClientRect().top,se=140;let me=-1;for(let he=0;he<E.length;he++){const je=f.querySelector(`[data-msg-id="${E[he].id}"]`);if(je)if(je.getBoundingClientRect().top<=J+se)me=he;else break}me!==Y.current&&(Y.current=me,fe(me))},[]);r.useEffect(()=>{xe()},[R,xe]);const ce=r.useCallback(f=>{j(E=>E.has(f)?E:new Set(E).add(f))},[]),Se=r.useCallback(f=>{const E=t.messages.findIndex(J=>J.id===f);E>=0&&E<O&&!v.has(f)&&us.flushSync(()=>ce(f))},[t.messages,O,v,ce]);r.useEffect(()=>{const f=E=>{if(!(E.ctrlKey||E.metaKey)||E.key.toLowerCase()!=="f")return;const J=E.target;J&&(J.tagName==="INPUT"||J.tagName==="TEXTAREA"||J.isContentEditable)||(E.preventDefault(),A(!0))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[]);const Ye=r.useCallback(f=>{j(E=>{if(!E.has(f))return E;const J=new Set(E);return J.delete(f),J})},[]),Te=r.useCallback(f=>{const E=t.messages.findIndex(se=>se.id===f);us.flushSync(()=>{E>=0&&E<O&&!v.has(f)&&ce(f),K(se=>se.has(f)?se:new Set(se).add(f))});const J=de.current.findIndex(se=>se.id===f);Y.current=J,fe(J),requestAnimationFrame(()=>{var me,he,je;const se=(me=p.current)==null?void 0:me.querySelector(`[data-msg-id="${f}"]`);se&&((he=p.current)==null||he.querySelectorAll(".msg-flash").forEach(Re=>Re.classList.remove("msg-flash")),se.scrollIntoView({block:"start"}),se.classList.remove("msg-flash"),se.offsetWidth,se.classList.add("msg-flash"),se!==((je=p.current)==null?void 0:je.lastElementChild)&&(w.current=!0))})},[t.messages,O,v,ce]),Ee=r.useMemo(()=>{var f;return o?((f=t.messages.find(E=>E.role===o.role&&E.timestamp===o.timestamp))==null?void 0:f.id)??null:null},[t.messages,o]);r.useEffect(()=>{if(o){if(Ee){Te(Ee),u==null||u();return}t.sessionFile===o.path&&t.messages.length>0&&(u==null||u())}},[Ee,Te,u,o,t.sessionFile,t.messages.length]);const Je=r.useCallback(()=>{const f=p.current;if(!f)return;const E=f.scrollTop-N.current,J=f.scrollHeight-B.current;N.current=f.scrollTop,B.current=f.scrollHeight;const se=f.scrollHeight-f.scrollTop-f.clientHeight<80,me=Date.now()<_.current,he=ja({dSt:E,dSh:J,escaped:w.current,graceActive:me,stuck:b.current});he.reassert&&(_.current=Date.now()+Nt,f.scrollTop=f.scrollHeight),he.flipEscape&&(w.current=!0),se&&E>=0&&(w.current=!1),me||(E<0?b.current=se&&!w.current:se&&(b.current=!0)),k(b.current),xe(),te()},[xe,te]),Me=r.useRef(!1);r.useEffect(()=>{const f=Me.current;if(Me.current=!!t.isStreaming,f&&!t.isStreaming&&!w.current){const E=()=>{const se=p.current;se&&!w.current&&(se.scrollTop=se.scrollHeight,b.current=!0,k(!0))};requestAnimationFrame(()=>requestAnimationFrame(E));const J=setTimeout(E,180);return()=>clearTimeout(J)}},[t.isStreaming]),r.useEffect(()=>{const f=p.current;f&&b.current&&(f.scrollTop=f.scrollHeight)},[S,t.isStreaming,s]);const Qe=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");r.useEffect(()=>{const f=p.current;f&&b.current&&(f.scrollTop=f.scrollHeight)},[Qe]),r.useEffect(()=>{const f=p.current;if(!f||typeof ResizeObserver>"u")return;const E=new ResizeObserver(()=>{b.current&&!w.current&&(f.scrollTop=f.scrollHeight,k(!0))});return E.observe(f),()=>E.disconnect()},[]),r.useEffect(()=>{const f=p.current;if(!f||typeof MutationObserver>"u")return;let E=!1;const J=new MutationObserver(()=>{E||(E=!0,requestAnimationFrame(()=>{E=!1;const se=p.current;se&&b.current&&!w.current&&(se.scrollTop=se.scrollHeight,k(!0))}))});return J.observe(f,{childList:!0,subtree:!0,characterData:!0}),()=>J.disconnect()},[]);const Fe=r.useCallback(()=>{if(!p.current)return;b.current=!0,w.current=!1,k(!0),_.current=Date.now()+Nt;const E=()=>{const J=p.current;!J||!b.current||w.current||(_.current=Date.now()+Nt,J.scrollTop=J.scrollHeight)};E(),requestAnimationFrame(()=>requestAnimationFrame(E)),setTimeout(E,120),setTimeout(E,300),setTimeout(E,600)},[]),$e=r.useRef(null);r.useEffect(()=>{const f=$e.current,E=p.current;if(!f||!E)return;const J=se=>{se.preventDefault();const me=f.querySelector(".qn-list");if(me&&me.contains(se.target)&&me.scrollHeight>me.clientHeight){me.scrollTop+=se.deltaY;return}E.scrollTop+=se.deltaY};return f.addEventListener("wheel",J,{passive:!1}),()=>f.removeEventListener("wheel",J)},[]);const[Oe,C]=r.useState(0);r.useEffect(()=>{const f=()=>{var E;C(((E=p.current)==null?void 0:E.clientHeight)??0),te()};return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[te]);const ue=R.length,ae=r.useMemo(()=>ue===0?27:Math.max(4,Math.min(27,Math.floor(((Oe||600)-16)/ue)-3)),[ue,Oe]),ye=ae<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:`messages${g?"":" anchor-live"}`,ref:p,onScroll:Je,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(Ca,{})}),t.messages.map((f,E)=>{const J=E<O,se=J&&v.has(f.id);if(J&&!se)return f.role==="toolResult"?null:e.jsx(la,{message:f,onExpand:ce},f.id);const me=f.role==="user"?le.get(f.id):void 0,he=!X||M.has(f.id)||H.has(f.id)||!Z.has(f.id);return e.jsx(ca,{id:f.id,show:he,height:ga(f.id,ge.get(f.id)??-1,x.current,tn(f.role,f.customType)),containerRef:p,onMeasured:re,lazyRef:d,children:e.jsx(hs,{message:f,qnIndex:me,qnActive:me!==void 0?me===ee:void 0,onJump:Te,toolResults:T,liveOutputs:js(f)?s:ys,toolStatuses:a,streaming:t.isStreaming,onKillBash:c,toolsWrap:n,thinkingWrap:i,isLast:f.id===D,onEdit:l,questionAttachments:m.get(f.id),onCollapse:se?Ye:void 0},f.id)},f.id)}),t.streamingMessage&&e.jsx(hs,{message:t.streamingMessage,toolResults:T,liveOutputs:js(t.streamingMessage)?s:ys,toolStatuses:a,streaming:!0,isLast:!0,onEdit:l,onKillBash:c,toolsWrap:n,thinkingWrap:i},t.streamingMessage.id),t.isStreaming&&S.length===0&&e.jsx("div",{className:"streaming-wait",children:h("waitingResponse")}),t.queue.steering.map((f,E)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:h("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:f})]})},`q-steer-${E}`)),t.queue.followUp.map((f,E)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:h("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:f})]})},`q-fu-${E}`))]}),!g&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Fe,children:[e.jsx(Os,{})," ",h("backToBottom")]}),e.jsx(ba,{containerRef:p,messages:S,open:I,onClose:()=>A(!1),onEnsureExpanded:Se}),R.length>0&&e.jsxs("div",{className:`qn-rail ${ye?"many":""}`,ref:$e,"aria-label":h("questionNavTitle"),style:{"--rail-gap":`${ae}px`},children:[R.map((f,E)=>e.jsx("button",{type:"button",className:`qn-bar ${E===ee?"active":""}`,"aria-label":`${E+1}. ${f.text}`,onClick:()=>Te(f.id),children:e.jsxs("span",{className:"qn-bar-text",children:[E+1,". ",f.text]})},f.id)),ye&&e.jsx("div",{className:"qn-list",children:R.map((f,E)=>e.jsxs("button",{type:"button",className:`qn-list-item ${E===ee?"active":""}`,"aria-label":`${E+1}. ${f.text}`,onClick:()=>Te(f.id),children:[e.jsx("span",{className:"qn-list-idx",children:E+1}),e.jsx("span",{className:"qn-list-text",children:f.text})]},f.id))})]})]})}const on="pi-web-model-usage";function Pa(t){if(!t||typeof t!="object")return{};const s={};for(const[a,l]of Object.entries(t)){const c=typeof l=="number"?Math.floor(l):0;Number.isFinite(c)&&c>0&&(s[a]=c)}return s}function Ia(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function La(t,s){const a=s;return t.map((l,c)=>({m:l,i:c,count:a[l.id]??0})).sort((l,c)=>c.count-l.count||l.i-c.i).map(l=>l.m)}function cn(){try{const t=localStorage.getItem(on);return t?Pa(JSON.parse(t)):{}}catch{return{}}}function Da(t){try{localStorage.setItem(on,JSON.stringify(t))}catch{}}function Ba(t){const s=Ia(cn(),t);return Da(s),s}const Aa=["off","minimal","low","medium","high","xhigh","max"],_a=r.memo(function({state:s,models:a,modelsLoading:l,send:c,onManageModels:i,compact:n=!1}){const o=pe(),u=s==null?void 0:s.model,h=u?`${u.provider}/${u.id}`:null,[p,g]=r.useState(!1),[k,b]=r.useState(!1),[N,B]=r.useState(""),[w,_]=r.useState(null),[v,j]=r.useState({}),I=r.useRef(null),A=r.useRef(null),[S,T]=r.useState(null);r.useEffect(()=>{if(!p){T(null);return}if(a.length===0)return;const x=requestAnimationFrame(()=>{const y=A.current;y&&T(y.offsetWidth)});return()=>cancelAnimationFrame(x)},[p,a.length]),r.useEffect(()=>{p&&j(cn())},[p]),r.useEffect(()=>{p||(B(""),_(null))},[p]);const m=r.useMemo(()=>{const x=new Map;for(const y of a)x.set(y.provider,(x.get(y.provider)??0)+1);return[...x.entries()].sort((y,$)=>y[0].localeCompare($[0])).map(([y,$])=>({name:y,count:$}))},[a]),D=r.useMemo(()=>La(a,v),[a,v]),O=r.useMemo(()=>{let x=D;w&&(x=x.filter($=>$.provider===w));const y=N.trim().toLowerCase();return y?x.filter($=>$.name.toLowerCase().includes(y)||$.provider.toLowerCase().includes(y)||$.id.toLowerCase().includes(y)):x},[D,N,w]),[Z,Q]=r.useState(!1),H=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,K=Aa.map(x=>({value:x,label:o(`thinking.${x}`),supported:H?H.has(x):!0})),ie=x=>{var y;return((y=K.find($=>$.value===x))==null?void 0:y.label)??x};return r.useEffect(()=>{p&&a.length===0&&!Z&&!l&&(Q(!0),c({type:"list_models"}))},[p,a.length,Z,l,c]),r.useEffect(()=>{a.length>0&&Q(!1)},[a.length]),r.useEffect(()=>{var y;if(!p)return;const x=(y=I.current)==null?void 0:y.querySelector(".dd-item.active");x==null||x.scrollIntoView({block:"nearest"})},[p,h,a.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(tt,{}),e.jsx("span",{className:"chip-model",children:u?u.name:o("selectModel")}),!n&&(u==null?void 0:u.vision)&&e.jsx("span",{className:"chip-vision",title:o("vision"),children:"🖼"}),!n&&u&&e.jsx("span",{className:"chip-sub",children:u.provider})]}),open:p,onOpenChange:g,menuClassName:"dd-menu-model",menuRef:A,menuStyle:S!=null?{width:S}:void 0,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(pt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:o("searchModels"),value:N,onChange:x=>B(x.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[m.length>1&&e.jsxs("div",{className:"dd-provider-col",children:[e.jsx("div",{className:"dd-provider-head",children:o("providers")}),e.jsx("button",{type:"button",className:`dd-provider-item ${w===null?"active":""}`,onClick:()=>_(null),children:e.jsx("span",{children:o("allProviders")})}),m.map(x=>e.jsxs("button",{type:"button",className:`dd-provider-item ${w===x.name?"active":""}`,onClick:()=>_(w===x.name?null:x.name),title:`${x.name} · ${x.count}`,children:[e.jsx("span",{className:"dd-provider-name",children:x.name}),e.jsx("span",{className:"dd-provider-count",children:x.count})]},x.name))]}),e.jsxs("div",{className:"dd-model-scroll",ref:I,children:[(Z||l)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),a.length===0&&!Z&&!l&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),O.length===0&&a.length>0&&e.jsx("div",{className:"dd-loading",children:o("noModelMatches")}),O.map(x=>e.jsx(Ne,{active:h===x.id,onClick:()=>{h!==x.id&&c({type:"set_model",modelId:x.id}),g(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:x.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:x.provider}),(v[x.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:o("modelUsedCount",{n:v[x.id]})}),(x.reasoning||x.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[x.reasoning&&e.jsx("span",{className:"dd-model-badge",children:o("reasoning")}),x.vision&&e.jsx("span",{className:"dd-model-badge",children:o("vision")})]})]})]})},x.id))]})]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>c({type:"list_models"}),children:o("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{g(!1),i()},children:o("manageModels")})]})]}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(at,{}),e.jsx("span",{className:"chip-sub",children:o("thinkingChip",{level:s?ie(s.thinkingLevel):"—"})})]}),open:k,onOpenChange:b,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("thinkingLevel")}),K.map(x=>e.jsx(Ne,{active:(s==null?void 0:s.thinkingLevel)===x.value,disabled:!x.supported,title:x.supported?void 0:o("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==x.value&&c({type:"set_thinking",level:x.value}),b(!1)},children:x.label},x.value))]})]})}),Fa=r.memo(function({ready:s,streaming:a,messages:l,slashCommands:c,modelState:i,models:n,modelsLoading:o,send:u,attachments:h,onRemoveAttachment:p,onAddImageFiles:g,onAddLocalFiles:k,onNotice:b,onSent:N,onManageModels:B}){const w=pe(),{locale:_}=Ft(),{openPicker:v}=rn(),j=d=>_==="en"&&d.descriptionEn?d.descriptionEn:d.description??"",I=d=>_==="en"&&d.argumentHintEn?d.argumentHintEn:d.argumentHint??"",[A,S]=r.useState(""),[T,m]=r.useState(!1),[D,O]=r.useState(null),[Z,Q]=r.useState(0),[H,K]=r.useState(!1),[ie,x]=r.useState(void 0),y=r.useRef(null),$=r.useRef(null),ge=r.useRef(null),z={builtin:w("slashBuiltin"),extension:w("slashExtension"),prompt:w("slashPrompt"),skill:w("slashSkill"),plugin:w("slashPlugin")},P=d=>{const R=d.match(/^\/([^\s]*)$/);if(R&&s){const le=R[1].toLowerCase(),ee=c.filter(fe=>fe.name.toLowerCase().startsWith(le));O(ee.length>0?ee:null),Q(0)}else O(null)};r.useEffect(()=>{var R;const d=(R=ge.current)==null?void 0:R.querySelector(".slash-item.active");d==null||d.scrollIntoView({block:"nearest"})},[Z,D]);const X=d=>{var Y;const R=D??[],le=d??R[Z%Math.max(R.length,1)];if(!le){O(null);return}const ee=A.match(/^\/([^\s]*)([\s\S]*)$/),fe=ee?ee[2]:"";S(`/${le.name} ${fe}`),O(null),(Y=y.current)==null||Y.focus()},V=async()=>{const R=[...l].reverse().find(ee=>ee.role==="assistant"&&ee.content.some(fe=>fe.type==="text"&&fe.text)),le=R==null?void 0:R.content.filter(ee=>ee.type==="text").map(ee=>ee.text).join(`
|
|
318
|
-
`);if(!le){b("warning",w("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(le),b("info",w("slashCopied"))}catch{b("error",w("slashCopyFailed"))}},M=d=>{if(!d||d.length===0){b("warning",w("foldersNotSupported"));return}const R=Array.from(d).filter(ee=>Le(ee.type)),le=Array.from(d).filter(ee=>!Le(ee.type));R.length>0&&g(R),le.length>0&&k(le)},F=d=>{var ee;const R=(ee=d.clipboardData)==null?void 0:ee.items;if(!R)return;const le=[];for(const fe of R)if(fe.kind==="file"&&Le(fe.type)){const Y=fe.getAsFile();Y&&le.push(Y)}le.length!==0&&(d.preventDefault(),g(le))},q=s,te=r.useRef(A);r.useEffect(()=>{te.current=A},[A]),r.useEffect(()=>{P(te.current)},[c]),r.useEffect(()=>{const d=R=>{var ee;const le=R.detail;S(le),(ee=y.current)==null||ee.focus()};return window.addEventListener("pi-web:fill",d),()=>window.removeEventListener("pi-web:fill",d)},[]),r.useEffect(()=>{if(!H)return;const d=R=>{R.key==="Escape"&&K(!1)};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[H]),r.useEffect(()=>{const d=y.current;if(!d)return;d.style.height="auto";const R=d.scrollHeight>220;d.style.height=`${Math.min(d.scrollHeight,220)}px`,d.style.overflowY=R?"auto":"hidden"},[A]);const U=(d=!1)=>{var ee,fe,Y,de,xe;const R=A.trim(),le=h.some(ce=>ce.imageData||ce.fileData);if(!(!q||!R&&!le)){if(R==="/help"){const ce=(fe=(ee=y.current)==null?void 0:ee.closest(".inputbox"))==null?void 0:fe.getBoundingClientRect();x(ce==null?void 0:ce.width),K(!0),S(""),(Y=y.current)==null||Y.focus();return}if(R==="/copy"){S(""),(de=y.current)==null||de.focus(),V();return}if(u({type:"prompt",text:R,queue:d,attachments:h.map(ce=>ce.imageData?{path:"",imageData:ce.imageData,mimeType:ce.mimeType,name:ce.name}:ce.fileData?{path:"",fileData:ce.fileData,mimeType:ce.mimeType,name:ce.name,size:ce.size}:{path:ce.path,mode:ce.mode,...ce.lines?{lines:ce.lines}:{}})})){S(""),N();const ce=i==null?void 0:i.model;ce&&Ba(`${ce.provider}/${ce.id}`),(xe=y.current)==null||xe.focus()}}},oe=d=>{if(!d.nativeEvent.isComposing){if(D&&D.length>0)switch(d.key){case"ArrowDown":d.preventDefault(),Q(R=>(R+1)%D.length);return;case"ArrowUp":d.preventDefault(),Q(R=>(R-1+D.length)%D.length);return;case"Tab":case"Enter":d.preventDefault(),X();return;case"Escape":d.preventDefault(),O(null);return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),U())}},re=()=>e.jsx("div",{className:"inputbox-actions",children:a?e.jsxs(e.Fragment,{children:[A.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:w("supplementTip"),onClick:()=>U(!0),children:[e.jsx(Bs,{})," ",w("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:w("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(dt,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:w("sendTip"),disabled:!q||!A.trim()&&!h.some(d=>d.imageData||d.fileData),onClick:()=>U(),children:e.jsx($s,{})})});return e.jsxs("div",{className:`inputbar${T?" drop-active":""}`,onDragOver:d=>{d.preventDefault(),d.stopPropagation(),m(!0)},onDragLeave:d=>{d.currentTarget.contains(d.relatedTarget)||m(!1)},onDrop:d=>{var R;d.preventDefault(),d.stopPropagation(),m(!1),M(((R=d.dataTransfer)==null?void 0:R.files)??null)},children:[T&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",w("dropHereToAttach")]})}),h.length>0&&e.jsxs("div",{className:"attach-row",children:[h.map(d=>e.jsxs("span",{className:`attach-chip ${d.imageData?"image":d.fileData?"file":d.mode}`,title:d.imageData?w("attachImage",{name:d.name}):d.fileData?w("attachFile",{name:d.name}):d.isDir?w("folderRef",{path:d.path}):d.mode==="reference"?w("refOnly",{path:d.path}):d.mode==="lines"&&d.lines?w("attachLines",{path:d.path,start:d.lines.start,end:d.lines.end}):w("attachContent",{path:d.path}),children:[d.imageData?"🖼":d.fileData?"📄":d.isDir?"📁":d.mode==="reference"?"🔗":"📎"," ",d.name,d.mode==="lines"&&d.lines&&e.jsxs("span",{className:"attach-range",children:["L",d.lines.start,"-",d.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:w("removeAttachment"),onClick:()=>p(d.key??d.path),children:"×"})]},d.key??`${d.path}|${d.mode}|${d.lines?`${d.lines.start}-${d.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:w("attachHint")})]}),D&&D.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:ge,"aria-label":w("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:w("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>O(null),children:"Esc"})]}),D.map((d,R)=>e.jsxs("button",{type:"button",className:`slash-item${R===Z?" active":""}`,onMouseEnter:()=>Q(R),onClick:()=>X(d),children:[e.jsxs("span",{className:"slash-name",children:["/",d.name]}),e.jsx("span",{className:`slash-source ${d.source}`,children:z[d.source]}),e.jsxs("span",{className:"slash-desc",children:[j(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(d)})]})]},d.name))]}),H&&e.jsx("div",{className:"modal-backdrop",onClick:()=>K(!1),children:e.jsxs("div",{className:"slash-help",style:ie?{width:ie}:void 0,onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",w("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>K(!1),children:w("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:w("slashLoading")}):c.map(d=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",d.name]}),e.jsx("span",{className:`slash-source ${d.source}`,children:z[d.source]}),e.jsxs("span",{className:"slash-help-desc",children:[j(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(d)})]})]},d.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:$,type:"file",multiple:!0,hidden:!0,onChange:d=>{M(d.target.files),d.target.value=""}}),e.jsx("textarea",{ref:y,value:A,rows:1,placeholder:w(q?a?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!q,onChange:d=>{S(d.target.value),P(d.target.value)},onKeyDown:oe,onPaste:F}),e.jsxs("div",{className:"composer-tools",children:[e.jsxs("div",{className:"composer-tools-left",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:w("uploadFile"),disabled:!q,onClick:()=>{var d;return(d=$.current)==null?void 0:d.click()},children:e.jsx(Fn,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:w("tpl.openPicker"),onClick:v,children:e.jsx(Gn,{})}),e.jsx(_a,{state:i,models:n,modelsLoading:o,send:u,onManageModels:B,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:re()})]})]})]})}),$a=r.memo(function({goal:s,models:a,modelsLoading:l,activeConversationId:c,send:i}){var Z,Q,H,K,ie,x;const n=pe(),o=!s.conversationId||s.conversationId===c,u=s.goal!==null&&o,[h,p]=r.useState(""),[g,k]=r.useState(s.reviewModel??""),[b,N]=r.useState(s.maxRounds),[B,w]=r.useState(s.locked),[_,v]=r.useState(!1),[j,I]=r.useState(!1),[A,S]=r.useState(!0);r.useEffect(()=>{k(s.reviewModel??""),N(s.maxRounds||0),w(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),r.useEffect(()=>{_&&a.length===0&&!j&&!l&&(I(!0),i({type:"list_models"}))},[_,a.length,j,l,i]),r.useEffect(()=>{a.length>0&&I(!1)},[a.length]);const T=()=>{var y;return g?((y=a.find($=>$.id===g))==null?void 0:y.name)??g:n("goalBarUseMainModel")},m=()=>{const y=h.trim();y&&(i({type:"set_goal",goal:y,...g?{reviewModel:g}:{},maxRounds:b,locked:B}),p(""),S(!1))},D=()=>{const y=h.trim();y&&(i({type:"start_goal_wizard",text:y,...g?{wizardModel:g}:{},maxRounds:b,locked:B}),p(""),S(!1))},O=(((Z=s.wizard)==null?void 0:Z.active)??!1)&&o;return O?e.jsx("div",{className:`goalbar goalbar-active ${O?"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:((Q=s.wizard)==null?void 0:Q.draft)??"",children:[n("goalWizardRunning"),": ",(H=s.wizard)==null?void 0:H.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[n("goalBarRound",{n:(((K=s.wizard)==null?void 0:K.step)??0)+1})," ","/ ",((ie=s.wizard)==null?void 0:ie.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((x=s.wizard)==null?void 0:x.status)||n("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:n("goalBarClear"),onClick:()=>{i({type:"clear_goal"}),S(!0)},children:e.jsx(we,{})})]})}):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:[n("goalBarReviewing")," ",n("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?n("goalBarPassed"):s.verdict==="fail"?n("goalBarFailed"):`${n("goalBarRound",{n:s.round||1})} · ${s.locked?n("goalBarLocked"):n("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:s.status}),e.jsx("button",{type:"button",className:"goalbar-x",title:n("goalBarClear"),disabled:s.reviewing,onClick:()=>{i({type:"clear_goal"}),S(!0)},children:e.jsx(we,{})})]})}):A?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:n("goalBarPlaceholder"),onClick:()=>S(!1),children:[e.jsx(es,{})," ",e.jsx("span",{children:n("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx(es,{})}),e.jsx("input",{className:"goalbar-input",value:h,placeholder:n("goalBarPlaceholder"),onChange:y=>p(y.target.value),onKeyDown:y=>{y.key==="Enter"&&m()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!h.trim(),onClick:m,children:n("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!h.trim(),title:n("goalWizardTip"),onClick:D,children:["🔍 ",n("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n(B?"goalBarLocked":"goalBarUnlocked"),onClick:()=>w(y=>(i({type:"set_goal_prefs",locked:!y}),!y)),children:B?e.jsx(Un,{}):e.jsx(Dn,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n("goalBarClear"),onClick:()=>S(!0),children:e.jsx(gt,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[e.jsxs(Ae,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[n("goalBarReviewModel"),": ",e.jsx("b",{children:T()})]}),open:_,onOpenChange:v,direction:"up",children:[e.jsx("div",{className:"dd-header",children:n("goalBarReviewModel")}),(j||l)&&e.jsx("div",{className:"dd-loading",children:n("loading")}),a.length===0&&!j&&!l&&e.jsx("div",{className:"dd-loading",children:n("noModels")}),e.jsx(Ne,{active:g==="",onClick:()=>{k(""),v(!1),i({type:"set_goal_prefs",reviewModel:""})},children:n("goalBarUseMainModel")}),a.map(y=>e.jsx(Ne,{active:g===y.id,onClick:()=>{k(y.id),v(!1),i({type:"set_goal_prefs",reviewModel:y.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:y.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:y.provider})})]})},y.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>i({type:"list_models"}),children:n("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:n("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:n("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:b,placeholder:n("goalBarUnlimitedShort"),onChange:y=>{const $=parseInt(y.target.value,10);if(Number.isNaN($)||$<0){N(0);return}N($)},onBlur:()=>i({type:"set_goal_prefs",maxRounds:b}),onKeyDown:y=>{y.key==="Enter"&&(i({type:"set_goal_prefs",maxRounds:b}),y.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:n(B?"goalBarLocked":"goalBarUnlocked")})]})]})});function Oa({chat:t,send:s}){const a=pe(),l=t.state,[c,i]=r.useState(!1),[n,o]=r.useState(""),[u,h]=r.useState(0),p=r.useRef(null),g=t.pathCompletions;if(r.useEffect(()=>{if(!c)return;const m=setTimeout(()=>{s({type:"complete_path",path:n})},150);return()=>clearTimeout(m)},[n,c,s]),r.useEffect(()=>h(0),[g]),r.useEffect(()=>{const m=document.querySelector(`.status-completions .pc-item[data-idx="${u}"]`);m==null||m.scrollIntoView({block:"nearest"})},[u]),!l)return null;const k=l.stats,b=t.ready?"ok":"busy",N=t.ready?a("connected"):a("connecting"),B=k.contextUsage,w=B.tokens!==null&&B.percent!==null?`${ws(B.tokens)} / ${ws(B.contextWindow)}`:"—",_=B.percent??null,v=_===null?"":_>=80?"warn":_>=50?"mid":"ok",j=l.queue.steering.length+l.queue.followUp.length,I=()=>{o(l.cwd),i(!0)},A=(m,D)=>{var Z;const O=m.includes("\\")?"\\":"/";o(D?`${m}${O}`:m),h(0),(Z=p.current)==null||Z.focus()},S=m=>{const D=m.trim();D&&D!==l.cwd&&s({type:"set_cwd",path:D}),i(!1)},T=m=>{if(m.key==="ArrowDown")m.preventDefault(),h(D=>Math.min(D+1,g.length-1));else if(m.key==="ArrowUp")m.preventDefault(),h(D=>Math.max(D-1,0));else if(m.key==="Tab"&&g.length>0){m.preventDefault();const D=g[Math.min(u,g.length-1)];A(D.path,D.type==="dir")}else if(m.key==="Enter"&&!m.nativeEvent.isComposing){const D=n.trim();if(D.endsWith("/")||D.endsWith("\\"))S(D);else if(g.some(O=>O.path===D))S(D);else if(g.length>0&&g[u]){m.preventDefault();const O=g[u];A(O.path,O.type==="dir")}else S(D)}else m.key==="Escape"&&(g.length>0?(m.stopPropagation(),s({type:"complete_path",path:""})):i(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${b}`,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:a("contextUsage"),children:[a("context"),e.jsx("span",{className:`ctx-bar ${v}`,children:_!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(_,100)}%`}})}),w]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:a("cumulativeCost"),children:["$",Wa(k.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:a("sessionMessages"),children:[a("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:a("pluginStatus"),children:t.statuses.map(m=>m.text).join(" · ")})]}),l.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"}),a("working"),j>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",j," ",a("queued")]})]})]}),c?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:p,className:"status-cwd-input",value:n,autoFocus:!0,placeholder:a("enterPath"),onChange:m=>o(m.target.value),onKeyDown:T,onBlur:()=>i(!1)}),g.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:m=>m.preventDefault(),children:g.map((m,D)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":D,className:`pc-item ${D===u?"sel":""}`,onMouseEnter:()=>h(D),onClick:()=>A(m.path,m.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:m.type==="dir"?e.jsx(Ge,{}):e.jsx(_s,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:m.name}),e.jsx("span",{className:"pc-path",children:m.path})]})]})},m.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:a("cwdTip",{path:l.cwd}),onClick:I,children:["📁 ",l.cwd]})]})}function ws(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function Wa(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function qa({dialog:t,send:s}){const a=pe(),[l,c]=r.useState(""),[i,n]=r.useState(0),o=p=>{s({type:"dialog_response",id:t.id,value:p})};r.useEffect(()=>{c(""),n(0);const p=g=>{g.key==="Escape"&&o(null)};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[t.id]);const u=Array.isArray(t.args[0])?t.args[0]:[],h=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:a("pluginRequest")}),t.title&&t.title!==a("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:a("cancel"),onClick:()=>o(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[u.map((p,g)=>e.jsx("button",{type:"button",className:`dialog-option ${g===i?"sel":""}`,onMouseEnter:()=>n(g),onClick:()=>o(p),children:p},g)),u.length===0&&e.jsx("div",{className:"dialog-hint",children:a("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:h}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(!1),children:a("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(!0),children:a("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:l,placeholder:h||a("inputPlaceholder"),autoFocus:!0,onChange:p=>c(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.nativeEvent.isComposing&&o(l)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(null),children:a("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(l),children:a("ok")})]})]})]})}function Ha(t){if(t.x==="?"&&t.y==="?")return"untracked";const s=t.x!==" "&&t.x!=="?",a=t.y!==" "&&t.y!=="?";return s&&a?"both":s?"staged":"unstaged"}function Ua({chat:t,send:s,terminal:a,active:l,onSwitchToTerminal:c}){var $e,Oe;const i=pe(),[n,o]=r.useState(null),[u,h]=r.useState([]),[p,g]=r.useState(""),[k,b]=r.useState(new Map),[N,B]=r.useState("changes"),[w,_]=r.useState([]),[v,j]=r.useState(null),[I,A]=r.useState(""),[S,T]=r.useState(!1),[m,D]=r.useState(null),[O,Z]=r.useState(null),[Q,H]=r.useState(!1),[K,ie]=r.useState(!1),[x,y]=r.useState(!1),[$,ge]=r.useState(null),[z,P]=r.useState(!1),[X,V]=r.useState(""),M=r.useRef(0),F=r.useRef(-1),q=r.useRef(-1),te=r.useRef(-1),U=r.useRef(-1),oe=r.useRef(void 0),re=r.useRef(null),d=r.useRef([]),R=r.useCallback(C=>{if(C.reqId===F.current){if(F.current=-1,ie(!1),ge(null),!C.ok){ge(C.error??"查询失败");return}if(C.notRepo){P(!0),o(null),h([]),b(new Map),_([]),j(null),A(""),Z(null);return}P(!1);const ue={branch:C.branch??"",detached:!!C.detached,upstream:C.upstream??null,ahead:C.ahead??0,behind:C.behind??0,upstreamGone:!!C.upstreamGone,files:(C.files??[]).map(f=>({...f}))},ae=(C.branches??[]).map(f=>({...f})),ye=new Map;for(const[f,E]of Object.entries(C.stats??{}))ye.set(f,{add:E[0],del:E[1]});o(ue),h(ae),b(ye),g(f=>{var E;return ue.detached?f||"":ue.branch&&ae.some(J=>J.name===ue.branch)?ue.branch:f&&ae.some(J=>J.name===f)?f:((E=ae[0])==null?void 0:E.name)??""}),Z(f=>f&&!ue.files.some(E=>E.path===f.file.path)?null:f)}else if(C.reqId===q.current){if(q.current=-1,H(!1),!C.ok){ge(C.error??"查询失败");return}const ue=re.current;if(!ue)return;Z({file:ue,staged:C.stagedText??"",worktree:C.worktreeText??"",untracked:!1})}else if(C.reqId===U.current){if(U.current=-1,y(!1),!C.ok){ge(C.error??"查询失败");return}_((C.history??[]).map(ue=>({...ue})))}else if(C.reqId===te.current){if(te.current=-1,T(!1),!C.ok){ge(C.error??"查询失败");return}A(C.text??"")}},[]);r.useEffect(()=>{const C=t.scmData;C&&C.type==="scm_data"&&R(C)},[t.scmData,R]);const le=r.useCallback((C,ue)=>{if(!t.ready||t.status!=="open")return!1;const ae=++M.current;return s({...C,reqId:ae})?(ue.current=ae,!0):(M.current-=1,!1)},[t.ready,t.status,s]),ee=r.useCallback((C=!1,ue=!1)=>{var ae;!t.ready||t.status!=="open"||(ae=t.state)!=null&&ae.cwd&&(oe.current!==void 0&&oe.current!==t.state.cwd&&(o(null),h([]),b(new Map),_([]),y(!1),U.current=-1,j(null),A(""),Z(null),D(null)),oe.current=t.state.cwd,ge(null),le({type:"scm_status"},F)&&(ue||ie(!0)))},[t.ready,($e=t.state)==null?void 0:$e.cwd,t.status,le]),fe=r.useCallback(C=>{if(D(C),j(null),re.current=C,C.x==="?"&&C.y==="?"){Z({file:C,staged:"",worktree:"",untracked:!0});return}H(!0),ge(null),le({type:"scm_filediff",path:C.path},q)||H(!1)},[le]),Y=r.useCallback(C=>{j(C),D(null),Z(null),A(""),T(!0),ge(null),le({type:"scm_commit",hash:C.hash},te)||T(!1)},[le]),de=r.useCallback((C,ue)=>{var f,E;if(!t.ready)return;const ae={name:C,command:ue,cwd:"${pwd}"},ye=t.terminals.find(J=>J.title===C);if(ye)a.restart(ye.id),s({type:"run_command",terminalId:ye.id,conversationId:ye.conversationId,command:ae,cols:80,rows:24});else{const J=De();a.create({id:J,conversationId:t.activeConversationId||((f=t.state)==null?void 0:f.conversationId)||"",title:C,cwd:((E=t.state)==null?void 0:E.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:ae})}c()},[t.ready,(Oe=t.state)==null?void 0:Oe.cwd,t.terminals,c,s,a]),xe=r.useCallback(()=>{const C=X.trim();if(!C||z)return;const ue=C.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");de("git commit",`git add -A && git commit -m "${ue}"`),V("")},[X,z,de]),ce=C=>`'${C.replace(/'/g,"'\\''")}`,Se=r.useCallback(C=>{z||de("git add",`git add -- ${ce(C.path)}`)},[z,de]),Ye=r.useCallback(C=>{z||de("git reset",`git reset HEAD -- ${ce(C.path)}`)},[z,de]),Te=r.useCallback(()=>{if(!p||z)return;const C=u.find(ue=>ue.name===p);if(C!=null&&C.remote&&typeof C.remote=="string"){const ue=p.slice(C.remote.length+1);de("git checkout",`git checkout -b ${ue} ${p} || git checkout ${p}`)}else de("git checkout",`git checkout ${p}`)},[p,u,z,de]),Ee=r.useCallback(()=>de("git push","git push"),[de]),Je=r.useCallback(()=>de("git pull","git pull"),[de]),Me=r.useCallback(()=>{le({type:"scm_history"},U)||(U.current=-1)},[le]);r.useEffect(()=>{l&&ee()},[l,ee]),r.useEffect(()=>{N==="history"&&n&&Me()},[N,n,Me]),r.useEffect(()=>{t.scmDirty>0&&l&&ee(!1,!0)},[t.scmDirty]),r.useEffect(()=>{if(!l||!t.ready||t.status!=="open")return;const C=setInterval(()=>{document.visibilityState!=="hidden"&&ee(!1,!0)},3e4);return()=>clearInterval(C)},[l,t.ready,t.status,ee]),r.useEffect(()=>{const C=d.current;if(d.current=t.terminals,!l)return;t.terminals.some(ae=>{var f;return ae.running!==!1?!1:((f=C.find(E=>E.id===ae.id))==null?void 0:f.running)===!0&&/^git /.test(ae.title)})&&t.ready&&t.status==="open"&&(ee(!1,!0),N==="history"&&n&&Me())},[t.terminals,l,t.ready,t.status,ee,N,n,Me]);const Qe={staged:i("scmStaged"),unstaged:i("scmUnstaged"),untracked:i("scmUntracked"),both:i("scmStagedUnstaged")},Fe=C=>{const ue=C.split(`
|
|
319
|
-
`);return e.jsx("pre",{className:"scm-diff-pre",children:ue.map((ae,ye)=>{let f="";return ae.startsWith("diff --git")||ae.startsWith("index ")||ae.startsWith("new file")||ae.startsWith("deleted file")||ae.startsWith("old mode")||ae.startsWith("new mode")||ae.startsWith("similarity index")||ae.startsWith("rename ")||ae.startsWith("copy ")||ae.startsWith("Binary files")||ae.startsWith("---")||ae.startsWith("+++")?f="hdr":ae.startsWith("@@")?f="hunk":ae.startsWith("+")?f="add":ae.startsWith("-")&&(f="del"),e.jsx("div",{className:`scm-diff-line ${f}`,children:ae||" "},ye)})})};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(rt,{}),i("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:()=>{B("changes"),ge(null)},children:i("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":N==="history",className:N==="history"?"active":"",onClick:()=>{B("history"),ge(null)},children:i("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:i("scmRefreshTip"),disabled:K,onClick:()=>ee(!0),children:e.jsx(ht,{className:K?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:i("scmCurrentBranch"),children:[e.jsx(rt,{}),n?n.detached?i("scmDetached"):n.branch:"…",(n==null?void 0:n.upstream)&&e.jsx("span",{className:"scm-upstream",children:n.upstreamGone?i("scmUpstreamGone"):n.ahead>0||n.behind>0?i("scmAheadBehind",{ahead:n.ahead,behind:n.behind}):n.upstream})]}),e.jsxs("select",{className:"scm-select",value:p,disabled:z||u.length===0,title:i("scmSwitchBranch"),onChange:C=>g(C.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:i("scmSelectBranch")}),u.filter(C=>!C.remote).map(C=>e.jsx("option",{value:C.name,children:C.current?`* ${C.name}`:C.name},C.name)),u.some(C=>C.remote)&&e.jsx("optgroup",{label:i("scmRemoteBranches"),children:u.filter(C=>C.remote).map(C=>e.jsx("option",{value:C.name,children:C.name},C.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!p||p===(n==null?void 0:n.branch)||z,title:i("scmSwitchBranchTip",{branch:p}),onClick:Te,children:[e.jsx(rt,{}),i("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!n||n.detached||z,title:i("scmPushTip"),onClick:Ee,children:[e.jsx($s,{}),i("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!n||n.detached||z,title:i("scmPullTip"),onClick:Je,children:[e.jsx(Os,{}),i("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:X,placeholder:i("scmCommitPlaceholder"),disabled:z,onChange:C=>V(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!C.nativeEvent.isComposing&&xe()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!X.trim()||z,title:i("scmCommitTip"),onClick:xe,children:[e.jsx(xt,{}),i("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:i("scmHistory")}),w.length>0&&e.jsx("span",{className:"scm-files-count",children:w.length})]}),e.jsx("div",{className:"scm-history-list",children:z?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):!n||x?e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")}):w.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoHistory")}):w.map(C=>e.jsxs("button",{type:"button",className:`scm-commit ${(v==null?void 0:v.hash)===C.hash?"active":""}`,onClick:()=>Y(C),title:C.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:C.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:C.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[C.shortHash," · ",C.author," · ",C.date]}),C.decorations&&e.jsx("span",{className:"scm-commit-refs",children:C.decorations})]})]},C.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmChanges")}),n&&n.files.length>0&&e.jsx("span",{className:"scm-files-count",children:n.files.length})]}),e.jsx("div",{className:"scm-files-list",children:z?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):n?n.files.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoChanges")}):n.files.map(C=>{const ue=Ha(C),ae=k.get(C.path);return e.jsxs("div",{className:`scm-file ${(m==null?void 0:m.path)===C.path?"active":""}`,title:Qe[ue],onClick:()=>fe(C),children:[e.jsx("span",{className:`scm-file-xy ${ue==="untracked"?"q":"x"}`,children:C.x!==" "?C.x:" "}),e.jsx("span",{className:`scm-file-xy ${ue==="untracked"?"q":"y"}`,children:C.y!==" "?C.y:" "}),e.jsx("span",{className:"scm-file-path",children:C.path}),ae&&(ae.add>0||ae.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[ae.add>0&&e.jsxs("span",{className:"add",children:["+",ae.add]}),ae.del>0&&e.jsxs("span",{className:"del",children:["-",ae.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(C.y!==" "||ue==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:i("scmStageTip",{path:C.path}),onClick:ye=>{ye.stopPropagation(),Se(C)},children:"+"}),ue==="staged"||ue==="both"?e.jsx("button",{type:"button",className:"scm-act",title:i("scmUnstageTip",{path:C.path}),onClick:ye=>{ye.stopPropagation(),Ye(C)},children:"−"}):null]})]},C.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:N==="history"?v?`${v.shortHash} ${v.subject}`:i("scmCommitDetail"):m?m.path:i("scmDiff")}),(N==="history"?S:Q)&&e.jsx("span",{className:"scm-diff-loading",children:i("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:N==="history"?e.jsxs(e.Fragment,{children:[$&&e.jsx("div",{className:"scm-error",children:$}),!v&&!$&&e.jsx("div",{className:"scm-empty",children:i("scmSelectCommitHint")}),v&&S&&!$&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),v&&!S&&!$&&I?Fe(I):null]}):e.jsxs(e.Fragment,{children:[$&&e.jsx("div",{className:"scm-error",children:$}),!m&&!$&&e.jsx("div",{className:"scm-empty",children:i("scmSelectFileHint")}),m&&!O&&!$&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),m&&O&&O.untracked&&e.jsx("div",{className:"scm-empty",children:i("scmUntrackedNote")}),m&&O&&!O.untracked&&e.jsxs(e.Fragment,{children:[O.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmStaged")}),Fe(O.staged)]}),O.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmUnstaged")}),Fe(O.worktree)]}),!O.staged&&!O.worktree&&e.jsx("div",{className:"scm-empty",children:i("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(ze,{}),e.jsx("span",{children:i("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:c,children:i("scmViewTerminal")})]})]})}function Ka({entry:t,send:s}){const a=r.useRef(null);return r.useEffect(()=>{const l=a.current;if(!l)return;let c;try{c=t.module.mount(l,yi(t.info.id,i=>s(i)))}catch(i){console.error(`[plugin:${t.info.id}] mount failed:`,i),l.textContent=`插件 ${t.info.name} 挂载失败`}return()=>{if(typeof c=="function")try{c()}catch(i){console.error(`[plugin:${t.info.id}] cleanup failed:`,i)}l.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:a})}function za({send:t,piConfigured:s,piAgentInstalled:a,providers:l,installResult:c,onClose:i}){const n=pe(),[o,u]=r.useState(!1),[h,p]=r.useState(""),[g,k]=r.useState(""),[b,N]=r.useState(!1);r.useEffect(()=>{t({type:"list_providers"})},[t]),r.useEffect(()=>{s&&i()},[s,i]),r.useEffect(()=>{c&&u(!1)},[c]),r.useEffect(()=>{var I;!h&&l.length>0&&p(((I=l.find(A=>!A.configured))==null?void 0:I.id)??l[0].id)},[l,h]);const B=()=>{o||(u(!0),t({type:"install_pi_agent"}))},w=()=>{!g.trim()||b||(N(!0),t({type:"set_provider_api_key",provider:h.trim(),apiKey:g.trim()}),setTimeout(()=>N(!1),3e3))},_=()=>{t({type:"get_state"}),t({type:"list_providers"})},v=l.find(I=>I.id===h),j=c!==null&&!c.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":n("close"),onClick:i,children:e.jsx(we,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(tt,{className:"modal-head-icon"}),e.jsx("h2",{children:n("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:n("setupDesc")}),j?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:n("installFailed")}),e.jsx("pre",{className:"setup-detail",children:c.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:B,children:n("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:n("skip")})]})]}):a||c!=null&&c.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:c!=null&&c.ok?n("installDone"):n("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:n("provider")}),e.jsxs("select",{value:h,onChange:I=>p(I.target.value),children:[l.length===0&&e.jsx("option",{value:"",children:n("loading")}),l.map(I=>e.jsxs("option",{value:I.id,children:[I.name,"(",I.id,")",I.configured?` · ${n("configured")}`:""]},I.id))]}),(v==null?void 0:v.configured)&&e.jsx("div",{className:"field-hint",children:n("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:n("apiKey")}),e.jsx("input",{type:"password",value:g,onChange:I=>k(I.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!g.trim()||b||!h,onClick:w,children:n(b?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:_,children:[e.jsx(ht,{})," ",n("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:B,children:n(o?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:n("skip")})]})]})})}const Va=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],Wt=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),Ga=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[Wt()]});function Ns(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:[Wt()]).map(s=>{var a;return{id:s.id,name:s.name??"",reasoning:s.reasoning??!1,input:(a=s.input)!=null&&a.includes("image")?"text-image":"text",contextWindow:s.contextWindow?String(s.contextWindow):"",maxTokens:s.maxTokens?String(s.maxTokens):""}})}}function Ya({send:t,providers:s,providerStatus:a,fetchModelsResult:l,refreshProviderResult:c,cloneProviderResult:i,onClose:n}){const o=pe(),[u,h]=r.useState(null),[p,g]=r.useState({}),[k,b]=r.useState(null),[N,B]=r.useState({}),[w,_]=r.useState(!1),[v,j]=r.useState(0),[I,A]=r.useState(null),S=r.useRef(0),[T,m]=r.useState({});r.useRef(0);const D=r.useRef(0),[O,Z]=r.useState(null),Q=r.useRef(0),H=r.useRef(0);r.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const K=()=>{if(!u)return;const P=u.baseUrl.trim();if(!P){A({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(w)return;_(!0),A(null);const X=v+1;j(X),t({type:"fetch_models",reqId:X,baseUrl:P,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};r.useEffect(()=>{var P;if(!(!l||l.reqId===S.current))if(S.current=l.reqId,_(!1),l.ok&&((P=l.models)!=null&&P.length)){const X=l.models;h(V=>{if(!V)return V;const M=V.models.map(U=>{var d;if(!U.id.trim())return U;const oe=X.find(R=>R.id===U.id.trim());if(!oe)return U;const re={...U};return!re.name&&oe.name&&(re.name=oe.name),!re.contextWindow&&oe.contextWindow&&(re.contextWindow=String(oe.contextWindow)),!re.maxTokens&&oe.maxTokens&&(re.maxTokens=String(oe.maxTokens)),re.input==="text"&&((d=oe.input)!=null&&d.includes("image"))&&(re.input="text-image"),!re.reasoning&&oe.reasoning&&(re.reasoning=!0),re}),F=new Set(M.map(U=>U.id.trim()).filter(Boolean)),q=X.filter(U=>!F.has(U.id)).map(U=>{var oe;return{id:U.id,name:U.name??"",reasoning:U.reasoning??!1,input:(oe=U.input)!=null&&oe.includes("image")?"text-image":"text",contextWindow:U.contextWindow?String(U.contextWindow):"",maxTokens:U.maxTokens?String(U.maxTokens):""}}),te=[...M,...q];return te.some(U=>U.id.trim())?{...V,models:te.filter(U=>U.id.trim())}:V}),A({ok:!0,text:o("fetchModelsOk",{n:X.length})})}else A({ok:!1,text:l.error||o("fetchModelsEmpty")})},[l]);const ie=P=>{const X=(p[P.id]??"").trim();!X||k||(b(P.id),t({type:"set_provider_api_key",provider:P.id,apiKey:X}),setTimeout(()=>{b(null),g(V=>({...V,[P.id]:""})),B(V=>({...V,[P.id]:!1})),t({type:"list_providers"})},1500))},x=()=>{if(!u)return;const P=u.providerId.trim(),X=u.models.filter(M=>M.id.trim()).map(M=>({id:M.id.trim(),name:M.name.trim()||void 0,reasoning:M.reasoning||void 0,input:M.input==="text-image"?["text","image"]:void 0,contextWindow:M.contextWindow?Number(M.contextWindow):void 0,maxTokens:M.maxTokens?Number(M.maxTokens):void 0})),V={providerId:P,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:X};t({type:"save_model_config",providerId:P,config:V}),n()};r.useEffect(()=>{!c||c.reqId===D.current||(D.current=c.reqId,m({}))},[c]);const y=P=>{if(O)return;Z(P.id);const X=++Q.current+Date.now();t({type:"clone_provider",provider:P.id,reqId:X})};r.useEffect(()=>{!i||i.reqId===H.current||(H.current=i.reqId,Z(null),i.ok&&i.config&&h(Ns({...i.config,apiKey:""})))},[i]);const $=P=>{window.confirm(o("clearKeyConfirm",{id:P}))&&t({type:"clear_provider_api_key",provider:P})},ge=P=>{window.confirm(o("deleteProviderConfirm",{id:P.providerId,n:P.models.length}))&&t({type:"delete_model_config",providerId:P.providerId})},z=(P,X)=>{u&&h({...u,models:u.models.map((V,M)=>M===P?{...V,...X}:V)})};return e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"modal model-modal",onClick:P=>P.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:n,children:e.jsx(we,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:o(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:[o("providerId")," ",e.jsx("em",{children:o("providerIdHint")})]}),e.jsx("input",{type:"text",value:u.providerId,disabled:s.some(P=>P.providerId===u.providerId),onChange:P=>h({...u,providerId:P.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("displayName")}),e.jsx("input",{type:"text",value:u.name,onChange:P=>h({...u,name:P.target.value}),placeholder:o("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiType")}),e.jsx("select",{value:u.api,onChange:P=>h({...u,api:P.target.value}),children:Va.map(P=>e.jsx("option",{value:P,children:P},P))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:o("baseUrlHint")})]}),e.jsx("input",{type:"text",value:u.baseUrl,onChange:P=>h({...u,baseUrl:P.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKey")}),e.jsx("input",{type:"password",value:u.apiKey,onChange:P=>h({...u,apiKey:P.target.value}),placeholder:o("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:P=>h({...u,authHeader:P.target.checked})}),e.jsx("span",{children:o("authHeader")})]})]}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:o("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[I&&e.jsx("span",{className:`fetch-msg ${I.ok?"ok":"err"}`,title:I.text,children:I.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:w||!u.baseUrl.trim(),title:o("fetchModelsHint"),onClick:K,children:[e.jsx(At,{})," ",o(w?"fetchingModels":"fetchModels")]})]})]}),u.models.map((P,X)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:P.id,onChange:V=>z(X,{id:V.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:P.name,onChange:V=>z(X,{name:V.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:P.input,onChange:V=>z(X,{input:V.target.value}),children:[e.jsx("option",{value:"text",children:o("text")}),e.jsx("option",{value:"text-image",children:o("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:P.reasoning,onChange:V=>z(X,{reasoning:V.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:P.contextWindow,onChange:V=>z(X,{contextWindow:V.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:P.maxTokens,onChange:V=>z(X,{maxTokens:V.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>h({...u,models:u.models.filter((V,M)=>M!==X)}),children:e.jsx(Ie,{})})]},X)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>h({...u,models:[...u.models,Wt()]}),children:[e.jsx(_e,{})," ",o("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>h(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(P=>P.id.trim()),onClick:x,children:o("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-section-title",children:[o("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:o("hintKeyOnly")})]}),e.jsxs("div",{className:"provider-list",children:[a.length===0&&e.jsx("div",{className:"dd-loading",children:o("loading")}),a.map(P=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:P.name}),e.jsxs("span",{className:"provider-sub",children:[P.id,P.configured&&e.jsx("span",{className:"auth-badge",children:o("configuredBadge")}),P.source&&!P.configured&&e.jsx("span",{className:"auth-badge dim",children:P.source})]})]}),e.jsxs("div",{className:"provider-actions",children:[P.configured&&!N[P.id]?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"auth-badge",children:o("keyReady")}),e.jsxs("button",{type:"button",className:"btn sm",title:o("replaceKeyTitle"),onClick:()=>B(X=>({...X,[P.id]:!0})),children:[e.jsx(Rt,{})," ",o("replaceKey")]}),P.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>$(P.id),children:[e.jsx(Ie,{})," ",o("clearKey")]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"password",className:"key-input",placeholder:o("pasteKey"),value:p[P.id]??"",onChange:X=>g(V=>({...V,[P.id]:X.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(p[P.id]??"").trim()||k===P.id,onClick:()=>ie(P),children:[e.jsx(Kn,{})," ",k===P.id?o("savingKey"):o("saveKey")]})]}),e.jsxs("button",{type:"button",className:"btn sm",disabled:O!==null,title:o("cloneProviderTitle"),onClick:()=>y(P),children:[e.jsx(_t,{})," ",O===P.id?o("cloning"):o("cloneProvider")]})]})]},P.id))]}),e.jsx("div",{className:"form-section-title",children:o("customProviders")}),e.jsx("p",{className:"modal-desc",children:o("customDesc")}),s.length===0&&e.jsx("div",{className:"dd-loading",children:o("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:s.map(P=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:P.providerId}),e.jsxs("span",{className:"provider-sub",children:[P.api??"—",P.baseUrl?` · ${P.baseUrl}`:"",P.models.length>0&&` · ${o("modelsCount",{n:P.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:o("edit"),onClick:()=>h(Ns(P)),children:e.jsx(Rt,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>ge(P),children:e.jsx(Ie,{})})]})]},P.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>h(Ga()),children:[e.jsx(_e,{})," ",o("addProvider")]})})]})]})})}function Ja({plugin:t,send:s}){const a=pe(),l=t.settingsSchema??[],[c,i]=r.useState(()=>({...t.settingsValues??{}})),[n,o]=r.useState(!1);if(l.length===0)return null;const u=(k,b)=>i(N=>({...N,[k]:b})),h=l.some(k=>{var b;return c[k.key]!==((b=t.settingsValues)==null?void 0:b[k.key])}),p=()=>{o(!0),s({type:"plugin_settings",pluginId:t.id,values:c}),setTimeout(()=>o(!1),800)},g=()=>i({...t.settingsValues??{}});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:l.map(k=>e.jsxs("label",{className:"plugin-settings-field",title:k.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:k.label}),k.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!c[k.key],onChange:b=>u(k.key,b.target.checked)}):k.type==="select"?e.jsx("select",{value:String(c[k.key]??""),onChange:b=>u(k.key,b.target.value),children:(k.options??[]).map(b=>e.jsx("option",{value:b,children:b},b))}):e.jsx("input",{type:k.type==="password"?"password":k.type==="number"?"number":"text",value:String(c[k.key]??""),min:k.min,max:k.max,onChange:b=>u(k.key,k.type==="number"?Number(b.target.value):b.target.value)})]},k.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!h||n,onClick:p,children:a(n?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:g,children:a("pluginSettingsReset")})]})]})}function lt({text:t}){const s=r.useRef(null),[a,l]=r.useState(!1),c=()=>{var n;const i=(n=s.current)==null?void 0:n.getBoundingClientRect();i&&l(window.innerWidth-i.right<340)};return e.jsxs("span",{ref:s,className:`set-tip${a?" flip":""}`,tabIndex:0,"aria-label":t,onMouseEnter:c,onFocus:c,children:["?",e.jsx("span",{className:"set-tip-bubble",role:"tooltip",children:t})]})}function Pe({title:t,subtitle:s,tip:a,enabled:l,onToggle:c,action:i}){const n=pe();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,a&&e.jsx(lt,{text:a})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),i,e.jsx("button",{type:"button",className:`set-switch ${l?"on":""}`,role:"switch","aria-checked":l,title:n(l?"settingsEnabled":"settingsDisabled"),onClick:c,children:e.jsx("span",{className:"set-switch-knob"})})]})}function Qa({chat:t,send:s,terminal:a,onSwitchToTerminal:l,onClose:c}){const i=pe(),n=t.settings,[o,u]=r.useState("prompt"),h=r.useRef(null);r.useEffect(()=>{var d;(d=h.current)==null||d.scrollTo({top:0})},[o]);const[p,g]=r.useState(""),[k,b]=r.useState("append"),N=r.useRef(!1),[B,w]=r.useState(""),[_,v]=r.useState("append"),j=r.useRef(!1),[I,A]=r.useState(""),S=r.useRef(!1),[T,m]=r.useState(""),[D,O]=r.useState(!1),[Z,Q]=r.useState(null),[H,K]=r.useState(null);r.useEffect(()=>{n&&(b(n.promptMode),!N.current&&(g(k==="append"||n.customSystemPrompt?n.customSystemPrompt:n.defaultSystemPrompt||""),v(n.visionBridgePromptMode),!j.current&&(w(_==="append"||n.visionBridgePrompt?n.visionBridgePrompt:n.visionBridgeDefaultPrompt||""),S.current||A(n.reviewPrompt))))},[n,k,_]);const[ie,x]=r.useState(String((n==null?void 0:n.terminalBashIdleMs)??15e3));if(r.useEffect(()=>{x(String((n==null?void 0:n.terminalBashIdleMs)??15e3))},[n==null?void 0:n.terminalBashIdleMs]),!n)return null;const y=[{id:"prompt",icon:e.jsx(Fs,{}),label:i("settingsSystemPrompt")},{id:"terminal",icon:e.jsx(ze,{}),label:i("settingsTerminalTools")},{id:"display",icon:e.jsx(Ve,{}),label:i("settingsMessageDisplay")},{id:"skills",icon:e.jsx(tt,{}),label:i("settingsSkills"),count:n.skills.length},{id:"extensions",icon:e.jsx(ts,{}),label:i("settingsExtensions"),count:n.extensions.length},{id:"plugins",icon:e.jsx(ns,{}),label:i("settingsUiPlugins"),count:t.plugins.length},{id:"review",icon:e.jsx(at,{}),label:i("settingsReview"),count:n.reviewSkills.length},{id:"vision",icon:e.jsx(Et,{}),label:i("settingsVisionBridge")},{id:"presets",icon:e.jsx(An,{}),label:i("settingsPresets"),count:n.presets.length}],$=new Set(n.disabledSkills),ge=new Set(n.disabledExtensions),z=d=>s({type:"set_settings",...d}),P=d=>{const R=new Set($);R.has(d.name)?R.delete(d.name):R.add(d.name),z({disabledSkills:[...R]})},X=new Set(n.disabledPlugins??[]),V=d=>{const R=new Set(X);R.has(d.id)?R.delete(d.id):R.add(d.id),z({disabledPlugins:[...R]})},M=d=>{const R=new Set(ge);R.has(d.id)?R.delete(d.id):R.add(d.id),z({disabledExtensions:[...R]})},F=(d,R)=>{var fe,Y;const le={name:d,command:R,cwd:"${pwd}"},ee=t.terminals.find(de=>de.title===d);ee?(a.restart(ee.id),s({type:"run_command",terminalId:ee.id,conversationId:ee.conversationId,command:le,cols:80,rows:24})):a.create({id:De(),conversationId:t.activeConversationId||((fe=t.state)==null?void 0:fe.conversationId)||"",title:d,cwd:((Y=t.state)==null?void 0:Y.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:le}),l(),c()},q=d=>{Q(null),F(`${i("uninstallTitle")} ${d}`,`pi remove npm:${d}`)},te=d=>{K(null),F(`${i("uninstallTitle")} ${d}`,`pi-web-ui uninstall ${d}`)},U=(d,R)=>{F(`${i("pluginUpdate")} ${d}`,`pi-web-ui install ${R} --name ${d} --force`)},oe=d=>{const R=new Set(n.reviewSkills.filter(le=>!le.enabled).map(le=>le.name));R.has(d.name)?R.delete(d.name):R.add(d.name),z({reviewDisabledSkills:[...R]})},re=()=>{const d=k==="replace"&&n.defaultSystemPrompt&&p===n.defaultSystemPrompt?"":p;z({promptMode:k,customSystemPrompt:d})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal settings-modal",onClick:d=>d.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:c,children:e.jsx(we,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(ut,{className:"modal-head-icon"}),e.jsx("h2",{children:i("settingsTitle")}),e.jsx(lt,{text:i("settingsDesc")})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-rail","aria-label":i("settingsTitle"),children:y.map(d=>e.jsxs("button",{type:"button",className:`settings-tab${o===d.id?" active":""}`,"aria-current":o===d.id?"true":void 0,title:d.label,onClick:()=>u(d.id),children:[e.jsx("span",{className:"settings-tab-icon",children:d.icon}),e.jsx("span",{className:"settings-tab-label",children:d.label}),d.count!==void 0&&e.jsx("span",{className:"set-count",children:d.count})]},d.id))}),e.jsxs("div",{className:"modal-body",ref:h,children:[o==="prompt"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(at,{className:"set-section-icon"}),i("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:k,onChange:d=>{const R=d.target.value;b(R),z({promptMode:R})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]}),e.jsx(lt,{text:i(k==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:i("promptPlaceholder"),value:p,onFocus:()=>N.current=!0,onBlur:()=>{N.current=!1,re()},onChange:d=>g(d.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":D,onClick:()=>O(d=>!d),children:[i("settingsViewPrompt")," ",D?"▴":"▾"]}),D&&e.jsxs("div",{className:"set-prompt-view",children:[e.jsxs("div",{className:"set-prompt-view-head",children:[e.jsx("span",{children:i("settingsViewPromptHint")}),e.jsx(Ks,{text:n.effectiveSystemPrompt})]}),n.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:n.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:i("settingsViewPromptEmpty")})]})]}),o==="terminal"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ze,{className:"set-section-icon"}),i("settingsTerminalTools")]}),e.jsx(Pe,{title:i("terminalToolsEnabled"),tip:i("settingsTerminalToolsDesc"),enabled:n.terminalToolsEnabled,onToggle:()=>z({terminalToolsEnabled:!n.terminalToolsEnabled})}),!n.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:i("terminalToolsOffHint")}),e.jsx(Pe,{title:i("terminalBashTakeover"),tip:i("terminalBashTakeoverDesc"),enabled:n.terminalBash,onToggle:()=>z({terminalBash:!n.terminalBash})}),n.terminalBash&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:i("terminalBashIdleMs")}),e.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:ie,onChange:d=>x(d.target.value),onBlur:()=>{const d=Math.max(0,Math.floor(Number(ie)||0));x(String(d)),d!==n.terminalBashIdleMs&&z({terminalBashIdleMs:d})}})]})]}),o==="display"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ve,{className:"set-section-icon"}),i("settingsMessageDisplay")]}),e.jsx(Pe,{title:i("thinkingWrap"),tip:i("thinkingWrapDesc"),enabled:n.thinkingWrap??!0,onToggle:()=>z({thinkingWrap:!(n.thinkingWrap??!0)})}),e.jsx(Pe,{title:i("toolsWrap"),tip:i("toolsWrapDesc"),enabled:n.toolsWrap??!0,onToggle:()=>z({toolsWrap:!(n.toolsWrap??!0)})})]}),o==="skills"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(tt,{className:"set-section-icon"}),i("settingsSkills"),e.jsx("span",{className:"set-count",children:n.skills.length})]}),n.skills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:n.skills.map(d=>e.jsx(Pe,{title:d.name,subtitle:d.description,enabled:d.enabled,onToggle:()=>P(d)},d.name))})]}),o==="extensions"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ts,{className:"set-section-icon"}),i("settingsExtensions"),e.jsx("span",{className:"set-count",children:n.extensions.length})]}),n.extensions.length===0?e.jsx("p",{className:"set-empty",children:i("noExtensions")}):e.jsx("div",{className:"set-list",children:n.extensions.map(d=>{const R=d.id.startsWith("npm:")?d.id.slice(4):null;return e.jsx(Pe,{title:d.name,subtitle:d.path,enabled:d.enabled,onToggle:()=>M(d),action:R?Z===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>q(R),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("uninstallHint"),onClick:()=>Q(d.id),children:[e.jsx(Ie,{}),i("uninstallExt")]}):void 0},d.id)})})]}),o==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ns,{className:"set-section-icon"}),i("settingsUiPlugins"),e.jsx("span",{className:"set-count",children:t.plugins.length})]}),t.plugins.length===0?e.jsx("p",{className:"set-empty",children:i("noUiPlugins")}):e.jsx("div",{className:"set-list",children:t.plugins.map(d=>{var R;return e.jsxs(e.Fragment,{children:[e.jsx(Pe,{title:`${d.icon?`${d.icon} `:""}${d.name}`,subtitle:(d.error?`${d.id} · ${d.error}`:d.source?`${d.id} · ${d.source}`:`${d.id} · ${i("uiPluginNoSource")}`)+((R=d.permissions)!=null&&R.length?` · ${i("uiPluginPerms")}: ${d.permissions.join(", ")}`:""),enabled:!X.has(d.id)&&!d.error,onToggle:()=>!d.error&&V(d),action:e.jsxs("div",{className:"set-row-actions",children:[d.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>U(d.id,d.source),children:[e.jsx(ht,{}),i("pluginUpdate")]}),H===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>te(d.id),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>K(d.id),children:[e.jsx(Ie,{}),i("uninstallExt")]})]})},d.id),d.settingsSchema&&d.settingsSchema.length>0&&e.jsx(Ja,{plugin:d,send:s})]})})})]}),o==="review"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(at,{className:"set-section-icon"}),i("settingsReview"),e.jsx(lt,{text:i("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:n.reviewSkills.length})]}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:i("reviewPromptPlaceholder"),value:I,onFocus:()=>S.current=!0,onBlur:()=>{S.current=!1,z({reviewPrompt:I})},onChange:d=>A(d.target.value)}),e.jsx("div",{className:"set-field-label",children:i("settingsReviewSkills")}),n.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:n.reviewSkills.map(d=>e.jsx(Pe,{title:d.name,subtitle:d.description,enabled:d.enabled,onToggle:()=>oe(d)},`review-${d.name}`))})]}),o==="vision"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Et,{className:"set-section-icon"}),i("settingsVisionBridge")]}),e.jsx(Pe,{title:i("visionBridgeEnabled"),tip:i("settingsVisionBridgeDesc"),enabled:n.visionBridgeEnabled,onToggle:()=>z({visionBridgeEnabled:!n.visionBridgeEnabled})}),!n.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:i("visionBridgeOffHint")}),n.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:n.visionBridgeModel??"",onChange:d=>z({visionBridgeModel:d.target.value||null}),children:[e.jsx("option",{value:"",children:i("visionBridgeAuto")}),n.visionModels.map(d=>e.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),n.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:_,onChange:d=>{const R=d.target.value;v(R),z({visionBridgePromptMode:R})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]})]}),n.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:i("visionBridgePromptPlaceholder"),value:B,onFocus:()=>j.current=!0,onBlur:()=>{j.current=!1;const d=_==="replace"&&n.visionBridgeDefaultPrompt&&B===n.visionBridgeDefaultPrompt?"":B;z({visionBridgePromptMode:_,visionBridgePrompt:d})},onChange:d=>w(d.target.value)}),n.visionBridgeEnabled&&(n.visionModels.length===0?e.jsx("p",{className:"set-hint",children:i("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:i("visionBridgeCurrent",{model:n.visionBridgeModel??i("visionBridgeAuto")})}))]}),o==="presets"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ut,{className:"set-section-icon"}),i("settingsPresets"),e.jsx("span",{className:"set-count",children:n.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:i("presetNamePlaceholder"),value:T,onChange:d=>m(d.target.value),onKeyDown:d=>{d.key==="Enter"&&T.trim()&&(s({type:"save_preset",name:T.trim()}),m(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!T.trim(),onClick:()=>{s({type:"save_preset",name:T.trim()}),m("")},children:[e.jsx(_e,{})," ",i("saveAsPreset")]})]}),n.presets.length===0?e.jsx("p",{className:"set-empty",children:i("noPresets")}):e.jsx("div",{className:"set-list",children:n.presets.map(d=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:d.name}),e.jsxs("div",{className:"set-row-desc",children:[d.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend"),d.disabledSkills.length>0&&` · ${i("settingsSkills")} ${d.disabledSkills.length}`,d.disabledExtensions.length>0&&` · ${i("settingsExtensions")} ${d.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:d.name}),children:i("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("deletePreset"),onClick:()=>s({type:"delete_preset",name:d.name}),children:e.jsx(Ie,{})})]})]},d.name))})]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:c,children:i("close")})})]})})}function Xa(t,s){const a=Math.max(0,Date.now()-t),l=Math.floor(a/6e4);if(l<1)return s("bgTaskJustNow");if(l<60)return s("bgTaskMinutes",{n:l});const c=Math.floor(l/60);return c<24?s("bgTaskHours",{n:c}):s("bgTaskDays",{n:Math.floor(c/24)})}function Za({servers:t,send:s,onClose:a}){const l=pe(),[c,i]=r.useState(new Set),n=o=>i(u=>{const h=new Set(u);return h.has(o)?h.delete(o):h.add(o),h});return r.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"bg-task-modal",onClick:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(mt,{})," ",l("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:l("close"),onClick:a,children:e.jsx(we,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(mt,{}),e.jsx("span",{children:l("bgTasksEmpty")}),e.jsx("small",{children:l("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(o=>{const u=!!o.taskId,h=o.taskId??String(o.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:u?o.plugin:l("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[u?e.jsxs("span",{className:"bg-task-port",title:o.taskId,children:["🧩 ",o.plugin]}):e.jsxs("span",{className:"bg-task-port",children:[":",o.port]}),o.name&&e.jsx("span",{className:"bg-task-name",children:o.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[!u&&e.jsxs("span",{children:[l("bgTaskPid")," ",o.pid]}),e.jsxs("span",{children:[l("bgTaskSince")," ",Xa(o.since,l)]}),u&&o.status&&e.jsx("span",{className:"bg-task-status",children:o.status})]}),o.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${c.has(h)?"open":""}`,title:`${l("bgTaskCommand")}: ${o.command}`,onClick:()=>n(h),children:[e.jsx(ze,{}),e.jsx("code",{children:o.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:l("bgTaskStop"),onClick:()=>s(u?{type:"kill_background_server",taskId:o.taskId}:{type:"kill_background_server",port:o.port}),children:[e.jsx(dt,{}),e.jsx("span",{children:l("bgTaskStop")})]})]},h)})}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:l("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(ht,{}),e.jsx("span",{children:l("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:l("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(dt,{}),e.jsx("span",{children:l("bgTaskStopAll")})]})]})]})})}function er(t,s){return t.toLowerCase().includes(s)}function tr({open:t,send:s,projects:a,cwd:l,fileSearch:c,sessionSearch:i,onClose:n,onSwitchSession:o,onSwitchProject:u,onPreviewFile:h}){const p=pe(),g=r.useRef(null),[k,b]=r.useState(""),N=r.useDeferredValue(k),[B,w]=r.useState(0),_=r.useRef(1),v=r.useRef(0),j=r.useRef(null);r.useEffect(()=>{if(!t)return;s({type:"list_sessions"}),s({type:"list_projects"});const x=k.trim();if(x){const y=++_.current;v.current=y,A(!0),s({type:"search_files",reqId:y,query:x}),s({type:"search_sessions",reqId:y,query:x})}requestAnimationFrame(()=>{var y;return(y=g.current)==null?void 0:y.select()})},[t]);const[I,A]=r.useState(!1);r.useEffect(()=>{j.current&&clearTimeout(j.current);const x=N.trim();if(!x){A(!1);return}return j.current=setTimeout(()=>{const y=++_.current;v.current=y,A(!0),s({type:"search_files",reqId:y,query:x}),s({type:"search_sessions",reqId:y,query:x})},300),()=>{j.current&&clearTimeout(j.current)}},[N]);const S=N.trim().toLowerCase(),T=r.useMemo(()=>!S||!i||i.reqId!==v.current||!i.ok?[]:i.results,[i,S]),m=r.useMemo(()=>S?a.filter(x=>er(x.path,S)).slice(0,10):[],[a,S]),D=r.useMemo(()=>!S||!c||c.reqId!==v.current||!c.ok?[]:c.results,[c,S]);r.useEffect(()=>{c&&c.reqId===v.current&&i&&i.reqId===v.current&&v.current!==0&&A(!1)},[c,i]);const O=!!c&&c.ok&&c.truncated,Z=r.useMemo(()=>[...T.map(x=>({kind:"session",path:x.path,anchors:x.anchors})),...m.map(x=>({kind:"project",path:x.path})),...D.filter(x=>x.type==="file").map(x=>({kind:"file",path:x.path,name:x.name}))],[T,m,D]);r.useEffect(()=>{w(0)},[N]);const Q=r.useCallback(x=>{if(x)if(x.kind==="session")o(x.path,x.anchors),n();else if(x.kind==="project"){u(x.path),s({type:"list_sessions"}),s({type:"list_projects"});const y=N.trim();if(y){const $=++_.current;v.current=$,A(!0),s({type:"search_files",reqId:$,query:y}),s({type:"search_sessions",reqId:$,query:y})}}else h(x.path,x.name)},[o,u,h,s,N]);r.useEffect(()=>{if(!t)return;const x=y=>{y.key==="Escape"?(y.preventDefault(),y.stopPropagation(),n()):y.key==="ArrowDown"?(y.preventDefault(),w($=>Math.min($+1,Z.length-1))):y.key==="ArrowUp"?(y.preventDefault(),w($=>Math.max($-1,0))):y.key==="Enter"&&(y.preventDefault(),Q(Z[B]))};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[Z,B,Q,n,t]);const H=T.length+m.length+D.length,K=(x,y,$)=>e.jsxs("div",{className:"gs-section-head",children:[$,e.jsx("span",{children:x}),e.jsx("em",{children:y})]});let ie=-1;return t?e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:n,children:e.jsxs("div",{className:"gs-modal",onClick:x=>x.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(pt,{}),e.jsx("input",{ref:g,type:"text",value:k,placeholder:p("gsPlaceholder"),onChange:x=>b(x.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:p("close"),onClick:n,children:e.jsx(we,{})})]}),e.jsxs("div",{className:"gs-results",children:[!S&&e.jsx("div",{className:"gs-empty",children:p("gsHint")}),S&&H===0&&!O&&e.jsx("div",{className:"gs-empty",children:p(I?"gsSearching":"gsNoResults")}),T.length>0&&e.jsxs("div",{className:"gs-section",children:[K(p("gsSessions"),T.length,e.jsx(Ve,{})),T.map(x=>{ie++;const y=ie;return e.jsxs("button",{type:"button",className:y===B?"gs-item active":"gs-item",onMouseEnter:()=>w(y),onClick:()=>Q({kind:"session",path:x.path,anchors:x.anchors}),children:[e.jsxs("span",{className:"gs-item-title",children:[x.name||x.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:x.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:x.firstMessage})]},x.path)})]}),m.length>0&&e.jsxs("div",{className:"gs-section",children:[K(p("gsProjects"),m.length,e.jsx(Ge,{})),m.map(x=>{ie++;const y=ie,$=l&&x.path===l;return e.jsxs("button",{type:"button",className:y===B?"gs-item active":"gs-item",onMouseEnter:()=>w(y),onClick:()=>Q({kind:"project",path:x.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[x.path.split(/[\\/]/).pop(),$&&e.jsx("em",{className:"gs-item-meta",children:p("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:x.path})]},x.path)})]}),(D.length>0||S&&O)&&e.jsxs("div",{className:"gs-section",children:[K(p("gsFiles"),D.length,e.jsx(Fs,{})),D.map(x=>{ie++;const y=ie;return e.jsxs("button",{type:"button",className:y===B?"gs-item active":"gs-item",disabled:x.type==="dir",title:x.type==="dir"?void 0:p("gsOpenPreview"),onMouseEnter:()=>w(y),onClick:()=>{x.type==="file"&&Q({kind:"file",path:x.path,name:x.name})},children:[e.jsx("span",{className:"gs-item-title",children:x.name}),e.jsx("span",{className:"gs-item-sub",children:x.path})]},`${x.type}:${x.path}`)}),O&&e.jsx("div",{className:"gs-truncated",children:p("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",p("gsNavigate")]}),e.jsxs("span",{children:["Enter ",p("gsOpen")]}),e.jsxs("span",{children:["Esc ",p("gsCloseHint")]})]})]})}):null}const Ct=5e3;function sr({file:t,content:s,send:a,onAddLines:l,onAttach:c,onClose:i}){const n=pe(),[o,u]=r.useState(null),[h,p]=r.useState(!1),[g,k]=r.useState(null),[b,N]=r.useState(!1),[B,w]=r.useState(!1),[_,v]=r.useState(!1),[j,I]=r.useState(""),[A,S]=r.useState(!0),T=r.useRef(!1),[m,D]=r.useState(!0),[O,Z]=r.useState(!1),[Q,H]=r.useState(100),K=r.useRef(0),ie=r.useRef(!1),x=r.useRef(null);r.useEffect(()=>{p(!0),u(null),k(null),v(!1),I(""),S(!0),T.current=!1,a({type:"read_file",path:t.path})},[t.path,a]),r.useEffect(()=>{s&&s.path===t.path&&(u(s),_||I(s.text),p(!1))},[s,_,t.path]),r.useEffect(()=>{const Y=de=>{if(de.key==="Escape"){te();return}if((de.ctrlKey||de.metaKey)&&de.key.toLowerCase()==="s"&&_){de.preventDefault(),q();return}const xe=de.target,ce=xe&&(xe.tagName==="INPUT"||xe.tagName==="TEXTAREA"||xe.isContentEditable);(de.ctrlKey||de.metaKey)&&de.key.toLowerCase()==="a"&&!ce&&(de.preventDefault(),P())};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[i,o,_,j]),r.useEffect(()=>{const Y=()=>{ie.current=!1,N(!1)};return window.addEventListener("mouseup",Y),()=>window.removeEventListener("mouseup",Y)},[]);const y=r.useMemo(()=>{if(!o)return[];const Y=o.text.split(`
|
|
320
|
-
`);return Y.length>0&&Y[Y.length-1]===""&&Y.pop(),Y.slice(0,Ct)},[o]),$=(o==null?void 0:o.lines)??0,ge=$>Ct,z=(Y,de)=>{if(de){const xe=K.current>0?K.current:Y;k({start:Math.min(xe,Y),end:Math.max(xe,Y)})}else K.current=Y,k({start:Y,end:Y})},P=()=>{y.length!==0&&(K.current=1,k({start:1,end:y.length}))},X=()=>{g&&(l(t.path,t.name,g.start,g.end),w(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>w(!1),1400))},V=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,M=()=>{I((o==null?void 0:o.text)??""),v(!1),T.current&&S(!0)},F=()=>{if(_){if(j!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges")))return;M();return}!V||!o||(T.current=St(t.name)&&A,St(t.name)&&S(!1),k(null),I(o.text),v(!0))},q=()=>{!_||!o||!V||a({type:"write_file",path:t.path,text:j})&&(v(!1),T.current&&S(!0),k(null))},te=()=>{_&&j!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges"))||i()},U=Y=>{H(Math.min(200,Math.max(50,Y)))},oe=g?g.end-g.start+1:0,re=(o==null?void 0:o.binary)??!1,d=(o==null?void 0:o.truncated)??!1,R=(o==null?void 0:o.kind)??"text",le=St(t.name),ee=le&&A&&!_&&R==="text"&&!re,fe=Y=>vt(`/api/file?clientId=${encodeURIComponent($t())}&path=${encodeURIComponent(Y)}`);return e.jsx("div",{className:`fp-overlay ${O?"fullscreen":""}`,onMouseDown:Y=>{Y.target===Y.currentTarget&&te()},children:e.jsxs("div",{className:`fp ${O?"fullscreen":""}`,style:{"--fp-zoom":Q/100},children:[e.jsxs("div",{className:"fp-head",children:[e.jsx("span",{className:"fp-name",title:t.path,children:t.name}),e.jsx("span",{className:"fp-path",children:t.path}),e.jsxs("span",{className:"fp-meta",children:[o&&R==="text"&&!re&&n("fileLines",{n:$}),o&&` · ${nr(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[le&&R==="text"&&!re&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${A?"on":""}`,"data-tip":n(A?"showMarkdownSource":"showMarkdownPreview"),disabled:_,onClick:()=>S(Y=>!Y),children:A?e.jsx(Et,{}):e.jsx(Qn,{})}),R==="text"&&!re&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${_?"on":""}`,"data-tip":n(d?"fileEditTruncated":_?"exitEditFile":"editFile"),disabled:!V&&!_,onClick:F,children:e.jsx(Mt,{})}),R==="text"&&!re&&!ee&&e.jsx("button",{type:"button",className:`fp-attach wrap ${m?"on":""}`,"data-tip":n(m?"disableWrap":"enableWrap"),onClick:()=>D(Y=>!Y),children:e.jsx(Jn,{})}),R==="text"&&o&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":n("zoomOut"),disabled:Q<=50,onClick:()=>U(Q-10),children:e.jsx(In,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:n("resetZoom"),onClick:()=>H(100),children:[Q,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":n("zoomIn"),disabled:Q>=200,onClick:()=>U(Q+10),children:e.jsx(Ln,{})})]}),R!=="video"&&R!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":n("attachInlineTip"),onClick:()=>c(t.path,t.name,"inline"),children:e.jsx(_e,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":n("referenceTip"),onClick:()=>c(t.path,t.name,"reference"),children:e.jsx(Tt,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${O?"on":""}`,"data-tip":n(O?"exitFullscreen":"fullscreen"),onClick:()=>Z(Y=>!Y),children:O?e.jsx(On,{}):e.jsx(qn,{})}),e.jsx("button",{type:"button",className:"fp-close",title:n("close"),onClick:te,children:e.jsx(we,{})})]})]}),d&&R==="text"&&!re&&e.jsx("div",{className:"fp-notice",children:n("previewTruncated")}),h&&!o&&e.jsx("div",{className:"fp-empty",children:n("loading")}),!h&&R==="none"&&!re&&e.jsx("div",{className:"fp-empty",children:n("previewNotSupported")}),!h&&R==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:fe(t.path),alt:t.name})}),!h&&R==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:fe(t.path),controls:!0,preload:"metadata"})}),!h&&ee&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(yt,{text:o.text})})}),!h&&re&&R!=="image"&&R!=="video"&&o&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[n("binaryFile"),o.truncated&&n("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:o.text})]}),!h&&_&&R==="text"&&!re&&o&&e.jsx("textarea",{className:`fp-editor ${m?"":"no-wrap"}`,value:j,onChange:Y=>I(Y.target.value),wrap:m?"soft":"off",spellCheck:!1,autoFocus:!0}),!h&&!ee&&!_&&R==="text"&&!re&&o&&y.length===0&&e.jsx("div",{className:"fp-empty",children:n("emptyFile")}),!h&&!ee&&!_&&R==="text"&&!re&&y.length>0&&e.jsxs("div",{className:`fp-code ${b?"dragging":""} ${m?"":"no-wrap"}`,onMouseDown:Y=>{Y.button===0&&Y.preventDefault()},children:[y.map((Y,de)=>{const xe=de+1,ce=g!==null&&xe>=g.start&&xe<=g.end;return e.jsxs("div",{className:`fp-line ${ce?"sel":""}`,onMouseDown:Se=>{Se.button===0&&(z(xe,Se.shiftKey),ie.current=!0,N(!0))},onMouseEnter:()=>{ie.current&&z(xe,!0)},children:[e.jsx("span",{className:"fp-num",children:xe}),e.jsx("span",{className:"fp-code-text",children:Y})]},xe)}),ge&&e.jsx("div",{className:"fp-lines-note",children:n("previewLinesTruncated",{n:Ct})})]}),e.jsx("div",{className:"fp-foot",children:_?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:n("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:F,children:n("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:j===((o==null?void 0:o.text)??""),onClick:q,children:[e.jsx(_n,{})," ",n("saveFile")]})]})]}):!ee&&R==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:g?n("selectedRange",{n:oe,start:g.start,end:g.end}):n("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:y.length===0,onClick:P,children:n("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!g,onClick:()=>k(null),children:n("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!g||re,onClick:X,children:[B?e.jsx(xt,{}):null,n(B?"addedToChat":"addToChat")]})]})]})})]})})}function St(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function nr(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const dn="pi-web-sounds",Xe={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function un(){try{const t=localStorage.getItem(dn);if(!t)return{...Xe};const s=JSON.parse(t),a={...Xe,...s};for(const l of["enabled","question","done","start","error"])typeof a[l]!="boolean"&&(a[l]=Xe[l]);return typeof a.volume!="number"||!Number.isFinite(a.volume)?a.volume=Xe.volume:a.volume=Math.round(Math.max(0,Math.min(100,a.volume))/5)*5,a}catch{return{...Xe}}}function ir(t){try{localStorage.setItem(dn,JSON.stringify(t))}catch{}}let Ze=null;function ar(){try{if(!Ze){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;Ze=new t}return Ze.state==="suspended"&&Ze.resume(),Ze}catch{return null}}const rr=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],lr=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],or=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],cr=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],dr={question:rr,done:lr,start:or,error:cr};function ur(t,s,a){const l=t.createOscillator(),c=t.createGain();l.type=s.type,l.frequency.value=s.freq;const i=t.currentTime+s.start,n=Math.max(1e-4,s.peak*a);c.gain.setValueAtTime(1e-4,i),c.gain.exponentialRampToValueAtTime(n,i+.012),c.gain.exponentialRampToValueAtTime(1e-4,i+s.dur),l.connect(c),c.connect(t.destination),l.start(i),l.stop(i+s.dur+.05)}function et(t,s=un()){if(!s.enabled||!s[t])return;const a=ar();if(!a)return;const l=Math.max(0,Math.min(1,s.volume/100));for(const c of dr[t])ur(a,c,l)}const Bt="pi-web-ui:theme",pn="dark",Cs="theme-stylesheet",Ss="pi-web-ui:theme-change";function mn(){try{const t=localStorage.getItem(Bt);if(t&&t!==pn)return t}catch{}return null}function pr(t){try{t?localStorage.setItem(Bt,t):localStorage.removeItem(Bt)}catch{}}function hn(t){let s=document.getElementById(Cs);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(Ss));return}s||(s=document.createElement("link"),s.id=Cs,s.rel="stylesheet",document.head.appendChild(s)),s.href=`/themes/${encodeURIComponent(t)}.css`,s.onload=()=>window.dispatchEvent(new CustomEvent(Ss))}async function mr(){try{const t=await fetch(vt("/api/themes"));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function hr(){const[t,s]=r.useState([]),[a,l]=r.useState(()=>mn());return r.useEffect(()=>{let i=!1;return mr().then(n=>{i||s(n)}),()=>{i=!0}},[]),r.useEffect(()=>{hn(a),pr(a)},[a]),{themes:t,theme:a,switchTheme:i=>l(i===pn?null:i)}}function jr(){const t=getComputedStyle(document.documentElement),s=(a,l)=>t.getPropertyValue(a).trim()||l;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 gr=r.lazy(()=>Ps(()=>import("./TerminalPanel-D7bIj91c.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function fr({notice:t,onDismiss:s}){const a=pe(),[l,c]=r.useState(!1);r.useEffect(()=>{if(l)return;const n=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(n)},[l,t.id,t.level,s]);const i=t.level==="error"?ti:t.level==="warning"?ei:zn;return e.jsxs("div",{className:`notice notice-${t.level}${l?" paused":""}`,role:"status",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[e.jsx(i,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:t.text}),e.jsx("button",{type:"button",className:"notice-close",title:a("close"),onClick:()=>s(t.id),children:e.jsx(we,{})})]})}const xr=[],gn=180,fn=520,xn=240,vn=t=>`pi-web-ui:${t}-panel-width`;function Ts(t){const s=Number(localStorage.getItem(vn(t)));return Number.isFinite(s)&&s>=gn&&s<=fn?s:xn}function Es({side:t,width:s,onResize:a}){const l=pe(),c=r.useCallback(i=>{i.preventDefault();const n=i.clientX,o=s;let u=o;const h=g=>{const k=t==="left"?g.clientX-n:n-g.clientX;u=Math.min(fn,Math.max(gn,Math.round(o+k))),a(u)},p=()=>{window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",p),document.body.classList.remove("panel-resizing"),localStorage.setItem(vn(t),String(u))};window.addEventListener("pointermove",h),window.addEventListener("pointerup",p),document.body.classList.add("panel-resizing")},[t,s,a]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:l("dragToResize"),onPointerDown:c,onDoubleClick:()=>a(xn)})}function vr(){var E,J,se,me,he,je,Re,qt,Ht,Ut,Kt,zt,Vt,Gt;const t=pe(),{chat:s,send:a,dismissNotice:l,pushNotice:c,terminal:i}=Si(),[n,o]=r.useState([]),[u,h]=r.useState(null),[p,g]=r.useState(!1),[k,b]=r.useState("chat"),N=r.useMemo(()=>s.plugins.filter(L=>{var W,ne;return!((ne=(W=s.settings)==null?void 0:W.disabledPlugins)!=null&&ne.includes(L.id))}),[s.plugins,(E=s.settings)==null?void 0:E.disabledPlugins]),[B,w]=r.useState([]);r.useEffect(()=>xi(w),[]),r.useEffect(()=>{vi(N,s.pluginsEpoch)},[N,s.pluginsEpoch]);const[_,v]=r.useState(()=>Ts("left")),[j,I]=r.useState(()=>Ts("right")),A=r.useCallback(L=>v(L),[]),S=r.useCallback(L=>I(L),[]),[T,m]=r.useState(null),[D,O]=r.useState(()=>window.matchMedia("(max-width: 768px)").matches);r.useEffect(()=>{const L=window.matchMedia("(max-width: 768px)"),W=ne=>O(ne.matches);return L.addEventListener("change",W),()=>L.removeEventListener("change",W)},[]);const[Z,Q]=r.useState(!1),[H,K]=r.useState(!1),[ie,x]=r.useState(!1),[y,$]=r.useState(!1),[ge,z]=r.useState(!1),[P,X]=r.useState(null);r.useEffect(()=>{if(!P)return;const L=setTimeout(()=>X(null),15e3);return()=>clearTimeout(L)},[P]),r.useEffect(()=>{const L=W=>{var Be,Yt;const ne=W.detail,ve=(ne==null?void 0:ne.title)||"插件命令",ke=ne==null?void 0:ne.command;if(!ke||!s.ready)return;const Ce={name:ve,command:ke,cwd:"${pwd}"},be=s.terminals.find(kt=>kt.title===ve);if(be)i.restart(be.id),a({type:"run_command",terminalId:be.id,conversationId:be.conversationId,command:Ce,cols:80,rows:24});else{const kt=De();i.create({id:kt,conversationId:s.activeConversationId||((Be=s.state)==null?void 0:Be.conversationId)||"",title:ve,cwd:((Yt=s.state)==null?void 0:Yt.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Ce})}b("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",L),()=>window.removeEventListener("pi-web-ui:plugin-run-command",L)},[s,i,a]),r.useEffect(()=>{const L=W=>{!(W.ctrlKey||W.metaKey)||W.key.toLowerCase()!=="k"||(W.preventDefault(),z(ne=>!ne))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[]);const[V,M]=r.useState(un),{themes:F,theme:q,switchTheme:te}=hr(),U=r.useRef(null),oe=r.useRef(null),re=r.useRef(0),d=r.useRef(!1),R=r.useRef(s.terminals);r.useEffect(()=>{ir(V)},[V]),r.useEffect(()=>{var W;const L=R.current;R.current=s.terminals;for(const ne of s.terminals){const ve=((W=ne.command)==null?void 0:W.command)??"",ke=L.find(Ce=>Ce.id===ne.id);!(ke!=null&&ke.running)||ne.running||(ve.startsWith("pi remove ")?a({type:"extensions_reload"}):ve.startsWith("pi-web-ui install ")||ve.startsWith("pi-web-ui uninstall ")?a({type:"plugins_reload"}):ve.startsWith("npm i -g ")&&(a({type:"extensions_reload"}),a({type:"plugins_reload"}),a({type:"check_updates_all",force:!0})))}},[s.terminals,a]),r.useEffect(()=>{var ne;const L=((ne=s.state)==null?void 0:ne.isStreaming)??!1,W=U.current;U.current=L,W!==null&&(!W&&L?et("start",V):W&&!L&&et("done",V))},[(J=s.state)==null?void 0:J.isStreaming,V]),r.useEffect(()=>{var W;const L=((W=s.dialog)==null?void 0:W.id)??null;L!==null&&L!==oe.current&&et("question",V),oe.current=L},[s.dialog,V]),r.useEffect(()=>{const L=[...s.notices].reverse().find(W=>W.level==="error");L&&L.id!==re.current&&(re.current=L.id,et("error",V))},[s.notices,V]);const le=(L,W,ne,ve=!1,ke)=>{const Ce=`${L}|${ne}|${ke?`${ke.start}-${ke.end}`:""}`;o(be=>be.some(Be=>`${Be.path}|${Be.mode}|${Be.lines?`${Be.lines.start}-${Be.lines.end}`:""}`===Ce)?be:[...be,{path:L,name:W,mode:ne,isDir:ve,...ke?{lines:ke}:{}}])},ee=L=>o(W=>W.filter(ne=>ne.key?ne.key!==L:ne.path!==L)),fe=r.useCallback(L=>(!L.type.startsWith("list_")&&!L.type.startsWith("get_")&&m(null),a(L)),[a]),Y=r.useRef(0),de=r.useRef(0),xe=L=>{var ve;const W=Date.now();(ve=s.state)!=null&&ve.model&&!s.state.model.vision&&W-de.current>1e4&&(de.current=W,c("warning",t("imageNotSupported")));const ne=`paste-${++Y.current}`;o(ke=>[...ke,{path:"",key:ne,name:L.name,mode:"inline",imageData:L.data,mimeType:L.mimeType}])},ce=async L=>{for(const W of L){const ne=await Ys(W);if(!ne){c("error",t("imageLoadFailed",{name:W.name}));continue}xe(ne)}},Se=20*1024*1024,Ye=r.useRef(0),Te=async L=>{if(L.size>Se){c("warning",t("fileTooLarge",{name:L.name,size:Se/1024/1024}));return}let W;try{W=(await new Promise((ke,Ce)=>{const be=new FileReader;be.onload=()=>ke(be.result),be.onerror=()=>Ce(be.error??new Error("read failed")),be.readAsDataURL(L)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",t("fileLoadFailed",{name:L.name}));return}const ne=`upload-${++Ye.current}`;o(ve=>[...ve,{path:"",key:ne,name:L.name,mode:"inline",fileData:W,size:L.size,mimeType:L.type||void 0}])},Ee=async L=>{for(const W of L)Le(W.type)?await ce([W]):await Te(W)},Je=r.useCallback((L,W,ne)=>{a({type:"edit_message",messageId:L,text:W,attachments:ne})},[a]),Me=r.useCallback(()=>K(!0),[]),Qe=r.useCallback(()=>o([]),[]),Fe=r.useCallback(ee,[]),$e=r.useCallback(ce,[ce]),Oe=r.useCallback(Ee,[Ee]),C=(se=s.state)==null?void 0:se.model,ue=(me=s.state)==null?void 0:me.thinkingLevel,ae=(he=s.state)==null?void 0:he.availableThinkingLevels,ye=r.useMemo(()=>C?{model:C,thinkingLevel:ue??"off",availableThinkingLevels:ae??[]}:null,[C,ue,ae]),f=r.useCallback(()=>{var L,W;return!s.ready||s.terminals.length!==0?!1:(i.create({id:De(),conversationId:s.activeConversationId||((L=s.state)==null?void 0:L.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((W=s.state)==null?void 0:W.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,(je=s.state)==null?void 0:je.cwd,s.terminals.length,t,i]);return r.useEffect(()=>{if(d.current){if(k!=="terminal"||s.terminals.length!==0){d.current=!1;return}f()&&(d.current=!1)}},[s.terminals.length,f,k]),e.jsxs("div",{className:"app",onDragOver:L=>{var W;Array.from(((W=L.dataTransfer)==null?void 0:W.types)??[]).includes("Files")&&(L.preventDefault(),g(!0))},onDragLeave:L=>{L.currentTarget.contains(L.relatedTarget)||g(!1)},onDrop:L=>{var ke,Ce;if(g(!1),!Array.from(((ke=L.dataTransfer)==null?void 0:ke.types)??[]).includes("Files"))return;L.preventDefault();const W=Array.from(((Ce=L.dataTransfer)==null?void 0:Ce.files)??[]);if(W.length===0){c("warning",t("foldersNotSupported"));return}const ne=W.filter(be=>Le(be.type)),ve=W.filter(be=>!Le(be.type));ne.length>0&&ce(ne),ve.length>0&&Ee(ve)},children:[p&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(oi,{chat:s,send:a,terminal:i,view:k,plugins:N,onViewChange:L=>{d.current=L==="terminal"&&s.terminals.length===0,d.current&&f()&&(d.current=!1),b(L),m(null)},onOpenPanel:m,onOpenSettings:()=>x(!0),onOpenBgTasks:()=>$(!0),onOpenGlobalSearch:()=>z(!0),sound:V,onSoundChange:M,onSoundPreview:L=>et(L,V),themes:F,theme:q,onThemeChange:te}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(L=>e.jsx(fr,{notice:L,onDismiss:l},L.id))}),e.jsx(Na,{send:a,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${_}px`,"--right-w":`${j}px`},children:[T&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>m(null)}),e.jsxs("div",{className:`view-pane ${k==="chat"?"":"hidden"}`,children:[e.jsx("div",{className:`panel-drawer drawer-left ${T==="left"?"open":""}`,children:e.jsx(di,{send:fe,active:!D||T==="left",ready:s.ready,status:s.status,cwd:((Re=s.state)==null?void 0:Re.cwd)??"",sessionFile:((qt=s.state)==null?void 0:qt.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!D&&e.jsx(Es,{side:"left",width:_,onResize:A}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(Ra,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:Je,onKillBash:()=>a({type:"abort_bash"}),thinkingWrap:((Ht=s.settings)==null?void 0:Ht.thinkingWrap)??!0,toolsWrap:((Ut=s.settings)==null?void 0:Ut.toolsWrap)??!0,jumpTarget:P,onJumpDone:()=>X(null)},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx($a,{send:a,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId}),s.dialog&&e.jsx(qa,{dialog:s.dialog,send:a}),e.jsx(Fa,{send:a,ready:s.ready,streaming:((Kt=s.state)==null?void 0:Kt.isStreaming)??!1,messages:((zt=s.state)==null?void 0:zt.messages)??xr,slashCommands:s.slashCommands,modelState:ye,models:s.models,modelsLoading:s.modelsLoading,attachments:n,onRemoveAttachment:Fe,onAddImageFiles:$e,onAddLocalFiles:Oe,onNotice:c,onManageModels:Me,onSent:Qe})]}),!D&&e.jsx(Es,{side:"right",width:j,onResize:S}),e.jsx("div",{className:`panel-drawer drawer-right ${T==="right"?"open":""}`,children:e.jsx(Bi,{send:fe,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((Vt=s.state)==null?void 0:Vt.cwd)??"",onAttach:(L,W,ne,ve)=>{m(null),le(L,W,ne,ve)},onPreview:(L,W)=>{m(null),h({path:L,name:W})},onNotice:(L,W)=>c(L,W)})})]}),e.jsx("div",{className:`view-pane ${k==="terminal"?"":"hidden"}`,children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(gr,{chat:s,send:a,terminal:i})})}),e.jsx("div",{className:`view-pane ${k==="git"?"":"hidden"}`,children:e.jsx(Ua,{chat:s,send:a,terminal:i,active:k==="git",onSwitchToTerminal:()=>b("terminal")})}),B.map(L=>{const W=`plugin:${L.info.id}`;return e.jsx("div",{className:`view-pane ${k===W?"":"hidden"}`,children:e.jsx(Ka,{entry:L,send:a})},L.info.id)})]})}),e.jsx(Oa,{chat:s,send:a}),u&&e.jsx(sr,{file:u,content:s.fileContent,send:a,onAddLines:(L,W,ne,ve)=>le(L,W,"lines",!1,{start:ne,end:ve}),onAttach:(L,W,ne)=>le(L,W,ne),onClose:()=>h(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!Z&&!H&&e.jsx(za,{send:a,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>Q(!0)}),H&&e.jsx(Ya,{send:a,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>K(!1)}),ie&&e.jsx(Qa,{chat:s,send:a,terminal:i,onSwitchToTerminal:()=>b("terminal"),onClose:()=>x(!1)}),y&&e.jsx(Za,{servers:s.bgServers,send:a,onClose:()=>$(!1)}),e.jsx(tr,{open:ge,send:a,projects:s.projects,cwd:((Gt=s.state)==null?void 0:Gt.cwd)??"",fileSearch:s.fileSearch,sessionSearch:s.sessionSearch,onClose:()=>z(!1),onSwitchSession:(L,W)=>{a({type:"switch_session",path:L});const ne=W&&W[0];X(ne?{path:L,role:ne.role,timestamp:ne.timestamp}:null)},onSwitchProject:L=>{a({type:"set_cwd",path:L})},onPreviewFile:(L,W)=>{h({path:L,name:W})}})]})}ui();hn(mn());jn.createRoot(document.getElementById("root")).render(e.jsx(r.StrictMode,{children:e.jsx(ri,{children:e.jsx(vr,{})})}));export{ht as F,Ss as T,_e as a,jr as b,br as c,Rt as d,Ie as e,we as f,Wn as g,ze as h,De as r,pe as u};
|
|
305
|
+
`)})]})}):null})()]})});var ms=Is();const zs=r.memo(function({text:s}){const i=pe(),[l,c]=r.useState(!1);return s?e.jsx("button",{type:"button",className:"copy-btn",title:i("copy"),onClick:()=>{navigator.clipboard.writeText(s).then(()=>{c(!0),setTimeout(()=>c(!1),1200)})},children:l?e.jsx(vt,{}):e.jsx($t,{})}):null});function Wi(t){const s=l=>{var c;if(typeof l=="string"||typeof l=="number"){const a=String(l);return a===""?[[]]:a.split(`
|
|
306
|
+
`).map(n=>n===""?[]:[n])}if(Array.isArray(l)){let a=[];for(const n of l){const o=s(n);if(a.length===0)a=o;else{const u=o[0]??[];a[a.length-1].push(...u),a.push(...o.slice(1))}}return a}if(l&&typeof l=="object"&&"props"in l){const a=l,n=(c=a.props)==null?void 0:c.children,o={...a.props??{},children:void 0},u=n==null?[]:s(n);return u.length===0?[[r.createElement(a.type,o)]]:u.map(h=>[r.createElement(a.type,o,...h)])}return[[l]]},i=s(t);return i.length>1&&i[i.length-1].length===0&&i.pop(),i}const Vs=[bn],Gs=[[kn,{detect:!0,ignoreMissing:!0}]];function Ys({text:t}){return e.jsx(Ps,{remarkPlugins:Vs,rehypePlugins:Gs,components:{pre:qi},children:t})}const kt=r.memo(function({text:s}){return e.jsx("div",{className:"md",children:e.jsx(Ys,{text:s})})});function qi({children:t,...s}){var n;const i=t&&typeof t=="object"&&"props"in t?(n=t.props)==null?void 0:n.children:t,l=Wi(i),c=l.length>1,a=c?`${String(l.length).length+1}ch`:void 0;return e.jsxs("div",{className:"codeblock",children:[e.jsx(zs,{text:At(t)}),e.jsx("pre",{...s,children:l.map((o,u)=>e.jsxs("div",{className:"code-line",children:[c&&e.jsx("span",{className:"code-num",style:a?{width:a}:void 0,children:u+1}),e.jsx("code",{className:"code-line-body hljs",children:o})]},u))})]})}function At(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(At).join("");if(t&&typeof t=="object"&&"props"in t){const s=t.props;return At(s==null?void 0:s.children)}return""}const Ui=/^\s{0,3}(`{3,}|~{3,})/,Hi=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function Ct(t){return t.trim()===""}function hs(t){const s=Ui.exec(t);return s?s[1]:null}function Ki(t){const s=t.split(`
|
|
307
|
+
`),i=[];let l=[],c=null;for(let a=0;a<s.length;a++){const n=s[a];if(c!==null){const u=hs(n);u&&u[0]===c[0]&&u.length>=c.length&&(c=null),l.push(n);continue}const o=hs(n);if(o&&!Ct(n)){c=o,l.push(n);continue}if(Ct(n)){let u=a;for(;u<s.length&&Ct(s[u]);)u++;if(!(u<s.length&&Hi.test(s[u]))&&l.length>0){i.push(l.join(`
|
|
308
|
+
`)),l=[];continue}l.push(n);continue}l.push(n)}return{frozen:i,active:l.join(`
|
|
309
|
+
`),inFence:c!==null}}const zi=r.memo(function({text:s}){return e.jsx(Ps,{remarkPlugins:Vs,rehypePlugins:Gs,children:s})}),gs=200;function Vi({text:t,inFence:s}){const[i,l]=r.useState(t),c=r.useRef(0),a=r.useRef(null);return r.useEffect(()=>{if(s)return;const n=Date.now()-c.current,o=()=>{c.current=Date.now(),l(t)};if(n>=gs){o();return}return a.current=setTimeout(o,gs-n),()=>{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(Ys,{text:i})}const Gi=r.memo(function({text:s}){const{frozen:i,active:l,inFence:c}=r.useMemo(()=>Ki(s),[s]);return e.jsxs("div",{className:"md",children:[i.map((a,n)=>e.jsx(zi,{text:a},n)),l.length>0&&e.jsx(Vi,{text:l,inFence:c},i.length)]})});function Yi({thinking:t,streaming:s,wrap:i=!0}){const l=pe(),[c,a]=r.useState(null),n=c??i,o=s?t.trimEnd().slice(-80):t.split(`
|
|
310
|
+
`)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${n?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>a(!n),children:[n?e.jsx(qe,{}):e.jsx(xt,{}),e.jsx(st,{className:"thinking-icon"}),e.jsx("span",{className:"thinking-label",children:s&&n?e.jsxs("span",{className:"thinking-live-label",children:[l("thinkingNow"),e.jsx("span",{className:"dots"})]}):n?l("thinking"):l("thinkingPreview",{preview:o})})]}),n&&e.jsx("div",{className:"thinking-body",children:t})]})}const Ji={bash:"$",read:"📄",write:"✍️",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function Qi(t){return Ji[t]??"🛠"}const Xi=r.memo(function({block:s,view:i,onKillBash:l,wrap:c=!0}){var A,S,T,m;const a=pe(),[n,o]=r.useState(c),[u,h]=r.useState(!1),p=!i.result&&i.streaming&&!i.status,g=s.name==="bash"&&p,k=i.result!==void 0,b=!i.result&&!!i.status,N=((A=i.result)==null?void 0:A.isError)??((S=i.status)==null?void 0:S.isError)??!1,D=i.result?i.result.content.map(B=>B.type==="text"?B.text:"").join(""):i.liveOutput??"",w=N?"err":k?"ok":p||b?"run":"idle";let _=a(N?"error":k?"done":p?"running":b?"toolDoneWaitingModel":"toolQueued");const v=b&&((T=i.status)==null?void 0:T.durationMs)!==void 0?ea(i.status.durationMs):"";b&&v&&(_=`${_} · ${v}`);const j=b&&((m=i.status)==null?void 0:m.exitCode)!==void 0?`exit ${i.status.exitCode}`:"",I=()=>{s.argumentsText&&(navigator.clipboard.writeText(s.argumentsText),h(!0),setTimeout(()=>h(!1),1200))};return e.jsxs("div",{className:`toolcall ${w}`,children:[e.jsxs("div",{className:"toolcall-head",children:[e.jsx("span",{className:"toolcall-icon",children:Qi(s.name)}),e.jsx("span",{className:"toolcall-name",children:s.name}),e.jsxs("span",{className:"toolcall-status",children:[_,j&&e.jsx("em",{className:"toolcall-exit",children:j})]}),e.jsx("span",{className:"toolcall-spacer"}),g&&l&&e.jsxs("button",{type:"button",className:"toolcall-kill",title:a("stopBashTip"),onClick:l,children:[e.jsx(ut,{}),e.jsx("span",{children:a("stopBash")})]}),e.jsx("button",{type:"button",className:"toolcall-copy",title:a("copyArgs"),onClick:I,children:u?e.jsx(ei,{}):e.jsx($t,{})}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>o(B=>!B),children:n?e.jsx(qe,{}):e.jsx(xt,{})})]}),n&&e.jsxs("div",{className:"toolcall-body",children:[s.argumentsText&&e.jsx("div",{className:"toolcall-args",children:s.name==="bash"&&s.argumentsText.startsWith("{")?e.jsx(Zi,{args:s.argumentsText}):e.jsx("pre",{children:s.argumentsText})}),D.length>0&&e.jsxs("div",{className:"toolcall-output",children:[e.jsxs("div",{className:"toolcall-output-label",children:[a(N?"errorOutput":"output"),(p||b)&&e.jsx("span",{className:"cursor"})]}),e.jsx("pre",{children:D})]}),p&&D.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",a("waitingOutput")]}),b&&D.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",a("waitingModel")]})]})]})});function Zi({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(ze,{className:"termline-icon"}),e.jsx("code",{children:s.command}),typeof s.timeout=="number"&&e.jsxs("span",{className:"termline-timeout",children:["⏱ ",s.timeout,"s"]})]})}function ea(t){if(t===void 0)return"";const s=t/1e3;if(s<60)return`${s.toFixed(1)}s`;const i=Math.floor(s/60),l=Math.round(s%60);return`${i}m ${String(l).padStart(2,"0")}s`}const ta=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function qt(t){var i;const s=t.match(ta);return s?{name:s[1],location:s[2],content:s[3],userMessage:((i=s[4])==null?void 0:i.trim())||void 0}:null}const sa=1568,na=2*1024*1024;function Le(t){return t.startsWith("image/")&&t!=="image/svg+xml"&&t!=="image/svg"}async function Js(t){if(!t.type.startsWith("image/"))return null;let s;try{s=await createImageBitmap(t,{imageOrientation:"from-image"})}catch{return null}try{const i=Math.min(1,sa/Math.max(s.width,s.height)),l=Math.max(1,Math.round(s.width*i)),c=Math.max(1,Math.round(s.height*i)),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 n=null;for(const[o,u]of a){const h=document.createElement("canvas");h.width=l,h.height=c;const p=h.getContext("2d");if(!p)continue;o!=="image/png"&&(p.fillStyle="#ffffff",p.fillRect(0,0,l,c)),p.drawImage(s,0,0,l,c);const g=h.toDataURL(o,u),k=g.match(/^data:([^;]+);base64,/),b=k?k[1]:o,N=g.replace(/^data:[^;]*;base64,/,""),D=Math.floor(N.length*3/4);if(n={data:N,mimeType:b,name:t.name,size:D},D<=na)return n}return n}finally{s.close()}}const ia=20*1024*1024;function nt(t){return t.type==="text"&&typeof t.text=="string"?t:null}function Qs(t){return t.type==="thinking"&&typeof t.thinking=="string"?t:null}function Xs(t){return t.type==="toolCall"&&typeof t.id=="string"&&typeof t.name=="string"?t:null}function Zs(t){return t.type==="image"&&typeof t.dataUrl=="string"?t:null}function en(t){return t.type==="bash"&&typeof t.command=="string"?t:null}function aa(t){return t.imageData?"image":t.uploadPath?"upload":t.fileData?"file":"path"}function ra(t,s){if(t.imageData)return s("attachImage",{name:t.name??"image"});if(t.uploadPath)return s("attachFile",{name:t.name??t.uploadPath});if(t.fileData)return s("attachFile",{name:t.name??"file"});const i=t.path.split("/").pop()??t.path;return t.mode==="lines"&&t.lines?s("attachLines",{path:i,start:t.lines.start,end:t.lines.end}):t.mode==="reference"?s("refOnly",{path:i}):s("attachContent",{path:i})}const fs=r.memo(function({message:s,toolResults:i,liveOutputs:l,toolStatuses:c,streaming:a,isLast:n,onEdit:o,onKillBash:u,onCollapse:h,questionAttachments:p,qnIndex:g,qnActive:k,onJump:b,thinkingWrap:N,toolsWrap:D}){const w=pe(),[_,v]=r.useState(!1),[j,I]=r.useState(""),[A,S]=r.useState([]),[T,m]=r.useState(!1),[B,O]=r.useState(null),Z=F=>{O(F),window.setTimeout(()=>O(q=>q===F?null:q),4e3)};if(s.role==="toolResult")return null;const Q=s.role==="custom"&&s.customType==="file",U=s.content.map(F=>{var q;return((q=nt(F))==null?void 0:q.text)??""}).filter(Boolean).join(`
|
|
311
|
+
`),K=s.role==="user"?qt(U):null,ie=K?K.userMessage??`skill:${K.name}`:U.split(`
|
|
312
|
+
`).join(" ").trim(),x=a&&n&&s.content.length===0,y=s.role==="user"&&!a&&!x&&!!o,$=async F=>{const q=[];for(const te of F){if(!Le(te.type))continue;const H=await Js(te);H&&q.push({path:"",imageData:H.data,mimeType:H.mimeType,name:H.name})}q.length>0&&S(te=>[...te,...q])},ge=async F=>{if(F.size>ia){Z(w("fileTooLarge",{name:F.name,size:20}));return}let q;try{q=(await new Promise((H,oe)=>{const re=new FileReader;re.onload=()=>H(re.result),re.onerror=()=>oe(re.error??new Error("read failed")),re.readAsDataURL(F)})).replace(/^data:[^;]*;base64,/,"")}catch{Z(w("fileLoadFailed",{name:F.name}));return}S(te=>[...te,{path:"",fileData:q,name:F.name,size:F.size,mimeType:F.type||void 0}])},z=async F=>{const q=[];for(const te of F)Le(te.type)?q.push(te):ge(te);q.length>0&&await $(q)},P=()=>{I(K?`/skill:${K.name}${K.userMessage?` ${K.userMessage}`:""}`:s.content.map(F=>{var q;return((q=nt(F))==null?void 0:q.text)??""}).filter(Boolean).join(`
|
|
313
|
+
`)),S(p??[]),v(!0)},X=()=>{const F=j.trim();F&&(o==null||o(s.id,F,A.length>0?A:void 0),v(!1))},V=s.role==="custom"&&(s.customType==="goal-review"||s.customType==="goal-wizard"),M=s.role==="custom"&&s.customType==="goal-wizard";return e.jsxs("div",{className:`msg msg-${s.role}${V?" 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"?M?w("goalWizardCard"):V?w("goalBarTitle"):s.customType==="file"?w("attachment"):`${w("plugin")} · ${s.customType??w("unknown")}`:tn(s.role,w)}),s.model&&e.jsx("span",{className:"msg-model",children:s.model}),s.timestamp&&e.jsx("span",{className:"msg-time",children:da(s.timestamp)}),h&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:w("collapseMsg"),onClick:()=>h(s.id),children:[e.jsx(ft,{})," ",w("collapseMsg")]}),g!==void 0&&b&&e.jsxs("button",{type:"button",className:`qn-tag ${k?"active":""}`,title:`${g+1}. ${ie}`,"aria-label":`${g+1}. ${ie}`,onClick:()=>b(s.id),children:[e.jsx("span",{className:"qn-tag-bar"}),e.jsx("span",{className:"qn-tag-idx",children:g+1})]})]}),e.jsx("div",{className:"msg-body",children:_?e.jsxs("div",{className:`msg-editor${T?" drag-over":""}`,onDragOver:F=>{F.preventDefault(),F.stopPropagation(),m(!0)},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||m(!1)},onDrop:F=>{var q;F.preventDefault(),F.stopPropagation(),m(!1),z(Array.from(((q=F.dataTransfer)==null?void 0:q.files)??[]))},children:[A.length>0&&e.jsx("div",{className:"msg-editor-images",children:A.map((F,q)=>{var H;const te=aa(F);return e.jsxs("span",{className:`msg-editor-img ${te==="image"?"":"file-chip"}`,title:ra(F,w),children:[te==="image"?e.jsx("img",{src:`data:${F.mimeType??"image/png"};base64,${F.imageData}`,alt:F.name}):e.jsxs("span",{className:"msg-editor-file",children:[e.jsx("span",{className:"msg-editor-file-icon",children:te==="path"?F.mode==="reference"?"🔗":"📎":"📄"}),e.jsx("span",{className:"msg-editor-file-name",children:F.name??((H=F.path)==null?void 0:H.split("/").pop())})]}),e.jsx("button",{type:"button",className:"msg-editor-img-remove",title:w("removeAttachment"),onClick:()=>S(oe=>oe.filter((re,d)=>d!==q)),children:e.jsx(we,{})})]},`${F.name??F.path??"att"}-${q}`)})}),B&&e.jsx("div",{className:"msg-editor-notice",children:B}),e.jsx("textarea",{className:"msg-editor-input",value:j,autoFocus:!0,placeholder:w("editPlaceholder"),rows:Math.max(2,Math.min(10,j.split(`
|
|
314
|
+
`).length+1)),onChange:F=>I(F.target.value),onPaste:F=>{var te;const q=[];for(const H of((te=F.clipboardData)==null?void 0:te.items)??[])if(H.kind==="file"&&Le(H.type)){const oe=H.getAsFile();oe&&q.push(oe)}q.length!==0&&(F.preventDefault(),$(q))},onKeyDown:F=>{F.key==="Enter"&&(F.metaKey||F.ctrlKey)?(F.preventDefault(),X()):F.key==="Escape"&&v(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(Yn,{})," ",w("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>v(!1),children:w("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!j.trim(),title:w("reaskFromHere"),onClick:X,children:[e.jsx(Pt,{})," ",w("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),Q?e.jsx(la,{message:s}):K?e.jsxs(e.Fragment,{children:[e.jsx(ca,{block:K}),K.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(kt,{text:K.userMessage})}),s.content.map((F,q)=>F.type==="text"?null:e.jsx(vs,{block:F,toolResults:i,liveOutputs:l,toolStatuses:c,streaming:a,isLast:n,onKillBash:u,toolsWrap:D,thinkingWrap:N},`${s.id}-${q}`))]}):s.content.map((F,q)=>e.jsx(vs,{block:F,toolResults:i,liveOutputs:l,toolStatuses:c,streaming:a,isLast:n,onKillBash:u,toolsWrap:D,thinkingWrap:N},`${s.id}-${q}`)),x&&e.jsxs("div",{className:"thinking-wait",children:[w("thinkingWait"),e.jsx("span",{className:"dot"})]}),a&&n&&!x&&e.jsx("span",{className:"stream-cursor"})]})}),y&&!_&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:w("editReaskTip"),onClick:P,children:[e.jsx(Pt,{})," ",w("editReask")]})})]})});function la({message:t}){const s=pe(),[i,l]=r.useState(!1),c=t.details??{},a=c.name??c.path??s("attachment"),n=c.type==="folder",o=c.mode==="reference",u=c.mode==="bridged",h=t.content.filter(b=>b.type==="text").map(b=>b.text).join(`
|
|
315
|
+
`),p=oa(h),g=t.content.find(b=>b.type==="image"),k=p.split(`
|
|
316
|
+
`).length;return e.jsxs("div",{className:`attachcard ${o?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>l(b=>!b),children:[e.jsx("span",{className:"attachcard-icon",children:n?"📁":"📎"}),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":o?"ref":u?"bridged":"inline"}`,children:o?n?s("folderRefShort"):`${s("refOnlyShort")} · ${xs(c.size)}`:u?s("bridgedVision"):g?s("image"):c.mode==="lines"?s("inlineLinesRange",{start:c.startLine??1,end:c.endLine??c.lines??1}):s("inlineLines",{n:c.lines??k})}),!o&&(i?e.jsx(qe,{}):e.jsx(xt,{}))]}),!o&&i&&(u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:s("bridgedVisionDetail")}),(g==null?void 0:g.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:g.dataUrl,alt:a})}),p&&e.jsx("pre",{className:"attachcard-content",children:p})]}):g!=null&&g.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:g.dataUrl,alt:a})}):e.jsx("pre",{className:"attachcard-content",children:p})),o&&e.jsx("div",{className:"attachcard-refnote",children:n?s("folderNotExpanded"):s("fileNotExpanded",{size:xs(c.size)})})]})}function xs(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function oa(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 i=t.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return i?i[1].trim():t.trim()}function ca({block:t}){const s=pe(),[i,l]=r.useState(!1);return e.jsxs("div",{className:`skillcard${i?" expanded":""}`,children:[e.jsxs("button",{type:"button",className:"skillcard-head",onClick:()=>l(c=>!c),title:t.location,children:[e.jsx("span",{className:"skillcard-icon",children:e.jsx(ti,{})}),e.jsx("span",{className:"skillcard-name",children:t.name}),e.jsx("span",{className:"skillcard-path",children:t.location}),e.jsxs("span",{className:"skillcard-action",children:[i?e.jsx(ft,{}):e.jsx(qe,{}),s(i?"collapseMsg":"expandMsg")]})]}),i&&e.jsx("div",{className:"skillcard-body",children:e.jsx(kt,{text:t.content})})]})}function vs({block:t,toolResults:s,liveOutputs:i,toolStatuses:l,streaming:c,isLast:a,onKillBash:n,thinkingWrap:o,toolsWrap:u}){const h=pe(),p=nt(t);if(p){const D=c&&a;return e.jsxs("div",{className:"msg-text",children:[D?e.jsx(Gi,{text:p.text}):e.jsx(kt,{text:p.text}),p.truncated&&e.jsx("div",{className:"trunc-note",children:h("truncated")})]})}const g=Qs(t);if(g)return e.jsx(Yi,{thinking:g.thinking,streaming:c&&a,wrap:o});const k=Xs(t);if(k){const D=s.get(k.id),w=i.get(k.id),_={result:D,liveOutput:w==null?void 0:w.text,streaming:c,status:l.get(k.id)};return e.jsx(Xi,{block:k,view:_,onKillBash:n,wrap:u})}const b=Zs(t);if(b&&b.dataUrl)return e.jsx("div",{className:"msg-image",children:e.jsx("img",{src:b.dataUrl,alt:"attachment"})});const N=en(t);return N?e.jsxs("div",{className:"bashblock",children:[e.jsxs("div",{className:"bashblock-command",children:[e.jsx("span",{className:"bashblock-prompt",children:"$"}),e.jsx("code",{children:N.command}),N.exitCode!==void 0&&e.jsx("span",{className:`bashblock-exit ${N.exitCode===0?"ok":"err"}`,children:h("exitCode",{code:N.exitCode})}),N.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:h("cancelled")})]}),N.output&&e.jsx("pre",{className:"bashblock-output",children:N.output}),N.truncated&&e.jsx("div",{className:"trunc-note",children:h("outputTruncated")})]}):null}function tn(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 da(t){const s=new Date(t),i=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${i}:${l}`}function ys(t,s,i){let l=!1;for(const c of s){const a=c;if(a.type!=="image"||typeof a.dataUrl!="string"||!a.dataUrl.startsWith("data:"))continue;const n=a.dataUrl.match(/^data:([^;]*);base64,(.+)$/);n&&(l=!0,t.push({path:"",imageData:n[2],mimeType:n[1]||"image/png",name:i??`image.${(n[1]||"image/png").split("/")[1]??"png"}`}))}return l}function ua(t){const s=new Map;for(let i=0;i<t.length;i++){const l=t[i];if(l.role!=="user"||!l.id)continue;const c=[];ys(c,l.content);for(let a=i+1;a<t.length&&t[a].role==="custom"&&t[a].customType==="file";a++){const n=t[a].details??{};if(!ys(c,t[a].content,n.name)){if(n.upload&&n.path){c.push({path:"",uploadPath:n.path,name:n.name??n.path,size:n.size});continue}if(n.path&&n.mode){const o=n.mode==="inline"||n.mode==="lines"?n.mode:"reference",u={path:n.path,mode:o};n.mode==="lines"&&typeof n.startLine=="number"&&typeof n.endLine=="number"&&(u.lines={start:n.startLine,end:n.endLine}),c.push(u)}}}c.length>0&&s.set(l.id,c)}return s}const pa=r.memo(function({message:s,onExpand:i}){const l=pe();let c="";for(const g of s.content){const k=nt(g);if(k&&k.text.trim()){const b=qt(k.text);b?c=`skill:${b.name}`+(b.userMessage?` · ${b.userMessage.replace(/\s+/g," ").trim()}`:""):c=k.text.replace(/\s+/g," ").trim();break}}if(!c&&s.role==="custom"&&s.customType==="file"){const g=s.details??{};c=g.name??g.path??""}c.length>90&&(c=`${c.slice(0,90)}…`);let n=0,o=0,u=0,h=0;for(const g of s.content)Qs(g)?n++:Xs(g)?o++:en(g)?u++:Zs(g)&&h++;const p=[];return n&&p.push(`${l("thinking")} ${n}`),o&&p.push(`${l("toolCalls")} ${o}`),u&&p.push(`${l("bashRuns")} ${u}`),h&&p.push(`${l("images")} ${h}`),e.jsxs("button",{type:"button",className:"msg-collapsed","data-msg-id":s.id,title:`${l("expandMsg")} · ${c||p.join(" · ")||s.role}`,onClick:()=>i(s.id),children:[e.jsx("span",{className:`msg-collapsed-role role-${s.role}`,children:s.role==="custom"&&s.customType==="file"?l("attachment"):tn(s.role,l)}),e.jsxs("span",{className:"msg-collapsed-body",children:[c&&e.jsx("span",{className:"msg-collapsed-preview",children:c}),p.length>0&&e.jsx("span",{className:"msg-collapsed-chips",children:p.map((g,k)=>e.jsx("span",{className:"msg-collapsed-chip",children:g},k))})]}),s.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:ma(s.timestamp)}):null,e.jsxs("span",{className:"msg-collapsed-action",children:[e.jsx(qe,{})," ",l("expandMsg")]})]})});function ma(t){const s=new Date(t),i=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${i}:${l}`}const ha=r.memo(function({id:s,show:i,height:l,containerRef:c,onMeasured:a,lazyRef:n,children:o}){const u=r.useRef(null),h=r.useRef(null);return r.useLayoutEffect(()=>{const p=h.current;if(h.current=i,!i||p!==!1)return;const g=u.current,k=c.current;if(!g||!k)return;const b=g.offsetHeight;a==null||a(s,b);const N=b-l;if(N!==0){const D=g.parentElement;D&&D.getBoundingClientRect().bottom<=k.getBoundingClientRect().top&&(k.scrollTop+=N)}},[i]),i?e.jsx("div",{ref:n,"data-lazy-id":s,children:e.jsx("div",{ref:u,children:o})}):e.jsx("div",{ref:n,className:"msg-lazy-ph","data-msg-id":s,"data-lazy-id":s,style:{height:l},"aria-hidden":"true"})});function ga(t,s,i,l){const c=[],a=[];let n=0;for(const o of t){if(i.has(o.id))continue;o.top<s.bottom&&o.bottom>s.top?l.has(o.id)&&c.push(o.id):l.has(o.id)||(a.push(o.id),o.bottom<=s.top&&(n+=o.bottom-o.top))}return{show:c,hide:a,shrinkAbove:n}}function fa(t,s){if(s.show.length===0&&s.hide.length===0)return t;const i=new Set(t);for(const l of s.show)i.delete(l);for(const l of s.hide)i.add(l);return i}function xa(t,s,i){const l=new Set;let c=0;for(let a=t.length-1;a>=0&&!(a<t.length-1&&c>=i);a--){const n=t[a];l.add(n.id),c+=s.get(n.id)??sn(n.role,n.customType)}return l}function sn(t,s){switch(t){case"user":return 72;case"assistant":return 280;case"toolResult":return 8;case"custom":return s==="file"?96:72;default:return 60}}const va=["text","thinking","argumentsText","output","command"];function ya(t){let s=0;for(const i of t.content){i.type==="image"&&(s+=1);for(const l of va){const c=i[l];typeof c=="string"&&(s+=c.length)}}return s}function ka(t,s,i,l){const c=i.get(t);return c&&c.len===s?c.h:l}function ba(t){if(t.role==="toolResult")return"";const s=[];for(const i of t.content)ja(i,s);return t.errorMessage&&s.push(t.errorMessage),s.join(`
|
|
317
|
+
`)}function ja(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 wa(t,s){const i=s.trim().toLowerCase();if(!i)return 0;const l=t.toLowerCase();let c=0,a=l.indexOf(i);for(;a!==-1;)c++,a=l.indexOf(i,a+i.length);return c}function Na(t,s){const i=s.trim().toLowerCase();if(!i)return[];const l=[];for(const c of t){const a=ba(c);if(!a)continue;const n=wa(a,i);for(let o=0;o<n;o++)l.push({messageId:c.id,occurrence:o})}return l}function Ca(t,s){var n;const i=new Map,l=[],c=s.toLowerCase();if(!c)return{byMsg:i,all:l};const a=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(o){const u=o.parentElement;return!u||u.closest(".search-bar")?NodeFilter.FILTER_REJECT:(o.textContent??"").toLowerCase().includes(c)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let o=a.nextNode();o;o=a.nextNode()){const u=(o.textContent??"").toLowerCase(),h=(n=o.parentElement)==null?void 0:n.closest("[data-msg-id]");if(!h)continue;const p=h.getAttribute("data-msg-id")??"";let g=u.indexOf(c);for(;g!==-1;){const k=document.createRange();k.setStart(o,g),k.setEnd(o,g+c.length),l.push(k);const b=i.get(p);b?b.push(k):i.set(p,[k]),g=u.indexOf(c,g+c.length)}}return{byMsg:i,all:l}}function He(t,s){const i=CSS;if(!i.highlights)return;if(s.length===0){i.highlights.delete(t);return}const l=window.Highlight;l&&i.highlights.set(t,new l(...s))}function Sa({containerRef:t,messages:s,open:i,onClose:l,onEnsureExpanded:c}){const a=pe(),n=r.useRef(null),[o,u]=r.useState(""),[h,p]=r.useState(0),g=r.useDeferredValue(o),k=i?g.trim():"",b=r.useMemo(()=>i?Na(s,k):[],[s,k,i]),N=r.useRef(b);N.current=b;const D=r.useRef(h);D.current=h,r.useEffect(()=>{i&&(p(0),requestAnimationFrame(()=>{var j;return(j=n.current)==null?void 0:j.select()}))},[i]),r.useEffect(()=>{if(!i)return;const j=I=>{I.key==="Escape"&&(I.preventDefault(),I.stopPropagation(),l())};return window.addEventListener("keydown",j,!0),()=>window.removeEventListener("keydown",j,!0)},[i,l]),r.useEffect(()=>(i||(He("msg-search",[]),He("msg-search-active",[])),()=>{He("msg-search",[]),He("msg-search-active",[])}),[i]);const w=r.useCallback(j=>{const I=t.current;if(!I)return;const A=I.querySelector(`[data-msg-id="${j}"]`);A&&(A.classList.remove("msg-flash"),A.offsetWidth,A.classList.add("msg-flash"))},[t]);r.useLayoutEffect(()=>{if(!i||!k)return;const j=t.current;if(!j)return;let I=!1,A=0;return A=requestAnimationFrame(()=>{var Z;if(I)return;const{byMsg:S,all:T}=Ca(j,k);He("msg-search",T);const m=N.current,B=m[Math.min(D.current,m.length-1)];if(!B)return;const O=(Z=S.get(B.messageId))==null?void 0:Z[B.occurrence];if(O){He("msg-search-active",[O]);const Q=O.startContainer.parentElement??j.querySelector(`[data-msg-id="${B.messageId}"]`);Q==null||Q.scrollIntoView({block:"center"})}else w(B.messageId)}),()=>{I=!0,cancelAnimationFrame(A)}},[i,k,b,t,w]);const _=r.useCallback(j=>{const I=N.current;if(I.length===0)return;const A=(D.current+j+I.length)%I.length;p(A),c(I[A].messageId)},[c]);if(!i)return null;const v=b.length;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:n,className:"search-input",type:"text",value:o,placeholder:a("searchPlaceholder"),onChange:j=>{u(j.target.value),p(0)},onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),_(j.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${v===0?"empty":""}`,children:v===0?a("searchNoResults"):`${Math.min(h+1,v)}/${v}`}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchPrev"),disabled:v===0,onClick:()=>_(-1),children:e.jsx(ft,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchNext"),disabled:v===0,onClick:()=>_(1),children:e.jsx(qe,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchClose"),onClick:l,children:e.jsx(we,{})})]})}function Ta(t){const{dSt:s,dSh:i,escaped:l,graceActive:c,stuck:a}=t;return c?{flipEscape:!1,reassert:!1}:s>=-4||s<=-500?{flipEscape:!1,reassert:!1}:i<0?{flipEscape:!1,reassert:a&&!l}:{flipEscape:!0,reassert:!1}}const nn=[{id:"setup-matt-pocock-skills",icon:"🛠",titleKey:"tpl.sk.setup",descKey:"tpl.sk.setup.desc",promptKey:"tpl.sk.setup.prompt"},{id:"ask-matt",icon:"🧭",titleKey:"tpl.sk.ask",descKey:"tpl.sk.ask.desc",promptKey:"tpl.sk.ask.prompt"},{id:"grill-with-docs",icon:"🗣",titleKey:"tpl.sk.grilldocs",descKey:"tpl.sk.grilldocs.desc",promptKey:"tpl.sk.grilldocs.prompt"},{id:"to-spec",icon:"📝",titleKey:"tpl.sk.tospec",descKey:"tpl.sk.tospec.desc",promptKey:"tpl.sk.tospec.prompt"},{id:"to-tickets",icon:"🎫",titleKey:"tpl.sk.totickets",descKey:"tpl.sk.totickets.desc",promptKey:"tpl.sk.totickets.prompt"},{id:"implement",icon:"🏗",titleKey:"tpl.sk.implement",descKey:"tpl.sk.implement.desc",promptKey:"tpl.sk.implement.prompt"},{id:"code-review",icon:"🧹",titleKey:"tpl.sk.codeview",descKey:"tpl.sk.codeview.desc",promptKey:"tpl.sk.codeview.prompt"},{id:"wayfinder",icon:"🗺",titleKey:"tpl.sk.wayfinder",descKey:"tpl.sk.wayfinder.desc",promptKey:"tpl.sk.wayfinder.prompt"},{id:"prototype",icon:"🔬",titleKey:"tpl.sk.prototype",descKey:"tpl.sk.prototype.desc",promptKey:"tpl.sk.prototype.prompt"},{id:"research",icon:"📚",titleKey:"tpl.sk.research",descKey:"tpl.sk.research.desc",promptKey:"tpl.sk.research.prompt"},{id:"improve-codebase-architecture",icon:"🏛",titleKey:"tpl.sk.arch",descKey:"tpl.sk.arch.desc",promptKey:"tpl.sk.arch.prompt"},{id:"diagnosing-bugs",icon:"🐛",titleKey:"tpl.sk.debug",descKey:"tpl.sk.debug.desc",promptKey:"tpl.sk.debug.prompt"},{id:"resolving-merge-conflicts",icon:"🔀",titleKey:"tpl.sk.merge",descKey:"tpl.sk.merge.desc",promptKey:"tpl.sk.merge.prompt"},{id:"triage",icon:"🗂",titleKey:"tpl.sk.triage",descKey:"tpl.sk.triage.desc",promptKey:"tpl.sk.triage.prompt"},{id:"wizard",icon:"✨",titleKey:"tpl.sk.wizard",descKey:"tpl.sk.wizard.desc",promptKey:"tpl.sk.wizard.prompt"},{id:"grill-me",icon:"🔍",titleKey:"tpl.sk.grillme",descKey:"tpl.sk.grillme.desc",promptKey:"tpl.sk.grillme.prompt"},{id:"handoff",icon:"🤝",titleKey:"tpl.sk.handoff",descKey:"tpl.sk.handoff.desc",promptKey:"tpl.sk.handoff.prompt"},{id:"to-questionnaire",icon:"📋",titleKey:"tpl.sk.questionnaire",descKey:"tpl.sk.questionnaire.desc",promptKey:"tpl.sk.questionnaire.prompt"},{id:"teach",icon:"🎓",titleKey:"tpl.sk.teach",descKey:"tpl.sk.teach.desc",promptKey:"tpl.sk.teach.prompt"},{id:"wait-what",icon:"💬",titleKey:"tpl.sk.ww",descKey:"tpl.sk.ww.desc",promptKey:"tpl.sk.ww.prompt"},{id:"writing-for-agents",icon:"📄",titleKey:"tpl.sk.wfa",descKey:"tpl.sk.wfa.desc",promptKey:"tpl.sk.wfa.prompt"},{id:"codebase-design",icon:"🧱",titleKey:"tpl.sk.codesign",descKey:"tpl.sk.codesign.desc",promptKey:"tpl.sk.codesign.prompt"},{id:"domain-modeling",icon:"🏷",titleKey:"tpl.sk.domain",descKey:"tpl.sk.domain.desc",promptKey:"tpl.sk.domain.prompt"},{id:"grilling",icon:"🔥",titleKey:"tpl.sk.grilling",descKey:"tpl.sk.grilling.desc",promptKey:"tpl.sk.grilling.prompt"},{id:"tdd",icon:"🧪",titleKey:"tpl.sk.tdd",descKey:"tpl.sk.tdd.desc",promptKey:"tpl.sk.tdd.prompt"}],an="pi-web-ui:prompt-templates";function Ea(){try{const t=localStorage.getItem(an);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(i=>!!i&&typeof i=="object"&&typeof i.id=="string"):[]}catch{return[]}}function ks(t){return nn.some(s=>s.id===t)}function at(t){return typeof t.title=="string"}const rn=r.createContext(null);function ln(){const t=r.useContext(rn);if(!t)throw new Error("useTemplates must be used within TemplateProvider");return t}function Ma({send:t,children:s}){const i=pe(),[l,c]=r.useState(Ea),[a,n]=r.useState(!1),[o,u]=r.useState(null),[h,p]=r.useState(!1),[g,k]=r.useState(!1),[b,N]=r.useState(!1);r.useEffect(()=>{try{localStorage.setItem(an,JSON.stringify(l))}catch{}},[l]);const D=r.useMemo(()=>{const U=new Map,K=new Set;for(const y of l)y.hidden?K.add(y.id):(at(y)&&!ks(y.id)||at(y))&&U.set(y.id,y);const ie=nn.filter(y=>!K.has(y.id)).map(y=>{const $=U.get(y.id);return{id:y.id,icon:($==null?void 0:$.icon)??y.icon,title:($==null?void 0:$.title)??i(y.titleKey),desc:($==null?void 0:$.desc)??i(y.descKey),prompt:($==null?void 0:$.prompt)??i(y.promptKey),builtin:!0}}),x=l.filter(y=>at(y)&&!ks(y.id)).map(y=>({id:y.id,icon:y.icon??"📌",title:y.title??"",desc:y.desc??"",prompt:y.prompt??""}));return[...ie,...x]},[l,i]),w=r.useCallback(()=>n(!0),[]),_=r.useCallback(U=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:U}))},[]),v=r.useCallback((U,K=!1)=>{N(K),U?(p(!1),u({...U})):(p(!0),u({id:Be(),icon:"📌",title:"",desc:"",prompt:""}))},[]),j=r.useCallback(()=>{n(!1),u(null),N(!1)},[]),I=r.useCallback(()=>{g?(c([]),k(!1)):(k(!0),setTimeout(()=>k(!1),5e3))},[g]),A=r.useCallback(U=>{n(!1),_(U.prompt)},[_]),S=r.useCallback(U=>{n(!1),v(U,!0)},[v]),T=r.useCallback(()=>{n(!1),v(void 0,!0)},[v]),m=r.useCallback(U=>{c(K=>{const ie=K.findIndex(x=>x.id===U.id);if(ie>=0){const x=[...K];return x[ie]=U,x}return[...K,U]}),u(null),b&&(n(!0),N(!1))},[b]),B=r.useCallback(U=>{c(K=>U.builtin?[...K.filter(x=>x.id!==U.id),{id:U.id,hidden:!0}]:K.filter(ie=>ie.id!==U.id)),u(null),b&&(n(!0),N(!1))},[b]),O=r.useCallback(U=>{c(K=>K.filter(ie=>ie.id!==U.id||ie.hidden)),u(null),b&&(n(!0),N(!1))},[b]),Z=r.useMemo(()=>({templates:D,fill:_,openPicker:w,openEdit:v,resetConfirm:g,toggleReset:I}),[D,_,w,v,g,I]),Q=o?l.some(U=>U.id===o.id&&!U.hidden&&at(U)):!1;return e.jsxs(rn.Provider,{value:Z,children:[s,a&&e.jsx(Pa,{templates:D,resetConfirm:g,onFill:A,onEditTpl:S,onNew:T,onResetToggle:I,onClose:j}),o&&e.jsx(Ia,{editing:o,isNew:h,hasOverride:Q,onDraft:u,onSave:m,onRestore:()=>O(o),onRemove:()=>B(o),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:o.prompt})),j()},onSend:()=>{const U=o.prompt.trim();U&&t({type:"prompt",text:U,queue:!1})&&j()},onClose:j})]})}function Ra(){const t=pe(),{templates:s,fill:i,openEdit:l,toggleReset:c,resetConfirm:a}=ln();return e.jsxs("div",{className:"empty-templates",children:[e.jsxs("div",{className:"empty-templates-head",children:[e.jsx("span",{className:"empty-templates-title",children:t("tpl.title")}),e.jsx("span",{className:"empty-templates-hint",children:t("tpl.hint")})]}),e.jsxs("div",{className:"empty-templates-grid",children:[s.map(n=>e.jsx(on,{tpl:n,title:t("tpl.clickCard"),onFill:()=>i(n.prompt),onEdit:()=>l(n),editTitle:t("tpl.editTpl")},n.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>l(),title:t("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(_e,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:t("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"empty-templates-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:c,children:[e.jsx(_s,{}),t(a?"tpl.resetConfirm":"tpl.reset")]})})]})}function on({tpl:t,title:s,onFill:i,onEdit:l,editTitle:c}){const a=pe();return e.jsxs("button",{type:"button",className:"empty-template",title:s,onClick:i,children:[e.jsx("span",{className:"empty-template-icon",children:t.icon}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t.title}),e.jsx("span",{className:"empty-template-desc",children:t.desc})]}),e.jsx("span",{className:"template-card-ops",role:"button",title:c??a("tpl.editTpl"),onClick:n=>{n.stopPropagation(),l()},children:e.jsx(It,{})})]})}function Pa({templates:t,resetConfirm:s,onFill:i,onEditTpl:l,onNew:c,onResetToggle:a,onClose:n}){const o=pe();return r.useEffect(()=>{const u=h=>{h.key==="Escape"&&n()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n]),e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"modal template-picker",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"template-picker-head",children:[e.jsx("span",{className:"template-picker-title",children:o("tpl.pickerTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:o("close"),onClick:n,children:e.jsx(we,{})})]}),e.jsx("div",{className:"template-picker-hint",children:o("tpl.pickerHint")}),e.jsxs("div",{className:"template-picker-grid",children:[t.map(u=>e.jsx(on,{tpl:u,title:o("tpl.clickCard"),onFill:()=>i(u),onEdit:()=>l(u),editTitle:o("tpl.editTpl")},u.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:c,title:o("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(_e,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:o("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:o("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"template-picker-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:a,children:[e.jsx(_s,{}),o(s?"tpl.resetConfirm":"tpl.reset")]})})]})})}function Ia({editing:t,isNew:s,hasOverride:i,onDraft:l,onSave:c,onRestore:a,onRemove:n,onFill:o,onSend:u,onClose:h}){const p=pe(),g=r.useRef(null);r.useEffect(()=>{const N=D=>{D.key==="Escape"&&h()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[h]),r.useEffect(()=>{const N=g.current;if(!N)return;N.style.height="auto";const D=N.scrollHeight>300;N.style.height=`${Math.min(N.scrollHeight,300)}px`,N.style.overflowY=D?"auto":"hidden"},[t.prompt]);const k=()=>{const N=t.title.trim(),D=t.prompt.trim();if(!N||!D){l({...t,error:p("tpl.required")});return}c({id:t.id,icon:t.icon.trim()||"📌",title:N,desc:t.desc.trim(),prompt:D})},b=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:h,children:e.jsxs("div",{className:"modal template-modal",onClick:N=>N.stopPropagation(),children:[e.jsxs("div",{className:"template-modal-head",children:[e.jsx("span",{className:"template-modal-icon",children:t.icon}),e.jsx("span",{className:"template-modal-badge",children:p(b?"tpl.builtin":"tpl.custom")}),e.jsx("span",{className:"template-modal-title",children:p(s?"tpl.newTitle":"tpl.editTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:p("close"),onClick:h,children:e.jsx(we,{})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:p("tpl.fieldIcon")}),e.jsx("input",{className:"template-field-input icon",value:t.icon,maxLength:4,onChange:N=>l({...t,icon:N.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:p("tpl.fieldTitle")}),e.jsx("input",{className:"template-field-input",value:t.title,placeholder:p("tpl.fieldTitlePh"),onChange:N=>l({...t,title:N.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:p("tpl.fieldDesc")}),e.jsx("input",{className:"template-field-input",value:t.desc,placeholder:p("tpl.fieldDescPh"),onChange:N=>l({...t,desc:N.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:p("tpl.fieldPrompt")}),e.jsx("textarea",{ref:g,className:"template-field-prompt",value:t.prompt,placeholder:p("tpl.fieldPromptPh"),onChange:N=>l({...t,prompt:N.target.value})})]}),t.error&&e.jsx("div",{className:"template-error",children:t.error}),e.jsxs("div",{className:"template-modal-actions",children:[e.jsxs("div",{className:"template-modal-actions-left",children:[!s&&b&&i&&e.jsx("button",{type:"button",className:"btn template-btn ghost",title:p("tpl.restoreTip"),onClick:a,children:p("tpl.restore")}),!s&&b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:p("tpl.removeTip"),onClick:n,children:[e.jsx(Ie,{})," ",p("tpl.remove")]}),!s&&!b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:p("tpl.deleteTip"),onClick:n,children:[e.jsx(Ie,{})," ",p("tpl.delete")]})]}),e.jsxs("div",{className:"template-modal-actions-right",children:[e.jsx("button",{type:"button",className:"btn template-btn",onClick:k,children:p("tpl.save")}),e.jsx("button",{type:"button",className:"btn template-btn fill",onClick:o,title:p("tpl.fillTip"),children:p("tpl.fill")}),e.jsxs("button",{type:"button",className:"btn template-btn send",onClick:u,title:p("tpl.sendTip"),children:[e.jsx(As,{})," ",p("tpl.sendNow")]})]})]})]})})}const bs=new Map,La=15,js=30,St=250,ws=1200,Ba=1600;function Ns(t){return t.content.some(s=>s.type==="toolCall")}function Da({state:t,liveOutputs:s,toolStatuses:i,onEdit:l,onKillBash:c,thinkingWrap:a,toolsWrap:n,jumpTarget:o,onJumpDone:u}){const h=pe(),p=r.useRef(null),[g,k]=r.useState(!0),b=r.useRef(!0),N=r.useRef(0),D=r.useRef(0),w=r.useRef(!1),_=r.useRef(0),[v,j]=r.useState(()=>new Set),[I,A]=r.useState(!1),S=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,T=r.useMemo(()=>{const f=new Map;for(const E of t.messages)E.role==="toolResult"&&E.toolCallId&&f.set(E.toolCallId,E);return f},[t.messages]),m=r.useMemo(()=>ua(t.messages),[t.messages]),B=S.length>0?S[S.length-1].id:null,O=t.messages.length>js?Math.max(0,t.messages.length-La):0,[Z,Q]=r.useState(()=>new Set),[U,K]=r.useState(()=>new Set),ie=r.useRef(new Map),x=r.useRef(new Map),y=r.useRef(new Map),$=r.useRef(0),ge=r.useMemo(()=>{const f=new Map;for(const E of t.messages)f.set(E.id,ya(E));return f},[t.messages]),z=r.useRef(ge);z.current=ge;const P=r.useRef(Z);P.current=Z;const X=t.messages.length>js&&!I,V=r.useRef(X);V.current=X;const M=xa(t.messages,ie.current,Ba),F=r.useRef(M);F.current=M;const q=r.useCallback(()=>{const f=p.current;if(!f)return;if(!V.current){Q(he=>he.size?new Set:he);return}const E=f.getBoundingClientRect(),J={top:E.top-ws,bottom:E.bottom+ws},se=[];for(const[he,je]of y.current){const Re=je.getBoundingClientRect();se.push({id:he,top:Re.top,bottom:Re.bottom}),P.current.has(he)||oe(he,Re.bottom-Re.top,z.current.get(he))}const me=ga(se,J,F.current,P.current);for(const he of me.hide){const je=y.current.get(he);je&&oe(he,je.offsetHeight,z.current.get(he))}Q(he=>fa(he,me))},[]),te=r.useCallback(()=>{$.current||($.current=requestAnimationFrame(()=>{$.current=0,q()}))},[q]);r.useLayoutEffect(()=>{q()},[q]);const H=r.useRef(I);r.useLayoutEffect(()=>{H.current&&!I&&q(),H.current=I},[I,q]);const oe=r.useCallback((f,E,J)=>{J!==void 0&&(x.current.set(f,{h:E,len:J}),ie.current.set(f,E))},[]),re=r.useCallback((f,E)=>{oe(f,E,z.current.get(f))},[oe]),d=r.useCallback(f=>{f&&y.current.set(f.dataset.lazyId??"",f)},[]);r.useEffect(()=>{const f=new Set(t.messages.map(E=>E.id));for(const[E,J]of y.current)f.has(E)||(y.current.delete(E),ie.current.delete(E),x.current.delete(E));Q(E=>{let J=!1;const se=new Set;for(const me of E)f.has(me)?se.add(me):J=!0;return J?se:E})},[t.messages,v]),r.useEffect(()=>()=>cancelAnimationFrame($.current),[]);const R=r.useMemo(()=>{const f=[];for(const E of t.messages){if(E.role!=="user")continue;const J=E.content.map(he=>{var je;return((je=nt(he))==null?void 0:je.text)??""}).filter(Boolean).join(" "),se=qt(J),me=se?se.userMessage??`skill:${se.name}`:J.trim();me&&f.push({id:E.id,text:me})}return f},[t.messages]),le=r.useMemo(()=>{const f=new Map;return R.forEach((E,J)=>f.set(E.id,J)),f},[R]),[ee,fe]=r.useState(-1),Y=r.useRef(-1),de=r.useRef(R);r.useEffect(()=>{de.current=R},[R]);const xe=r.useCallback(()=>{const f=p.current,E=de.current;if(!f||E.length===0)return;const J=f.getBoundingClientRect().top,se=140;let me=-1;for(let he=0;he<E.length;he++){const je=f.querySelector(`[data-msg-id="${E[he].id}"]`);if(je)if(je.getBoundingClientRect().top<=J+se)me=he;else break}me!==Y.current&&(Y.current=me,fe(me))},[]);r.useEffect(()=>{xe()},[R,xe]);const ce=r.useCallback(f=>{j(E=>E.has(f)?E:new Set(E).add(f))},[]),Se=r.useCallback(f=>{const E=t.messages.findIndex(J=>J.id===f);E>=0&&E<O&&!v.has(f)&&ms.flushSync(()=>ce(f))},[t.messages,O,v,ce]);r.useEffect(()=>{const f=E=>{if(!(E.ctrlKey||E.metaKey)||E.key.toLowerCase()!=="f")return;const J=E.target;J&&(J.tagName==="INPUT"||J.tagName==="TEXTAREA"||J.isContentEditable)||(E.preventDefault(),A(!0))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[]);const Je=r.useCallback(f=>{j(E=>{if(!E.has(f))return E;const J=new Set(E);return J.delete(f),J})},[]),Te=r.useCallback(f=>{const E=t.messages.findIndex(se=>se.id===f);ms.flushSync(()=>{E>=0&&E<O&&!v.has(f)&&ce(f),K(se=>se.has(f)?se:new Set(se).add(f))});const J=de.current.findIndex(se=>se.id===f);Y.current=J,fe(J),requestAnimationFrame(()=>{var me,he,je;const se=(me=p.current)==null?void 0:me.querySelector(`[data-msg-id="${f}"]`);se&&((he=p.current)==null||he.querySelectorAll(".msg-flash").forEach(Re=>Re.classList.remove("msg-flash")),se.scrollIntoView({block:"start"}),se.classList.remove("msg-flash"),se.offsetWidth,se.classList.add("msg-flash"),se!==((je=p.current)==null?void 0:je.lastElementChild)&&(w.current=!0))})},[t.messages,O,v,ce]),Ee=r.useMemo(()=>{var f;return o?((f=t.messages.find(E=>E.role===o.role&&E.timestamp===o.timestamp))==null?void 0:f.id)??null:null},[t.messages,o]);r.useEffect(()=>{if(o){if(Ee){Te(Ee),u==null||u();return}t.sessionFile===o.path&&t.messages.length>0&&(u==null||u())}},[Ee,Te,u,o,t.sessionFile,t.messages.length]);const Qe=r.useCallback(()=>{const f=p.current;if(!f)return;const E=f.scrollTop-N.current,J=f.scrollHeight-D.current;N.current=f.scrollTop,D.current=f.scrollHeight;const se=f.scrollHeight-f.scrollTop-f.clientHeight<80,me=Date.now()<_.current,he=Ta({dSt:E,dSh:J,escaped:w.current,graceActive:me,stuck:b.current});he.reassert&&(_.current=Date.now()+St,f.scrollTop=f.scrollHeight),he.flipEscape&&(w.current=!0),se&&E>=0&&(w.current=!1),me||(E<0?b.current=se&&!w.current:se&&(b.current=!0)),k(b.current),xe(),te()},[xe,te]),Me=r.useRef(!1);r.useEffect(()=>{const f=Me.current;if(Me.current=!!t.isStreaming,f&&!t.isStreaming&&!w.current){const E=()=>{const se=p.current;se&&!w.current&&(se.scrollTop=se.scrollHeight,b.current=!0,k(!0))};requestAnimationFrame(()=>requestAnimationFrame(E));const J=setTimeout(E,180);return()=>clearTimeout(J)}},[t.isStreaming]),r.useEffect(()=>{const f=p.current;f&&b.current&&(f.scrollTop=f.scrollHeight)},[S,t.isStreaming,s]);const Xe=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");r.useEffect(()=>{const f=p.current;f&&b.current&&(f.scrollTop=f.scrollHeight)},[Xe]),r.useEffect(()=>{const f=p.current;if(!f||typeof ResizeObserver>"u")return;const E=new ResizeObserver(()=>{b.current&&!w.current&&(f.scrollTop=f.scrollHeight,k(!0))});return E.observe(f),()=>E.disconnect()},[]),r.useEffect(()=>{const f=p.current;if(!f||typeof MutationObserver>"u")return;let E=!1;const J=new MutationObserver(()=>{E||(E=!0,requestAnimationFrame(()=>{E=!1;const se=p.current;se&&b.current&&!w.current&&(se.scrollTop=se.scrollHeight,k(!0))}))});return J.observe(f,{childList:!0,subtree:!0,characterData:!0}),()=>J.disconnect()},[]);const Fe=r.useCallback(()=>{if(!p.current)return;b.current=!0,w.current=!1,k(!0),_.current=Date.now()+St;const E=()=>{const J=p.current;!J||!b.current||w.current||(_.current=Date.now()+St,J.scrollTop=J.scrollHeight)};E(),requestAnimationFrame(()=>requestAnimationFrame(E)),setTimeout(E,120),setTimeout(E,300),setTimeout(E,600)},[]),$e=r.useRef(null);r.useEffect(()=>{const f=$e.current,E=p.current;if(!f||!E)return;const J=se=>{se.preventDefault();const me=f.querySelector(".qn-list");if(me&&me.contains(se.target)&&me.scrollHeight>me.clientHeight){me.scrollTop+=se.deltaY;return}E.scrollTop+=se.deltaY};return f.addEventListener("wheel",J,{passive:!1}),()=>f.removeEventListener("wheel",J)},[]);const[Oe,C]=r.useState(0);r.useEffect(()=>{const f=()=>{var E;C(((E=p.current)==null?void 0:E.clientHeight)??0),te()};return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[te]);const ue=R.length,ae=r.useMemo(()=>ue===0?27:Math.max(4,Math.min(27,Math.floor(((Oe||600)-16)/ue)-3)),[ue,Oe]),ye=ae<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:`messages${g?"":" anchor-live"}`,ref:p,onScroll:Qe,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(Ra,{})}),t.messages.map((f,E)=>{const J=E<O,se=J&&v.has(f.id);if(J&&!se)return f.role==="toolResult"?null:e.jsx(pa,{message:f,onExpand:ce},f.id);const me=f.role==="user"?le.get(f.id):void 0,he=!X||M.has(f.id)||U.has(f.id)||!Z.has(f.id);return e.jsx(ha,{id:f.id,show:he,height:ka(f.id,ge.get(f.id)??-1,x.current,sn(f.role,f.customType)),containerRef:p,onMeasured:re,lazyRef:d,children:e.jsx(fs,{message:f,qnIndex:me,qnActive:me!==void 0?me===ee:void 0,onJump:Te,toolResults:T,liveOutputs:Ns(f)?s:bs,toolStatuses:i,streaming:t.isStreaming,onKillBash:c,toolsWrap:n,thinkingWrap:a,isLast:f.id===B,onEdit:l,questionAttachments:m.get(f.id),onCollapse:se?Je:void 0},f.id)},f.id)}),t.streamingMessage&&e.jsx(fs,{message:t.streamingMessage,toolResults:T,liveOutputs:Ns(t.streamingMessage)?s:bs,toolStatuses:i,streaming:!0,isLast:!0,onEdit:l,onKillBash:c,toolsWrap:n,thinkingWrap:a},t.streamingMessage.id),t.isStreaming&&S.length===0&&e.jsx("div",{className:"streaming-wait",children:h("waitingResponse")}),t.queue.steering.map((f,E)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:h("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:f})]})},`q-steer-${E}`)),t.queue.followUp.map((f,E)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:h("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:f})]})},`q-fu-${E}`))]}),!g&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Fe,children:[e.jsx(Ws,{})," ",h("backToBottom")]}),e.jsx(Sa,{containerRef:p,messages:S,open:I,onClose:()=>A(!1),onEnsureExpanded:Se}),R.length>0&&e.jsxs("div",{className:`qn-rail ${ye?"many":""}`,ref:$e,"aria-label":h("questionNavTitle"),style:{"--rail-gap":`${ae}px`},children:[R.map((f,E)=>e.jsx("button",{type:"button",className:`qn-bar ${E===ee?"active":""}`,"aria-label":`${E+1}. ${f.text}`,onClick:()=>Te(f.id),children:e.jsxs("span",{className:"qn-bar-text",children:[E+1,". ",f.text]})},f.id)),ye&&e.jsx("div",{className:"qn-list",children:R.map((f,E)=>e.jsxs("button",{type:"button",className:`qn-list-item ${E===ee?"active":""}`,"aria-label":`${E+1}. ${f.text}`,onClick:()=>Te(f.id),children:[e.jsx("span",{className:"qn-list-idx",children:E+1}),e.jsx("span",{className:"qn-list-text",children:f.text})]},f.id))})]})]})}const cn="pi-web-model-usage";function Aa(t){if(!t||typeof t!="object")return{};const s={};for(const[i,l]of Object.entries(t)){const c=typeof l=="number"?Math.floor(l):0;Number.isFinite(c)&&c>0&&(s[i]=c)}return s}function _a(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function Fa(t,s){const i=s;return t.map((l,c)=>({m:l,i:c,count:i[l.id]??0})).sort((l,c)=>c.count-l.count||l.i-c.i).map(l=>l.m)}function dn(){try{const t=localStorage.getItem(cn);return t?Aa(JSON.parse(t)):{}}catch{return{}}}function $a(t){try{localStorage.setItem(cn,JSON.stringify(t))}catch{}}function Oa(t){const s=_a(dn(),t);return $a(s),s}const Wa=["off","minimal","low","medium","high","xhigh","max"],qa=r.memo(function({state:s,models:i,modelsLoading:l,send:c,onManageModels:a,compact:n=!1}){const o=pe(),u=s==null?void 0:s.model,h=u?`${u.provider}/${u.id}`:null,[p,g]=r.useState(!1),[k,b]=r.useState(!1),[N,D]=r.useState(""),[w,_]=r.useState(null),[v,j]=r.useState({}),I=r.useRef(null),A=r.useRef(null),[S,T]=r.useState(null);r.useEffect(()=>{if(!p){T(null);return}if(i.length===0)return;const x=requestAnimationFrame(()=>{const y=A.current;y&&T(y.offsetWidth)});return()=>cancelAnimationFrame(x)},[p,i.length]),r.useEffect(()=>{p&&j(dn())},[p]),r.useEffect(()=>{p||(D(""),_(null))},[p]);const m=r.useMemo(()=>{const x=new Map;for(const y of i)x.set(y.provider,(x.get(y.provider)??0)+1);return[...x.entries()].sort((y,$)=>y[0].localeCompare($[0])).map(([y,$])=>({name:y,count:$}))},[i]),B=r.useMemo(()=>Fa(i,v),[i,v]),O=r.useMemo(()=>{let x=B;w&&(x=x.filter($=>$.provider===w));const y=N.trim().toLowerCase();return y?x.filter($=>$.name.toLowerCase().includes(y)||$.provider.toLowerCase().includes(y)||$.id.toLowerCase().includes(y)):x},[B,N,w]),[Z,Q]=r.useState(!1),U=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,K=Wa.map(x=>({value:x,label:o(`thinking.${x}`),supported:U?U.has(x):!0})),ie=x=>{var y;return((y=K.find($=>$.value===x))==null?void 0:y.label)??x};return r.useEffect(()=>{p&&i.length===0&&!Z&&!l&&(Q(!0),c({type:"list_models"}))},[p,i.length,Z,l,c]),r.useEffect(()=>{i.length>0&&Q(!1)},[i.length]),r.useEffect(()=>{var y;if(!p)return;const x=(y=I.current)==null?void 0:y.querySelector(".dd-item.active");x==null||x.scrollIntoView({block:"nearest"})},[p,h,i.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(st,{}),e.jsx("span",{className:"chip-model",children:u?u.name:o("selectModel")}),!n&&(u==null?void 0:u.vision)&&e.jsx("span",{className:"chip-vision",title:o("vision"),children:"🖼"}),!n&&u&&e.jsx("span",{className:"chip-sub",children:u.provider})]}),open:p,onOpenChange:g,menuClassName:"dd-menu-model",menuRef:A,menuStyle:S!=null?{width:S}:void 0,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(mt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:o("searchModels"),value:N,onChange:x=>D(x.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[m.length>1&&e.jsxs("div",{className:"dd-provider-col",children:[e.jsx("div",{className:"dd-provider-head",children:o("providers")}),e.jsx("button",{type:"button",className:`dd-provider-item ${w===null?"active":""}`,onClick:()=>_(null),children:e.jsx("span",{children:o("allProviders")})}),m.map(x=>e.jsxs("button",{type:"button",className:`dd-provider-item ${w===x.name?"active":""}`,onClick:()=>_(w===x.name?null:x.name),title:`${x.name} · ${x.count}`,children:[e.jsx("span",{className:"dd-provider-name",children:x.name}),e.jsx("span",{className:"dd-provider-count",children:x.count})]},x.name))]}),e.jsxs("div",{className:"dd-model-scroll",ref:I,children:[(Z||l)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),i.length===0&&!Z&&!l&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),O.length===0&&i.length>0&&e.jsx("div",{className:"dd-loading",children:o("noModelMatches")}),O.map(x=>e.jsx(Ne,{active:h===x.id,onClick:()=>{h!==x.id&&c({type:"set_model",modelId:x.id}),g(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:x.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:x.provider}),(v[x.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:o("modelUsedCount",{n:v[x.id]})}),(x.reasoning||x.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[x.reasoning&&e.jsx("span",{className:"dd-model-badge",children:o("reasoning")}),x.vision&&e.jsx("span",{className:"dd-model-badge",children:o("vision")})]})]})]})},x.id))]})]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>c({type:"list_models"}),children:o("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{g(!1),a()},children:o("manageModels")})]})]}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(rt,{}),e.jsx("span",{className:"chip-sub",children:o("thinkingChip",{level:s?ie(s.thinkingLevel):"—"})})]}),open:k,onOpenChange:b,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("thinkingLevel")}),K.map(x=>e.jsx(Ne,{active:(s==null?void 0:s.thinkingLevel)===x.value,disabled:!x.supported,title:x.supported?void 0:o("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==x.value&&c({type:"set_thinking",level:x.value}),b(!1)},children:x.label},x.value))]})]})}),Ua=r.memo(function({ready:s,streaming:i,messages:l,slashCommands:c,modelState:a,models:n,modelsLoading:o,send:u,attachments:h,onRemoveAttachment:p,onAddImageFiles:g,onAddLocalFiles:k,onNotice:b,onSent:N,onManageModels:D}){const w=pe(),{locale:_}=Ot(),{openPicker:v}=ln(),j=d=>_==="en"&&d.descriptionEn?d.descriptionEn:d.description??"",I=d=>_==="en"&&d.argumentHintEn?d.argumentHintEn:d.argumentHint??"",[A,S]=r.useState(""),[T,m]=r.useState(!1),[B,O]=r.useState(null),[Z,Q]=r.useState(0),[U,K]=r.useState(!1),[ie,x]=r.useState(void 0),y=r.useRef(null),$=r.useRef(null),ge=r.useRef(null),z={builtin:w("slashBuiltin"),extension:w("slashExtension"),prompt:w("slashPrompt"),skill:w("slashSkill"),plugin:w("slashPlugin")},P=d=>{const R=d.match(/^\/([^\s]*)$/);if(R&&s){const le=R[1].toLowerCase(),ee=c.filter(fe=>fe.name.toLowerCase().startsWith(le));O(ee.length>0?ee:null),Q(0)}else O(null)};r.useEffect(()=>{var R;const d=(R=ge.current)==null?void 0:R.querySelector(".slash-item.active");d==null||d.scrollIntoView({block:"nearest"})},[Z,B]);const X=d=>{var Y;const R=B??[],le=d??R[Z%Math.max(R.length,1)];if(!le){O(null);return}const ee=A.match(/^\/([^\s]*)([\s\S]*)$/),fe=ee?ee[2]:"";S(`/${le.name} ${fe}`),O(null),(Y=y.current)==null||Y.focus()},V=async()=>{const R=[...l].reverse().find(ee=>ee.role==="assistant"&&ee.content.some(fe=>fe.type==="text"&&fe.text)),le=R==null?void 0:R.content.filter(ee=>ee.type==="text").map(ee=>ee.text).join(`
|
|
318
|
+
`);if(!le){b("warning",w("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(le),b("info",w("slashCopied"))}catch{b("error",w("slashCopyFailed"))}},M=d=>{if(!d||d.length===0){b("warning",w("foldersNotSupported"));return}const R=Array.from(d).filter(ee=>Le(ee.type)),le=Array.from(d).filter(ee=>!Le(ee.type));R.length>0&&g(R),le.length>0&&k(le)},F=d=>{var ee;const R=(ee=d.clipboardData)==null?void 0:ee.items;if(!R)return;const le=[];for(const fe of R)if(fe.kind==="file"&&Le(fe.type)){const Y=fe.getAsFile();Y&&le.push(Y)}le.length!==0&&(d.preventDefault(),g(le))},q=s,te=r.useRef(A);r.useEffect(()=>{te.current=A},[A]),r.useEffect(()=>{P(te.current)},[c]),r.useEffect(()=>{const d=R=>{var ee;const le=R.detail;S(le),(ee=y.current)==null||ee.focus()};return window.addEventListener("pi-web:fill",d),()=>window.removeEventListener("pi-web:fill",d)},[]),r.useEffect(()=>{if(!U)return;const d=R=>{R.key==="Escape"&&K(!1)};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[U]),r.useEffect(()=>{const d=y.current;if(!d)return;d.style.height="auto";const R=d.scrollHeight>220;d.style.height=`${Math.min(d.scrollHeight,220)}px`,d.style.overflowY=R?"auto":"hidden"},[A]);const H=(d=!1)=>{var ee,fe,Y,de,xe;const R=A.trim(),le=h.some(ce=>ce.imageData||ce.fileData);if(!(!q||!R&&!le)){if(R==="/help"){const ce=(fe=(ee=y.current)==null?void 0:ee.closest(".inputbox"))==null?void 0:fe.getBoundingClientRect();x(ce==null?void 0:ce.width),K(!0),S(""),(Y=y.current)==null||Y.focus();return}if(R==="/copy"){S(""),(de=y.current)==null||de.focus(),V();return}if(u({type:"prompt",text:R,queue:d,attachments:h.map(ce=>ce.imageData?{path:"",imageData:ce.imageData,mimeType:ce.mimeType,name:ce.name}:ce.fileData?{path:"",fileData:ce.fileData,mimeType:ce.mimeType,name:ce.name,size:ce.size}:{path:ce.path,mode:ce.mode,...ce.lines?{lines:ce.lines}:{}})})){S(""),N();const ce=a==null?void 0:a.model;ce&&Oa(`${ce.provider}/${ce.id}`),(xe=y.current)==null||xe.focus()}}},oe=d=>{if(!d.nativeEvent.isComposing){if(B&&B.length>0)switch(d.key){case"ArrowDown":d.preventDefault(),Q(R=>(R+1)%B.length);return;case"ArrowUp":d.preventDefault(),Q(R=>(R-1+B.length)%B.length);return;case"Tab":case"Enter":d.preventDefault(),X();return;case"Escape":d.preventDefault(),O(null);return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),H())}},re=()=>e.jsx("div",{className:"inputbox-actions",children:i?e.jsxs(e.Fragment,{children:[A.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:w("supplementTip"),onClick:()=>H(!0),children:[e.jsx(As,{})," ",w("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:w("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(ut,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:w("sendTip"),disabled:!q||!A.trim()&&!h.some(d=>d.imageData||d.fileData),onClick:()=>H(),children:e.jsx(Os,{})})});return e.jsxs("div",{className:`inputbar${T?" drop-active":""}`,onDragOver:d=>{d.preventDefault(),d.stopPropagation(),m(!0)},onDragLeave:d=>{d.currentTarget.contains(d.relatedTarget)||m(!1)},onDrop:d=>{var R;d.preventDefault(),d.stopPropagation(),m(!1),M(((R=d.dataTransfer)==null?void 0:R.files)??null)},children:[T&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",w("dropHereToAttach")]})}),h.length>0&&e.jsxs("div",{className:"attach-row",children:[h.map(d=>e.jsxs("span",{className:`attach-chip ${d.imageData?"image":d.fileData?"file":d.mode}`,title:d.imageData?w("attachImage",{name:d.name}):d.fileData?w("attachFile",{name:d.name}):d.isDir?w("folderRef",{path:d.path}):d.mode==="reference"?w("refOnly",{path:d.path}):d.mode==="lines"&&d.lines?w("attachLines",{path:d.path,start:d.lines.start,end:d.lines.end}):w("attachContent",{path:d.path}),children:[d.imageData?"🖼":d.fileData?"📄":d.isDir?"📁":d.mode==="reference"?"🔗":"📎"," ",d.name,d.mode==="lines"&&d.lines&&e.jsxs("span",{className:"attach-range",children:["L",d.lines.start,"-",d.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:w("removeAttachment"),onClick:()=>p(d.key??d.path),children:"×"})]},d.key??`${d.path}|${d.mode}|${d.lines?`${d.lines.start}-${d.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:w("attachHint")})]}),B&&B.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:ge,"aria-label":w("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:w("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>O(null),children:"Esc"})]}),B.map((d,R)=>e.jsxs("button",{type:"button",className:`slash-item${R===Z?" active":""}`,onMouseEnter:()=>Q(R),onClick:()=>X(d),children:[e.jsxs("span",{className:"slash-name",children:["/",d.name]}),e.jsx("span",{className:`slash-source ${d.source}`,children:z[d.source]}),e.jsxs("span",{className:"slash-desc",children:[j(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(d)})]})]},d.name))]}),U&&e.jsx("div",{className:"modal-backdrop",onClick:()=>K(!1),children:e.jsxs("div",{className:"slash-help",style:ie?{width:ie}:void 0,onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",w("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>K(!1),children:w("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:w("slashLoading")}):c.map(d=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",d.name]}),e.jsx("span",{className:`slash-source ${d.source}`,children:z[d.source]}),e.jsxs("span",{className:"slash-help-desc",children:[j(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(d)})]})]},d.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:$,type:"file",multiple:!0,hidden:!0,onChange:d=>{M(d.target.files),d.target.value=""}}),e.jsx("textarea",{ref:y,value:A,rows:1,placeholder:w(q?i?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!q,onChange:d=>{S(d.target.value),P(d.target.value)},onKeyDown:oe,onPaste:F}),e.jsxs("div",{className:"composer-tools",children:[e.jsxs("div",{className:"composer-tools-left",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:w("uploadFile"),disabled:!q,onClick:()=>{var d;return(d=$.current)==null?void 0:d.click()},children:e.jsx(On,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:w("tpl.openPicker"),onClick:v,children:e.jsx(Jn,{})}),e.jsx(qa,{state:a,models:n,modelsLoading:o,send:u,onManageModels:D,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:re()})]})]})]})}),Ha=r.memo(function({goal:s,models:i,modelsLoading:l,activeConversationId:c,send:a}){var Z,Q,U,K,ie,x;const n=pe(),o=!s.conversationId||s.conversationId===c,u=s.goal!==null&&o,[h,p]=r.useState(""),[g,k]=r.useState(s.reviewModel??""),[b,N]=r.useState(s.maxRounds),[D,w]=r.useState(s.locked),[_,v]=r.useState(!1),[j,I]=r.useState(!1),[A,S]=r.useState(!0);r.useEffect(()=>{k(s.reviewModel??""),N(s.maxRounds||0),w(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),r.useEffect(()=>{_&&i.length===0&&!j&&!l&&(I(!0),a({type:"list_models"}))},[_,i.length,j,l,a]),r.useEffect(()=>{i.length>0&&I(!1)},[i.length]);const T=()=>{var y;return g?((y=i.find($=>$.id===g))==null?void 0:y.name)??g:n("goalBarUseMainModel")},m=()=>{const y=h.trim();y&&(a({type:"set_goal",goal:y,...g?{reviewModel:g}:{},maxRounds:b,locked:D}),p(""),S(!1))},B=()=>{const y=h.trim();y&&(a({type:"start_goal_wizard",text:y,...g?{wizardModel:g}:{},maxRounds:b,locked:D}),p(""),S(!1))},O=(((Z=s.wizard)==null?void 0:Z.active)??!1)&&o;return O?e.jsx("div",{className:`goalbar goalbar-active ${O?"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:((Q=s.wizard)==null?void 0:Q.draft)??"",children:[n("goalWizardRunning"),": ",(U=s.wizard)==null?void 0:U.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[n("goalBarRound",{n:(((K=s.wizard)==null?void 0:K.step)??0)+1})," ","/ ",((ie=s.wizard)==null?void 0:ie.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((x=s.wizard)==null?void 0:x.status)||n("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:n("goalBarClear"),onClick:()=>{a({type:"clear_goal"}),S(!0)},children:e.jsx(we,{})})]})}):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:[n("goalBarReviewing")," ",n("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?n("goalBarPassed"):s.verdict==="fail"?n("goalBarFailed"):`${n("goalBarRound",{n:s.round||1})} · ${s.locked?n("goalBarLocked"):n("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:s.status}),e.jsx("button",{type:"button",className:"goalbar-x",title:n("goalBarClear"),disabled:s.reviewing,onClick:()=>{a({type:"clear_goal"}),S(!0)},children:e.jsx(we,{})})]})}):A?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:n("goalBarPlaceholder"),onClick:()=>S(!1),children:[e.jsx(ss,{})," ",e.jsx("span",{children:n("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx(ss,{})}),e.jsx("input",{className:"goalbar-input",value:h,placeholder:n("goalBarPlaceholder"),onChange:y=>p(y.target.value),onKeyDown:y=>{y.key==="Enter"&&m()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!h.trim(),onClick:m,children:n("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!h.trim(),title:n("goalWizardTip"),onClick:B,children:["🔍 ",n("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n(D?"goalBarLocked":"goalBarUnlocked"),onClick:()=>w(y=>(a({type:"set_goal_prefs",locked:!y}),!y)),children:D?e.jsx(zn,{}):e.jsx(An,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n("goalBarClear"),onClick:()=>S(!0),children:e.jsx(ft,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[e.jsxs(Ae,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[n("goalBarReviewModel"),": ",e.jsx("b",{children:T()})]}),open:_,onOpenChange:v,direction:"up",children:[e.jsx("div",{className:"dd-header",children:n("goalBarReviewModel")}),(j||l)&&e.jsx("div",{className:"dd-loading",children:n("loading")}),i.length===0&&!j&&!l&&e.jsx("div",{className:"dd-loading",children:n("noModels")}),e.jsx(Ne,{active:g==="",onClick:()=>{k(""),v(!1),a({type:"set_goal_prefs",reviewModel:""})},children:n("goalBarUseMainModel")}),i.map(y=>e.jsx(Ne,{active:g===y.id,onClick:()=>{k(y.id),v(!1),a({type:"set_goal_prefs",reviewModel:y.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:y.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:y.provider})})]})},y.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>a({type:"list_models"}),children:n("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:n("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:n("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:b,placeholder:n("goalBarUnlimitedShort"),onChange:y=>{const $=parseInt(y.target.value,10);if(Number.isNaN($)||$<0){N(0);return}N($)},onBlur:()=>a({type:"set_goal_prefs",maxRounds:b}),onKeyDown:y=>{y.key==="Enter"&&(a({type:"set_goal_prefs",maxRounds:b}),y.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:n(D?"goalBarLocked":"goalBarUnlocked")})]})]})});function Ka({chat:t,send:s}){const i=pe(),l=t.state,[c,a]=r.useState(!1),[n,o]=r.useState(""),[u,h]=r.useState(0),p=r.useRef(null),g=t.pathCompletions;if(r.useEffect(()=>{if(!c)return;const m=setTimeout(()=>{s({type:"complete_path",path:n})},150);return()=>clearTimeout(m)},[n,c,s]),r.useEffect(()=>h(0),[g]),r.useEffect(()=>{const m=document.querySelector(`.status-completions .pc-item[data-idx="${u}"]`);m==null||m.scrollIntoView({block:"nearest"})},[u]),!l)return null;const k=l.stats,b=t.ready?"ok":"busy",N=t.ready?i("connected"):i("connecting"),D=k.contextUsage,w=D.tokens!==null&&D.percent!==null?`${Cs(D.tokens)} / ${Cs(D.contextWindow)}`:"—",_=D.percent??null,v=_===null?"":_>=80?"warn":_>=50?"mid":"ok",j=l.queue.steering.length+l.queue.followUp.length,I=()=>{o(l.cwd),a(!0)},A=(m,B)=>{var Z;const O=m.includes("\\")?"\\":"/";o(B?`${m}${O}`:m),h(0),(Z=p.current)==null||Z.focus()},S=m=>{const B=m.trim();B&&B!==l.cwd&&s({type:"set_cwd",path:B}),a(!1)},T=m=>{if(m.key==="ArrowDown")m.preventDefault(),h(B=>Math.min(B+1,g.length-1));else if(m.key==="ArrowUp")m.preventDefault(),h(B=>Math.max(B-1,0));else if(m.key==="Tab"&&g.length>0){m.preventDefault();const B=g[Math.min(u,g.length-1)];A(B.path,B.type==="dir")}else if(m.key==="Enter"&&!m.nativeEvent.isComposing){const B=n.trim();if(B.endsWith("/")||B.endsWith("\\"))S(B);else if(g.some(O=>O.path===B))S(B);else if(g.length>0&&g[u]){m.preventDefault();const O=g[u];A(O.path,O.type==="dir")}else S(B)}else m.key==="Escape"&&(g.length>0?(m.stopPropagation(),s({type:"complete_path",path:""})):a(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${b}`,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:i("contextUsage"),children:[i("context"),e.jsx("span",{className:`ctx-bar ${v}`,children:_!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(_,100)}%`}})}),w]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:i("cumulativeCost"),children:["$",za(k.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:i("sessionMessages"),children:[i("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:i("pluginStatus"),children:t.statuses.map(m=>m.text).join(" · ")})]}),l.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"}),i("working"),j>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",j," ",i("queued")]})]})]}),c?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:p,className:"status-cwd-input",value:n,autoFocus:!0,placeholder:i("enterPath"),onChange:m=>o(m.target.value),onKeyDown:T,onBlur:()=>a(!1)}),g.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:m=>m.preventDefault(),children:g.map((m,B)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":B,className:`pc-item ${B===u?"sel":""}`,onMouseEnter:()=>h(B),onClick:()=>A(m.path,m.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:m.type==="dir"?e.jsx(Ge,{}):e.jsx(Fs,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:m.name}),e.jsx("span",{className:"pc-path",children:m.path})]})]})},m.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:i("cwdTip",{path:l.cwd}),onClick:I,children:["📁 ",l.cwd]})]})}function Cs(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function za(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function Va({dialog:t,send:s}){const i=pe(),[l,c]=r.useState(""),[a,n]=r.useState(0),o=p=>{s({type:"dialog_response",id:t.id,value:p})};r.useEffect(()=>{c(""),n(0);const p=g=>{g.key==="Escape"&&o(null)};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[t.id]);const u=Array.isArray(t.args[0])?t.args[0]:[],h=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:i("pluginRequest")}),t.title&&t.title!==i("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:i("cancel"),onClick:()=>o(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[u.map((p,g)=>e.jsx("button",{type:"button",className:`dialog-option ${g===a?"sel":""}`,onMouseEnter:()=>n(g),onClick:()=>o(p),children:p},g)),u.length===0&&e.jsx("div",{className:"dialog-hint",children:i("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:h}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(!1),children:i("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(!0),children:i("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:l,placeholder:h||i("inputPlaceholder"),autoFocus:!0,onChange:p=>c(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.nativeEvent.isComposing&&o(l)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(null),children:i("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(l),children:i("ok")})]})]})]})}function Ga(t){if(t.x==="?"&&t.y==="?")return"untracked";const s=t.x!==" "&&t.x!=="?",i=t.y!==" "&&t.y!=="?";return s&&i?"both":s?"staged":"unstaged"}function Ya({chat:t,send:s,terminal:i,active:l,onSwitchToTerminal:c}){var $e,Oe;const a=pe(),[n,o]=r.useState(null),[u,h]=r.useState([]),[p,g]=r.useState(""),[k,b]=r.useState(new Map),[N,D]=r.useState("changes"),[w,_]=r.useState([]),[v,j]=r.useState(null),[I,A]=r.useState(""),[S,T]=r.useState(!1),[m,B]=r.useState(null),[O,Z]=r.useState(null),[Q,U]=r.useState(!1),[K,ie]=r.useState(!1),[x,y]=r.useState(!1),[$,ge]=r.useState(null),[z,P]=r.useState(!1),[X,V]=r.useState(""),M=r.useRef(0),F=r.useRef(-1),q=r.useRef(-1),te=r.useRef(-1),H=r.useRef(-1),oe=r.useRef(void 0),re=r.useRef(null),d=r.useRef([]),R=r.useCallback(C=>{if(C.reqId===F.current){if(F.current=-1,ie(!1),ge(null),!C.ok){ge(C.error??"查询失败");return}if(C.notRepo){P(!0),o(null),h([]),b(new Map),_([]),j(null),A(""),Z(null);return}P(!1);const ue={branch:C.branch??"",detached:!!C.detached,upstream:C.upstream??null,ahead:C.ahead??0,behind:C.behind??0,upstreamGone:!!C.upstreamGone,files:(C.files??[]).map(f=>({...f}))},ae=(C.branches??[]).map(f=>({...f})),ye=new Map;for(const[f,E]of Object.entries(C.stats??{}))ye.set(f,{add:E[0],del:E[1]});o(ue),h(ae),b(ye),g(f=>{var E;return ue.detached?f||"":ue.branch&&ae.some(J=>J.name===ue.branch)?ue.branch:f&&ae.some(J=>J.name===f)?f:((E=ae[0])==null?void 0:E.name)??""}),Z(f=>f&&!ue.files.some(E=>E.path===f.file.path)?null:f)}else if(C.reqId===q.current){if(q.current=-1,U(!1),!C.ok){ge(C.error??"查询失败");return}const ue=re.current;if(!ue)return;Z({file:ue,staged:C.stagedText??"",worktree:C.worktreeText??"",untracked:!1})}else if(C.reqId===H.current){if(H.current=-1,y(!1),!C.ok){ge(C.error??"查询失败");return}_((C.history??[]).map(ue=>({...ue})))}else if(C.reqId===te.current){if(te.current=-1,T(!1),!C.ok){ge(C.error??"查询失败");return}A(C.text??"")}},[]);r.useEffect(()=>{const C=t.scmData;C&&C.type==="scm_data"&&R(C)},[t.scmData,R]);const le=r.useCallback((C,ue)=>{if(!t.ready||t.status!=="open")return!1;const ae=++M.current;return s({...C,reqId:ae})?(ue.current=ae,!0):(M.current-=1,!1)},[t.ready,t.status,s]),ee=r.useCallback((C=!1,ue=!1)=>{var ae;!t.ready||t.status!=="open"||(ae=t.state)!=null&&ae.cwd&&(oe.current!==void 0&&oe.current!==t.state.cwd&&(o(null),h([]),b(new Map),_([]),y(!1),H.current=-1,j(null),A(""),Z(null),B(null)),oe.current=t.state.cwd,ge(null),le({type:"scm_status"},F)&&(ue||ie(!0)))},[t.ready,($e=t.state)==null?void 0:$e.cwd,t.status,le]),fe=r.useCallback(C=>{if(B(C),j(null),re.current=C,C.x==="?"&&C.y==="?"){Z({file:C,staged:"",worktree:"",untracked:!0});return}U(!0),ge(null),le({type:"scm_filediff",path:C.path},q)||U(!1)},[le]),Y=r.useCallback(C=>{j(C),B(null),Z(null),A(""),T(!0),ge(null),le({type:"scm_commit",hash:C.hash},te)||T(!1)},[le]),de=r.useCallback((C,ue)=>{var f,E;if(!t.ready)return;const ae={name:C,command:ue,cwd:"${pwd}"},ye=t.terminals.find(J=>J.title===C);if(ye)i.restart(ye.id),s({type:"run_command",terminalId:ye.id,conversationId:ye.conversationId,command:ae,cols:80,rows:24});else{const J=Be();i.create({id:J,conversationId:t.activeConversationId||((f=t.state)==null?void 0:f.conversationId)||"",title:C,cwd:((E=t.state)==null?void 0:E.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:ae})}c()},[t.ready,(Oe=t.state)==null?void 0:Oe.cwd,t.terminals,c,s,i]),xe=r.useCallback(()=>{const C=X.trim();if(!C||z)return;const ue=C.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");de("git commit",`git add -A && git commit -m "${ue}"`),V("")},[X,z,de]),ce=C=>`'${C.replace(/'/g,"'\\''")}`,Se=r.useCallback(C=>{z||de("git add",`git add -- ${ce(C.path)}`)},[z,de]),Je=r.useCallback(C=>{z||de("git reset",`git reset HEAD -- ${ce(C.path)}`)},[z,de]),Te=r.useCallback(()=>{if(!p||z)return;const C=u.find(ue=>ue.name===p);if(C!=null&&C.remote&&typeof C.remote=="string"){const ue=p.slice(C.remote.length+1);de("git checkout",`git checkout -b ${ue} ${p} || git checkout ${p}`)}else de("git checkout",`git checkout ${p}`)},[p,u,z,de]),Ee=r.useCallback(()=>de("git push","git push"),[de]),Qe=r.useCallback(()=>de("git pull","git pull"),[de]),Me=r.useCallback(()=>{le({type:"scm_history"},H)||(H.current=-1)},[le]);r.useEffect(()=>{l&&ee()},[l,ee]),r.useEffect(()=>{N==="history"&&n&&Me()},[N,n,Me]),r.useEffect(()=>{t.scmDirty>0&&l&&ee(!1,!0)},[t.scmDirty]),r.useEffect(()=>{if(!l||!t.ready||t.status!=="open")return;const C=setInterval(()=>{document.visibilityState!=="hidden"&&ee(!1,!0)},3e4);return()=>clearInterval(C)},[l,t.ready,t.status,ee]),r.useEffect(()=>{const C=d.current;if(d.current=t.terminals,!l)return;t.terminals.some(ae=>{var f;return ae.running!==!1?!1:((f=C.find(E=>E.id===ae.id))==null?void 0:f.running)===!0&&/^git /.test(ae.title)})&&t.ready&&t.status==="open"&&(ee(!1,!0),N==="history"&&n&&Me())},[t.terminals,l,t.ready,t.status,ee,N,n,Me]);const Xe={staged:a("scmStaged"),unstaged:a("scmUnstaged"),untracked:a("scmUntracked"),both:a("scmStagedUnstaged")},Fe=C=>{const ue=C.split(`
|
|
319
|
+
`);return e.jsx("pre",{className:"scm-diff-pre",children:ue.map((ae,ye)=>{let f="";return ae.startsWith("diff --git")||ae.startsWith("index ")||ae.startsWith("new file")||ae.startsWith("deleted file")||ae.startsWith("old mode")||ae.startsWith("new mode")||ae.startsWith("similarity index")||ae.startsWith("rename ")||ae.startsWith("copy ")||ae.startsWith("Binary files")||ae.startsWith("---")||ae.startsWith("+++")?f="hdr":ae.startsWith("@@")?f="hunk":ae.startsWith("+")?f="add":ae.startsWith("-")&&(f="del"),e.jsx("div",{className:`scm-diff-line ${f}`,children:ae||" "},ye)})})};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(lt,{}),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"),ge(null)},children:a("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":N==="history",className:N==="history"?"active":"",onClick:()=>{D("history"),ge(null)},children:a("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:a("scmRefreshTip"),disabled:K,onClick:()=>ee(!0),children:e.jsx(gt,{className:K?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:a("scmCurrentBranch"),children:[e.jsx(lt,{}),n?n.detached?a("scmDetached"):n.branch:"…",(n==null?void 0:n.upstream)&&e.jsx("span",{className:"scm-upstream",children:n.upstreamGone?a("scmUpstreamGone"):n.ahead>0||n.behind>0?a("scmAheadBehind",{ahead:n.ahead,behind:n.behind}):n.upstream})]}),e.jsxs("select",{className:"scm-select",value:p,disabled:z||u.length===0,title:a("scmSwitchBranch"),onChange:C=>g(C.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:a("scmSelectBranch")}),u.filter(C=>!C.remote).map(C=>e.jsx("option",{value:C.name,children:C.current?`* ${C.name}`:C.name},C.name)),u.some(C=>C.remote)&&e.jsx("optgroup",{label:a("scmRemoteBranches"),children:u.filter(C=>C.remote).map(C=>e.jsx("option",{value:C.name,children:C.name},C.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!p||p===(n==null?void 0:n.branch)||z,title:a("scmSwitchBranchTip",{branch:p}),onClick:Te,children:[e.jsx(lt,{}),a("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!n||n.detached||z,title:a("scmPushTip"),onClick:Ee,children:[e.jsx(Os,{}),a("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!n||n.detached||z,title:a("scmPullTip"),onClick:Qe,children:[e.jsx(Ws,{}),a("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:X,placeholder:a("scmCommitPlaceholder"),disabled:z,onChange:C=>V(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!C.nativeEvent.isComposing&&xe()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!X.trim()||z,title:a("scmCommitTip"),onClick:xe,children:[e.jsx(vt,{}),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")}),w.length>0&&e.jsx("span",{className:"scm-files-count",children:w.length})]}),e.jsx("div",{className:"scm-history-list",children:z?e.jsx("div",{className:"scm-empty",children:a("scmNotGitRepo")}):!n||x?e.jsx("div",{className:"scm-empty",children:t.status==="open"?a("scmLoading"):a("scmConnecting")}):w.length===0?e.jsx("div",{className:"scm-empty",children:a("scmNoHistory")}):w.map(C=>e.jsxs("button",{type:"button",className:`scm-commit ${(v==null?void 0:v.hash)===C.hash?"active":""}`,onClick:()=>Y(C),title:C.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:C.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:C.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[C.shortHash," · ",C.author," · ",C.date]}),C.decorations&&e.jsx("span",{className:"scm-commit-refs",children:C.decorations})]})]},C.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:a("scmChanges")}),n&&n.files.length>0&&e.jsx("span",{className:"scm-files-count",children:n.files.length})]}),e.jsx("div",{className:"scm-files-list",children:z?e.jsx("div",{className:"scm-empty",children:a("scmNotGitRepo")}):n?n.files.length===0?e.jsx("div",{className:"scm-empty",children:a("scmNoChanges")}):n.files.map(C=>{const ue=Ga(C),ae=k.get(C.path);return e.jsxs("div",{className:`scm-file ${(m==null?void 0:m.path)===C.path?"active":""}`,title:Xe[ue],onClick:()=>fe(C),children:[e.jsx("span",{className:`scm-file-xy ${ue==="untracked"?"q":"x"}`,children:C.x!==" "?C.x:" "}),e.jsx("span",{className:`scm-file-xy ${ue==="untracked"?"q":"y"}`,children:C.y!==" "?C.y:" "}),e.jsx("span",{className:"scm-file-path",children:C.path}),ae&&(ae.add>0||ae.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[ae.add>0&&e.jsxs("span",{className:"add",children:["+",ae.add]}),ae.del>0&&e.jsxs("span",{className:"del",children:["-",ae.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(C.y!==" "||ue==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:a("scmStageTip",{path:C.path}),onClick:ye=>{ye.stopPropagation(),Se(C)},children:"+"}),ue==="staged"||ue==="both"?e.jsx("button",{type:"button",className:"scm-act",title:a("scmUnstageTip",{path:C.path}),onClick:ye=>{ye.stopPropagation(),Je(C)},children:"−"}):null]})]},C.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"?v?`${v.shortHash} ${v.subject}`:a("scmCommitDetail"):m?m.path:a("scmDiff")}),(N==="history"?S:Q)&&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:$}),!v&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmSelectCommitHint")}),v&&S&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmLoading")}),v&&!S&&!$&&I?Fe(I):null]}):e.jsxs(e.Fragment,{children:[$&&e.jsx("div",{className:"scm-error",children:$}),!m&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmSelectFileHint")}),m&&!O&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmLoading")}),m&&O&&O.untracked&&e.jsx("div",{className:"scm-empty",children:a("scmUntrackedNote")}),m&&O&&!O.untracked&&e.jsxs(e.Fragment,{children:[O.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:a("scmStaged")}),Fe(O.staged)]}),O.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:a("scmUnstaged")}),Fe(O.worktree)]}),!O.staged&&!O.worktree&&e.jsx("div",{className:"scm-empty",children:a("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(ze,{}),e.jsx("span",{children:a("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:c,children:a("scmViewTerminal")})]})]})}function Ja({entry:t,send:s}){const i=r.useRef(null);return r.useEffect(()=>{const l=i.current;if(!l)return;let c;try{c=t.module.mount(l,Ni(t.info.id,a=>s(a)))}catch(a){console.error(`[plugin:${t.info.id}] mount failed:`,a),l.textContent=`插件 ${t.info.name} 挂载失败`}return()=>{if(typeof c=="function")try{c()}catch(a){console.error(`[plugin:${t.info.id}] cleanup failed:`,a)}l.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:i})}function Qa({send:t,piConfigured:s,piAgentInstalled:i,providers:l,installResult:c,onClose:a}){const n=pe(),[o,u]=r.useState(!1),[h,p]=r.useState(""),[g,k]=r.useState(""),[b,N]=r.useState(!1);r.useEffect(()=>{t({type:"list_providers"})},[t]),r.useEffect(()=>{s&&a()},[s,a]),r.useEffect(()=>{c&&u(!1)},[c]),r.useEffect(()=>{var I;!h&&l.length>0&&p(((I=l.find(A=>!A.configured))==null?void 0:I.id)??l[0].id)},[l,h]);const D=()=>{o||(u(!0),t({type:"install_pi_agent"}))},w=()=>{!g.trim()||b||(N(!0),t({type:"set_provider_api_key",provider:h.trim(),apiKey:g.trim()}),setTimeout(()=>N(!1),3e3))},_=()=>{t({type:"get_state"}),t({type:"list_providers"})},v=l.find(I=>I.id===h),j=c!==null&&!c.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":n("close"),onClick:a,children:e.jsx(we,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(st,{className:"modal-head-icon"}),e.jsx("h2",{children:n("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:n("setupDesc")}),j?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:n("installFailed")}),e.jsx("pre",{className:"setup-detail",children:c.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:D,children:n("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:a,children:n("skip")})]})]}):i||c!=null&&c.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:c!=null&&c.ok?n("installDone"):n("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:n("provider")}),e.jsxs("select",{value:h,onChange:I=>p(I.target.value),children:[l.length===0&&e.jsx("option",{value:"",children:n("loading")}),l.map(I=>e.jsxs("option",{value:I.id,children:[I.name,"(",I.id,")",I.configured?` · ${n("configured")}`:""]},I.id))]}),(v==null?void 0:v.configured)&&e.jsx("div",{className:"field-hint",children:n("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:n("apiKey")}),e.jsx("input",{type:"password",value:g,onChange:I=>k(I.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!g.trim()||b||!h,onClick:w,children:n(b?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:_,children:[e.jsx(gt,{})," ",n("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:D,children:n(o?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:a,children:n("skip")})]})]})})}const Xa=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],Ut=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),Za=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[Ut()]});function Ss(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:[Ut()]).map(s=>{var i;return{id:s.id,name:s.name??"",reasoning:s.reasoning??!1,input:(i=s.input)!=null&&i.includes("image")?"text-image":"text",contextWindow:s.contextWindow?String(s.contextWindow):"",maxTokens:s.maxTokens?String(s.maxTokens):""}})}}function er({send:t,providers:s,providerStatus:i,fetchModelsResult:l,refreshProviderResult:c,cloneProviderResult:a,onClose:n}){const o=pe(),[u,h]=r.useState(null),[p,g]=r.useState({}),[k,b]=r.useState(null),[N,D]=r.useState({}),[w,_]=r.useState(!1),[v,j]=r.useState(0),[I,A]=r.useState(null),S=r.useRef(0),[T,m]=r.useState({});r.useRef(0);const B=r.useRef(0),[O,Z]=r.useState(null),Q=r.useRef(0),U=r.useRef(0);r.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const K=()=>{if(!u)return;const P=u.baseUrl.trim();if(!P){A({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(w)return;_(!0),A(null);const X=v+1;j(X),t({type:"fetch_models",reqId:X,baseUrl:P,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};r.useEffect(()=>{var P;if(!(!l||l.reqId===S.current))if(S.current=l.reqId,_(!1),l.ok&&((P=l.models)!=null&&P.length)){const X=l.models;h(V=>{if(!V)return V;const M=V.models.map(H=>{var d;if(!H.id.trim())return H;const oe=X.find(R=>R.id===H.id.trim());if(!oe)return H;const re={...H};return!re.name&&oe.name&&(re.name=oe.name),!re.contextWindow&&oe.contextWindow&&(re.contextWindow=String(oe.contextWindow)),!re.maxTokens&&oe.maxTokens&&(re.maxTokens=String(oe.maxTokens)),re.input==="text"&&((d=oe.input)!=null&&d.includes("image"))&&(re.input="text-image"),!re.reasoning&&oe.reasoning&&(re.reasoning=!0),re}),F=new Set(M.map(H=>H.id.trim()).filter(Boolean)),q=X.filter(H=>!F.has(H.id)).map(H=>{var oe;return{id:H.id,name:H.name??"",reasoning:H.reasoning??!1,input:(oe=H.input)!=null&&oe.includes("image")?"text-image":"text",contextWindow:H.contextWindow?String(H.contextWindow):"",maxTokens:H.maxTokens?String(H.maxTokens):""}}),te=[...M,...q];return te.some(H=>H.id.trim())?{...V,models:te.filter(H=>H.id.trim())}:V}),A({ok:!0,text:o("fetchModelsOk",{n:X.length})})}else A({ok:!1,text:l.error||o("fetchModelsEmpty")})},[l]);const ie=P=>{const X=(p[P.id]??"").trim();!X||k||(b(P.id),t({type:"set_provider_api_key",provider:P.id,apiKey:X}),setTimeout(()=>{b(null),g(V=>({...V,[P.id]:""})),D(V=>({...V,[P.id]:!1})),t({type:"list_providers"})},1500))},x=()=>{if(!u)return;const P=u.providerId.trim(),X=u.models.filter(M=>M.id.trim()).map(M=>({id:M.id.trim(),name:M.name.trim()||void 0,reasoning:M.reasoning||void 0,input:M.input==="text-image"?["text","image"]:void 0,contextWindow:M.contextWindow?Number(M.contextWindow):void 0,maxTokens:M.maxTokens?Number(M.maxTokens):void 0})),V={providerId:P,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:X};t({type:"save_model_config",providerId:P,config:V}),n()};r.useEffect(()=>{!c||c.reqId===B.current||(B.current=c.reqId,m({}))},[c]);const y=P=>{if(O)return;Z(P.id);const X=++Q.current+Date.now();t({type:"clone_provider",provider:P.id,reqId:X})};r.useEffect(()=>{!a||a.reqId===U.current||(U.current=a.reqId,Z(null),a.ok&&a.config&&h(Ss({...a.config,apiKey:""})))},[a]);const $=P=>{window.confirm(o("clearKeyConfirm",{id:P}))&&t({type:"clear_provider_api_key",provider:P})},ge=P=>{window.confirm(o("deleteProviderConfirm",{id:P.providerId,n:P.models.length}))&&t({type:"delete_model_config",providerId:P.providerId})},z=(P,X)=>{u&&h({...u,models:u.models.map((V,M)=>M===P?{...V,...X}:V)})};return e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"modal model-modal",onClick:P=>P.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:n,children:e.jsx(we,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:o(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:[o("providerId")," ",e.jsx("em",{children:o("providerIdHint")})]}),e.jsx("input",{type:"text",value:u.providerId,disabled:s.some(P=>P.providerId===u.providerId),onChange:P=>h({...u,providerId:P.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("displayName")}),e.jsx("input",{type:"text",value:u.name,onChange:P=>h({...u,name:P.target.value}),placeholder:o("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiType")}),e.jsx("select",{value:u.api,onChange:P=>h({...u,api:P.target.value}),children:Xa.map(P=>e.jsx("option",{value:P,children:P},P))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:o("baseUrlHint")})]}),e.jsx("input",{type:"text",value:u.baseUrl,onChange:P=>h({...u,baseUrl:P.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKey")}),e.jsx("input",{type:"password",value:u.apiKey,onChange:P=>h({...u,apiKey:P.target.value}),placeholder:o("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:P=>h({...u,authHeader:P.target.checked})}),e.jsx("span",{children:o("authHeader")})]})]}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:o("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[I&&e.jsx("span",{className:`fetch-msg ${I.ok?"ok":"err"}`,title:I.text,children:I.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:w||!u.baseUrl.trim(),title:o("fetchModelsHint"),onClick:K,children:[e.jsx(Ft,{})," ",o(w?"fetchingModels":"fetchModels")]})]})]}),u.models.map((P,X)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:P.id,onChange:V=>z(X,{id:V.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:P.name,onChange:V=>z(X,{name:V.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:P.input,onChange:V=>z(X,{input:V.target.value}),children:[e.jsx("option",{value:"text",children:o("text")}),e.jsx("option",{value:"text-image",children:o("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:P.reasoning,onChange:V=>z(X,{reasoning:V.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:P.contextWindow,onChange:V=>z(X,{contextWindow:V.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:P.maxTokens,onChange:V=>z(X,{maxTokens:V.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>h({...u,models:u.models.filter((V,M)=>M!==X)}),children:e.jsx(Ie,{})})]},X)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>h({...u,models:[...u.models,Ut()]}),children:[e.jsx(_e,{})," ",o("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>h(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(P=>P.id.trim()),onClick:x,children:o("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-section-title",children:[o("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:o("hintKeyOnly")})]}),e.jsxs("div",{className:"provider-list",children:[i.length===0&&e.jsx("div",{className:"dd-loading",children:o("loading")}),i.map(P=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:P.name}),e.jsxs("span",{className:"provider-sub",children:[P.id,P.configured&&e.jsx("span",{className:"auth-badge",children:o("configuredBadge")}),P.source&&!P.configured&&e.jsx("span",{className:"auth-badge dim",children:P.source})]})]}),e.jsxs("div",{className:"provider-actions",children:[P.configured&&!N[P.id]?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"auth-badge",children:o("keyReady")}),e.jsxs("button",{type:"button",className:"btn sm",title:o("replaceKeyTitle"),onClick:()=>D(X=>({...X,[P.id]:!0})),children:[e.jsx(It,{})," ",o("replaceKey")]}),P.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>$(P.id),children:[e.jsx(Ie,{})," ",o("clearKey")]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"password",className:"key-input",placeholder:o("pasteKey"),value:p[P.id]??"",onChange:X=>g(V=>({...V,[P.id]:X.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(p[P.id]??"").trim()||k===P.id,onClick:()=>ie(P),children:[e.jsx(Vn,{})," ",k===P.id?o("savingKey"):o("saveKey")]})]}),e.jsxs("button",{type:"button",className:"btn sm",disabled:O!==null,title:o("cloneProviderTitle"),onClick:()=>y(P),children:[e.jsx($t,{})," ",O===P.id?o("cloning"):o("cloneProvider")]})]})]},P.id))]}),e.jsx("div",{className:"form-section-title",children:o("customProviders")}),e.jsx("p",{className:"modal-desc",children:o("customDesc")}),s.length===0&&e.jsx("div",{className:"dd-loading",children:o("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:s.map(P=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:P.providerId}),e.jsxs("span",{className:"provider-sub",children:[P.api??"—",P.baseUrl?` · ${P.baseUrl}`:"",P.models.length>0&&` · ${o("modelsCount",{n:P.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:o("edit"),onClick:()=>h(Ss(P)),children:e.jsx(It,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>ge(P),children:e.jsx(Ie,{})})]})]},P.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>h(Za()),children:[e.jsx(_e,{})," ",o("addProvider")]})})]})]})})}function tr({plugin:t,send:s}){const i=pe(),l=t.settingsSchema??[],[c,a]=r.useState(()=>({...t.settingsValues??{}})),[n,o]=r.useState(!1);if(l.length===0)return null;const u=(k,b)=>a(N=>({...N,[k]:b})),h=l.some(k=>{var b;return c[k.key]!==((b=t.settingsValues)==null?void 0:b[k.key])}),p=()=>{o(!0),s({type:"plugin_settings",pluginId:t.id,values:c}),setTimeout(()=>o(!1),800)},g=()=>a({...t.settingsValues??{}});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:l.map(k=>e.jsxs("label",{className:"plugin-settings-field",title:k.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:k.label}),k.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!c[k.key],onChange:b=>u(k.key,b.target.checked)}):k.type==="select"?e.jsx("select",{value:String(c[k.key]??""),onChange:b=>u(k.key,b.target.value),children:(k.options??[]).map(b=>e.jsx("option",{value:b,children:b},b))}):e.jsx("input",{type:k.type==="password"?"password":k.type==="number"?"number":"text",value:String(c[k.key]??""),min:k.min,max:k.max,onChange:b=>u(k.key,k.type==="number"?Number(b.target.value):b.target.value)})]},k.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!h||n,onClick:p,children:i(n?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:g,children:i("pluginSettingsReset")})]})]})}function ot({text:t}){const s=r.useRef(null),[i,l]=r.useState(!1),c=()=>{var n;const a=(n=s.current)==null?void 0:n.getBoundingClientRect();a&&l(window.innerWidth-a.right<340)};return e.jsxs("span",{ref:s,className:`set-tip${i?" flip":""}`,tabIndex:0,"aria-label":t,onMouseEnter:c,onFocus:c,children:["?",e.jsx("span",{className:"set-tip-bubble",role:"tooltip",children:t})]})}function Pe({title:t,subtitle:s,tip:i,enabled:l,onToggle:c,action:a}){const n=pe();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,i&&e.jsx(ot,{text:i})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),a,e.jsx("button",{type:"button",className:`set-switch ${l?"on":""}`,role:"switch","aria-checked":l,title:n(l?"settingsEnabled":"settingsDisabled"),onClick:c,children:e.jsx("span",{className:"set-switch-knob"})})]})}function sr({chat:t,send:s,terminal:i,onSwitchToTerminal:l,onClose:c}){const a=pe(),n=t.settings,[o,u]=r.useState("prompt"),h=r.useRef(null);r.useEffect(()=>{var d;(d=h.current)==null||d.scrollTo({top:0})},[o]);const[p,g]=r.useState(""),[k,b]=r.useState("append"),N=r.useRef(!1),[D,w]=r.useState(""),[_,v]=r.useState("append"),j=r.useRef(!1),[I,A]=r.useState(""),S=r.useRef(!1),[T,m]=r.useState(""),[B,O]=r.useState(!1),[Z,Q]=r.useState(null),[U,K]=r.useState(null);r.useEffect(()=>{n&&(b(n.promptMode),!N.current&&(g(k==="append"||n.customSystemPrompt?n.customSystemPrompt:n.defaultSystemPrompt||""),v(n.visionBridgePromptMode),!j.current&&(w(_==="append"||n.visionBridgePrompt?n.visionBridgePrompt:n.visionBridgeDefaultPrompt||""),S.current||A(n.reviewPrompt))))},[n,k,_]);const[ie,x]=r.useState(String((n==null?void 0:n.terminalBashIdleMs)??15e3));if(r.useEffect(()=>{x(String((n==null?void 0:n.terminalBashIdleMs)??15e3))},[n==null?void 0:n.terminalBashIdleMs]),!n)return null;const y=[{id:"prompt",icon:e.jsx($s,{}),label:a("settingsSystemPrompt")},{id:"terminal",icon:e.jsx(ze,{}),label:a("settingsTerminalTools")},{id:"display",icon:e.jsx(Ve,{}),label:a("settingsMessageDisplay")},{id:"skills",icon:e.jsx(st,{}),label:a("settingsSkills"),count:n.skills.length},{id:"extensions",icon:e.jsx(ns,{}),label:a("settingsExtensions"),count:n.extensions.length},{id:"plugins",icon:e.jsx(as,{}),label:a("settingsUiPlugins"),count:t.plugins.length},{id:"review",icon:e.jsx(rt,{}),label:a("settingsReview"),count:n.reviewSkills.length},{id:"vision",icon:e.jsx(Rt,{}),label:a("settingsVisionBridge")},{id:"presets",icon:e.jsx(Fn,{}),label:a("settingsPresets"),count:n.presets.length}],$=new Set(n.disabledSkills),ge=new Set(n.disabledExtensions),z=d=>s({type:"set_settings",...d}),P=d=>{const R=new Set($);R.has(d.name)?R.delete(d.name):R.add(d.name),z({disabledSkills:[...R]})},X=new Set(n.disabledPlugins??[]),V=d=>{const R=new Set(X);R.has(d.id)?R.delete(d.id):R.add(d.id),z({disabledPlugins:[...R]})},M=d=>{const R=new Set(ge);R.has(d.id)?R.delete(d.id):R.add(d.id),z({disabledExtensions:[...R]})},F=(d,R)=>{var fe,Y;const le={name:d,command:R,cwd:"${pwd}"},ee=t.terminals.find(de=>de.title===d);ee?(i.restart(ee.id),s({type:"run_command",terminalId:ee.id,conversationId:ee.conversationId,command:le,cols:80,rows:24})):i.create({id:Be(),conversationId:t.activeConversationId||((fe=t.state)==null?void 0:fe.conversationId)||"",title:d,cwd:((Y=t.state)==null?void 0:Y.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:le}),l(),c()},q=d=>{Q(null),F(`${a("uninstallTitle")} ${d}`,`pi remove npm:${d}`)},te=d=>{K(null),F(`${a("uninstallTitle")} ${d}`,`pi-web-ui uninstall ${d}`)},H=(d,R)=>{F(`${a("pluginUpdate")} ${d}`,`pi-web-ui install ${R} --name ${d} --force`)},oe=d=>{const R=new Set(n.reviewSkills.filter(le=>!le.enabled).map(le=>le.name));R.has(d.name)?R.delete(d.name):R.add(d.name),z({reviewDisabledSkills:[...R]})},re=()=>{const d=k==="replace"&&n.defaultSystemPrompt&&p===n.defaultSystemPrompt?"":p;z({promptMode:k,customSystemPrompt:d})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal settings-modal",onClick:d=>d.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":a("close"),onClick:c,children:e.jsx(we,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(pt,{className:"modal-head-icon"}),e.jsx("h2",{children:a("settingsTitle")}),e.jsx(ot,{text:a("settingsDesc")})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-rail","aria-label":a("settingsTitle"),children:y.map(d=>e.jsxs("button",{type:"button",className:`settings-tab${o===d.id?" active":""}`,"aria-current":o===d.id?"true":void 0,title:d.label,onClick:()=>u(d.id),children:[e.jsx("span",{className:"settings-tab-icon",children:d.icon}),e.jsx("span",{className:"settings-tab-label",children:d.label}),d.count!==void 0&&e.jsx("span",{className:"set-count",children:d.count})]},d.id))}),e.jsxs("div",{className:"modal-body",ref:h,children:[o==="prompt"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(rt,{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:k,onChange:d=>{const R=d.target.value;b(R),z({promptMode:R})},children:[e.jsx("option",{value:"append",children:a("promptModeAppend")}),e.jsx("option",{value:"replace",children:a("promptModeReplace")})]}),e.jsx(ot,{text:a(k==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:a("promptPlaceholder"),value:p,onFocus:()=>N.current=!0,onBlur:()=>{N.current=!1,re()},onChange:d=>g(d.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":B,onClick:()=>O(d=>!d),children:[a("settingsViewPrompt")," ",B?"▴":"▾"]}),B&&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(zs,{text:n.effectiveSystemPrompt})]}),n.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:n.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:a("settingsViewPromptEmpty")})]})]}),o==="terminal"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ze,{className:"set-section-icon"}),a("settingsTerminalTools")]}),e.jsx(Pe,{title:a("terminalToolsEnabled"),tip:a("settingsTerminalToolsDesc"),enabled:n.terminalToolsEnabled,onToggle:()=>z({terminalToolsEnabled:!n.terminalToolsEnabled})}),!n.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:a("terminalToolsOffHint")}),e.jsx(Pe,{title:a("terminalBashTakeover"),tip:a("terminalBashTakeoverDesc"),enabled:n.terminalBash,onToggle:()=>z({terminalBash:!n.terminalBash})}),n.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:ie,onChange:d=>x(d.target.value),onBlur:()=>{const d=Math.max(0,Math.floor(Number(ie)||0));x(String(d)),d!==n.terminalBashIdleMs&&z({terminalBashIdleMs:d})}})]})]}),o==="display"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ve,{className:"set-section-icon"}),a("settingsMessageDisplay")]}),e.jsx(Pe,{title:a("thinkingWrap"),tip:a("thinkingWrapDesc"),enabled:n.thinkingWrap??!0,onToggle:()=>z({thinkingWrap:!(n.thinkingWrap??!0)})}),e.jsx(Pe,{title:a("toolsWrap"),tip:a("toolsWrapDesc"),enabled:n.toolsWrap??!0,onToggle:()=>z({toolsWrap:!(n.toolsWrap??!0)})})]}),o==="skills"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(st,{className:"set-section-icon"}),a("settingsSkills"),e.jsx("span",{className:"set-count",children:n.skills.length})]}),n.skills.length===0?e.jsx("p",{className:"set-empty",children:a("noSkills")}):e.jsx("div",{className:"set-list",children:n.skills.map(d=>e.jsx(Pe,{title:d.name,subtitle:d.description,enabled:d.enabled,onToggle:()=>P(d)},d.name))})]}),o==="extensions"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ns,{className:"set-section-icon"}),a("settingsExtensions"),e.jsx("span",{className:"set-count",children:n.extensions.length})]}),n.extensions.length===0?e.jsx("p",{className:"set-empty",children:a("noExtensions")}):e.jsx("div",{className:"set-list",children:n.extensions.map(d=>{const R=d.id.startsWith("npm:")?d.id.slice(4):null;return e.jsx(Pe,{title:d.name,subtitle:d.path,enabled:d.enabled,onToggle:()=>M(d),action:R?Z===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("uninstallConfirmHint"),onClick:()=>q(R),children:a("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:a("uninstallHint"),onClick:()=>Q(d.id),children:[e.jsx(Ie,{}),a("uninstallExt")]}):void 0},d.id)})})]}),o==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(as,{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(d=>{var R;return e.jsxs(e.Fragment,{children:[e.jsx(Pe,{title:`${d.icon?`${d.icon} `:""}${d.name}`,subtitle:(d.error?`${d.id} · ${d.error}`:d.source?`${d.id} · ${d.source}`:`${d.id} · ${a("uiPluginNoSource")}`)+((R=d.permissions)!=null&&R.length?` · ${a("uiPluginPerms")}: ${d.permissions.join(", ")}`:""),enabled:!X.has(d.id)&&!d.error,onToggle:()=>!d.error&&V(d),action:e.jsxs("div",{className:"set-row-actions",children:[d.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUpdateHint"),onClick:()=>H(d.id,d.source),children:[e.jsx(gt,{}),a("pluginUpdate")]}),U===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("pluginUninstallHint"),onClick:()=>te(d.id),children:a("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUninstallHint"),onClick:()=>K(d.id),children:[e.jsx(Ie,{}),a("uninstallExt")]})]})},d.id),d.settingsSchema&&d.settingsSchema.length>0&&e.jsx(tr,{plugin:d,send:s})]})})})]}),o==="review"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(rt,{className:"set-section-icon"}),a("settingsReview"),e.jsx(ot,{text:a("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:n.reviewSkills.length})]}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:a("reviewPromptPlaceholder"),value:I,onFocus:()=>S.current=!0,onBlur:()=>{S.current=!1,z({reviewPrompt:I})},onChange:d=>A(d.target.value)}),e.jsx("div",{className:"set-field-label",children:a("settingsReviewSkills")}),n.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:a("noSkills")}):e.jsx("div",{className:"set-list",children:n.reviewSkills.map(d=>e.jsx(Pe,{title:d.name,subtitle:d.description,enabled:d.enabled,onToggle:()=>oe(d)},`review-${d.name}`))})]}),o==="vision"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Rt,{className:"set-section-icon"}),a("settingsVisionBridge")]}),e.jsx(Pe,{title:a("visionBridgeEnabled"),tip:a("settingsVisionBridgeDesc"),enabled:n.visionBridgeEnabled,onToggle:()=>z({visionBridgeEnabled:!n.visionBridgeEnabled})}),!n.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:a("visionBridgeOffHint")}),n.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:n.visionBridgeModel??"",onChange:d=>z({visionBridgeModel:d.target.value||null}),children:[e.jsx("option",{value:"",children:a("visionBridgeAuto")}),n.visionModels.map(d=>e.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),n.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:_,onChange:d=>{const R=d.target.value;v(R),z({visionBridgePromptMode:R})},children:[e.jsx("option",{value:"append",children:a("promptModeAppend")}),e.jsx("option",{value:"replace",children:a("promptModeReplace")})]})]}),n.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:a("visionBridgePromptPlaceholder"),value:D,onFocus:()=>j.current=!0,onBlur:()=>{j.current=!1;const d=_==="replace"&&n.visionBridgeDefaultPrompt&&D===n.visionBridgeDefaultPrompt?"":D;z({visionBridgePromptMode:_,visionBridgePrompt:d})},onChange:d=>w(d.target.value)}),n.visionBridgeEnabled&&(n.visionModels.length===0?e.jsx("p",{className:"set-hint",children:a("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:a("visionBridgeCurrent",{model:n.visionBridgeModel??a("visionBridgeAuto")})}))]}),o==="presets"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(pt,{className:"set-section-icon"}),a("settingsPresets"),e.jsx("span",{className:"set-count",children:n.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:a("presetNamePlaceholder"),value:T,onChange:d=>m(d.target.value),onKeyDown:d=>{d.key==="Enter"&&T.trim()&&(s({type:"save_preset",name:T.trim()}),m(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!T.trim(),onClick:()=>{s({type:"save_preset",name:T.trim()}),m("")},children:[e.jsx(_e,{})," ",a("saveAsPreset")]})]}),n.presets.length===0?e.jsx("p",{className:"set-empty",children:a("noPresets")}):e.jsx("div",{className:"set-list",children:n.presets.map(d=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:d.name}),e.jsxs("div",{className:"set-row-desc",children:[d.promptMode==="replace"?a("promptModeReplace"):a("promptModeAppend"),d.disabledSkills.length>0&&` · ${a("settingsSkills")} ${d.disabledSkills.length}`,d.disabledExtensions.length>0&&` · ${a("settingsExtensions")} ${d.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:d.name}),children:a("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:a("deletePreset"),onClick:()=>s({type:"delete_preset",name:d.name}),children:e.jsx(Ie,{})})]})]},d.name))})]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:c,children:a("close")})})]})})}function nr(t,s){const i=Math.max(0,Date.now()-t),l=Math.floor(i/6e4);if(l<1)return s("bgTaskJustNow");if(l<60)return s("bgTaskMinutes",{n:l});const c=Math.floor(l/60);return c<24?s("bgTaskHours",{n:c}):s("bgTaskDays",{n:Math.floor(c/24)})}function ir({servers:t,send:s,onClose:i}){const l=pe(),[c,a]=r.useState(new Set),n=o=>a(u=>{const h=new Set(u);return h.has(o)?h.delete(o):h.add(o),h});return r.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:i,children:e.jsxs("div",{className:"bg-task-modal",onClick:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(ht,{})," ",l("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:l("close"),onClick:i,children:e.jsx(we,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(ht,{}),e.jsx("span",{children:l("bgTasksEmpty")}),e.jsx("small",{children:l("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(o=>{const u=!!o.taskId,h=o.taskId??String(o.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:u?o.plugin:l("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[u?e.jsxs("span",{className:"bg-task-port",title:o.taskId,children:["🧩 ",o.plugin]}):e.jsxs("span",{className:"bg-task-port",children:[":",o.port]}),o.name&&e.jsx("span",{className:"bg-task-name",children:o.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[!u&&e.jsxs("span",{children:[l("bgTaskPid")," ",o.pid]}),e.jsxs("span",{children:[l("bgTaskSince")," ",nr(o.since,l)]}),u&&o.status&&e.jsx("span",{className:"bg-task-status",children:o.status})]}),o.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${c.has(h)?"open":""}`,title:`${l("bgTaskCommand")}: ${o.command}`,onClick:()=>n(h),children:[e.jsx(ze,{}),e.jsx("code",{children:o.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:l("bgTaskStop"),onClick:()=>s(u?{type:"kill_background_server",taskId:o.taskId}:{type:"kill_background_server",port:o.port}),children:[e.jsx(ut,{}),e.jsx("span",{children:l("bgTaskStop")})]})]},h)})}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:l("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(gt,{}),e.jsx("span",{children:l("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:l("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(ut,{}),e.jsx("span",{children:l("bgTaskStopAll")})]})]})]})})}function ar(t,s){return t.toLowerCase().includes(s)}function rr({open:t,send:s,projects:i,cwd:l,fileSearch:c,sessionSearch:a,onClose:n,onSwitchSession:o,onSwitchProject:u,onPreviewFile:h}){const p=pe(),g=r.useRef(null),[k,b]=r.useState(""),N=r.useDeferredValue(k),[D,w]=r.useState(0),_=r.useRef(1),v=r.useRef(0),j=r.useRef(null);r.useEffect(()=>{if(!t)return;s({type:"list_sessions"}),s({type:"list_projects"});const x=k.trim();if(x){const y=++_.current;v.current=y,A(!0),s({type:"search_files",reqId:y,query:x}),s({type:"search_sessions",reqId:y,query:x})}requestAnimationFrame(()=>{var y;return(y=g.current)==null?void 0:y.select()})},[t]);const[I,A]=r.useState(!1);r.useEffect(()=>{j.current&&clearTimeout(j.current);const x=N.trim();if(!x){A(!1);return}return j.current=setTimeout(()=>{const y=++_.current;v.current=y,A(!0),s({type:"search_files",reqId:y,query:x}),s({type:"search_sessions",reqId:y,query:x})},300),()=>{j.current&&clearTimeout(j.current)}},[N]);const S=N.trim().toLowerCase(),T=r.useMemo(()=>!S||!a||a.reqId!==v.current||!a.ok?[]:a.results,[a,S]),m=r.useMemo(()=>S?i.filter(x=>ar(x.path,S)).slice(0,10):[],[i,S]),B=r.useMemo(()=>!S||!c||c.reqId!==v.current||!c.ok?[]:c.results,[c,S]);r.useEffect(()=>{c&&c.reqId===v.current&&a&&a.reqId===v.current&&v.current!==0&&A(!1)},[c,a]);const O=!!c&&c.ok&&c.truncated,Z=r.useMemo(()=>[...T.map(x=>({kind:"session",path:x.path,anchors:x.anchors})),...m.map(x=>({kind:"project",path:x.path})),...B.filter(x=>x.type==="file").map(x=>({kind:"file",path:x.path,name:x.name}))],[T,m,B]);r.useEffect(()=>{w(0)},[N]);const Q=r.useCallback(x=>{if(x)if(x.kind==="session")o(x.path,x.anchors),n();else if(x.kind==="project"){u(x.path),s({type:"list_sessions"}),s({type:"list_projects"});const y=N.trim();if(y){const $=++_.current;v.current=$,A(!0),s({type:"search_files",reqId:$,query:y}),s({type:"search_sessions",reqId:$,query:y})}}else h(x.path,x.name)},[o,u,h,s,N]);r.useEffect(()=>{if(!t)return;const x=y=>{y.key==="Escape"?(y.preventDefault(),y.stopPropagation(),n()):y.key==="ArrowDown"?(y.preventDefault(),w($=>Math.min($+1,Z.length-1))):y.key==="ArrowUp"?(y.preventDefault(),w($=>Math.max($-1,0))):y.key==="Enter"&&(y.preventDefault(),Q(Z[D]))};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[Z,D,Q,n,t]);const U=T.length+m.length+B.length,K=(x,y,$)=>e.jsxs("div",{className:"gs-section-head",children:[$,e.jsx("span",{children:x}),e.jsx("em",{children:y})]});let ie=-1;return t?e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:n,children:e.jsxs("div",{className:"gs-modal",onClick:x=>x.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(mt,{}),e.jsx("input",{ref:g,type:"text",value:k,placeholder:p("gsPlaceholder"),onChange:x=>b(x.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:p("close"),onClick:n,children:e.jsx(we,{})})]}),e.jsxs("div",{className:"gs-results",children:[!S&&e.jsx("div",{className:"gs-empty",children:p("gsHint")}),S&&U===0&&!O&&e.jsx("div",{className:"gs-empty",children:p(I?"gsSearching":"gsNoResults")}),T.length>0&&e.jsxs("div",{className:"gs-section",children:[K(p("gsSessions"),T.length,e.jsx(Ve,{})),T.map(x=>{ie++;const y=ie;return e.jsxs("button",{type:"button",className:y===D?"gs-item active":"gs-item",onMouseEnter:()=>w(y),onClick:()=>Q({kind:"session",path:x.path,anchors:x.anchors}),children:[e.jsxs("span",{className:"gs-item-title",children:[x.name||x.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:x.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:x.firstMessage})]},x.path)})]}),m.length>0&&e.jsxs("div",{className:"gs-section",children:[K(p("gsProjects"),m.length,e.jsx(Ge,{})),m.map(x=>{ie++;const y=ie,$=l&&x.path===l;return e.jsxs("button",{type:"button",className:y===D?"gs-item active":"gs-item",onMouseEnter:()=>w(y),onClick:()=>Q({kind:"project",path:x.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[x.path.split(/[\\/]/).pop(),$&&e.jsx("em",{className:"gs-item-meta",children:p("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:x.path})]},x.path)})]}),(B.length>0||S&&O)&&e.jsxs("div",{className:"gs-section",children:[K(p("gsFiles"),B.length,e.jsx($s,{})),B.map(x=>{ie++;const y=ie;return e.jsxs("button",{type:"button",className:y===D?"gs-item active":"gs-item",disabled:x.type==="dir",title:x.type==="dir"?void 0:p("gsOpenPreview"),onMouseEnter:()=>w(y),onClick:()=>{x.type==="file"&&Q({kind:"file",path:x.path,name:x.name})},children:[e.jsx("span",{className:"gs-item-title",children:x.name}),e.jsx("span",{className:"gs-item-sub",children:x.path})]},`${x.type}:${x.path}`)}),O&&e.jsx("div",{className:"gs-truncated",children:p("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",p("gsNavigate")]}),e.jsxs("span",{children:["Enter ",p("gsOpen")]}),e.jsxs("span",{children:["Esc ",p("gsCloseHint")]})]})]})}):null}const Tt=5e3;function lr({file:t,content:s,send:i,onAddLines:l,onAttach:c,onClose:a}){const n=pe(),[o,u]=r.useState(null),[h,p]=r.useState(!1),[g,k]=r.useState(null),[b,N]=r.useState(!1),[D,w]=r.useState(!1),[_,v]=r.useState(!1),[j,I]=r.useState(""),[A,S]=r.useState(!0),T=r.useRef(!1),[m,B]=r.useState(!0),[O,Z]=r.useState(!1),[Q,U]=r.useState(100),K=r.useRef(0),ie=r.useRef(!1),x=r.useRef(null);r.useEffect(()=>{p(!0),u(null),k(null),v(!1),I(""),S(!0),T.current=!1,i({type:"read_file",path:t.path})},[t.path,i]),r.useEffect(()=>{s&&s.path===t.path&&(u(s),_||I(s.text),p(!1))},[s,_,t.path]),r.useEffect(()=>{const Y=de=>{if(de.key==="Escape"){te();return}if((de.ctrlKey||de.metaKey)&&de.key.toLowerCase()==="s"&&_){de.preventDefault(),q();return}const xe=de.target,ce=xe&&(xe.tagName==="INPUT"||xe.tagName==="TEXTAREA"||xe.isContentEditable);(de.ctrlKey||de.metaKey)&&de.key.toLowerCase()==="a"&&!ce&&(de.preventDefault(),P())};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[a,o,_,j]),r.useEffect(()=>{const Y=()=>{ie.current=!1,N(!1)};return window.addEventListener("mouseup",Y),()=>window.removeEventListener("mouseup",Y)},[]);const y=r.useMemo(()=>{if(!o)return[];const Y=o.text.split(`
|
|
320
|
+
`);return Y.length>0&&Y[Y.length-1]===""&&Y.pop(),Y.slice(0,Tt)},[o]),$=(o==null?void 0:o.lines)??0,ge=$>Tt,z=(Y,de)=>{if(de){const xe=K.current>0?K.current:Y;k({start:Math.min(xe,Y),end:Math.max(xe,Y)})}else K.current=Y,k({start:Y,end:Y})},P=()=>{y.length!==0&&(K.current=1,k({start:1,end:y.length}))},X=()=>{g&&(l(t.path,t.name,g.start,g.end),w(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>w(!1),1400))},V=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,M=()=>{I((o==null?void 0:o.text)??""),v(!1),T.current&&S(!0)},F=()=>{if(_){if(j!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges")))return;M();return}!V||!o||(T.current=Et(t.name)&&A,Et(t.name)&&S(!1),k(null),I(o.text),v(!0))},q=()=>{!_||!o||!V||i({type:"write_file",path:t.path,text:j})&&(v(!1),T.current&&S(!0),k(null))},te=()=>{_&&j!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges"))||a()},H=Y=>{U(Math.min(200,Math.max(50,Y)))},oe=g?g.end-g.start+1:0,re=(o==null?void 0:o.binary)??!1,d=(o==null?void 0:o.truncated)??!1,R=(o==null?void 0:o.kind)??"text",le=Et(t.name),ee=le&&A&&!_&&R==="text"&&!re,fe=Y=>yt(Ye(`/api/file?clientId=${encodeURIComponent(Wt())}&path=${encodeURIComponent(Y)}`));return e.jsx("div",{className:`fp-overlay ${O?"fullscreen":""}`,onMouseDown:Y=>{Y.target===Y.currentTarget&&te()},children:e.jsxs("div",{className:`fp ${O?"fullscreen":""}`,style:{"--fp-zoom":Q/100},children:[e.jsxs("div",{className:"fp-head",children:[e.jsx("span",{className:"fp-name",title:t.path,children:t.name}),e.jsx("span",{className:"fp-path",children:t.path}),e.jsxs("span",{className:"fp-meta",children:[o&&R==="text"&&!re&&n("fileLines",{n:$}),o&&` · ${or(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[le&&R==="text"&&!re&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${A?"on":""}`,"data-tip":n(A?"showMarkdownSource":"showMarkdownPreview"),disabled:_,onClick:()=>S(Y=>!Y),children:A?e.jsx(Rt,{}):e.jsx(Zn,{})}),R==="text"&&!re&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${_?"on":""}`,"data-tip":n(d?"fileEditTruncated":_?"exitEditFile":"editFile"),disabled:!V&&!_,onClick:F,children:e.jsx(Pt,{})}),R==="text"&&!re&&!ee&&e.jsx("button",{type:"button",className:`fp-attach wrap ${m?"on":""}`,"data-tip":n(m?"disableWrap":"enableWrap"),onClick:()=>B(Y=>!Y),children:e.jsx(Xn,{})}),R==="text"&&o&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":n("zoomOut"),disabled:Q<=50,onClick:()=>H(Q-10),children:e.jsx(Bn,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:n("resetZoom"),onClick:()=>U(100),children:[Q,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":n("zoomIn"),disabled:Q>=200,onClick:()=>H(Q+10),children:e.jsx(Dn,{})})]}),R!=="video"&&R!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":n("attachInlineTip"),onClick:()=>c(t.path,t.name,"inline"),children:e.jsx(_e,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":n("referenceTip"),onClick:()=>c(t.path,t.name,"reference"),children:e.jsx(Mt,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${O?"on":""}`,"data-tip":n(O?"exitFullscreen":"fullscreen"),onClick:()=>Z(Y=>!Y),children:O?e.jsx(qn,{}):e.jsx(Hn,{})}),e.jsx("button",{type:"button",className:"fp-close",title:n("close"),onClick:te,children:e.jsx(we,{})})]})]}),d&&R==="text"&&!re&&e.jsx("div",{className:"fp-notice",children:n("previewTruncated")}),h&&!o&&e.jsx("div",{className:"fp-empty",children:n("loading")}),!h&&R==="none"&&!re&&e.jsx("div",{className:"fp-empty",children:n("previewNotSupported")}),!h&&R==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:fe(t.path),alt:t.name})}),!h&&R==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:fe(t.path),controls:!0,preload:"metadata"})}),!h&&ee&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(kt,{text:o.text})})}),!h&&re&&R!=="image"&&R!=="video"&&o&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[n("binaryFile"),o.truncated&&n("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:o.text})]}),!h&&_&&R==="text"&&!re&&o&&e.jsx("textarea",{className:`fp-editor ${m?"":"no-wrap"}`,value:j,onChange:Y=>I(Y.target.value),wrap:m?"soft":"off",spellCheck:!1,autoFocus:!0}),!h&&!ee&&!_&&R==="text"&&!re&&o&&y.length===0&&e.jsx("div",{className:"fp-empty",children:n("emptyFile")}),!h&&!ee&&!_&&R==="text"&&!re&&y.length>0&&e.jsxs("div",{className:`fp-code ${b?"dragging":""} ${m?"":"no-wrap"}`,onMouseDown:Y=>{Y.button===0&&Y.preventDefault()},children:[y.map((Y,de)=>{const xe=de+1,ce=g!==null&&xe>=g.start&&xe<=g.end;return e.jsxs("div",{className:`fp-line ${ce?"sel":""}`,onMouseDown:Se=>{Se.button===0&&(z(xe,Se.shiftKey),ie.current=!0,N(!0))},onMouseEnter:()=>{ie.current&&z(xe,!0)},children:[e.jsx("span",{className:"fp-num",children:xe}),e.jsx("span",{className:"fp-code-text",children:Y})]},xe)}),ge&&e.jsx("div",{className:"fp-lines-note",children:n("previewLinesTruncated",{n:Tt})})]}),e.jsx("div",{className:"fp-foot",children:_?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:n("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:F,children:n("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:j===((o==null?void 0:o.text)??""),onClick:q,children:[e.jsx($n,{})," ",n("saveFile")]})]})]}):!ee&&R==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:g?n("selectedRange",{n:oe,start:g.start,end:g.end}):n("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:y.length===0,onClick:P,children:n("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!g,onClick:()=>k(null),children:n("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!g||re,onClick:X,children:[D?e.jsx(vt,{}):null,n(D?"addedToChat":"addToChat")]})]})]})})]})})}function Et(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function or(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const un="pi-web-sounds",Ze={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function pn(){try{const t=localStorage.getItem(un);if(!t)return{...Ze};const s=JSON.parse(t),i={...Ze,...s};for(const l of["enabled","question","done","start","error"])typeof i[l]!="boolean"&&(i[l]=Ze[l]);return typeof i.volume!="number"||!Number.isFinite(i.volume)?i.volume=Ze.volume:i.volume=Math.round(Math.max(0,Math.min(100,i.volume))/5)*5,i}catch{return{...Ze}}}function cr(t){try{localStorage.setItem(un,JSON.stringify(t))}catch{}}let et=null;function dr(){try{if(!et){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;et=new t}return et.state==="suspended"&&et.resume(),et}catch{return null}}const ur=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],pr=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],mr=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],hr=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],gr={question:ur,done:pr,start:mr,error:hr};function fr(t,s,i){const l=t.createOscillator(),c=t.createGain();l.type=s.type,l.frequency.value=s.freq;const a=t.currentTime+s.start,n=Math.max(1e-4,s.peak*i);c.gain.setValueAtTime(1e-4,a),c.gain.exponentialRampToValueAtTime(n,a+.012),c.gain.exponentialRampToValueAtTime(1e-4,a+s.dur),l.connect(c),c.connect(t.destination),l.start(a),l.stop(a+s.dur+.05)}function tt(t,s=pn()){if(!s.enabled||!s[t])return;const i=dr();if(!i)return;const l=Math.max(0,Math.min(1,s.volume/100));for(const c of gr[t])fr(i,c,l)}const _t="pi-web-ui:theme",mn="dark",Ts="theme-stylesheet",Es="pi-web-ui:theme-change";function hn(){try{const t=localStorage.getItem(_t);if(t&&t!==mn)return t}catch{}return null}function xr(t){try{t?localStorage.setItem(_t,t):localStorage.removeItem(_t)}catch{}}function gn(t){let s=document.getElementById(Ts);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(Es));return}s||(s=document.createElement("link"),s.id=Ts,s.rel="stylesheet",document.head.appendChild(s)),s.href=Ye(`/themes/${encodeURIComponent(t)}.css`),s.onload=()=>window.dispatchEvent(new CustomEvent(Es))}async function vr(){try{const t=await fetch(yt(Ye("/api/themes")));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function yr(){const[t,s]=r.useState([]),[i,l]=r.useState(()=>hn());return r.useEffect(()=>{let a=!1;return vr().then(n=>{a||s(n)}),()=>{a=!0}},[]),r.useEffect(()=>{gn(i),xr(i)},[i]),{themes:t,theme:i,switchTheme:a=>l(a===mn?null:a)}}function Tr(){const t=getComputedStyle(document.documentElement),s=(i,l)=>t.getPropertyValue(i).trim()||l;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 kr=r.lazy(()=>Sn(()=>import("./TerminalPanel-BQakjBG_.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function br({notice:t,onDismiss:s}){const i=pe(),[l,c]=r.useState(!1);r.useEffect(()=>{if(l)return;const n=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(n)},[l,t.id,t.level,s]);const a=t.level==="error"?ni:t.level==="warning"?si:Gn;return e.jsxs("div",{className:`notice notice-${t.level}${l?" 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:i("close"),onClick:()=>s(t.id),children:e.jsx(we,{})})]})}const jr=[],fn=180,xn=520,vn=240,yn=t=>`pi-web-ui:${t}-panel-width`;function Ms(t){const s=Number(localStorage.getItem(yn(t)));return Number.isFinite(s)&&s>=fn&&s<=xn?s:vn}function Rs({side:t,width:s,onResize:i}){const l=pe(),c=r.useCallback(a=>{a.preventDefault();const n=a.clientX,o=s;let u=o;const h=g=>{const k=t==="left"?g.clientX-n:n-g.clientX;u=Math.min(xn,Math.max(fn,Math.round(o+k))),i(u)},p=()=>{window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",p),document.body.classList.remove("panel-resizing"),localStorage.setItem(yn(t),String(u))};window.addEventListener("pointermove",h),window.addEventListener("pointerup",p),document.body.classList.add("panel-resizing")},[t,s,i]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:l("dragToResize"),onPointerDown:c,onDoubleClick:()=>i(vn)})}function wr(){var E,J,se,me,he,je,Re,Ht,Kt,zt,Vt,Gt,Yt,Jt;const t=pe(),{chat:s,send:i,dismissNotice:l,pushNotice:c,terminal:a}=Pi(),[n,o]=r.useState([]),[u,h]=r.useState(null),[p,g]=r.useState(!1),[k,b]=r.useState("chat"),N=r.useMemo(()=>s.plugins.filter(L=>{var W,ne;return!((ne=(W=s.settings)==null?void 0:W.disabledPlugins)!=null&&ne.includes(L.id))}),[s.plugins,(E=s.settings)==null?void 0:E.disabledPlugins]),[D,w]=r.useState([]);r.useEffect(()=>ji(w),[]),r.useEffect(()=>{wi(N,s.pluginsEpoch)},[N,s.pluginsEpoch]);const[_,v]=r.useState(()=>Ms("left")),[j,I]=r.useState(()=>Ms("right")),A=r.useCallback(L=>v(L),[]),S=r.useCallback(L=>I(L),[]),[T,m]=r.useState(null),[B,O]=r.useState(()=>window.matchMedia("(max-width: 768px)").matches);r.useEffect(()=>{const L=window.matchMedia("(max-width: 768px)"),W=ne=>O(ne.matches);return L.addEventListener("change",W),()=>L.removeEventListener("change",W)},[]);const[Z,Q]=r.useState(!1),[U,K]=r.useState(!1),[ie,x]=r.useState(!1),[y,$]=r.useState(!1),[ge,z]=r.useState(!1),[P,X]=r.useState(null);r.useEffect(()=>{if(!P)return;const L=setTimeout(()=>X(null),15e3);return()=>clearTimeout(L)},[P]),r.useEffect(()=>{const L=W=>{var De,Qt;const ne=W.detail,ve=(ne==null?void 0:ne.title)||"插件命令",ke=ne==null?void 0:ne.command;if(!ke||!s.ready)return;const Ce={name:ve,command:ke,cwd:"${pwd}"},be=s.terminals.find(bt=>bt.title===ve);if(be)a.restart(be.id),i({type:"run_command",terminalId:be.id,conversationId:be.conversationId,command:Ce,cols:80,rows:24});else{const bt=Be();a.create({id:bt,conversationId:s.activeConversationId||((De=s.state)==null?void 0:De.conversationId)||"",title:ve,cwd:((Qt=s.state)==null?void 0:Qt.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Ce})}b("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",L),()=>window.removeEventListener("pi-web-ui:plugin-run-command",L)},[s,a,i]),r.useEffect(()=>{const L=W=>{!(W.ctrlKey||W.metaKey)||W.key.toLowerCase()!=="k"||(W.preventDefault(),z(ne=>!ne))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[]);const[V,M]=r.useState(pn),{themes:F,theme:q,switchTheme:te}=yr(),H=r.useRef(null),oe=r.useRef(null),re=r.useRef(0),d=r.useRef(!1),R=r.useRef(s.terminals);r.useEffect(()=>{cr(V)},[V]),r.useEffect(()=>{var W;const L=R.current;R.current=s.terminals;for(const ne of s.terminals){const ve=((W=ne.command)==null?void 0:W.command)??"",ke=L.find(Ce=>Ce.id===ne.id);!(ke!=null&&ke.running)||ne.running||(ve.startsWith("pi remove ")?i({type:"extensions_reload"}):ve.startsWith("pi-web-ui install ")||ve.startsWith("pi-web-ui uninstall ")?i({type:"plugins_reload"}):ve.startsWith("npm i -g ")&&(i({type:"extensions_reload"}),i({type:"plugins_reload"}),i({type:"check_updates_all",force:!0})))}},[s.terminals,i]),r.useEffect(()=>{var ne;const L=((ne=s.state)==null?void 0:ne.isStreaming)??!1,W=H.current;H.current=L,W!==null&&(!W&&L?tt("start",V):W&&!L&&tt("done",V))},[(J=s.state)==null?void 0:J.isStreaming,V]),r.useEffect(()=>{var W;const L=((W=s.dialog)==null?void 0:W.id)??null;L!==null&&L!==oe.current&&tt("question",V),oe.current=L},[s.dialog,V]),r.useEffect(()=>{const L=[...s.notices].reverse().find(W=>W.level==="error");L&&L.id!==re.current&&(re.current=L.id,tt("error",V))},[s.notices,V]);const le=(L,W,ne,ve=!1,ke)=>{const Ce=`${L}|${ne}|${ke?`${ke.start}-${ke.end}`:""}`;o(be=>be.some(De=>`${De.path}|${De.mode}|${De.lines?`${De.lines.start}-${De.lines.end}`:""}`===Ce)?be:[...be,{path:L,name:W,mode:ne,isDir:ve,...ke?{lines:ke}:{}}])},ee=L=>o(W=>W.filter(ne=>ne.key?ne.key!==L:ne.path!==L)),fe=r.useCallback(L=>(!L.type.startsWith("list_")&&!L.type.startsWith("get_")&&m(null),i(L)),[i]),Y=r.useRef(0),de=r.useRef(0),xe=L=>{var ve;const W=Date.now();(ve=s.state)!=null&&ve.model&&!s.state.model.vision&&W-de.current>1e4&&(de.current=W,c("warning",t("imageNotSupported")));const ne=`paste-${++Y.current}`;o(ke=>[...ke,{path:"",key:ne,name:L.name,mode:"inline",imageData:L.data,mimeType:L.mimeType}])},ce=async L=>{for(const W of L){const ne=await Js(W);if(!ne){c("error",t("imageLoadFailed",{name:W.name}));continue}xe(ne)}},Se=20*1024*1024,Je=r.useRef(0),Te=async L=>{if(L.size>Se){c("warning",t("fileTooLarge",{name:L.name,size:Se/1024/1024}));return}let W;try{W=(await new Promise((ke,Ce)=>{const be=new FileReader;be.onload=()=>ke(be.result),be.onerror=()=>Ce(be.error??new Error("read failed")),be.readAsDataURL(L)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",t("fileLoadFailed",{name:L.name}));return}const ne=`upload-${++Je.current}`;o(ve=>[...ve,{path:"",key:ne,name:L.name,mode:"inline",fileData:W,size:L.size,mimeType:L.type||void 0}])},Ee=async L=>{for(const W of L)Le(W.type)?await ce([W]):await Te(W)},Qe=r.useCallback((L,W,ne)=>{i({type:"edit_message",messageId:L,text:W,attachments:ne})},[i]),Me=r.useCallback(()=>K(!0),[]),Xe=r.useCallback(()=>o([]),[]),Fe=r.useCallback(ee,[]),$e=r.useCallback(ce,[ce]),Oe=r.useCallback(Ee,[Ee]),C=(se=s.state)==null?void 0:se.model,ue=(me=s.state)==null?void 0:me.thinkingLevel,ae=(he=s.state)==null?void 0:he.availableThinkingLevels,ye=r.useMemo(()=>C?{model:C,thinkingLevel:ue??"off",availableThinkingLevels:ae??[]}:null,[C,ue,ae]),f=r.useCallback(()=>{var L,W;return!s.ready||s.terminals.length!==0?!1:(a.create({id:Be(),conversationId:s.activeConversationId||((L=s.state)==null?void 0:L.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((W=s.state)==null?void 0:W.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,(je=s.state)==null?void 0:je.cwd,s.terminals.length,t,a]);return r.useEffect(()=>{if(d.current){if(k!=="terminal"||s.terminals.length!==0){d.current=!1;return}f()&&(d.current=!1)}},[s.terminals.length,f,k]),e.jsxs("div",{className:"app",onDragOver:L=>{var W;Array.from(((W=L.dataTransfer)==null?void 0:W.types)??[]).includes("Files")&&(L.preventDefault(),g(!0))},onDragLeave:L=>{L.currentTarget.contains(L.relatedTarget)||g(!1)},onDrop:L=>{var ke,Ce;if(g(!1),!Array.from(((ke=L.dataTransfer)==null?void 0:ke.types)??[]).includes("Files"))return;L.preventDefault();const W=Array.from(((Ce=L.dataTransfer)==null?void 0:Ce.files)??[]);if(W.length===0){c("warning",t("foldersNotSupported"));return}const ne=W.filter(be=>Le(be.type)),ve=W.filter(be=>!Le(be.type));ne.length>0&&ce(ne),ve.length>0&&Ee(ve)},children:[p&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(di,{chat:s,send:i,terminal:a,view:k,plugins:N,onViewChange:L=>{d.current=L==="terminal"&&s.terminals.length===0,d.current&&f()&&(d.current=!1),b(L),m(null)},onOpenPanel:m,onOpenSettings:()=>x(!0),onOpenBgTasks:()=>$(!0),onOpenGlobalSearch:()=>z(!0),sound:V,onSoundChange:M,onSoundPreview:L=>tt(L,V),themes:F,theme:q,onThemeChange:te}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(L=>e.jsx(br,{notice:L,onDismiss:l},L.id))}),e.jsx(Ma,{send:i,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${_}px`,"--right-w":`${j}px`},children:[T&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>m(null)}),e.jsxs("div",{className:`view-pane ${k==="chat"?"":"hidden"}`,children:[e.jsx("div",{className:`panel-drawer drawer-left ${T==="left"?"open":""}`,children:e.jsx(pi,{send:fe,active:!B||T==="left",ready:s.ready,status:s.status,cwd:((Re=s.state)==null?void 0:Re.cwd)??"",sessionFile:((Ht=s.state)==null?void 0:Ht.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!B&&e.jsx(Rs,{side:"left",width:_,onResize:A}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(Da,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:Qe,onKillBash:()=>i({type:"abort_bash"}),thinkingWrap:((Kt=s.settings)==null?void 0:Kt.thinkingWrap)??!0,toolsWrap:((zt=s.settings)==null?void 0:zt.toolsWrap)??!0,jumpTarget:P,onJumpDone:()=>X(null)},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(Ha,{send:i,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId}),s.dialog&&e.jsx(Va,{dialog:s.dialog,send:i}),e.jsx(Ua,{send:i,ready:s.ready,streaming:((Vt=s.state)==null?void 0:Vt.isStreaming)??!1,messages:((Gt=s.state)==null?void 0:Gt.messages)??jr,slashCommands:s.slashCommands,modelState:ye,models:s.models,modelsLoading:s.modelsLoading,attachments:n,onRemoveAttachment:Fe,onAddImageFiles:$e,onAddLocalFiles:Oe,onNotice:c,onManageModels:Me,onSent:Xe})]}),!B&&e.jsx(Rs,{side:"right",width:j,onResize:S}),e.jsx("div",{className:`panel-drawer drawer-right ${T==="right"?"open":""}`,children:e.jsx(Oi,{send:fe,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((Yt=s.state)==null?void 0:Yt.cwd)??"",onAttach:(L,W,ne,ve)=>{m(null),le(L,W,ne,ve)},onPreview:(L,W)=>{m(null),h({path:L,name:W})},onNotice:(L,W)=>c(L,W)})})]}),e.jsx("div",{className:`view-pane ${k==="terminal"?"":"hidden"}`,children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(kr,{chat:s,send:i,terminal:a})})}),e.jsx("div",{className:`view-pane ${k==="git"?"":"hidden"}`,children:e.jsx(Ya,{chat:s,send:i,terminal:a,active:k==="git",onSwitchToTerminal:()=>b("terminal")})}),D.map(L=>{const W=`plugin:${L.info.id}`;return e.jsx("div",{className:`view-pane ${k===W?"":"hidden"}`,children:e.jsx(Ja,{entry:L,send:i})},L.info.id)})]})}),e.jsx(Ka,{chat:s,send:i}),u&&e.jsx(lr,{file:u,content:s.fileContent,send:i,onAddLines:(L,W,ne,ve)=>le(L,W,"lines",!1,{start:ne,end:ve}),onAttach:(L,W,ne)=>le(L,W,ne),onClose:()=>h(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!Z&&!U&&e.jsx(Qa,{send:i,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>Q(!0)}),U&&e.jsx(er,{send:i,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>K(!1)}),ie&&e.jsx(sr,{chat:s,send:i,terminal:a,onSwitchToTerminal:()=>b("terminal"),onClose:()=>x(!1)}),y&&e.jsx(ir,{servers:s.bgServers,send:i,onClose:()=>$(!1)}),e.jsx(rr,{open:ge,send:i,projects:s.projects,cwd:((Jt=s.state)==null?void 0:Jt.cwd)??"",fileSearch:s.fileSearch,sessionSearch:s.sessionSearch,onClose:()=>z(!1),onSwitchSession:(L,W)=>{i({type:"switch_session",path:L});const ne=W&&W[0];X(ne?{path:L,role:ne.role,timestamp:ne.timestamp}:null)},onSwitchProject:L=>{i({type:"set_cwd",path:L})},onPreviewFile:(L,W)=>{h({path:L,name:W})}})]})}mi();gn(hn());wn.createRoot(document.getElementById("root")).render(e.jsx(r.StrictMode,{children:e.jsx(oi,{children:e.jsx(wr,{})})}));export{gt as F,Es as T,_e as a,Tr as b,Sr as c,It as d,Ie as e,we as f,Un as g,ze as h,Be as r,pe as u};
|