pi-web-ui 0.56.0 → 0.56.1
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,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-qfBdYdPT.js","assets/markdown-DRBrS2Nf.js","assets/xterm-D1D2FVe3.js","assets/react-C9ovnpIm.js","assets/TerminalPanel-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
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(m){return Promise.all(m.map(p=>Promise.resolve(p).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};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(m=>{if(m=Cn(m),m in Zt)return;Zt[m]=!0;const p=m.endsWith(".css"),f=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${f}`))return;const k=document.createElement("link");if(k.rel=p?"stylesheet":Nn,p||(k.as="script"),k.crossOrigin="",k.href=m,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 ${m}`)))})}))}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 Ds(t){return t&&t.map((s,i)=>We.createElement(s.tag,dt({key:i},s.attr),Ds(s.child)))}function J(t){return s=>We.createElement(Ln,ct({attr:dt({},t.attr)},s),Ds(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 Dn(t){return J({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 Bn(t){return J({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 J({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 J({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 Bs(t){return J({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 J({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"17 8 12 3 7 8"},child:[]},{tag:"line",attr:{x1:"12",y1:"3",x2:"12",y2:"15"},child:[]}]})(t)}function _n(t){return J({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 J({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 J({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 J({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 Fn(t){return J({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 J({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 $n(t){return J({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 J({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 J({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 J({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 On(t){return J({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 J({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 J({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 J({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 Tr(t){return J({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 Wn(t){return J({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 J({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 Un(t){return J({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 J({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 J({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 Hn(t){return J({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 Kn(t){return J({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 zn(t){return J({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 Vn(t){return J({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 J({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 J({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 Gn(t){return J({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 Yn(t){return J({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 Jn(t){return J({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 Qn(t){return J({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 Xn(t){return J({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 J({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 J({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 J({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 J({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 J({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 J({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 J({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 J({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 J({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 J({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 Zn(t){return J({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 J({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 ei(t){return J({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 J({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 J({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 Ue(t){return J({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 J({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 ti(t){return J({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 J({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 si(t){return J({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 J({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 J({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 ni(t){return J({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 ii(t){return J({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 ai(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 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:m}){const p=r.useRef(null);return r.useEffect(()=>{if(!s)return;const f=b=>{p.current&&!p.current.contains(b.target)&&i(!1)},k=b=>{b.key==="Escape"&&i(!1)};return document.addEventListener("mousedown",f),document.addEventListener("keydown",k),()=>{document.removeEventListener("mousedown",f),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(Ue,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${o??""}`,ref:u,style:m,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 Us="pi-web-ui:lang",ri={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}",uploadToFolder:"上传文件到此文件夹",uploadToCurrentDir:"上传文件到当前目录",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",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. 项目类型、技术栈与目录结构
|
|
@@ -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 oi(){try{const t=localStorage.getItem(Us);if(t==="zh"||t==="en")return t}catch{}return"zh"}function ci({children:t}){const[s,i]=r.useState(oi),l=r.useCallback(n=>{i(n);try{localStorage.setItem(Us,n)}catch{}},[]),c=r.useCallback((n,o)=>{let u=li[n];if(s==="zh"&&(u=ri[n]),o)for(const[m,p]of Object.entries(o))u=u.replaceAll(`{${m}}`,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(qs.Provider,{value:a,children:t})}function Ot(){const t=r.useContext(qs);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function pe(){return Ot().t}const di=[{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(Bs,{className:"sound-icon"}),e.jsx("span",{children:l("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:a=>c({enabled:a.target.checked})})]}),di.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 ui({chat:t,send:s,terminal:i,view:l,plugins:c,onViewChange:a,onOpenPanel:n,onOpenSettings:o,onOpenBgTasks:u,onOpenGlobalSearch:m,sound:p,onSoundChange:f,onSoundPreview:k,themes:b,theme:N,onThemeChange:A}){var Y;const{locale:j,setLocale:_,t:y}=Ot(),[w,I]=r.useState(!1),[D,S]=r.useState(!1),[O,h]=r.useState(!1),[B,W]=r.useState(!1),[G,X]=r.useState(!1),q=[{value:"zh",label:y("langZh")},{value:"en",label:y("langEn")}],K=t.ready?y("connected"):t.status==="closed"?y("reconnecting"):y("connecting"),P=t.ready?"ok":"busy",g=()=>{var se,V;if(!t.ready)return;const M=y("updateTabTitle"),F={name:M,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},H=t.terminals.find(oe=>oe.title===M);H?(i.restart(H.id),s({type:"run_command",terminalId:H.id,conversationId:H.conversationId,command:F,cols:80,rows:24})):i.create({id:De(),conversationId:t.activeConversationId||((se=t.state)==null?void 0:se.conversationId)||"",title:M,cwd:((V=t.state)==null?void 0:V.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:F}),W(!1),X(!1),a("terminal")},v=(M,F)=>{var V,oe;if(!t.ready||M.length===0)return;const H={name:F,command:ai(M),cwd:"${pwd}"},se=t.terminals.find(re=>re.title===F);se?(i.restart(se.id),s({type:"run_command",terminalId:se.id,conversationId:se.conversationId,command:H,cols:80,rows:24})):i.create({id:De(),conversationId:t.activeConversationId||((V=t.state)==null?void 0:V.conversationId)||"",title:F,cwd:((oe=t.state)==null?void 0:oe.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:H}),W(!1),X(!1),a("terminal")},$=t.updatesAll??[],me=$.filter(M=>!M.upToDate&&!M.error).length,z=$.filter(M=>!M.upToDate&&!M.error&&M.kind!=="webui"),E=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:y("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:y("checkingUpdate")}):$.length===0?e.jsx("div",{className:"dd-note",children:y("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"?y("kindWebUi"):M.kind==="pi-core"?y("kindPiCore"):y("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:M.error?y("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:()=>v([M],y("updatePkgTabTitle",{name:M.name})),children:y("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:()=>v(z,y("updateAllTabTitle")),children:y("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:y("updatesAllRefresh")})]})]}),ee=()=>{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:y("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:y("latestVersion")}),e.jsx("b",{children:t.update===null?y("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:y("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:y("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:y("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:y("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:y("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?y("checkingUpdate"):y("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:g,children:y("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:y("openHistory"),onClick:()=>n("left"),children:e.jsx(Hn,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${P}`,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":y("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:y("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:y("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:y("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:y("searchGlobalTip"),onClick:m,children:[e.jsx(mt,{}),e.jsx("span",{className:"chip-sub",children:y("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":y("bgTasksTip"),onClick:u,children:[e.jsx(ht,{}),e.jsx("span",{className:"chip-sub",children:y("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:y("settingsTitle"),onClick:o,children:[e.jsx(pt,{}),e.jsx("span",{className:"chip-sub",children:y("settings")})]}),e.jsx(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Bs,{}),e.jsx("span",{className:"chip-sub",children:y("sound")})]}),open:w,onOpenChange:I,children:e.jsx(rs,{settings:p,onChange:f,onPreview:k})}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Xn,{}),e.jsx("span",{className:"chip-sub",children:j==="zh"?y("langZh"):"EN"})]}),open:D,onOpenChange:S,children:[e.jsx("div",{className:"dd-header",children:y("language")}),q.map(M=>e.jsx(Ne,{active:j===M.value,onClick:()=>{_(M.value),S(!1)},children:M.label},M.value))]}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Fn,{}),e.jsx("span",{className:"chip-sub",children:y("theme")})]}),open:O,onOpenChange:h,children:[e.jsx("div",{className:"dd-header",children:y("theme")}),e.jsx(Ne,{active:N===null,onClick:()=>{A(null),h(!1)},children:y("themeDefault")}),b.map(M=>e.jsx(Ne,{active:N===M.id,onClick:()=>{A(M.id),h(!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",((Y=t.update)==null?void 0:Y.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:y("updateAvailable",{version:t.update.latest??""})}),me>0&&e.jsx("span",{className:"update-badge",children:y("updatesAllBadge",{n:me})})]}),open:B,onOpenChange:M=>{W(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:y("update")}),ee(),E()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:y("githubRepo"),children:e.jsx(is,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":y("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(_e,{}),e.jsx("span",{children:y("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Un,{}),e.jsx("span",{className:"chip-sub",children:y("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:G,onOpenChange:M=>{X(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:y("sound")}),e.jsx("div",{className:"dd-header",children:y("settings")}),e.jsxs(Ne,{onClick:()=>{X(!1),o()},children:[e.jsx(pt,{})," ",y("settingsTitle")]}),e.jsxs(Ne,{onClick:()=>{X(!1),m()},children:[e.jsx(mt,{})," ",y("searchGlobal")]}),e.jsxs(Ne,{onClick:()=>{X(!1),u()},children:[e.jsx(ht,{})," ",y("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(rs,{settings:p,onChange:f,onPreview:k}),e.jsx("div",{className:"dd-header",children:y("language")}),q.map(M=>e.jsx(Ne,{active:j===M.value,onClick:()=>_(M.value),children:M.label},M.value)),e.jsx("div",{className:"dd-header",children:y("theme")}),e.jsx(Ne,{active:N===null,onClick:()=>{A(null),X(!1)},children:y("themeDefault")}),b.map(M=>e.jsx(Ne,{active:N===M.id,onClick:()=>{A(M.id),X(!1)},children:M.name},M.id)),e.jsx("div",{className:"dd-header",children:y("update")}),ee(),E(),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,{})," ",y("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:y("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 pi(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 mi=r.memo(function({ready:s,status:i,cwd:l,sessionFile:c,conversations:a,sessions:n,projects:o,activeConversationId:u,send:m,active:p}){const f=pe(),k=c,b=l,[N,A]=r.useState(null);r.useEffect(()=>{!p||!s||i!=="open"||l&&(m({type:"list_sessions"}),m({type:"list_projects"}))},[p,s,i,l,m]);const j=w=>{const I=w.name||w.firstMessage.trim();return I.length>0?I:f("emptyChat")},_=w=>w.split(/[\\/]/).pop()||w,y=(w,I,D,S)=>{const O=N===w;return e.jsx("button",{type:"button",className:`lp-del ${O?"confirm":""}`,title:O?D:I,onClick:h=>{h.stopPropagation(),O?(A(null),S()):A(w)},children:O?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:f("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:o.map(w=>{const I=b===w.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>A(D=>D===`proj:${w.path}`?null:D),children:[e.jsxs("button",{type:"button",className:`project-item ${I?"active":""}`,title:w.path,onClick:()=>{I||m({type:"set_cwd",path:w.path})},children:[e.jsx(Ge,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:_(w.path)}),e.jsx("span",{className:"project-path",children:w.path})]}),e.jsx("span",{className:"project-time",children:ls(w.lastUsed)})]}),y(`proj:${w.path}`,f("deleteProject"),f("deleteProjectConfirm"),()=>m({type:"remove_project",path:w.path}))]},w.path)})})]}),a.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:f("runningConversations")}),pi(a,l).map(w=>e.jsxs("div",{className:"panel-conv-group",children:[!w.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:w.cwd,children:_(w.cwd)}),w.convs.map(I=>{const D=u===I.id;return e.jsxs("button",{type:"button",className:`session-item ${D?"active":""}`,title:`${I.title}${w.isCurrent?"":` — ${w.cwd}`}`,onClick:()=>{D||m({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:D?f("current"):f("messageCount",{n:I.messageCount})})]}),I.isStreaming&&e.jsx("span",{className:"conv-streaming",title:f("streaming")})]},I.id)})]},w.cwd)),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:f("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[n.length===0&&e.jsx("div",{className:"panel-empty",children:f("noHistory")}),n.map(w=>{const I=k===w.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>A(D=>D===`sess:${w.path}`?null:D),children:[e.jsxs("button",{type:"button",className:`session-item ${I?"active":""}`,title:w.path,onClick:()=>{I||m({type:"switch_session",path:w.path})},children:[e.jsx(Ve,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:j(w)}),e.jsxs("span",{className:"session-sub",children:[I?f("current"):f("messageCount",{n:w.messageCount}),w.source==="tui"&&e.jsx("span",{className:"session-src",title:f("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:ls(w.modified)})]}),y(`sess:${w.path}`,f("deleteSession"),f("deleteSessionConfirm"),()=>m({type:"delete_session",path:w.path}))]},w.path)})]})]})]})}),Hs="pi-web-ui:token";function hi(){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 gi(){try{return localStorage.getItem(Hs)??""}catch{return""}}function yt(t){const s=gi();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}let jt=null;function fi(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 xi(){return jt===null&&(jt=fi()),jt}function vi(t,s){return s==="/"?t:s+t.replace(/^\/+/,"")}function Ye(t){return vi(t,xi())}function yi(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:[]},m=[...u.content],p=i.type==="thinking_delta"?"thinking":"text",f=i.contentIndex??m.length-1;return f>=0&&f<m.length&&m[f].type===p?m[f]=p==="thinking"?{type:"thinking",thinking:(m[f].thinking??"")+n}:{type:"text",text:(m[f].text??"")+n}:m.push(p==="thinking"?{type:"thinking",thinking:n}:{type:"text",text:n}),{...t,stats:a,streamingMessage:{...u,id:s.messageId,content:m}}}const Lt="pi-web-ui:plugin-data";function ki(t,s){window.dispatchEvent(new CustomEvent(Lt,{detail:{pluginId:t,payload:s}}))}function bi(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,Dt=new Set,qe=new Set;let os=-1;function Ks(){return[...Ke.values()]}function ji(){const t=Ks();for(const s of Dt)s(t)}function wi(t){return Dt.add(t),t(Ks()),()=>Dt.delete(t)}async function Ni(t,s){s!==os&&(os=s,Ke.clear(),qe.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[...qe])i.has(l)||qe.delete(l);await Promise.all(t.filter(l=>l.hasClient&&!l.error&&!Ke.has(l.id)&&!qe.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}):(qe.add(l.id),console.error(`[plugin:${l.id}] entry.mjs 缺少 default.mount`))}catch(c){qe.add(l.id),console.error(`[plugin:${l.id}] 客户端加载失败:`,c)}})),ji()}function Ci(t,s){return{pluginId:t,send:i=>s({type:"plugin_message",pluginId:t,payload:i}),onData:i=>bi((l,c)=>{l===t&&i(c)})}}const Si=10,wt=2e5,Ti=2e5,Ei={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 Mi(){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)??"",m=u.length+a.length>Ti?a:u+a;s.set(n,m)},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 m=t.get(n);m&&(m.delete(a),m.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 Ri(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!==Si};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,m=new Map(t.liveOutputs);return m.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:m}}case"message_delta":{const n=t.state;return!n||n.conversationId!==s.msg.conversationId?t:{...t,state:yi(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=De(),sessionStorage.setItem(us,t))}catch{t=t??De()}return Nt=t,t}function Pi(){const t=location.protocol==="https:"?"wss:":"ws:";return yt(`${t}//${location.host}${Ye("/ws")}`)}function Ii(){const[t,s]=r.useReducer(Ri,{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:Ei,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(Mi()),c=r.useRef(0),a=r.useRef(null),n=r.useRef(!0),o=r.useRef(0),u=r.useRef(0),m=r.useRef(new Map),p=r.useRef(null),f=()=>{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,O)=>{var W;const h=m.current,B=h.get(S);if(B!==void 0&&O!==B+1){const G=D.current.chat,X=G.activeConversationId||((W=G.state)==null?void 0:W.conversationId);S===X&&f()}h.set(S,O)},b=r.useCallback((S,O)=>{const h=++u.current;s({type:"notice",notice:{id:h,level:S,text:O}})},[]),N=r.useCallback(S=>{const O=i.current;return O&&O.readyState===WebSocket.OPEN?(S.type==="check_updates_all"&&S.force===!0&&s({type:"updates_check_started"}),O.send(JSON.stringify(S)),!0):!1},[]),A=r.useCallback(()=>{if(!n.current)return;s({type:"status",status:"connecting"});const S=new WebSocket(Pi());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=O=>{if(i.current!==S)return;o.current=Date.now();let h;try{h=JSON.parse(O.data)}catch{return}switch(h.type){case"ready":s({type:"ready",serverVersion:h.serverVersion,protocolVersion:h.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":m.current=new Map,s({type:"snapshot",state:h.state});break;case"snapshot_delta":{const B=D.current.chat.state;(!B||B.conversationId!==h.conversationId||B.rev!==h.baseRev)&&f(),s({type:"snapshot_delta",msg:h});break}case"tool_delta":k(h.conversationId,h.seq),s({type:"tool_delta",toolCallId:h.toolCallId,toolName:h.toolName,delta:h.delta});break;case"tool_status":s({type:"tool_status",status:h});break;case"message_delta":{k(h.conversationId,h.seq),s({type:"message_delta",msg:h});break}case"notice":{const B=++u.current;s({type:"notice",notice:{id:B,level:h.level,text:h.text}});break}case"sessions":s({type:"sessions",sessions:h.sessions});break;case"conversations":s({type:"conversations",conversations:h.conversations,activeId:h.activeId});break;case"projects":s({type:"projects",projects:h.projects});break;case"files":s({type:"files",files:h});break;case"file_changed":s({type:"file_changed",path:h.path});break;case"file_content":s({type:"file_content",content:h});break;case"models":s({type:"models",models:h.models,loading:!1});break;case"models_config":s({type:"models_config",providers:h.providers});break;case"providers_status":s({type:"providers_status",providers:h.providers});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:h.reqId,ok:h.ok,models:h.models,error:h.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:h.reqId,ok:h.ok,added:h.added,total:h.total,error:h.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:h.reqId,ok:h.ok,config:h.config,error:h.error}});break;case"scm_data":s({type:"scm_data",data:h});break;case"search_files_result":s({type:"file_search_result",result:{reqId:h.reqId,ok:h.ok,results:h.results,truncated:h.truncated}});break;case"session_search_results":s({type:"session_search_result",result:{reqId:h.reqId,ok:h.ok,results:h.results}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:h});break;case"path_completions":s({type:"path_completions",completions:h.completions});break;case"update_status":s({type:"update_status",status:h});break;case"update_status_all":s({type:"update_status_all",items:h.items});break;case"widgets":s({type:"widgets",widgets:h.widgets});break;case"statuses":s({type:"statuses",statuses:h.statuses});break;case"dialog":s({type:"dialog",dialog:{id:h.id,kind:h.kind,title:h.title,args:h.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"terminal_output":l.current.write(h.conversationId??D.current.chat.activeConversationId,h.terminalId,h.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:h.conversationId,terminalId:h.terminalId,exitCode:h.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:h.conversationId,terminals:h.terminals});break;case"commands":s({type:"commands",commands:h.commands,path:h.path});break;case"slash_commands":s({type:"slash_commands",commands:h.commands});break;case"goal_status":s({type:"goal_status",status:h.status});break;case"settings_state":s({type:"settings",settings:h.settings});break;case"bg_servers":s({type:"bg_servers",servers:h.servers});break;case"plugins":s({type:"plugins",plugins:h.plugins,epoch:h.epoch});break;case"plugin_data":ki(h.pluginId,h.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 O=Math.min(1e3*2**c.current,1e4);c.current+=1,a.current=setTimeout(()=>{a.current=null,A()},O)},S.onerror=()=>{}},[]);r.useEffect(()=>{n.current=!0,A();const S=setInterval(()=>{if(!n.current)return;const O=i.current;O&&O.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&O.close()},5e3);return()=>{var O;n.current=!1,clearInterval(S),a.current&&(clearTimeout(a.current),a.current=null),(O=i.current)==null||O.close(),i.current=null}},[A]);const j=r.useCallback(S=>s({type:"dismiss_notice",id:S}),[]),_=r.useCallback(S=>s({type:"terminal_add",meta:S}),[]),y=r.useCallback(S=>s({type:"terminal_remove",id:S}),[]),w=r.useCallback(S=>s({type:"terminal_restart",terminalId:S}),[]),I=r.useCallback((S,O,h)=>l.current.register(S,O,h),[]),D=r.useRef({chat:t,send:N,pushNotice:b,dismissNotice:j,terminal:{create:_,close:y,register:I,restart:w}});return D.current={chat:t,send:N,pushNotice:b,dismissNotice:j,terminal:{create:_,close:y,register:I,restart:w}},D.current}const Li=200*1024*1024,Di=/windows/i.test(navigator.userAgent),Bi=/[<>:"/\\|?*\u0000-\u001f]/g,Ai=/[. ]+$/,_i=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Fi(t){const s=t.replace(Bi,"_").replace(Ai,"");return s?_i.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 $i(t,s){const i=Di?Fi(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")>Li)return window.location.assign(ps(t)),{ok:!0};const a=await l.blob();return window.showSaveFilePicker&&window.isSecureContext?Oi(a,i):Bt(a,i)}catch(l){return{ok:!1,cancelled:!1,error:l instanceof Error?l.message:String(l)}}}async function Oi(t,s){let i;const l=window.showSaveFilePicker;if(!l)return Bt(t,s);try{i=await l({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:Bt(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 Bt(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 Wi=r.memo(function({files:s,fileChanged:i,widgets:l,cwd:c,send:a,onAttach:n,onPreview:o,onNotice:u}){const m=pe(),[p,f]=r.useState(""),[k,b]=r.useState(null),[N,A]=r.useState(!1),[j,_]=r.useState(null),y=r.useRef(""),w=r.useRef(null),I=r.useCallback((P,g)=>{P.preventDefault(),y.current=g,_({x:Math.min(P.clientX,window.innerWidth-220),y:Math.min(P.clientY,window.innerHeight-90)})},[]),D=r.useCallback(()=>_(null),[]);r.useEffect(()=>{if(!j)return;const P=()=>D(),g=v=>{v.key==="Escape"&&D()};return window.addEventListener("mousedown",P,!0),window.addEventListener("keydown",g),window.addEventListener("blur",P),()=>{window.removeEventListener("mousedown",P,!0),window.removeEventListener("keydown",g),window.removeEventListener("blur",P)}},[j,D]);const S=r.useCallback(()=>{var P;D(),w.current&&(w.current.value=""),(P=w.current)==null||P.click()},[D]),O=r.useCallback(P=>{const g=y.current,v=Array.from(P.target.files??[]);for(const $ of v){const me=new FileReader;me.onload=()=>{const z=me.result,E=z.slice(z.indexOf(",")+1);E&&a({type:"upload_file",dirPath:g,name:$.name,data:E})},me.readAsDataURL($)}},[a]),h=1e4,B=r.useRef(0),W=r.useRef(void 0),G=r.useCallback((P,g)=>{const v=++B.current;f(P),g!=null&&g.silent||A(!0),a({type:"list_files",path:P===""?void 0:P})||B.current===v&&A(!1)},[a]);r.useEffect(()=>{s&&s.path===p&&A(!1)},[s,p]),r.useEffect(()=>{if(c!==W.current){W.current=c,G("",{silent:!0});return}const P=setInterval(()=>{document.visibilityState!=="hidden"&&G(p,{silent:!0})},h);return()=>clearInterval(P)},[c,p,G]),r.useEffect(()=>{i&&i.path===p&&G(p,{silent:!0})},[i,p,G]);const X=P=>G(P),q=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&G(s.parent)},K=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:()=>G(""),children:m("rootDir")}),K.map((P,g)=>{const v=K.slice(0,g+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(xt,{}),e.jsx("button",{type:"button",className:`crumb ${v===p?"active":""}`,onClick:()=>G(v),children:P})]},v)})]}),e.jsxs("div",{className:"panel-body",onContextMenu:P=>I(P,p),children:[e.jsx("input",{ref:w,type:"file",multiple:!0,hidden:!0,onChange:O}),N&&e.jsx("div",{className:"panel-empty",children:m("loading")}),!N&&s&&s.path===p&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:q,children:[e.jsx(Ge,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(P=>P.type==="dir"?e.jsxs("div",{className:"file-item dir",onContextMenu:g=>I(g,P.path),children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>X(P.path),children:[e.jsx(Ge,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:P.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":m("linkFolderTip"),onClick:()=>n(P.path,P.name,"reference",!0),children:e.jsx(Mt,{})})]},P.path):e.jsxs("div",{className:"file-item file",onContextMenu:g=>I(g,p),children:[e.jsxs("button",{type:"button",className:"file-name",title:`${P.path} — ${m("previewFile")}`,onClick:()=>o(P.path,P.name),children:[e.jsx(Fs,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:P.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":m("downloadFile"),onClick:()=>{$i(P.path,P.name).then(g=>{g.ok||g.cancelled||u("error",m("downloadFailed",{error:g.error}))})},children:e.jsx(Ft,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":m("attachInlineTip"),onClick:()=>n(P.path,P.name,"inline"),children:e.jsx(_e,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":m("referenceTip"),onClick:()=>n(P.path,P.name,"reference"),children:e.jsx(Mt,{})})]},P.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:m("filesTruncated")})]}),!N&&!s&&e.jsx("div",{className:"panel-empty",children:m("noFiles")})]}),l.filter(P=>P.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:l.filter(P=>P.lines.length>0).map(P=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:m("widgetExpand"),onClick:()=>b(P.key),children:[e.jsx("span",{children:P.key}),e.jsx(zn,{})]}),e.jsx("pre",{className:"widget-lines",children:P.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…"},qs=r.createContext(null);function oi(){try{const t=localStorage.getItem(Us);if(t==="zh"||t==="en")return t}catch{}return"zh"}function ci({children:t}){const[s,i]=r.useState(oi),l=r.useCallback(n=>{i(n);try{localStorage.setItem(Us,n)}catch{}},[]),c=r.useCallback((n,o)=>{let u=li[n];if(s==="zh"&&(u=ri[n]),o)for(const[m,p]of Object.entries(o))u=u.replaceAll(`{${m}}`,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(qs.Provider,{value:a,children:t})}function Ot(){const t=r.useContext(qs);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function me(){return Ot().t}const di=[{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=me(),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(Bs,{className:"sound-icon"}),e.jsx("span",{children:l("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:a=>c({enabled:a.target.checked})})]}),di.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 ui({chat:t,send:s,terminal:i,view:l,plugins:c,onViewChange:a,onOpenPanel:n,onOpenSettings:o,onOpenBgTasks:u,onOpenGlobalSearch:m,sound:p,onSoundChange:f,onSoundPreview:k,themes:b,theme:N,onThemeChange:A}){var Y;const{locale:j,setLocale:_,t:y}=Ot(),[w,I]=r.useState(!1),[D,S]=r.useState(!1),[O,h]=r.useState(!1),[B,W]=r.useState(!1),[G,X]=r.useState(!1),q=[{value:"zh",label:y("langZh")},{value:"en",label:y("langEn")}],K=t.ready?y("connected"):t.status==="closed"?y("reconnecting"):y("connecting"),P=t.ready?"ok":"busy",g=()=>{var se,V;if(!t.ready)return;const M=y("updateTabTitle"),F={name:M,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},H=t.terminals.find(oe=>oe.title===M);H?(i.restart(H.id),s({type:"run_command",terminalId:H.id,conversationId:H.conversationId,command:F,cols:80,rows:24})):i.create({id:De(),conversationId:t.activeConversationId||((se=t.state)==null?void 0:se.conversationId)||"",title:M,cwd:((V=t.state)==null?void 0:V.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:F}),W(!1),X(!1),a("terminal")},v=(M,F)=>{var V,oe;if(!t.ready||M.length===0)return;const H={name:F,command:ai(M),cwd:"${pwd}"},se=t.terminals.find(re=>re.title===F);se?(i.restart(se.id),s({type:"run_command",terminalId:se.id,conversationId:se.conversationId,command:H,cols:80,rows:24})):i.create({id:De(),conversationId:t.activeConversationId||((V=t.state)==null?void 0:V.conversationId)||"",title:F,cwd:((oe=t.state)==null?void 0:oe.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:H}),W(!1),X(!1),a("terminal")},$=t.updatesAll??[],pe=$.filter(M=>!M.upToDate&&!M.error).length,z=$.filter(M=>!M.upToDate&&!M.error&&M.kind!=="webui"),E=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:y("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:y("checkingUpdate")}):$.length===0?e.jsx("div",{className:"dd-note",children:y("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"?y("kindWebUi"):M.kind==="pi-core"?y("kindPiCore"):y("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:M.error?y("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:()=>v([M],y("updatePkgTabTitle",{name:M.name})),children:y("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:()=>v(z,y("updateAllTabTitle")),children:y("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:y("updatesAllRefresh")})]})]}),ee=()=>{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:y("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:y("latestVersion")}),e.jsx("b",{children:t.update===null?y("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:y("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:y("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:y("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:y("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:y("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?y("checkingUpdate"):y("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:g,children:y("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:y("openHistory"),onClick:()=>n("left"),children:e.jsx(Hn,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${P}`,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":y("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:y("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:y("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:y("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:y("searchGlobalTip"),onClick:m,children:[e.jsx(mt,{}),e.jsx("span",{className:"chip-sub",children:y("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":y("bgTasksTip"),onClick:u,children:[e.jsx(ht,{}),e.jsx("span",{className:"chip-sub",children:y("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:y("settingsTitle"),onClick:o,children:[e.jsx(pt,{}),e.jsx("span",{className:"chip-sub",children:y("settings")})]}),e.jsx(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Bs,{}),e.jsx("span",{className:"chip-sub",children:y("sound")})]}),open:w,onOpenChange:I,children:e.jsx(rs,{settings:p,onChange:f,onPreview:k})}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Xn,{}),e.jsx("span",{className:"chip-sub",children:j==="zh"?y("langZh"):"EN"})]}),open:D,onOpenChange:S,children:[e.jsx("div",{className:"dd-header",children:y("language")}),q.map(M=>e.jsx(Ne,{active:j===M.value,onClick:()=>{_(M.value),S(!1)},children:M.label},M.value))]}),e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Fn,{}),e.jsx("span",{className:"chip-sub",children:y("theme")})]}),open:O,onOpenChange:h,children:[e.jsx("div",{className:"dd-header",children:y("theme")}),e.jsx(Ne,{active:N===null,onClick:()=>{A(null),h(!1)},children:y("themeDefault")}),b.map(M=>e.jsx(Ne,{active:N===M.id,onClick:()=>{A(M.id),h(!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",((Y=t.update)==null?void 0:Y.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:y("updateAvailable",{version:t.update.latest??""})}),pe>0&&e.jsx("span",{className:"update-badge",children:y("updatesAllBadge",{n:pe})})]}),open:B,onOpenChange:M=>{W(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:y("update")}),ee(),E()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:y("githubRepo"),children:e.jsx(is,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":y("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(_e,{}),e.jsx("span",{children:y("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Ae,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Un,{}),e.jsx("span",{className:"chip-sub",children:y("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:G,onOpenChange:M=>{X(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:y("sound")}),e.jsx("div",{className:"dd-header",children:y("settings")}),e.jsxs(Ne,{onClick:()=>{X(!1),o()},children:[e.jsx(pt,{})," ",y("settingsTitle")]}),e.jsxs(Ne,{onClick:()=>{X(!1),m()},children:[e.jsx(mt,{})," ",y("searchGlobal")]}),e.jsxs(Ne,{onClick:()=>{X(!1),u()},children:[e.jsx(ht,{})," ",y("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(rs,{settings:p,onChange:f,onPreview:k}),e.jsx("div",{className:"dd-header",children:y("language")}),q.map(M=>e.jsx(Ne,{active:j===M.value,onClick:()=>_(M.value),children:M.label},M.value)),e.jsx("div",{className:"dd-header",children:y("theme")}),e.jsx(Ne,{active:N===null,onClick:()=>{A(null),X(!1)},children:y("themeDefault")}),b.map(M=>e.jsx(Ne,{active:N===M.id,onClick:()=>{A(M.id),X(!1)},children:M.name},M.id)),e.jsx("div",{className:"dd-header",children:y("update")}),ee(),E(),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,{})," ",y("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:y("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 pi(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 mi=r.memo(function({ready:s,status:i,cwd:l,sessionFile:c,conversations:a,sessions:n,projects:o,activeConversationId:u,send:m,active:p}){const f=me(),k=c,b=l,[N,A]=r.useState(null);r.useEffect(()=>{!p||!s||i!=="open"||l&&(m({type:"list_sessions"}),m({type:"list_projects"}))},[p,s,i,l,m]);const j=w=>{const I=w.name||w.firstMessage.trim();return I.length>0?I:f("emptyChat")},_=w=>w.split(/[\\/]/).pop()||w,y=(w,I,D,S)=>{const O=N===w;return e.jsx("button",{type:"button",className:`lp-del ${O?"confirm":""}`,title:O?D:I,onClick:h=>{h.stopPropagation(),O?(A(null),S()):A(w)},children:O?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:f("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:o.map(w=>{const I=b===w.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>A(D=>D===`proj:${w.path}`?null:D),children:[e.jsxs("button",{type:"button",className:`project-item ${I?"active":""}`,title:w.path,onClick:()=>{I||m({type:"set_cwd",path:w.path})},children:[e.jsx(Ge,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:_(w.path)}),e.jsx("span",{className:"project-path",children:w.path})]}),e.jsx("span",{className:"project-time",children:ls(w.lastUsed)})]}),y(`proj:${w.path}`,f("deleteProject"),f("deleteProjectConfirm"),()=>m({type:"remove_project",path:w.path}))]},w.path)})})]}),a.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:f("runningConversations")}),pi(a,l).map(w=>e.jsxs("div",{className:"panel-conv-group",children:[!w.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:w.cwd,children:_(w.cwd)}),w.convs.map(I=>{const D=u===I.id;return e.jsxs("button",{type:"button",className:`session-item ${D?"active":""}`,title:`${I.title}${w.isCurrent?"":` — ${w.cwd}`}`,onClick:()=>{D||m({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:D?f("current"):f("messageCount",{n:I.messageCount})})]}),I.isStreaming&&e.jsx("span",{className:"conv-streaming",title:f("streaming")})]},I.id)})]},w.cwd)),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:f("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[n.length===0&&e.jsx("div",{className:"panel-empty",children:f("noHistory")}),n.map(w=>{const I=k===w.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>A(D=>D===`sess:${w.path}`?null:D),children:[e.jsxs("button",{type:"button",className:`session-item ${I?"active":""}`,title:w.path,onClick:()=>{I||m({type:"switch_session",path:w.path})},children:[e.jsx(Ve,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:j(w)}),e.jsxs("span",{className:"session-sub",children:[I?f("current"):f("messageCount",{n:w.messageCount}),w.source==="tui"&&e.jsx("span",{className:"session-src",title:f("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:ls(w.modified)})]}),y(`sess:${w.path}`,f("deleteSession"),f("deleteSessionConfirm"),()=>m({type:"delete_session",path:w.path}))]},w.path)})]})]})]})}),Hs="pi-web-ui:token";function hi(){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 gi(){try{return localStorage.getItem(Hs)??""}catch{return""}}function yt(t){const s=gi();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}let jt=null;function fi(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 xi(){return jt===null&&(jt=fi()),jt}function vi(t,s){return s==="/"?t:s+t.replace(/^\/+/,"")}function Ye(t){return vi(t,xi())}function yi(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:[]},m=[...u.content],p=i.type==="thinking_delta"?"thinking":"text",f=i.contentIndex??m.length-1;return f>=0&&f<m.length&&m[f].type===p?m[f]=p==="thinking"?{type:"thinking",thinking:(m[f].thinking??"")+n}:{type:"text",text:(m[f].text??"")+n}:m.push(p==="thinking"?{type:"thinking",thinking:n}:{type:"text",text:n}),{...t,stats:a,streamingMessage:{...u,id:s.messageId,content:m}}}const Lt="pi-web-ui:plugin-data";function ki(t,s){window.dispatchEvent(new CustomEvent(Lt,{detail:{pluginId:t,payload:s}}))}function bi(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,Dt=new Set,qe=new Set;let os=-1;function Ks(){return[...Ke.values()]}function ji(){const t=Ks();for(const s of Dt)s(t)}function wi(t){return Dt.add(t),t(Ks()),()=>Dt.delete(t)}async function Ni(t,s){s!==os&&(os=s,Ke.clear(),qe.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[...qe])i.has(l)||qe.delete(l);await Promise.all(t.filter(l=>l.hasClient&&!l.error&&!Ke.has(l.id)&&!qe.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}):(qe.add(l.id),console.error(`[plugin:${l.id}] entry.mjs 缺少 default.mount`))}catch(c){qe.add(l.id),console.error(`[plugin:${l.id}] 客户端加载失败:`,c)}})),ji()}function Ci(t,s){return{pluginId:t,send:i=>s({type:"plugin_message",pluginId:t,payload:i}),onData:i=>bi((l,c)=>{l===t&&i(c)})}}const Si=10,wt=2e5,Ti=2e5,Ei={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 Mi(){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)??"",m=u.length+a.length>Ti?a:u+a;s.set(n,m)},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 m=t.get(n);m&&(m.delete(a),m.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 Ri(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!==Si};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,m=new Map(t.liveOutputs);return m.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:m}}case"message_delta":{const n=t.state;return!n||n.conversationId!==s.msg.conversationId?t:{...t,state:yi(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=De(),sessionStorage.setItem(us,t))}catch{t=t??De()}return Nt=t,t}function Pi(){const t=location.protocol==="https:"?"wss:":"ws:";return yt(`${t}//${location.host}${Ye("/ws")}`)}function Ii(){const[t,s]=r.useReducer(Ri,{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:Ei,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(Mi()),c=r.useRef(0),a=r.useRef(null),n=r.useRef(!0),o=r.useRef(0),u=r.useRef(0),m=r.useRef(new Map),p=r.useRef(null),f=()=>{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,O)=>{var W;const h=m.current,B=h.get(S);if(B!==void 0&&O!==B+1){const G=D.current.chat,X=G.activeConversationId||((W=G.state)==null?void 0:W.conversationId);S===X&&f()}h.set(S,O)},b=r.useCallback((S,O)=>{const h=++u.current;s({type:"notice",notice:{id:h,level:S,text:O}})},[]),N=r.useCallback(S=>{const O=i.current;return O&&O.readyState===WebSocket.OPEN?(S.type==="check_updates_all"&&S.force===!0&&s({type:"updates_check_started"}),O.send(JSON.stringify(S)),!0):!1},[]),A=r.useCallback(()=>{if(!n.current)return;s({type:"status",status:"connecting"});const S=new WebSocket(Pi());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=O=>{if(i.current!==S)return;o.current=Date.now();let h;try{h=JSON.parse(O.data)}catch{return}switch(h.type){case"ready":s({type:"ready",serverVersion:h.serverVersion,protocolVersion:h.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":m.current=new Map,s({type:"snapshot",state:h.state});break;case"snapshot_delta":{const B=D.current.chat.state;(!B||B.conversationId!==h.conversationId||B.rev!==h.baseRev)&&f(),s({type:"snapshot_delta",msg:h});break}case"tool_delta":k(h.conversationId,h.seq),s({type:"tool_delta",toolCallId:h.toolCallId,toolName:h.toolName,delta:h.delta});break;case"tool_status":s({type:"tool_status",status:h});break;case"message_delta":{k(h.conversationId,h.seq),s({type:"message_delta",msg:h});break}case"notice":{const B=++u.current;s({type:"notice",notice:{id:B,level:h.level,text:h.text}});break}case"sessions":s({type:"sessions",sessions:h.sessions});break;case"conversations":s({type:"conversations",conversations:h.conversations,activeId:h.activeId});break;case"projects":s({type:"projects",projects:h.projects});break;case"files":s({type:"files",files:h});break;case"file_changed":s({type:"file_changed",path:h.path});break;case"file_content":s({type:"file_content",content:h});break;case"models":s({type:"models",models:h.models,loading:!1});break;case"models_config":s({type:"models_config",providers:h.providers});break;case"providers_status":s({type:"providers_status",providers:h.providers});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:h.reqId,ok:h.ok,models:h.models,error:h.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:h.reqId,ok:h.ok,added:h.added,total:h.total,error:h.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:h.reqId,ok:h.ok,config:h.config,error:h.error}});break;case"scm_data":s({type:"scm_data",data:h});break;case"search_files_result":s({type:"file_search_result",result:{reqId:h.reqId,ok:h.ok,results:h.results,truncated:h.truncated}});break;case"session_search_results":s({type:"session_search_result",result:{reqId:h.reqId,ok:h.ok,results:h.results}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:h});break;case"path_completions":s({type:"path_completions",completions:h.completions});break;case"update_status":s({type:"update_status",status:h});break;case"update_status_all":s({type:"update_status_all",items:h.items});break;case"widgets":s({type:"widgets",widgets:h.widgets});break;case"statuses":s({type:"statuses",statuses:h.statuses});break;case"dialog":s({type:"dialog",dialog:{id:h.id,kind:h.kind,title:h.title,args:h.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"terminal_output":l.current.write(h.conversationId??D.current.chat.activeConversationId,h.terminalId,h.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:h.conversationId,terminalId:h.terminalId,exitCode:h.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:h.conversationId,terminals:h.terminals});break;case"commands":s({type:"commands",commands:h.commands,path:h.path});break;case"slash_commands":s({type:"slash_commands",commands:h.commands});break;case"goal_status":s({type:"goal_status",status:h.status});break;case"settings_state":s({type:"settings",settings:h.settings});break;case"bg_servers":s({type:"bg_servers",servers:h.servers});break;case"plugins":s({type:"plugins",plugins:h.plugins,epoch:h.epoch});break;case"plugin_data":ki(h.pluginId,h.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 O=Math.min(1e3*2**c.current,1e4);c.current+=1,a.current=setTimeout(()=>{a.current=null,A()},O)},S.onerror=()=>{}},[]);r.useEffect(()=>{n.current=!0,A();const S=setInterval(()=>{if(!n.current)return;const O=i.current;O&&O.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&O.close()},5e3);return()=>{var O;n.current=!1,clearInterval(S),a.current&&(clearTimeout(a.current),a.current=null),(O=i.current)==null||O.close(),i.current=null}},[A]);const j=r.useCallback(S=>s({type:"dismiss_notice",id:S}),[]),_=r.useCallback(S=>s({type:"terminal_add",meta:S}),[]),y=r.useCallback(S=>s({type:"terminal_remove",id:S}),[]),w=r.useCallback(S=>s({type:"terminal_restart",terminalId:S}),[]),I=r.useCallback((S,O,h)=>l.current.register(S,O,h),[]),D=r.useRef({chat:t,send:N,pushNotice:b,dismissNotice:j,terminal:{create:_,close:y,register:I,restart:w}});return D.current={chat:t,send:N,pushNotice:b,dismissNotice:j,terminal:{create:_,close:y,register:I,restart:w}},D.current}const Li=200*1024*1024,Di=/windows/i.test(navigator.userAgent),Bi=/[<>:"/\\|?*\u0000-\u001f]/g,Ai=/[. ]+$/,_i=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Fi(t){const s=t.replace(Bi,"_").replace(Ai,"");return s?_i.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 $i(t,s){const i=Di?Fi(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")>Li)return window.location.assign(ps(t)),{ok:!0};const a=await l.blob();return window.showSaveFilePicker&&window.isSecureContext?Oi(a,i):Bt(a,i)}catch(l){return{ok:!1,cancelled:!1,error:l instanceof Error?l.message:String(l)}}}async function Oi(t,s){let i;const l=window.showSaveFilePicker;if(!l)return Bt(t,s);try{i=await l({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:Bt(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 Bt(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 Wi=r.memo(function({files:s,fileChanged:i,widgets:l,cwd:c,send:a,onAttach:n,onPreview:o,onNotice:u}){const m=me(),[p,f]=r.useState(""),[k,b]=r.useState(null),[N,A]=r.useState(!1),[j,_]=r.useState(null),y=r.useRef(""),w=r.useRef(null),I=r.useCallback((P,g)=>{P.preventDefault(),y.current=g,_({x:Math.min(P.clientX,window.innerWidth-220),y:Math.min(P.clientY,window.innerHeight-90)})},[]),D=r.useCallback(()=>_(null),[]);r.useEffect(()=>{if(!j)return;const P=$=>{var pe;(pe=$.target)!=null&&pe.closest(".ctx-menu")||D()},g=$=>{$.key==="Escape"&&D()};window.addEventListener("mousedown",P,!0),window.addEventListener("keydown",g);const v=()=>D();return window.addEventListener("blur",v),()=>{window.removeEventListener("mousedown",P,!0),window.removeEventListener("keydown",g),window.removeEventListener("blur",v)}},[j,D]);const S=r.useCallback(()=>{var P;D(),w.current&&(w.current.value=""),(P=w.current)==null||P.click()},[D]),O=r.useCallback(P=>{const g=y.current,v=Array.from(P.target.files??[]);for(const $ of v){const pe=new FileReader;pe.onload=()=>{const z=pe.result,E=z.slice(z.indexOf(",")+1);E&&a({type:"upload_file",dirPath:g,name:$.name,data:E})},pe.readAsDataURL($)}},[a]),h=1e4,B=r.useRef(0),W=r.useRef(void 0),G=r.useCallback((P,g)=>{const v=++B.current;f(P),g!=null&&g.silent||A(!0),a({type:"list_files",path:P===""?void 0:P})||B.current===v&&A(!1)},[a]);r.useEffect(()=>{s&&s.path===p&&A(!1)},[s,p]),r.useEffect(()=>{if(c!==W.current){W.current=c,G("",{silent:!0});return}const P=setInterval(()=>{document.visibilityState!=="hidden"&&G(p,{silent:!0})},h);return()=>clearInterval(P)},[c,p,G]),r.useEffect(()=>{i&&i.path===p&&G(p,{silent:!0})},[i,p,G]);const X=P=>G(P),q=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&G(s.parent)},K=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:()=>G(""),children:m("rootDir")}),K.map((P,g)=>{const v=K.slice(0,g+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(xt,{}),e.jsx("button",{type:"button",className:`crumb ${v===p?"active":""}`,onClick:()=>G(v),children:P})]},v)})]}),e.jsxs("div",{className:"panel-body",onContextMenu:P=>I(P,p),children:[e.jsx("input",{ref:w,type:"file",multiple:!0,hidden:!0,onChange:O}),N&&e.jsx("div",{className:"panel-empty",children:m("loading")}),!N&&s&&s.path===p&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:q,children:[e.jsx(Ge,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(P=>P.type==="dir"?e.jsxs("div",{className:"file-item dir",onContextMenu:g=>{g.stopPropagation(),I(g,P.path)},children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>X(P.path),children:[e.jsx(Ge,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:P.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":m("linkFolderTip"),onClick:()=>n(P.path,P.name,"reference",!0),children:e.jsx(Mt,{})})]},P.path):e.jsxs("div",{className:"file-item file",onContextMenu:g=>{g.stopPropagation(),I(g,p)},children:[e.jsxs("button",{type:"button",className:"file-name",title:`${P.path} — ${m("previewFile")}`,onClick:()=>o(P.path,P.name),children:[e.jsx(Fs,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:P.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":m("downloadFile"),onClick:()=>{$i(P.path,P.name).then(g=>{g.ok||g.cancelled||u("error",m("downloadFailed",{error:g.error}))})},children:e.jsx(Ft,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":m("attachInlineTip"),onClick:()=>n(P.path,P.name,"inline"),children:e.jsx(_e,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":m("referenceTip"),onClick:()=>n(P.path,P.name,"reference"),children:e.jsx(Mt,{})})]},P.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:m("filesTruncated")})]}),!N&&!s&&e.jsx("div",{className:"panel-empty",children:m("noFiles")})]}),l.filter(P=>P.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:l.filter(P=>P.lines.length>0).map(P=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:m("widgetExpand"),onClick:()=>b(P.key),children:[e.jsx("span",{children:P.key}),e.jsx(zn,{})]}),e.jsx("pre",{className:"widget-lines",children:P.lines.join(`
|
|
304
304
|
`)})]},P.key))}),k&&(()=>{const P=l.find(g=>g.key===k);return P?e.jsx("div",{className:"modal-backdrop",onClick:()=>b(null),children:e.jsxs("div",{className:"widget-expand",onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"widget-expand-head",children:[e.jsx("span",{className:"widget-expand-title",children:P.key}),e.jsx("button",{type:"button",className:"btn",title:m("close"),onClick:()=>b(null),children:e.jsx(we,{})})]}),e.jsx("pre",{className:"widget-expand-lines",children:P.lines.join(`
|
|
305
|
-
`)})]})}):null})(),j&&e.jsx("div",{className:"ctx-menu",style:{left:j.x,top:j.y},onContextMenu:P=>{P.preventDefault(),P.stopPropagation()},children:e.jsxs("button",{type:"button",className:"ctx-item",onClick:S,children:[e.jsx(An,{}),y.current===p?m("uploadToCurrentDir"):m("uploadToFolder")]})})]})});var ms=Is();const zs=r.memo(function({text:s}){const i=
|
|
305
|
+
`)})]})}):null})(),j&&e.jsx("div",{className:"ctx-menu",style:{left:j.x,top:j.y},onContextMenu:P=>{P.preventDefault(),P.stopPropagation()},children:e.jsxs("button",{type:"button",className:"ctx-item",onClick:S,children:[e.jsx(An,{}),y.current===p?m("uploadToCurrentDir"):m("uploadToFolder")]})})]})});var ms=Is();const zs=r.memo(function({text:s}){const i=me(),[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 Ui(t){const s=l=>{var c;if(typeof l=="string"||typeof l=="number"){const a=String(l);return a===""?[[]]:a.split(`
|
|
306
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(m=>[r.createElement(a.type,o,...m)])}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=Ui(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 Hi=/^\s{0,3}(`{3,}|~{3,})/,Ki=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function Ct(t){return t.trim()===""}function hs(t){const s=Hi.exec(t);return s?s[1]:null}function zi(t){const s=t.split(`
|
|
307
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&&Ki.test(s[u]))&&l.length>0){i.push(l.join(`
|
|
308
308
|
`)),l=[];continue}l.push(n);continue}l.push(n)}return{frozen:i,active:l.join(`
|
|
309
|
-
`),inFence:c!==null}}const Vi=r.memo(function({text:s}){return e.jsx(Ps,{remarkPlugins:Vs,rehypePlugins:Gs,children:s})}),gs=200;function Gi({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 Yi=r.memo(function({text:s}){const{frozen:i,active:l,inFence:c}=r.useMemo(()=>zi(s),[s]);return e.jsxs("div",{className:"md",children:[i.map((a,n)=>e.jsx(Vi,{text:a},n)),l.length>0&&e.jsx(Gi,{text:l,inFence:c},i.length)]})});function Ji({thinking:t,streaming:s,wrap:i=!0}){const l=
|
|
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(Ue,{}):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 Qi={bash:"$",read:"📄",write:"✍️",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function Xi(t){return Qi[t]??"🛠"}const Zi=r.memo(function({block:s,view:i,onKillBash:l,wrap:c=!0}){var D,S,O,h;const a=
|
|
309
|
+
`),inFence:c!==null}}const Vi=r.memo(function({text:s}){return e.jsx(Ps,{remarkPlugins:Vs,rehypePlugins:Gs,children:s})}),gs=200;function Gi({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 Yi=r.memo(function({text:s}){const{frozen:i,active:l,inFence:c}=r.useMemo(()=>zi(s),[s]);return e.jsxs("div",{className:"md",children:[i.map((a,n)=>e.jsx(Vi,{text:a},n)),l.length>0&&e.jsx(Gi,{text:l,inFence:c},i.length)]})});function Ji({thinking:t,streaming:s,wrap:i=!0}){const l=me(),[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(Ue,{}):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 Qi={bash:"$",read:"📄",write:"✍️",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function Xi(t){return Qi[t]??"🛠"}const Zi=r.memo(function({block:s,view:i,onKillBash:l,wrap:c=!0}){var D,S,O,h;const a=me(),[n,o]=r.useState(c),[u,m]=r.useState(!1),p=!i.result&&i.streaming&&!i.status,f=s.name==="bash"&&p,k=i.result!==void 0,b=!i.result&&!!i.status,N=((D=i.result)==null?void 0:D.isError)??((S=i.status)==null?void 0:S.isError)??!1,A=i.result?i.result.content.map(B=>B.type==="text"?B.text:"").join(""):i.liveOutput??"",j=N?"err":k?"ok":p||b?"run":"idle";let _=a(N?"error":k?"done":p?"running":b?"toolDoneWaitingModel":"toolQueued");const y=b&&((O=i.status)==null?void 0:O.durationMs)!==void 0?ta(i.status.durationMs):"";b&&y&&(_=`${_} · ${y}`);const w=b&&((h=i.status)==null?void 0:h.exitCode)!==void 0?`exit ${i.status.exitCode}`:"",I=()=>{s.argumentsText&&(navigator.clipboard.writeText(s.argumentsText),m(!0),setTimeout(()=>m(!1),1200))};return e.jsxs("div",{className:`toolcall ${j}`,children:[e.jsxs("div",{className:"toolcall-head",children:[e.jsx("span",{className:"toolcall-icon",children:Xi(s.name)}),e.jsx("span",{className:"toolcall-name",children:s.name}),e.jsxs("span",{className:"toolcall-status",children:[_,w&&e.jsx("em",{className:"toolcall-exit",children:w})]}),e.jsx("span",{className:"toolcall-spacer"}),f&&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(ti,{}):e.jsx($t,{})}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>o(B=>!B),children:n?e.jsx(Ue,{}):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(ea,{args:s.argumentsText}):e.jsx("pre",{children:s.argumentsText})}),A.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:A})]}),p&&A.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",a("waitingOutput")]}),b&&A.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",a("waitingModel")]})]})]})});function ea({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 ta(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 sa=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function Ut(t){var i;const s=t.match(sa);return s?{name:s[1],location:s[2],content:s[3],userMessage:((i=s[4])==null?void 0:i.trim())||void 0}:null}const na=1568,ia=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,na/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 m=document.createElement("canvas");m.width=l,m.height=c;const p=m.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 f=m.toDataURL(o,u),k=f.match(/^data:([^;]+);base64,/),b=k?k[1]:o,N=f.replace(/^data:[^;]*;base64,/,""),A=Math.floor(N.length*3/4);if(n={data:N,mimeType:b,name:t.name,size:A},A<=ia)return n}return n}finally{s.close()}}const aa=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 ra(t){return t.imageData?"image":t.uploadPath?"upload":t.fileData?"file":"path"}function la(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:m,questionAttachments:p,qnIndex:f,qnActive:k,onJump:b,thinkingWrap:N,toolsWrap:A}){const j=me(),[_,y]=r.useState(!1),[w,I]=r.useState(""),[D,S]=r.useState([]),[O,h]=r.useState(!1),[B,W]=r.useState(null),G=F=>{W(F),window.setTimeout(()=>W(H=>H===F?null:H),4e3)};if(s.role==="toolResult")return null;const X=s.role==="custom"&&s.customType==="file",q=s.content.map(F=>{var H;return((H=nt(F))==null?void 0:H.text)??""}).filter(Boolean).join(`
|
|
311
311
|
`),K=s.role==="user"?Ut(q):null,P=K?K.userMessage??`skill:${K.name}`:q.split(`
|
|
312
|
-
`).join(" ").trim(),g=a&&n&&s.content.length===0,v=s.role==="user"&&!a&&!g&&!!o,$=async F=>{const H=[];for(const se of F){if(!Le(se.type))continue;const V=await Js(se);V&&H.push({path:"",imageData:V.data,mimeType:V.mimeType,name:V.name})}H.length>0&&S(se=>[...se,...H])},
|
|
312
|
+
`).join(" ").trim(),g=a&&n&&s.content.length===0,v=s.role==="user"&&!a&&!g&&!!o,$=async F=>{const H=[];for(const se of F){if(!Le(se.type))continue;const V=await Js(se);V&&H.push({path:"",imageData:V.data,mimeType:V.mimeType,name:V.name})}H.length>0&&S(se=>[...se,...H])},pe=async F=>{if(F.size>aa){G(j("fileTooLarge",{name:F.name,size:20}));return}let H;try{H=(await new Promise((V,oe)=>{const re=new FileReader;re.onload=()=>V(re.result),re.onerror=()=>oe(re.error??new Error("read failed")),re.readAsDataURL(F)})).replace(/^data:[^;]*;base64,/,"")}catch{G(j("fileLoadFailed",{name:F.name}));return}S(se=>[...se,{path:"",fileData:H,name:F.name,size:F.size,mimeType:F.type||void 0}])},z=async F=>{const H=[];for(const se of F)Le(se.type)?H.push(se):pe(se);H.length>0&&await $(H)},E=()=>{I(K?`/skill:${K.name}${K.userMessage?` ${K.userMessage}`:""}`:s.content.map(F=>{var H;return((H=nt(F))==null?void 0:H.text)??""}).filter(Boolean).join(`
|
|
313
313
|
`)),S(p??[]),y(!0)},ee=()=>{const F=w.trim();F&&(o==null||o(s.id,F,D.length>0?D:void 0),y(!1))},Y=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}${Y?" 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?j("goalWizardCard"):Y?j("goalBarTitle"):s.customType==="file"?j("attachment"):`${j("plugin")} · ${s.customType??j("unknown")}`:tn(s.role,j)}),s.model&&e.jsx("span",{className:"msg-model",children:s.model}),s.timestamp&&e.jsx("span",{className:"msg-time",children:ua(s.timestamp)}),m&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:j("collapseMsg"),onClick:()=>m(s.id),children:[e.jsx(ft,{})," ",j("collapseMsg")]}),f!==void 0&&b&&e.jsxs("button",{type:"button",className:`qn-tag ${k?"active":""}`,title:`${f+1}. ${P}`,"aria-label":`${f+1}. ${P}`,onClick:()=>b(s.id),children:[e.jsx("span",{className:"qn-tag-bar"}),e.jsx("span",{className:"qn-tag-idx",children:f+1})]})]}),e.jsx("div",{className:"msg-body",children:_?e.jsxs("div",{className:`msg-editor${O?" drag-over":""}`,onDragOver:F=>{F.preventDefault(),F.stopPropagation(),h(!0)},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||h(!1)},onDrop:F=>{var H;F.preventDefault(),F.stopPropagation(),h(!1),z(Array.from(((H=F.dataTransfer)==null?void 0:H.files)??[]))},children:[D.length>0&&e.jsx("div",{className:"msg-editor-images",children:D.map((F,H)=>{var V;const se=ra(F);return e.jsxs("span",{className:`msg-editor-img ${se==="image"?"":"file-chip"}`,title:la(F,j),children:[se==="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:se==="path"?F.mode==="reference"?"🔗":"📎":"📄"}),e.jsx("span",{className:"msg-editor-file-name",children:F.name??((V=F.path)==null?void 0:V.split("/").pop())})]}),e.jsx("button",{type:"button",className:"msg-editor-img-remove",title:j("removeAttachment"),onClick:()=>S(oe=>oe.filter((re,d)=>d!==H)),children:e.jsx(we,{})})]},`${F.name??F.path??"att"}-${H}`)})}),B&&e.jsx("div",{className:"msg-editor-notice",children:B}),e.jsx("textarea",{className:"msg-editor-input",value:w,autoFocus:!0,placeholder:j("editPlaceholder"),rows:Math.max(2,Math.min(10,w.split(`
|
|
314
|
-
`).length+1)),onChange:F=>I(F.target.value),onPaste:F=>{var se;const H=[];for(const V of((se=F.clipboardData)==null?void 0:se.items)??[])if(V.kind==="file"&&Le(V.type)){const oe=V.getAsFile();oe&&H.push(oe)}H.length!==0&&(F.preventDefault(),$(H))},onKeyDown:F=>{F.key==="Enter"&&(F.metaKey||F.ctrlKey)?(F.preventDefault(),ee()):F.key==="Escape"&&y(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(Jn,{})," ",j("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>y(!1),children:j("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!w.trim(),title:j("reaskFromHere"),onClick:ee,children:[e.jsx(Pt,{})," ",j("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),X?e.jsx(oa,{message:s}):K?e.jsxs(e.Fragment,{children:[e.jsx(da,{block:K}),K.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(kt,{text:K.userMessage})}),s.content.map((F,H)=>F.type==="text"?null:e.jsx(vs,{block:F,toolResults:i,liveOutputs:l,toolStatuses:c,streaming:a,isLast:n,onKillBash:u,toolsWrap:A,thinkingWrap:N},`${s.id}-${H}`))]}):s.content.map((F,H)=>e.jsx(vs,{block:F,toolResults:i,liveOutputs:l,toolStatuses:c,streaming:a,isLast:n,onKillBash:u,toolsWrap:A,thinkingWrap:N},`${s.id}-${H}`)),g&&e.jsxs("div",{className:"thinking-wait",children:[j("thinkingWait"),e.jsx("span",{className:"dot"})]}),a&&n&&!g&&e.jsx("span",{className:"stream-cursor"})]})}),v&&!_&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:j("editReaskTip"),onClick:E,children:[e.jsx(Pt,{})," ",j("editReask")]})})]})});function oa({message:t}){const s=
|
|
314
|
+
`).length+1)),onChange:F=>I(F.target.value),onPaste:F=>{var se;const H=[];for(const V of((se=F.clipboardData)==null?void 0:se.items)??[])if(V.kind==="file"&&Le(V.type)){const oe=V.getAsFile();oe&&H.push(oe)}H.length!==0&&(F.preventDefault(),$(H))},onKeyDown:F=>{F.key==="Enter"&&(F.metaKey||F.ctrlKey)?(F.preventDefault(),ee()):F.key==="Escape"&&y(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(Jn,{})," ",j("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>y(!1),children:j("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!w.trim(),title:j("reaskFromHere"),onClick:ee,children:[e.jsx(Pt,{})," ",j("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),X?e.jsx(oa,{message:s}):K?e.jsxs(e.Fragment,{children:[e.jsx(da,{block:K}),K.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(kt,{text:K.userMessage})}),s.content.map((F,H)=>F.type==="text"?null:e.jsx(vs,{block:F,toolResults:i,liveOutputs:l,toolStatuses:c,streaming:a,isLast:n,onKillBash:u,toolsWrap:A,thinkingWrap:N},`${s.id}-${H}`))]}):s.content.map((F,H)=>e.jsx(vs,{block:F,toolResults:i,liveOutputs:l,toolStatuses:c,streaming:a,isLast:n,onKillBash:u,toolsWrap:A,thinkingWrap:N},`${s.id}-${H}`)),g&&e.jsxs("div",{className:"thinking-wait",children:[j("thinkingWait"),e.jsx("span",{className:"dot"})]}),a&&n&&!g&&e.jsx("span",{className:"stream-cursor"})]})}),v&&!_&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:j("editReaskTip"),onClick:E,children:[e.jsx(Pt,{})," ",j("editReask")]})})]})});function oa({message:t}){const s=me(),[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",m=t.content.filter(b=>b.type==="text").map(b=>b.text).join(`
|
|
315
315
|
`),p=ca(m),f=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"):f?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(Ue,{}):e.jsx(xt,{}))]}),!o&&i&&(u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:s("bridgedVisionDetail")}),(f==null?void 0:f.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:f.dataUrl,alt:a})}),p&&e.jsx("pre",{className:"attachcard-content",children:p})]}):f!=null&&f.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:f.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 ca(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 da({block:t}){const s=
|
|
317
|
-
`)}function wa(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 Na(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 Ca(t,s){const i=s.trim().toLowerCase();if(!i)return[];const l=[];for(const c of t){const a=ja(c);if(!a)continue;const n=Na(a,i);for(let o=0;o<n;o++)l.push({messageId:c.id,occurrence:o})}return l}function Sa(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(),m=(n=o.parentElement)==null?void 0:n.closest("[data-msg-id]");if(!m)continue;const p=m.getAttribute("data-msg-id")??"";let f=u.indexOf(c);for(;f!==-1;){const k=document.createRange();k.setStart(o,f),k.setEnd(o,f+c.length),l.push(k);const b=i.get(p);b?b.push(k):i.set(p,[k]),f=u.indexOf(c,f+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 Ta({containerRef:t,messages:s,open:i,onClose:l,onEnsureExpanded:c}){const a=pe(),n=r.useRef(null),[o,u]=r.useState(""),[m,p]=r.useState(0),f=r.useDeferredValue(o),k=i?f.trim():"",b=r.useMemo(()=>i?Ca(s,k):[],[s,k,i]),N=r.useRef(b);N.current=b;const A=r.useRef(m);A.current=m,r.useEffect(()=>{i&&(p(0),requestAnimationFrame(()=>{var w;return(w=n.current)==null?void 0:w.select()}))},[i]),r.useEffect(()=>{if(!i)return;const w=I=>{I.key==="Escape"&&(I.preventDefault(),I.stopPropagation(),l())};return window.addEventListener("keydown",w,!0),()=>window.removeEventListener("keydown",w,!0)},[i,l]),r.useEffect(()=>(i||(He("msg-search",[]),He("msg-search-active",[])),()=>{He("msg-search",[]),He("msg-search-active",[])}),[i]);const j=r.useCallback(w=>{const I=t.current;if(!I)return;const D=I.querySelector(`[data-msg-id="${w}"]`);D&&(D.classList.remove("msg-flash"),D.offsetWidth,D.classList.add("msg-flash"))},[t]);r.useLayoutEffect(()=>{if(!i||!k)return;const w=t.current;if(!w)return;let I=!1,D=0;return D=requestAnimationFrame(()=>{var G;if(I)return;const{byMsg:S,all:O}=Sa(w,k);He("msg-search",O);const h=N.current,B=h[Math.min(A.current,h.length-1)];if(!B)return;const W=(G=S.get(B.messageId))==null?void 0:G[B.occurrence];if(W){He("msg-search-active",[W]);const X=W.startContainer.parentElement??w.querySelector(`[data-msg-id="${B.messageId}"]`);X==null||X.scrollIntoView({block:"center"})}else j(B.messageId)}),()=>{I=!0,cancelAnimationFrame(D)}},[i,k,b,t,j]);const _=r.useCallback(w=>{const I=N.current;if(I.length===0)return;const D=(A.current+w+I.length)%I.length;p(D),c(I[D].messageId)},[c]);if(!i)return null;const y=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:w=>{u(w.target.value),p(0)},onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),_(w.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${y===0?"empty":""}`,children:y===0?a("searchNoResults"):`${Math.min(m+1,y)}/${y}`}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchPrev"),disabled:y===0,onClick:()=>_(-1),children:e.jsx(ft,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchNext"),disabled:y===0,onClick:()=>_(1),children:e.jsx(Ue,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchClose"),onClick:l,children:e.jsx(we,{})})]})}function Ea(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 Ma(){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 Ra({send:t,children:s}){const i=pe(),[l,c]=r.useState(Ma),[a,n]=r.useState(!1),[o,u]=r.useState(null),[m,p]=r.useState(!1),[f,k]=r.useState(!1),[b,N]=r.useState(!1);r.useEffect(()=>{try{localStorage.setItem(an,JSON.stringify(l))}catch{}},[l]);const A=r.useMemo(()=>{const q=new Map,K=new Set;for(const v of l)v.hidden?K.add(v.id):(at(v)&&!ks(v.id)||at(v))&&q.set(v.id,v);const P=nn.filter(v=>!K.has(v.id)).map(v=>{const $=q.get(v.id);return{id:v.id,icon:($==null?void 0:$.icon)??v.icon,title:($==null?void 0:$.title)??i(v.titleKey),desc:($==null?void 0:$.desc)??i(v.descKey),prompt:($==null?void 0:$.prompt)??i(v.promptKey),builtin:!0}}),g=l.filter(v=>at(v)&&!ks(v.id)).map(v=>({id:v.id,icon:v.icon??"📌",title:v.title??"",desc:v.desc??"",prompt:v.prompt??""}));return[...P,...g]},[l,i]),j=r.useCallback(()=>n(!0),[]),_=r.useCallback(q=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:q}))},[]),y=r.useCallback((q,K=!1)=>{N(K),q?(p(!1),u({...q})):(p(!0),u({id:De(),icon:"📌",title:"",desc:"",prompt:""}))},[]),w=r.useCallback(()=>{n(!1),u(null),N(!1)},[]),I=r.useCallback(()=>{f?(c([]),k(!1)):(k(!0),setTimeout(()=>k(!1),5e3))},[f]),D=r.useCallback(q=>{n(!1),_(q.prompt)},[_]),S=r.useCallback(q=>{n(!1),y(q,!0)},[y]),O=r.useCallback(()=>{n(!1),y(void 0,!0)},[y]),h=r.useCallback(q=>{c(K=>{const P=K.findIndex(g=>g.id===q.id);if(P>=0){const g=[...K];return g[P]=q,g}return[...K,q]}),u(null),b&&(n(!0),N(!1))},[b]),B=r.useCallback(q=>{c(K=>q.builtin?[...K.filter(g=>g.id!==q.id),{id:q.id,hidden:!0}]:K.filter(P=>P.id!==q.id)),u(null),b&&(n(!0),N(!1))},[b]),W=r.useCallback(q=>{c(K=>K.filter(P=>P.id!==q.id||P.hidden)),u(null),b&&(n(!0),N(!1))},[b]),G=r.useMemo(()=>({templates:A,fill:_,openPicker:j,openEdit:y,resetConfirm:f,toggleReset:I}),[A,_,j,y,f,I]),X=o?l.some(q=>q.id===o.id&&!q.hidden&&at(q)):!1;return e.jsxs(rn.Provider,{value:G,children:[s,a&&e.jsx(Ia,{templates:A,resetConfirm:f,onFill:D,onEditTpl:S,onNew:O,onResetToggle:I,onClose:w}),o&&e.jsx(La,{editing:o,isNew:m,hasOverride:X,onDraft:u,onSave:h,onRestore:()=>W(o),onRemove:()=>B(o),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:o.prompt})),w()},onSend:()=>{const q=o.prompt.trim();q&&t({type:"prompt",text:q,queue:!1})&&w()},onClose:w})]})}function Pa(){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 Ia({templates:t,resetConfirm:s,onFill:i,onEditTpl:l,onNew:c,onResetToggle:a,onClose:n}){const o=pe();return r.useEffect(()=>{const u=m=>{m.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 La({editing:t,isNew:s,hasOverride:i,onDraft:l,onSave:c,onRestore:a,onRemove:n,onFill:o,onSend:u,onClose:m}){const p=pe(),f=r.useRef(null);r.useEffect(()=>{const N=A=>{A.key==="Escape"&&m()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[m]),r.useEffect(()=>{const N=f.current;if(!N)return;N.style.height="auto";const A=N.scrollHeight>300;N.style.height=`${Math.min(N.scrollHeight,300)}px`,N.style.overflowY=A?"auto":"hidden"},[t.prompt]);const k=()=>{const N=t.title.trim(),A=t.prompt.trim();if(!N||!A){l({...t,error:p("tpl.required")});return}c({id:t.id,icon:t.icon.trim()||"📌",title:N,desc:t.desc.trim(),prompt:A})},b=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:m,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:m,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:f,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,Da=15,js=30,St=250,ws=1200,Ba=1600;function Ns(t){return t.content.some(s=>s.type==="toolCall")}function Aa({state:t,liveOutputs:s,toolStatuses:i,onEdit:l,onKillBash:c,thinkingWrap:a,toolsWrap:n,jumpTarget:o,onJumpDone:u}){const m=pe(),p=r.useRef(null),[f,k]=r.useState(!0),b=r.useRef(!0),N=r.useRef(0),A=r.useRef(0),j=r.useRef(!1),_=r.useRef(0),[y,w]=r.useState(()=>new Set),[I,D]=r.useState(!1),S=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,O=r.useMemo(()=>{const x=new Map;for(const T of t.messages)T.role==="toolResult"&&T.toolCallId&&x.set(T.toolCallId,T);return x},[t.messages]),h=r.useMemo(()=>pa(t.messages),[t.messages]),B=S.length>0?S[S.length-1].id:null,W=t.messages.length>js?Math.max(0,t.messages.length-Da):0,[G,X]=r.useState(()=>new Set),[q,K]=r.useState(()=>new Set),P=r.useRef(new Map),g=r.useRef(new Map),v=r.useRef(new Map),$=r.useRef(0),me=r.useMemo(()=>{const x=new Map;for(const T of t.messages)x.set(T.id,ka(T));return x},[t.messages]),z=r.useRef(me);z.current=me;const E=r.useRef(G);E.current=G;const ee=t.messages.length>js&&!I,Y=r.useRef(ee);Y.current=ee;const M=va(t.messages,P.current,Ba),F=r.useRef(M);F.current=M;const H=r.useCallback(()=>{const x=p.current;if(!x)return;if(!Y.current){X(ge=>ge.size?new Set:ge);return}const T=x.getBoundingClientRect(),Z={top:T.top-ws,bottom:T.bottom+ws},ne=[];for(const[ge,je]of v.current){const Re=je.getBoundingClientRect();ne.push({id:ge,top:Re.top,bottom:Re.bottom}),E.current.has(ge)||oe(ge,Re.bottom-Re.top,z.current.get(ge))}const he=fa(ne,Z,F.current,E.current);for(const ge of he.hide){const je=v.current.get(ge);je&&oe(ge,je.offsetHeight,z.current.get(ge))}X(ge=>xa(ge,he))},[]),se=r.useCallback(()=>{$.current||($.current=requestAnimationFrame(()=>{$.current=0,H()}))},[H]);r.useLayoutEffect(()=>{H()},[H]);const V=r.useRef(I);r.useLayoutEffect(()=>{V.current&&!I&&H(),V.current=I},[I,H]);const oe=r.useCallback((x,T,Z)=>{Z!==void 0&&(g.current.set(x,{h:T,len:Z}),P.current.set(x,T))},[]),re=r.useCallback((x,T)=>{oe(x,T,z.current.get(x))},[oe]),d=r.useCallback(x=>{x&&v.current.set(x.dataset.lazyId??"",x)},[]);r.useEffect(()=>{const x=new Set(t.messages.map(T=>T.id));for(const[T,Z]of v.current)x.has(T)||(v.current.delete(T),P.current.delete(T),g.current.delete(T));X(T=>{let Z=!1;const ne=new Set;for(const he of T)x.has(he)?ne.add(he):Z=!0;return Z?ne:T})},[t.messages,y]),r.useEffect(()=>()=>cancelAnimationFrame($.current),[]);const R=r.useMemo(()=>{const x=[];for(const T of t.messages){if(T.role!=="user")continue;const Z=T.content.map(ge=>{var je;return((je=nt(ge))==null?void 0:je.text)??""}).filter(Boolean).join(" "),ne=Ut(Z),he=ne?ne.userMessage??`skill:${ne.name}`:Z.trim();he&&x.push({id:T.id,text:he})}return x},[t.messages]),le=r.useMemo(()=>{const x=new Map;return R.forEach((T,Z)=>x.set(T.id,Z)),x},[R]),[te,fe]=r.useState(-1),Q=r.useRef(-1),de=r.useRef(R);r.useEffect(()=>{de.current=R},[R]);const xe=r.useCallback(()=>{const x=p.current,T=de.current;if(!x||T.length===0)return;const Z=x.getBoundingClientRect().top,ne=140;let he=-1;for(let ge=0;ge<T.length;ge++){const je=x.querySelector(`[data-msg-id="${T[ge].id}"]`);if(je)if(je.getBoundingClientRect().top<=Z+ne)he=ge;else break}he!==Q.current&&(Q.current=he,fe(he))},[]);r.useEffect(()=>{xe()},[R,xe]);const ce=r.useCallback(x=>{w(T=>T.has(x)?T:new Set(T).add(x))},[]),Se=r.useCallback(x=>{const T=t.messages.findIndex(Z=>Z.id===x);T>=0&&T<W&&!y.has(x)&&ms.flushSync(()=>ce(x))},[t.messages,W,y,ce]);r.useEffect(()=>{const x=T=>{if(!(T.ctrlKey||T.metaKey)||T.key.toLowerCase()!=="f")return;const Z=T.target;Z&&(Z.tagName==="INPUT"||Z.tagName==="TEXTAREA"||Z.isContentEditable)||(T.preventDefault(),D(!0))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[]);const Je=r.useCallback(x=>{w(T=>{if(!T.has(x))return T;const Z=new Set(T);return Z.delete(x),Z})},[]),Te=r.useCallback(x=>{const T=t.messages.findIndex(ne=>ne.id===x);ms.flushSync(()=>{T>=0&&T<W&&!y.has(x)&&ce(x),K(ne=>ne.has(x)?ne:new Set(ne).add(x))});const Z=de.current.findIndex(ne=>ne.id===x);Q.current=Z,fe(Z),requestAnimationFrame(()=>{var he,ge,je;const ne=(he=p.current)==null?void 0:he.querySelector(`[data-msg-id="${x}"]`);ne&&((ge=p.current)==null||ge.querySelectorAll(".msg-flash").forEach(Re=>Re.classList.remove("msg-flash")),ne.scrollIntoView({block:"start"}),ne.classList.remove("msg-flash"),ne.offsetWidth,ne.classList.add("msg-flash"),ne!==((je=p.current)==null?void 0:je.lastElementChild)&&(j.current=!0))})},[t.messages,W,y,ce]),Ee=r.useMemo(()=>{var x;return o?((x=t.messages.find(T=>T.role===o.role&&T.timestamp===o.timestamp))==null?void 0:x.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 x=p.current;if(!x)return;const T=x.scrollTop-N.current,Z=x.scrollHeight-A.current;N.current=x.scrollTop,A.current=x.scrollHeight;const ne=x.scrollHeight-x.scrollTop-x.clientHeight<80,he=Date.now()<_.current,ge=Ea({dSt:T,dSh:Z,escaped:j.current,graceActive:he,stuck:b.current});ge.reassert&&(_.current=Date.now()+St,x.scrollTop=x.scrollHeight),ge.flipEscape&&(j.current=!0),ne&&T>=0&&(j.current=!1),he||(T<0?b.current=ne&&!j.current:ne&&(b.current=!0)),k(b.current),xe(),se()},[xe,se]),Me=r.useRef(!1);r.useEffect(()=>{const x=Me.current;if(Me.current=!!t.isStreaming,x&&!t.isStreaming&&!j.current){const T=()=>{const ne=p.current;ne&&!j.current&&(ne.scrollTop=ne.scrollHeight,b.current=!0,k(!0))};requestAnimationFrame(()=>requestAnimationFrame(T));const Z=setTimeout(T,180);return()=>clearTimeout(Z)}},[t.isStreaming]),r.useEffect(()=>{const x=p.current;x&&b.current&&(x.scrollTop=x.scrollHeight)},[S,t.isStreaming,s]);const Xe=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");r.useEffect(()=>{const x=p.current;x&&b.current&&(x.scrollTop=x.scrollHeight)},[Xe]),r.useEffect(()=>{const x=p.current;if(!x||typeof ResizeObserver>"u")return;const T=new ResizeObserver(()=>{b.current&&!j.current&&(x.scrollTop=x.scrollHeight,k(!0))});return T.observe(x),()=>T.disconnect()},[]),r.useEffect(()=>{const x=p.current;if(!x||typeof MutationObserver>"u")return;let T=!1;const Z=new MutationObserver(()=>{T||(T=!0,requestAnimationFrame(()=>{T=!1;const ne=p.current;ne&&b.current&&!j.current&&(ne.scrollTop=ne.scrollHeight,k(!0))}))});return Z.observe(x,{childList:!0,subtree:!0,characterData:!0}),()=>Z.disconnect()},[]);const Fe=r.useCallback(()=>{if(!p.current)return;b.current=!0,j.current=!1,k(!0),_.current=Date.now()+St;const T=()=>{const Z=p.current;!Z||!b.current||j.current||(_.current=Date.now()+St,Z.scrollTop=Z.scrollHeight)};T(),requestAnimationFrame(()=>requestAnimationFrame(T)),setTimeout(T,120),setTimeout(T,300),setTimeout(T,600)},[]),$e=r.useRef(null);r.useEffect(()=>{const x=$e.current,T=p.current;if(!x||!T)return;const Z=ne=>{ne.preventDefault();const he=x.querySelector(".qn-list");if(he&&he.contains(ne.target)&&he.scrollHeight>he.clientHeight){he.scrollTop+=ne.deltaY;return}T.scrollTop+=ne.deltaY};return x.addEventListener("wheel",Z,{passive:!1}),()=>x.removeEventListener("wheel",Z)},[]);const[Oe,C]=r.useState(0);r.useEffect(()=>{const x=()=>{var T;C(((T=p.current)==null?void 0:T.clientHeight)??0),se()};return x(),window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[se]);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${f?"":" anchor-live"}`,ref:p,onScroll:Qe,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(Pa,{})}),t.messages.map((x,T)=>{const Z=T<W,ne=Z&&y.has(x.id);if(Z&&!ne)return x.role==="toolResult"?null:e.jsx(ma,{message:x,onExpand:ce},x.id);const he=x.role==="user"?le.get(x.id):void 0,ge=!ee||M.has(x.id)||q.has(x.id)||!G.has(x.id);return e.jsx(ga,{id:x.id,show:ge,height:ba(x.id,me.get(x.id)??-1,g.current,sn(x.role,x.customType)),containerRef:p,onMeasured:re,lazyRef:d,children:e.jsx(fs,{message:x,qnIndex:he,qnActive:he!==void 0?he===te:void 0,onJump:Te,toolResults:O,liveOutputs:Ns(x)?s:bs,toolStatuses:i,streaming:t.isStreaming,onKillBash:c,toolsWrap:n,thinkingWrap:a,isLast:x.id===B,onEdit:l,questionAttachments:h.get(x.id),onCollapse:ne?Je:void 0},x.id)},x.id)}),t.streamingMessage&&e.jsx(fs,{message:t.streamingMessage,toolResults:O,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:m("waitingResponse")}),t.queue.steering.map((x,T)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:m("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:x})]})},`q-steer-${T}`)),t.queue.followUp.map((x,T)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:m("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:x})]})},`q-fu-${T}`))]}),!f&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Fe,children:[e.jsx(Ws,{})," ",m("backToBottom")]}),e.jsx(Ta,{containerRef:p,messages:S,open:I,onClose:()=>D(!1),onEnsureExpanded:Se}),R.length>0&&e.jsxs("div",{className:`qn-rail ${ye?"many":""}`,ref:$e,"aria-label":m("questionNavTitle"),style:{"--rail-gap":`${ae}px`},children:[R.map((x,T)=>e.jsx("button",{type:"button",className:`qn-bar ${T===te?"active":""}`,"aria-label":`${T+1}. ${x.text}`,onClick:()=>Te(x.id),children:e.jsxs("span",{className:"qn-bar-text",children:[T+1,". ",x.text]})},x.id)),ye&&e.jsx("div",{className:"qn-list",children:R.map((x,T)=>e.jsxs("button",{type:"button",className:`qn-list-item ${T===te?"active":""}`,"aria-label":`${T+1}. ${x.text}`,onClick:()=>Te(x.id),children:[e.jsx("span",{className:"qn-list-idx",children:T+1}),e.jsx("span",{className:"qn-list-text",children:x.text})]},x.id))})]})]})}const cn="pi-web-model-usage";function _a(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 Fa(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function $a(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?_a(JSON.parse(t)):{}}catch{return{}}}function Oa(t){try{localStorage.setItem(cn,JSON.stringify(t))}catch{}}function Wa(t){const s=Fa(dn(),t);return Oa(s),s}const Ua=["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,m=u?`${u.provider}/${u.id}`:null,[p,f]=r.useState(!1),[k,b]=r.useState(!1),[N,A]=r.useState(""),[j,_]=r.useState(null),[y,w]=r.useState({}),I=r.useRef(null),D=r.useRef(null),[S,O]=r.useState(null);r.useEffect(()=>{if(!p){O(null);return}if(i.length===0)return;const g=requestAnimationFrame(()=>{const v=D.current;v&&O(v.offsetWidth)});return()=>cancelAnimationFrame(g)},[p,i.length]),r.useEffect(()=>{p&&w(dn())},[p]),r.useEffect(()=>{p||(A(""),_(null))},[p]);const h=r.useMemo(()=>{const g=new Map;for(const v of i)g.set(v.provider,(g.get(v.provider)??0)+1);return[...g.entries()].sort((v,$)=>v[0].localeCompare($[0])).map(([v,$])=>({name:v,count:$}))},[i]),B=r.useMemo(()=>$a(i,y),[i,y]),W=r.useMemo(()=>{let g=B;j&&(g=g.filter($=>$.provider===j));const v=N.trim().toLowerCase();return v?g.filter($=>$.name.toLowerCase().includes(v)||$.provider.toLowerCase().includes(v)||$.id.toLowerCase().includes(v)):g},[B,N,j]),[G,X]=r.useState(!1),q=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,K=Ua.map(g=>({value:g,label:o(`thinking.${g}`),supported:q?q.has(g):!0})),P=g=>{var v;return((v=K.find($=>$.value===g))==null?void 0:v.label)??g};return r.useEffect(()=>{p&&i.length===0&&!G&&!l&&(X(!0),c({type:"list_models"}))},[p,i.length,G,l,c]),r.useEffect(()=>{i.length>0&&X(!1)},[i.length]),r.useEffect(()=>{var v;if(!p)return;const g=(v=I.current)==null?void 0:v.querySelector(".dd-item.active");g==null||g.scrollIntoView({block:"nearest"})},[p,m,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:f,menuClassName:"dd-menu-model",menuRef:D,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:g=>A(g.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[h.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 ${j===null?"active":""}`,onClick:()=>_(null),children:e.jsx("span",{children:o("allProviders")})}),h.map(g=>e.jsxs("button",{type:"button",className:`dd-provider-item ${j===g.name?"active":""}`,onClick:()=>_(j===g.name?null:g.name),title:`${g.name} · ${g.count}`,children:[e.jsx("span",{className:"dd-provider-name",children:g.name}),e.jsx("span",{className:"dd-provider-count",children:g.count})]},g.name))]}),e.jsxs("div",{className:"dd-model-scroll",ref:I,children:[(G||l)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),i.length===0&&!G&&!l&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),W.length===0&&i.length>0&&e.jsx("div",{className:"dd-loading",children:o("noModelMatches")}),W.map(g=>e.jsx(Ne,{active:m===g.id,onClick:()=>{m!==g.id&&c({type:"set_model",modelId:g.id}),f(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:g.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:g.provider}),(y[g.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:o("modelUsedCount",{n:y[g.id]})}),(g.reasoning||g.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[g.reasoning&&e.jsx("span",{className:"dd-model-badge",children:o("reasoning")}),g.vision&&e.jsx("span",{className:"dd-model-badge",children:o("vision")})]})]})]})},g.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:()=>{f(!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?P(s.thinkingLevel):"—"})})]}),open:k,onOpenChange:b,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("thinkingLevel")}),K.map(g=>e.jsx(Ne,{active:(s==null?void 0:s.thinkingLevel)===g.value,disabled:!g.supported,title:g.supported?void 0:o("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==g.value&&c({type:"set_thinking",level:g.value}),b(!1)},children:g.label},g.value))]})]})}),Ha=r.memo(function({ready:s,streaming:i,messages:l,slashCommands:c,modelState:a,models:n,modelsLoading:o,send:u,attachments:m,onRemoveAttachment:p,onAddImageFiles:f,onAddLocalFiles:k,onNotice:b,onSent:N,onManageModels:A}){const j=pe(),{locale:_}=Ot(),{openPicker:y}=ln(),w=d=>_==="en"&&d.descriptionEn?d.descriptionEn:d.description??"",I=d=>_==="en"&&d.argumentHintEn?d.argumentHintEn:d.argumentHint??"",[D,S]=r.useState(""),[O,h]=r.useState(!1),[B,W]=r.useState(null),[G,X]=r.useState(0),[q,K]=r.useState(!1),[P,g]=r.useState(void 0),v=r.useRef(null),$=r.useRef(null),me=r.useRef(null),z={builtin:j("slashBuiltin"),extension:j("slashExtension"),prompt:j("slashPrompt"),skill:j("slashSkill"),plugin:j("slashPlugin")},E=d=>{const R=d.match(/^\/([^\s]*)$/);if(R&&s){const le=R[1].toLowerCase(),te=c.filter(fe=>fe.name.toLowerCase().startsWith(le));W(te.length>0?te:null),X(0)}else W(null)};r.useEffect(()=>{var R;const d=(R=me.current)==null?void 0:R.querySelector(".slash-item.active");d==null||d.scrollIntoView({block:"nearest"})},[G,B]);const ee=d=>{var Q;const R=B??[],le=d??R[G%Math.max(R.length,1)];if(!le){W(null);return}const te=D.match(/^\/([^\s]*)([\s\S]*)$/),fe=te?te[2]:"";S(`/${le.name} ${fe}`),W(null),(Q=v.current)==null||Q.focus()},Y=async()=>{const R=[...l].reverse().find(te=>te.role==="assistant"&&te.content.some(fe=>fe.type==="text"&&fe.text)),le=R==null?void 0:R.content.filter(te=>te.type==="text").map(te=>te.text).join(`
|
|
318
|
-
`);if(!le){b("warning",j("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(le),b("info",j("slashCopied"))}catch{b("error",j("slashCopyFailed"))}},M=d=>{if(!d||d.length===0){b("warning",j("foldersNotSupported"));return}const R=Array.from(d).filter(te=>Le(te.type)),le=Array.from(d).filter(te=>!Le(te.type));R.length>0&&f(R),le.length>0&&k(le)},F=d=>{var te;const R=(te=d.clipboardData)==null?void 0:te.items;if(!R)return;const le=[];for(const fe of R)if(fe.kind==="file"&&Le(fe.type)){const Q=fe.getAsFile();Q&&le.push(Q)}le.length!==0&&(d.preventDefault(),f(le))},H=s,se=r.useRef(D);r.useEffect(()=>{se.current=D},[D]),r.useEffect(()=>{E(se.current)},[c]),r.useEffect(()=>{const d=R=>{var te;const le=R.detail;S(le),(te=v.current)==null||te.focus()};return window.addEventListener("pi-web:fill",d),()=>window.removeEventListener("pi-web:fill",d)},[]),r.useEffect(()=>{if(!q)return;const d=R=>{R.key==="Escape"&&K(!1)};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[q]),r.useEffect(()=>{const d=v.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"},[D]);const V=(d=!1)=>{var te,fe,Q,de,xe;const R=D.trim(),le=m.some(ce=>ce.imageData||ce.fileData);if(!(!H||!R&&!le)){if(R==="/help"){const ce=(fe=(te=v.current)==null?void 0:te.closest(".inputbox"))==null?void 0:fe.getBoundingClientRect();g(ce==null?void 0:ce.width),K(!0),S(""),(Q=v.current)==null||Q.focus();return}if(R==="/copy"){S(""),(de=v.current)==null||de.focus(),Y();return}if(u({type:"prompt",text:R,queue:d,attachments:m.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&&Wa(`${ce.provider}/${ce.id}`),(xe=v.current)==null||xe.focus()}}},oe=d=>{if(!d.nativeEvent.isComposing){if(B&&B.length>0)switch(d.key){case"ArrowDown":d.preventDefault(),X(R=>(R+1)%B.length);return;case"ArrowUp":d.preventDefault(),X(R=>(R-1+B.length)%B.length);return;case"Tab":case"Enter":d.preventDefault(),ee();return;case"Escape":d.preventDefault(),W(null);return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),V())}},re=()=>e.jsx("div",{className:"inputbox-actions",children:i?e.jsxs(e.Fragment,{children:[D.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:j("supplementTip"),onClick:()=>V(!0),children:[e.jsx(As,{})," ",j("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:j("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(ut,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:j("sendTip"),disabled:!H||!D.trim()&&!m.some(d=>d.imageData||d.fileData),onClick:()=>V(),children:e.jsx(Os,{})})});return e.jsxs("div",{className:`inputbar${O?" drop-active":""}`,onDragOver:d=>{d.preventDefault(),d.stopPropagation(),h(!0)},onDragLeave:d=>{d.currentTarget.contains(d.relatedTarget)||h(!1)},onDrop:d=>{var R;d.preventDefault(),d.stopPropagation(),h(!1),M(((R=d.dataTransfer)==null?void 0:R.files)??null)},children:[O&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",j("dropHereToAttach")]})}),m.length>0&&e.jsxs("div",{className:"attach-row",children:[m.map(d=>e.jsxs("span",{className:`attach-chip ${d.imageData?"image":d.fileData?"file":d.mode}`,title:d.imageData?j("attachImage",{name:d.name}):d.fileData?j("attachFile",{name:d.name}):d.isDir?j("folderRef",{path:d.path}):d.mode==="reference"?j("refOnly",{path:d.path}):d.mode==="lines"&&d.lines?j("attachLines",{path:d.path,start:d.lines.start,end:d.lines.end}):j("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:j("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:j("attachHint")})]}),B&&B.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:me,"aria-label":j("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:j("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>W(null),children:"Esc"})]}),B.map((d,R)=>e.jsxs("button",{type:"button",className:`slash-item${R===G?" active":""}`,onMouseEnter:()=>X(R),onClick:()=>ee(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:[w(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(d)})]})]},d.name))]}),q&&e.jsx("div",{className:"modal-backdrop",onClick:()=>K(!1),children:e.jsxs("div",{className:"slash-help",style:P?{width:P}:void 0,onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",j("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>K(!1),children:j("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:j("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:[w(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:v,value:D,rows:1,placeholder:j(H?i?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!H,onChange:d=>{S(d.target.value),E(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:j("uploadFile"),disabled:!H,onClick:()=>{var d;return(d=$.current)==null?void 0:d.click()},children:e.jsx(Wn,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:j("tpl.openPicker"),onClick:y,children:e.jsx(Qn,{})}),e.jsx(qa,{state:a,models:n,modelsLoading:o,send:u,onManageModels:A,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:re()})]})]})]})}),Ka=r.memo(function({goal:s,models:i,modelsLoading:l,activeConversationId:c,send:a}){var G,X,q,K,P,g;const n=pe(),o=!s.conversationId||s.conversationId===c,u=s.goal!==null&&o,[m,p]=r.useState(""),[f,k]=r.useState(s.reviewModel??""),[b,N]=r.useState(s.maxRounds),[A,j]=r.useState(s.locked),[_,y]=r.useState(!1),[w,I]=r.useState(!1),[D,S]=r.useState(!0);r.useEffect(()=>{k(s.reviewModel??""),N(s.maxRounds||0),j(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),r.useEffect(()=>{_&&i.length===0&&!w&&!l&&(I(!0),a({type:"list_models"}))},[_,i.length,w,l,a]),r.useEffect(()=>{i.length>0&&I(!1)},[i.length]);const O=()=>{var v;return f?((v=i.find($=>$.id===f))==null?void 0:v.name)??f:n("goalBarUseMainModel")},h=()=>{const v=m.trim();v&&(a({type:"set_goal",goal:v,...f?{reviewModel:f}:{},maxRounds:b,locked:A}),p(""),S(!1))},B=()=>{const v=m.trim();v&&(a({type:"start_goal_wizard",text:v,...f?{wizardModel:f}:{},maxRounds:b,locked:A}),p(""),S(!1))},W=(((G=s.wizard)==null?void 0:G.active)??!1)&&o;return W?e.jsx("div",{className:`goalbar goalbar-active ${W?"wizard":""}`,children:e.jsxs("div",{className:"goalbar-active-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx("span",{className:"goalbar-spin",children:"🔍"})}),e.jsxs("span",{className:"goalbar-text",title:((X=s.wizard)==null?void 0:X.draft)??"",children:[n("goalWizardRunning"),": ",(q=s.wizard)==null?void 0:q.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[n("goalBarRound",{n:(((K=s.wizard)==null?void 0:K.step)??0)+1})," ","/ ",((P=s.wizard)==null?void 0:P.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((g=s.wizard)==null?void 0:g.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,{})})]})}):D?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:m,placeholder:n("goalBarPlaceholder"),onChange:v=>p(v.target.value),onKeyDown:v=>{v.key==="Enter"&&h()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!m.trim(),onClick:h,children:n("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!m.trim(),title:n("goalWizardTip"),onClick:B,children:["🔍 ",n("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n(A?"goalBarLocked":"goalBarUnlocked"),onClick:()=>j(v=>(a({type:"set_goal_prefs",locked:!v}),!v)),children:A?e.jsx(Vn,{}):e.jsx(_n,{})}),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:O()})]}),open:_,onOpenChange:y,direction:"up",children:[e.jsx("div",{className:"dd-header",children:n("goalBarReviewModel")}),(w||l)&&e.jsx("div",{className:"dd-loading",children:n("loading")}),i.length===0&&!w&&!l&&e.jsx("div",{className:"dd-loading",children:n("noModels")}),e.jsx(Ne,{active:f==="",onClick:()=>{k(""),y(!1),a({type:"set_goal_prefs",reviewModel:""})},children:n("goalBarUseMainModel")}),i.map(v=>e.jsx(Ne,{active:f===v.id,onClick:()=>{k(v.id),y(!1),a({type:"set_goal_prefs",reviewModel:v.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:v.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:v.provider})})]})},v.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:v=>{const $=parseInt(v.target.value,10);if(Number.isNaN($)||$<0){N(0);return}N($)},onBlur:()=>a({type:"set_goal_prefs",maxRounds:b}),onKeyDown:v=>{v.key==="Enter"&&(a({type:"set_goal_prefs",maxRounds:b}),v.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:n(A?"goalBarLocked":"goalBarUnlocked")})]})]})});function za({chat:t,send:s}){const i=pe(),l=t.state,[c,a]=r.useState(!1),[n,o]=r.useState(""),[u,m]=r.useState(0),p=r.useRef(null),f=t.pathCompletions;if(r.useEffect(()=>{if(!c)return;const h=setTimeout(()=>{s({type:"complete_path",path:n})},150);return()=>clearTimeout(h)},[n,c,s]),r.useEffect(()=>m(0),[f]),r.useEffect(()=>{const h=document.querySelector(`.status-completions .pc-item[data-idx="${u}"]`);h==null||h.scrollIntoView({block:"nearest"})},[u]),!l)return null;const k=l.stats,b=t.ready?"ok":"busy",N=t.ready?i("connected"):i("connecting"),A=k.contextUsage,j=A.tokens!==null&&A.percent!==null?`${Cs(A.tokens)} / ${Cs(A.contextWindow)}`:"—",_=A.percent??null,y=_===null?"":_>=80?"warn":_>=50?"mid":"ok",w=l.queue.steering.length+l.queue.followUp.length,I=()=>{o(l.cwd),a(!0)},D=(h,B)=>{var G;const W=h.includes("\\")?"\\":"/";o(B?`${h}${W}`:h),m(0),(G=p.current)==null||G.focus()},S=h=>{const B=h.trim();B&&B!==l.cwd&&s({type:"set_cwd",path:B}),a(!1)},O=h=>{if(h.key==="ArrowDown")h.preventDefault(),m(B=>Math.min(B+1,f.length-1));else if(h.key==="ArrowUp")h.preventDefault(),m(B=>Math.max(B-1,0));else if(h.key==="Tab"&&f.length>0){h.preventDefault();const B=f[Math.min(u,f.length-1)];D(B.path,B.type==="dir")}else if(h.key==="Enter"&&!h.nativeEvent.isComposing){const B=n.trim();if(B.endsWith("/")||B.endsWith("\\"))S(B);else if(f.some(W=>W.path===B))S(B);else if(f.length>0&&f[u]){h.preventDefault();const W=f[u];D(W.path,W.type==="dir")}else S(B)}else h.key==="Escape"&&(f.length>0?(h.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 ${y}`,children:_!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(_,100)}%`}})}),j]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:i("cumulativeCost"),children:["$",Va(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(h=>h.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"),w>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",w," ",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:h=>o(h.target.value),onKeyDown:O,onBlur:()=>a(!1)}),f.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:h=>h.preventDefault(),children:f.map((h,B)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":B,className:`pc-item ${B===u?"sel":""}`,onMouseEnter:()=>m(B),onClick:()=>D(h.path,h.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:h.type==="dir"?e.jsx(Ge,{}):e.jsx(Fs,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:h.name}),e.jsx("span",{className:"pc-path",children:h.path})]})]})},h.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 Va(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function Ga({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=f=>{f.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]:[],m=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children: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,f)=>e.jsx("button",{type:"button",className:`dialog-option ${f===a?"sel":""}`,onMouseEnter:()=>n(f),onClick:()=>o(p),children:p},f)),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:m}),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:m||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 Ya(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 Ja({chat:t,send:s,terminal:i,active:l,onSwitchToTerminal:c}){var $e,Oe;const a=pe(),[n,o]=r.useState(null),[u,m]=r.useState([]),[p,f]=r.useState(""),[k,b]=r.useState(new Map),[N,A]=r.useState("changes"),[j,_]=r.useState([]),[y,w]=r.useState(null),[I,D]=r.useState(""),[S,O]=r.useState(!1),[h,B]=r.useState(null),[W,G]=r.useState(null),[X,q]=r.useState(!1),[K,P]=r.useState(!1),[g,v]=r.useState(!1),[$,me]=r.useState(null),[z,E]=r.useState(!1),[ee,Y]=r.useState(""),M=r.useRef(0),F=r.useRef(-1),H=r.useRef(-1),se=r.useRef(-1),V=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,P(!1),me(null),!C.ok){me(C.error??"查询失败");return}if(C.notRepo){E(!0),o(null),m([]),b(new Map),_([]),w(null),D(""),G(null);return}E(!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(x=>({...x}))},ae=(C.branches??[]).map(x=>({...x})),ye=new Map;for(const[x,T]of Object.entries(C.stats??{}))ye.set(x,{add:T[0],del:T[1]});o(ue),m(ae),b(ye),f(x=>{var T;return ue.detached?x||"":ue.branch&&ae.some(Z=>Z.name===ue.branch)?ue.branch:x&&ae.some(Z=>Z.name===x)?x:((T=ae[0])==null?void 0:T.name)??""}),G(x=>x&&!ue.files.some(T=>T.path===x.file.path)?null:x)}else if(C.reqId===H.current){if(H.current=-1,q(!1),!C.ok){me(C.error??"查询失败");return}const ue=re.current;if(!ue)return;G({file:ue,staged:C.stagedText??"",worktree:C.worktreeText??"",untracked:!1})}else if(C.reqId===V.current){if(V.current=-1,v(!1),!C.ok){me(C.error??"查询失败");return}_((C.history??[]).map(ue=>({...ue})))}else if(C.reqId===se.current){if(se.current=-1,O(!1),!C.ok){me(C.error??"查询失败");return}D(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]),te=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),m([]),b(new Map),_([]),v(!1),V.current=-1,w(null),D(""),G(null),B(null)),oe.current=t.state.cwd,me(null),le({type:"scm_status"},F)&&(ue||P(!0)))},[t.ready,($e=t.state)==null?void 0:$e.cwd,t.status,le]),fe=r.useCallback(C=>{if(B(C),w(null),re.current=C,C.x==="?"&&C.y==="?"){G({file:C,staged:"",worktree:"",untracked:!0});return}q(!0),me(null),le({type:"scm_filediff",path:C.path},H)||q(!1)},[le]),Q=r.useCallback(C=>{w(C),B(null),G(null),D(""),O(!0),me(null),le({type:"scm_commit",hash:C.hash},se)||O(!1)},[le]),de=r.useCallback((C,ue)=>{var x,T;if(!t.ready)return;const ae={name:C,command:ue,cwd:"${pwd}"},ye=t.terminals.find(Z=>Z.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 Z=De();i.create({id:Z,conversationId:t.activeConversationId||((x=t.state)==null?void 0:x.conversationId)||"",title:C,cwd:((T=t.state)==null?void 0:T.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=ee.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}"`),Y("")},[ee,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"},V)||(V.current=-1)},[le]);r.useEffect(()=>{l&&te()},[l,te]),r.useEffect(()=>{N==="history"&&n&&Me()},[N,n,Me]),r.useEffect(()=>{t.scmDirty>0&&l&&te(!1,!0)},[t.scmDirty]),r.useEffect(()=>{if(!l||!t.ready||t.status!=="open")return;const C=setInterval(()=>{document.visibilityState!=="hidden"&&te(!1,!0)},3e4);return()=>clearInterval(C)},[l,t.ready,t.status,te]),r.useEffect(()=>{const C=d.current;if(d.current=t.terminals,!l)return;t.terminals.some(ae=>{var x;return ae.running!==!1?!1:((x=C.find(T=>T.id===ae.id))==null?void 0:x.running)===!0&&/^git /.test(ae.title)})&&t.ready&&t.status==="open"&&(te(!1,!0),N==="history"&&n&&Me())},[t.terminals,l,t.ready,t.status,te,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 x="";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("+++")?x="hdr":ae.startsWith("@@")?x="hunk":ae.startsWith("+")?x="add":ae.startsWith("-")&&(x="del"),e.jsx("div",{className:`scm-diff-line ${x}`,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:()=>{A("changes"),me(null)},children:a("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":N==="history",className:N==="history"?"active":"",onClick:()=>{A("history"),me(null)},children:a("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:a("scmRefreshTip"),disabled:K,onClick:()=>te(!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=>f(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:ee,placeholder:a("scmCommitPlaceholder"),disabled:z,onChange:C=>Y(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!C.nativeEvent.isComposing&&xe()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!ee.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")}),j.length>0&&e.jsx("span",{className:"scm-files-count",children:j.length})]}),e.jsx("div",{className:"scm-history-list",children:z?e.jsx("div",{className:"scm-empty",children:a("scmNotGitRepo")}):!n||g?e.jsx("div",{className:"scm-empty",children:t.status==="open"?a("scmLoading"):a("scmConnecting")}):j.length===0?e.jsx("div",{className:"scm-empty",children:a("scmNoHistory")}):j.map(C=>e.jsxs("button",{type:"button",className:`scm-commit ${(y==null?void 0:y.hash)===C.hash?"active":""}`,onClick:()=>Q(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=Ya(C),ae=k.get(C.path);return e.jsxs("div",{className:`scm-file ${(h==null?void 0:h.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"?y?`${y.shortHash} ${y.subject}`:a("scmCommitDetail"):h?h.path:a("scmDiff")}),(N==="history"?S:X)&&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:$}),!y&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmSelectCommitHint")}),y&&S&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmLoading")}),y&&!S&&!$&&I?Fe(I):null]}):e.jsxs(e.Fragment,{children:[$&&e.jsx("div",{className:"scm-error",children:$}),!h&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmSelectFileHint")}),h&&!W&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmLoading")}),h&&W&&W.untracked&&e.jsx("div",{className:"scm-empty",children:a("scmUntrackedNote")}),h&&W&&!W.untracked&&e.jsxs(e.Fragment,{children:[W.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:a("scmStaged")}),Fe(W.staged)]}),W.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:a("scmUnstaged")}),Fe(W.worktree)]}),!W.staged&&!W.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 Qa({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,Ci(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 Xa({send:t,piConfigured:s,piAgentInstalled:i,providers:l,installResult:c,onClose:a}){const n=pe(),[o,u]=r.useState(!1),[m,p]=r.useState(""),[f,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;!m&&l.length>0&&p(((I=l.find(D=>!D.configured))==null?void 0:I.id)??l[0].id)},[l,m]);const A=()=>{o||(u(!0),t({type:"install_pi_agent"}))},j=()=>{!f.trim()||b||(N(!0),t({type:"set_provider_api_key",provider:m.trim(),apiKey:f.trim()}),setTimeout(()=>N(!1),3e3))},_=()=>{t({type:"get_state"}),t({type:"list_providers"})},y=l.find(I=>I.id===m),w=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")}),w?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:A,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:m,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))]}),(y==null?void 0:y.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:f,onChange:I=>k(I.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!f.trim()||b||!m,onClick:j,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:A,children:n(o?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:a,children:n("skip")})]})]})})}const Za=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],qt=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),er=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[qt()]});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:[qt()]).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 tr({send:t,providers:s,providerStatus:i,fetchModelsResult:l,refreshProviderResult:c,cloneProviderResult:a,onClose:n}){const o=pe(),[u,m]=r.useState(null),[p,f]=r.useState({}),[k,b]=r.useState(null),[N,A]=r.useState({}),[j,_]=r.useState(!1),[y,w]=r.useState(0),[I,D]=r.useState(null),S=r.useRef(0),[O,h]=r.useState({});r.useRef(0);const B=r.useRef(0),[W,G]=r.useState(null),X=r.useRef(0),q=r.useRef(0);r.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const K=()=>{if(!u)return;const E=u.baseUrl.trim();if(!E){D({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(j)return;_(!0),D(null);const ee=y+1;w(ee),t({type:"fetch_models",reqId:ee,baseUrl:E,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};r.useEffect(()=>{var E;if(!(!l||l.reqId===S.current))if(S.current=l.reqId,_(!1),l.ok&&((E=l.models)!=null&&E.length)){const ee=l.models;m(Y=>{if(!Y)return Y;const M=Y.models.map(V=>{var d;if(!V.id.trim())return V;const oe=ee.find(R=>R.id===V.id.trim());if(!oe)return V;const re={...V};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(V=>V.id.trim()).filter(Boolean)),H=ee.filter(V=>!F.has(V.id)).map(V=>{var oe;return{id:V.id,name:V.name??"",reasoning:V.reasoning??!1,input:(oe=V.input)!=null&&oe.includes("image")?"text-image":"text",contextWindow:V.contextWindow?String(V.contextWindow):"",maxTokens:V.maxTokens?String(V.maxTokens):""}}),se=[...M,...H];return se.some(V=>V.id.trim())?{...Y,models:se.filter(V=>V.id.trim())}:Y}),D({ok:!0,text:o("fetchModelsOk",{n:ee.length})})}else D({ok:!1,text:l.error||o("fetchModelsEmpty")})},[l]);const P=E=>{const ee=(p[E.id]??"").trim();!ee||k||(b(E.id),t({type:"set_provider_api_key",provider:E.id,apiKey:ee}),setTimeout(()=>{b(null),f(Y=>({...Y,[E.id]:""})),A(Y=>({...Y,[E.id]:!1})),t({type:"list_providers"})},1500))},g=()=>{if(!u)return;const E=u.providerId.trim(),ee=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})),Y={providerId:E,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:ee};t({type:"save_model_config",providerId:E,config:Y}),n()};r.useEffect(()=>{!c||c.reqId===B.current||(B.current=c.reqId,h({}))},[c]);const v=E=>{if(W)return;G(E.id);const ee=++X.current+Date.now();t({type:"clone_provider",provider:E.id,reqId:ee})};r.useEffect(()=>{!a||a.reqId===q.current||(q.current=a.reqId,G(null),a.ok&&a.config&&m(Ss({...a.config,apiKey:""})))},[a]);const $=E=>{window.confirm(o("clearKeyConfirm",{id:E}))&&t({type:"clear_provider_api_key",provider:E})},me=E=>{window.confirm(o("deleteProviderConfirm",{id:E.providerId,n:E.models.length}))&&t({type:"delete_model_config",providerId:E.providerId})},z=(E,ee)=>{u&&m({...u,models:u.models.map((Y,M)=>M===E?{...Y,...ee}:Y)})};return e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"modal model-modal",onClick:E=>E.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(E=>E.providerId===u.providerId),onChange:E=>m({...u,providerId:E.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:E=>m({...u,name:E.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:E=>m({...u,api:E.target.value}),children:Za.map(E=>e.jsx("option",{value:E,children:E},E))})]}),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:E=>m({...u,baseUrl:E.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:E=>m({...u,apiKey:E.target.value}),placeholder:o("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:E=>m({...u,authHeader:E.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:j||!u.baseUrl.trim(),title:o("fetchModelsHint"),onClick:K,children:[e.jsx(Ft,{})," ",o(j?"fetchingModels":"fetchModels")]})]})]}),u.models.map((E,ee)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:E.id,onChange:Y=>z(ee,{id:Y.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:E.name,onChange:Y=>z(ee,{name:Y.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:E.input,onChange:Y=>z(ee,{input:Y.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:E.reasoning,onChange:Y=>z(ee,{reasoning:Y.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:E.contextWindow,onChange:Y=>z(ee,{contextWindow:Y.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:E.maxTokens,onChange:Y=>z(ee,{maxTokens:Y.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>m({...u,models:u.models.filter((Y,M)=>M!==ee)}),children:e.jsx(Ie,{})})]},ee)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>m({...u,models:[...u.models,qt()]}),children:[e.jsx(_e,{})," ",o("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>m(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(E=>E.id.trim()),onClick:g,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(E=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:E.name}),e.jsxs("span",{className:"provider-sub",children:[E.id,E.configured&&e.jsx("span",{className:"auth-badge",children:o("configuredBadge")}),E.source&&!E.configured&&e.jsx("span",{className:"auth-badge dim",children:E.source})]})]}),e.jsxs("div",{className:"provider-actions",children:[E.configured&&!N[E.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:()=>A(ee=>({...ee,[E.id]:!0})),children:[e.jsx(It,{})," ",o("replaceKey")]}),E.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>$(E.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[E.id]??"",onChange:ee=>f(Y=>({...Y,[E.id]:ee.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(p[E.id]??"").trim()||k===E.id,onClick:()=>P(E),children:[e.jsx(Gn,{})," ",k===E.id?o("savingKey"):o("saveKey")]})]}),e.jsxs("button",{type:"button",className:"btn sm",disabled:W!==null,title:o("cloneProviderTitle"),onClick:()=>v(E),children:[e.jsx($t,{})," ",W===E.id?o("cloning"):o("cloneProvider")]})]})]},E.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(E=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:E.providerId}),e.jsxs("span",{className:"provider-sub",children:[E.api??"—",E.baseUrl?` · ${E.baseUrl}`:"",E.models.length>0&&` · ${o("modelsCount",{n:E.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:o("edit"),onClick:()=>m(Ss(E)),children:e.jsx(It,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>me(E),children:e.jsx(Ie,{})})]})]},E.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>m(er()),children:[e.jsx(_e,{})," ",o("addProvider")]})})]})]})})}function sr({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})),m=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)},f=()=>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:!m||n,onClick:p,children:i(n?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:f,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 nr({chat:t,send:s,terminal:i,onSwitchToTerminal:l,onClose:c}){const a=pe(),n=t.settings,[o,u]=r.useState("prompt"),m=r.useRef(null);r.useEffect(()=>{var d;(d=m.current)==null||d.scrollTo({top:0})},[o]);const[p,f]=r.useState(""),[k,b]=r.useState("append"),N=r.useRef(!1),[A,j]=r.useState(""),[_,y]=r.useState("append"),w=r.useRef(!1),[I,D]=r.useState(""),S=r.useRef(!1),[O,h]=r.useState(""),[B,W]=r.useState(!1),[G,X]=r.useState(null),[q,K]=r.useState(null);r.useEffect(()=>{n&&(b(n.promptMode),!N.current&&(f(k==="append"||n.customSystemPrompt?n.customSystemPrompt:n.defaultSystemPrompt||""),y(n.visionBridgePromptMode),!w.current&&(j(_==="append"||n.visionBridgePrompt?n.visionBridgePrompt:n.visionBridgeDefaultPrompt||""),S.current||D(n.reviewPrompt))))},[n,k,_]);const[P,g]=r.useState(String((n==null?void 0:n.terminalBashIdleMs)??15e3));if(r.useEffect(()=>{g(String((n==null?void 0:n.terminalBashIdleMs)??15e3))},[n==null?void 0:n.terminalBashIdleMs]),!n)return null;const v=[{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($n,{}),label:a("settingsPresets"),count:n.presets.length}],$=new Set(n.disabledSkills),me=new Set(n.disabledExtensions),z=d=>s({type:"set_settings",...d}),E=d=>{const R=new Set($);R.has(d.name)?R.delete(d.name):R.add(d.name),z({disabledSkills:[...R]})},ee=new Set(n.disabledPlugins??[]),Y=d=>{const R=new Set(ee);R.has(d.id)?R.delete(d.id):R.add(d.id),z({disabledPlugins:[...R]})},M=d=>{const R=new Set(me);R.has(d.id)?R.delete(d.id):R.add(d.id),z({disabledExtensions:[...R]})},F=(d,R)=>{var fe,Q;const le={name:d,command:R,cwd:"${pwd}"},te=t.terminals.find(de=>de.title===d);te?(i.restart(te.id),s({type:"run_command",terminalId:te.id,conversationId:te.conversationId,command:le,cols:80,rows:24})):i.create({id:De(),conversationId:t.activeConversationId||((fe=t.state)==null?void 0:fe.conversationId)||"",title:d,cwd:((Q=t.state)==null?void 0:Q.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:le}),l(),c()},H=d=>{X(null),F(`${a("uninstallTitle")} ${d}`,`pi remove npm:${d}`)},se=d=>{K(null),F(`${a("uninstallTitle")} ${d}`,`pi-web-ui uninstall ${d}`)},V=(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:v.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:m,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=>f(d.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":B,onClick:()=>W(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:P,onChange:d=>g(d.target.value),onBlur:()=>{const d=Math.max(0,Math.floor(Number(P)||0));g(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:()=>E(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?G===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("uninstallConfirmHint"),onClick:()=>H(R),children:a("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:a("uninstallHint"),onClick:()=>X(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:!ee.has(d.id)&&!d.error,onToggle:()=>!d.error&&Y(d),action:e.jsxs("div",{className:"set-row-actions",children:[d.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUpdateHint"),onClick:()=>V(d.id,d.source),children:[e.jsx(gt,{}),a("pluginUpdate")]}),q===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("pluginUninstallHint"),onClick:()=>se(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(sr,{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=>D(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;y(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:A,onFocus:()=>w.current=!0,onBlur:()=>{w.current=!1;const d=_==="replace"&&n.visionBridgeDefaultPrompt&&A===n.visionBridgeDefaultPrompt?"":A;z({visionBridgePromptMode:_,visionBridgePrompt:d})},onChange:d=>j(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:O,onChange:d=>h(d.target.value),onKeyDown:d=>{d.key==="Enter"&&O.trim()&&(s({type:"save_preset",name:O.trim()}),h(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!O.trim(),onClick:()=>{s({type:"save_preset",name:O.trim()}),h("")},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 ir(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 ar({servers:t,send:s,onClose:i}){const l=pe(),[c,a]=r.useState(new Set),n=o=>a(u=>{const m=new Set(u);return m.has(o)?m.delete(o):m.add(o),m});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,m=o.taskId??String(o.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:u?o.plugin: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")," ",ir(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(m)?"open":""}`,title:`${l("bgTaskCommand")}: ${o.command}`,onClick:()=>n(m),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")})]})]},m)})}),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 rr(t,s){return t.toLowerCase().includes(s)}function lr({open:t,send:s,projects:i,cwd:l,fileSearch:c,sessionSearch:a,onClose:n,onSwitchSession:o,onSwitchProject:u,onPreviewFile:m}){const p=pe(),f=r.useRef(null),[k,b]=r.useState(""),N=r.useDeferredValue(k),[A,j]=r.useState(0),_=r.useRef(1),y=r.useRef(0),w=r.useRef(null);r.useEffect(()=>{if(!t)return;s({type:"list_sessions"}),s({type:"list_projects"});const g=k.trim();if(g){const v=++_.current;y.current=v,D(!0),s({type:"search_files",reqId:v,query:g}),s({type:"search_sessions",reqId:v,query:g})}requestAnimationFrame(()=>{var v;return(v=f.current)==null?void 0:v.select()})},[t]);const[I,D]=r.useState(!1);r.useEffect(()=>{w.current&&clearTimeout(w.current);const g=N.trim();if(!g){D(!1);return}return w.current=setTimeout(()=>{const v=++_.current;y.current=v,D(!0),s({type:"search_files",reqId:v,query:g}),s({type:"search_sessions",reqId:v,query:g})},300),()=>{w.current&&clearTimeout(w.current)}},[N]);const S=N.trim().toLowerCase(),O=r.useMemo(()=>!S||!a||a.reqId!==y.current||!a.ok?[]:a.results,[a,S]),h=r.useMemo(()=>S?i.filter(g=>rr(g.path,S)).slice(0,10):[],[i,S]),B=r.useMemo(()=>!S||!c||c.reqId!==y.current||!c.ok?[]:c.results,[c,S]);r.useEffect(()=>{c&&c.reqId===y.current&&a&&a.reqId===y.current&&y.current!==0&&D(!1)},[c,a]);const W=!!c&&c.ok&&c.truncated,G=r.useMemo(()=>[...O.map(g=>({kind:"session",path:g.path,anchors:g.anchors})),...h.map(g=>({kind:"project",path:g.path})),...B.filter(g=>g.type==="file").map(g=>({kind:"file",path:g.path,name:g.name}))],[O,h,B]);r.useEffect(()=>{j(0)},[N]);const X=r.useCallback(g=>{if(g)if(g.kind==="session")o(g.path,g.anchors),n();else if(g.kind==="project"){u(g.path),s({type:"list_sessions"}),s({type:"list_projects"});const v=N.trim();if(v){const $=++_.current;y.current=$,D(!0),s({type:"search_files",reqId:$,query:v}),s({type:"search_sessions",reqId:$,query:v})}}else m(g.path,g.name)},[o,u,m,s,N]);r.useEffect(()=>{if(!t)return;const g=v=>{v.key==="Escape"?(v.preventDefault(),v.stopPropagation(),n()):v.key==="ArrowDown"?(v.preventDefault(),j($=>Math.min($+1,G.length-1))):v.key==="ArrowUp"?(v.preventDefault(),j($=>Math.max($-1,0))):v.key==="Enter"&&(v.preventDefault(),X(G[A]))};return window.addEventListener("keydown",g,!0),()=>window.removeEventListener("keydown",g,!0)},[G,A,X,n,t]);const q=O.length+h.length+B.length,K=(g,v,$)=>e.jsxs("div",{className:"gs-section-head",children:[$,e.jsx("span",{children:g}),e.jsx("em",{children:v})]});let P=-1;return t?e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:n,children:e.jsxs("div",{className:"gs-modal",onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(mt,{}),e.jsx("input",{ref:f,type:"text",value:k,placeholder:p("gsPlaceholder"),onChange:g=>b(g.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&&q===0&&!W&&e.jsx("div",{className:"gs-empty",children:p(I?"gsSearching":"gsNoResults")}),O.length>0&&e.jsxs("div",{className:"gs-section",children:[K(p("gsSessions"),O.length,e.jsx(Ve,{})),O.map(g=>{P++;const v=P;return e.jsxs("button",{type:"button",className:v===A?"gs-item active":"gs-item",onMouseEnter:()=>j(v),onClick:()=>X({kind:"session",path:g.path,anchors:g.anchors}),children:[e.jsxs("span",{className:"gs-item-title",children:[g.name||g.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:g.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:g.firstMessage})]},g.path)})]}),h.length>0&&e.jsxs("div",{className:"gs-section",children:[K(p("gsProjects"),h.length,e.jsx(Ge,{})),h.map(g=>{P++;const v=P,$=l&&g.path===l;return e.jsxs("button",{type:"button",className:v===A?"gs-item active":"gs-item",onMouseEnter:()=>j(v),onClick:()=>X({kind:"project",path:g.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[g.path.split(/[\\/]/).pop(),$&&e.jsx("em",{className:"gs-item-meta",children:p("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:g.path})]},g.path)})]}),(B.length>0||S&&W)&&e.jsxs("div",{className:"gs-section",children:[K(p("gsFiles"),B.length,e.jsx($s,{})),B.map(g=>{P++;const v=P;return e.jsxs("button",{type:"button",className:v===A?"gs-item active":"gs-item",disabled:g.type==="dir",title:g.type==="dir"?void 0:p("gsOpenPreview"),onMouseEnter:()=>j(v),onClick:()=>{g.type==="file"&&X({kind:"file",path:g.path,name:g.name})},children:[e.jsx("span",{className:"gs-item-title",children:g.name}),e.jsx("span",{className:"gs-item-sub",children:g.path})]},`${g.type}:${g.path}`)}),W&&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 or({file:t,content:s,send:i,onAddLines:l,onAttach:c,onClose:a}){const n=pe(),[o,u]=r.useState(null),[m,p]=r.useState(!1),[f,k]=r.useState(null),[b,N]=r.useState(!1),[A,j]=r.useState(!1),[_,y]=r.useState(!1),[w,I]=r.useState(""),[D,S]=r.useState(!0),O=r.useRef(!1),[h,B]=r.useState(!0),[W,G]=r.useState(!1),[X,q]=r.useState(100),K=r.useRef(0),P=r.useRef(!1),g=r.useRef(null);r.useEffect(()=>{p(!0),u(null),k(null),y(!1),I(""),S(!0),O.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 Q=de=>{if(de.key==="Escape"){se();return}if((de.ctrlKey||de.metaKey)&&de.key.toLowerCase()==="s"&&_){de.preventDefault(),H();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(),E())};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[a,o,_,w]),r.useEffect(()=>{const Q=()=>{P.current=!1,N(!1)};return window.addEventListener("mouseup",Q),()=>window.removeEventListener("mouseup",Q)},[]);const v=r.useMemo(()=>{if(!o)return[];const Q=o.text.split(`
|
|
320
|
-
`);return Q.length>0&&Q[Q.length-1]===""&&Q.pop(),Q.slice(0,Tt)},[o]),$=(o==null?void 0:o.lines)??0,me=$>Tt,z=(Q,de)=>{if(de){const xe=K.current>0?K.current:Q;k({start:Math.min(xe,Q),end:Math.max(xe,Q)})}else K.current=Q,k({start:Q,end:Q})},E=()=>{v.length!==0&&(K.current=1,k({start:1,end:v.length}))},ee=()=>{f&&(l(t.path,t.name,f.start,f.end),j(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>j(!1),1400))},Y=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,M=()=>{I((o==null?void 0:o.text)??""),y(!1),O.current&&S(!0)},F=()=>{if(_){if(w!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges")))return;M();return}!Y||!o||(O.current=Et(t.name)&&D,Et(t.name)&&S(!1),k(null),I(o.text),y(!0))},H=()=>{!_||!o||!Y||i({type:"write_file",path:t.path,text:w})&&(y(!1),O.current&&S(!0),k(null))},se=()=>{_&&w!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges"))||a()},V=Q=>{q(Math.min(200,Math.max(50,Q)))},oe=f?f.end-f.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),te=le&&D&&!_&&R==="text"&&!re,fe=Q=>yt(Ye(`/api/file?clientId=${encodeURIComponent(Wt())}&path=${encodeURIComponent(Q)}`));return e.jsx("div",{className:`fp-overlay ${W?"fullscreen":""}`,onMouseDown:Q=>{Q.target===Q.currentTarget&&se()},children:e.jsxs("div",{className:`fp ${W?"fullscreen":""}`,style:{"--fp-zoom":X/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&&` · ${cr(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[le&&R==="text"&&!re&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${D?"on":""}`,"data-tip":n(D?"showMarkdownSource":"showMarkdownPreview"),disabled:_,onClick:()=>S(Q=>!Q),children:D?e.jsx(Rt,{}):e.jsx(ei,{})}),R==="text"&&!re&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${_?"on":""}`,"data-tip":n(d?"fileEditTruncated":_?"exitEditFile":"editFile"),disabled:!Y&&!_,onClick:F,children:e.jsx(Pt,{})}),R==="text"&&!re&&!te&&e.jsx("button",{type:"button",className:`fp-attach wrap ${h?"on":""}`,"data-tip":n(h?"disableWrap":"enableWrap"),onClick:()=>B(Q=>!Q),children:e.jsx(Zn,{})}),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:X<=50,onClick:()=>V(X-10),children:e.jsx(Dn,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:n("resetZoom"),onClick:()=>q(100),children:[X,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":n("zoomIn"),disabled:X>=200,onClick:()=>V(X+10),children:e.jsx(Bn,{})})]}),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 ${W?"on":""}`,"data-tip":n(W?"exitFullscreen":"fullscreen"),onClick:()=>G(Q=>!Q),children:W?e.jsx(qn,{}):e.jsx(Kn,{})}),e.jsx("button",{type:"button",className:"fp-close",title:n("close"),onClick:se,children:e.jsx(we,{})})]})]}),d&&R==="text"&&!re&&e.jsx("div",{className:"fp-notice",children:n("previewTruncated")}),m&&!o&&e.jsx("div",{className:"fp-empty",children:n("loading")}),!m&&R==="none"&&!re&&e.jsx("div",{className:"fp-empty",children:n("previewNotSupported")}),!m&&R==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:fe(t.path),alt:t.name})}),!m&&R==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:fe(t.path),controls:!0,preload:"metadata"})}),!m&&te&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(kt,{text:o.text})})}),!m&&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})]}),!m&&_&&R==="text"&&!re&&o&&e.jsx("textarea",{className:`fp-editor ${h?"":"no-wrap"}`,value:w,onChange:Q=>I(Q.target.value),wrap:h?"soft":"off",spellCheck:!1,autoFocus:!0}),!m&&!te&&!_&&R==="text"&&!re&&o&&v.length===0&&e.jsx("div",{className:"fp-empty",children:n("emptyFile")}),!m&&!te&&!_&&R==="text"&&!re&&v.length>0&&e.jsxs("div",{className:`fp-code ${b?"dragging":""} ${h?"":"no-wrap"}`,onMouseDown:Q=>{Q.button===0&&Q.preventDefault()},children:[v.map((Q,de)=>{const xe=de+1,ce=f!==null&&xe>=f.start&&xe<=f.end;return e.jsxs("div",{className:`fp-line ${ce?"sel":""}`,onMouseDown:Se=>{Se.button===0&&(z(xe,Se.shiftKey),P.current=!0,N(!0))},onMouseEnter:()=>{P.current&&z(xe,!0)},children:[e.jsx("span",{className:"fp-num",children:xe}),e.jsx("span",{className:"fp-code-text",children:Q})]},xe)}),me&&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:w===((o==null?void 0:o.text)??""),onClick:H,children:[e.jsx(On,{})," ",n("saveFile")]})]})]}):!te&&R==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:f?n("selectedRange",{n:oe,start:f.start,end:f.end}):n("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:v.length===0,onClick:E,children:n("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!f,onClick:()=>k(null),children:n("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!f||re,onClick:ee,children:[A?e.jsx(vt,{}):null,n(A?"addedToChat":"addToChat")]})]})]})})]})})}function Et(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function cr(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 dr(t){try{localStorage.setItem(un,JSON.stringify(t))}catch{}}let et=null;function ur(){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 pr=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],mr=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],hr=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],gr=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],fr={question:pr,done:mr,start:hr,error:gr};function xr(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=ur();if(!i)return;const l=Math.max(0,Math.min(1,s.volume/100));for(const c of fr[t])xr(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 vr(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 yr(){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 kr(){const[t,s]=r.useState([]),[i,l]=r.useState(()=>hn());return r.useEffect(()=>{let a=!1;return yr().then(n=>{a||s(n)}),()=>{a=!0}},[]),r.useEffect(()=>{gn(i),vr(i)},[i]),{themes:t,theme:i,switchTheme:a=>l(a===mn?null:a)}}function Er(){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 br=r.lazy(()=>Sn(()=>import("./TerminalPanel-DZhWBAsQ.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function jr({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"?ii:t.level==="warning"?ni:Yn;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 wr=[],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 m=f=>{const k=t==="left"?f.clientX-n:n-f.clientX;u=Math.min(xn,Math.max(fn,Math.round(o+k))),i(u)},p=()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",p),document.body.classList.remove("panel-resizing"),localStorage.setItem(yn(t),String(u))};window.addEventListener("pointermove",m),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 Nr(){var T,Z,ne,he,ge,je,Re,Ht,Kt,zt,Vt,Gt,Yt,Jt;const t=pe(),{chat:s,send:i,dismissNotice:l,pushNotice:c,terminal:a}=Ii(),[n,o]=r.useState([]),[u,m]=r.useState(null),[p,f]=r.useState(!1),[k,b]=r.useState("chat"),N=r.useMemo(()=>s.plugins.filter(L=>{var U,ie;return!((ie=(U=s.settings)==null?void 0:U.disabledPlugins)!=null&&ie.includes(L.id))}),[s.plugins,(T=s.settings)==null?void 0:T.disabledPlugins]),[A,j]=r.useState([]);r.useEffect(()=>wi(j),[]),r.useEffect(()=>{Ni(N,s.pluginsEpoch)},[N,s.pluginsEpoch]);const[_,y]=r.useState(()=>Ms("left")),[w,I]=r.useState(()=>Ms("right")),D=r.useCallback(L=>y(L),[]),S=r.useCallback(L=>I(L),[]),[O,h]=r.useState(null),[B,W]=r.useState(()=>window.matchMedia("(max-width: 768px)").matches);r.useEffect(()=>{const L=window.matchMedia("(max-width: 768px)"),U=ie=>W(ie.matches);return L.addEventListener("change",U),()=>L.removeEventListener("change",U)},[]);const[G,X]=r.useState(!1),[q,K]=r.useState(!1),[P,g]=r.useState(!1),[v,$]=r.useState(!1),[me,z]=r.useState(!1),[E,ee]=r.useState(null);r.useEffect(()=>{if(!E)return;const L=setTimeout(()=>ee(null),15e3);return()=>clearTimeout(L)},[E]),r.useEffect(()=>{const L=U=>{var Be,Qt;const ie=U.detail,ve=(ie==null?void 0:ie.title)||"插件命令",ke=ie==null?void 0:ie.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=De();a.create({id:bt,conversationId:s.activeConversationId||((Be=s.state)==null?void 0:Be.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=U=>{!(U.ctrlKey||U.metaKey)||U.key.toLowerCase()!=="k"||(U.preventDefault(),z(ie=>!ie))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[]);const[Y,M]=r.useState(pn),{themes:F,theme:H,switchTheme:se}=kr(),V=r.useRef(null),oe=r.useRef(null),re=r.useRef(0),d=r.useRef(!1),R=r.useRef(s.terminals);r.useEffect(()=>{dr(Y)},[Y]),r.useEffect(()=>{var U;const L=R.current;R.current=s.terminals;for(const ie of s.terminals){const ve=((U=ie.command)==null?void 0:U.command)??"",ke=L.find(Ce=>Ce.id===ie.id);!(ke!=null&&ke.running)||ie.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 ie;const L=((ie=s.state)==null?void 0:ie.isStreaming)??!1,U=V.current;V.current=L,U!==null&&(!U&&L?tt("start",Y):U&&!L&&tt("done",Y))},[(Z=s.state)==null?void 0:Z.isStreaming,Y]),r.useEffect(()=>{var U;const L=((U=s.dialog)==null?void 0:U.id)??null;L!==null&&L!==oe.current&&tt("question",Y),oe.current=L},[s.dialog,Y]),r.useEffect(()=>{const L=[...s.notices].reverse().find(U=>U.level==="error");L&&L.id!==re.current&&(re.current=L.id,tt("error",Y))},[s.notices,Y]);const le=(L,U,ie,ve=!1,ke)=>{const Ce=`${L}|${ie}|${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:U,mode:ie,isDir:ve,...ke?{lines:ke}:{}}])},te=L=>o(U=>U.filter(ie=>ie.key?ie.key!==L:ie.path!==L)),fe=r.useCallback(L=>(!L.type.startsWith("list_")&&!L.type.startsWith("get_")&&h(null),i(L)),[i]),Q=r.useRef(0),de=r.useRef(0),xe=L=>{var ve;const U=Date.now();(ve=s.state)!=null&&ve.model&&!s.state.model.vision&&U-de.current>1e4&&(de.current=U,c("warning",t("imageNotSupported")));const ie=`paste-${++Q.current}`;o(ke=>[...ke,{path:"",key:ie,name:L.name,mode:"inline",imageData:L.data,mimeType:L.mimeType}])},ce=async L=>{for(const U of L){const ie=await Js(U);if(!ie){c("error",t("imageLoadFailed",{name:U.name}));continue}xe(ie)}},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 U;try{U=(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 ie=`upload-${++Je.current}`;o(ve=>[...ve,{path:"",key:ie,name:L.name,mode:"inline",fileData:U,size:L.size,mimeType:L.type||void 0}])},Ee=async L=>{for(const U of L)Le(U.type)?await ce([U]):await Te(U)},Qe=r.useCallback((L,U,ie)=>{i({type:"edit_message",messageId:L,text:U,attachments:ie})},[i]),Me=r.useCallback(()=>K(!0),[]),Xe=r.useCallback(()=>o([]),[]),Fe=r.useCallback(te,[]),$e=r.useCallback(ce,[ce]),Oe=r.useCallback(Ee,[Ee]),C=(ne=s.state)==null?void 0:ne.model,ue=(he=s.state)==null?void 0:he.thinkingLevel,ae=(ge=s.state)==null?void 0:ge.availableThinkingLevels,ye=r.useMemo(()=>C?{model:C,thinkingLevel:ue??"off",availableThinkingLevels:ae??[]}:null,[C,ue,ae]),x=r.useCallback(()=>{var L,U;return!s.ready||s.terminals.length!==0?!1:(a.create({id:De(),conversationId:s.activeConversationId||((L=s.state)==null?void 0:L.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((U=s.state)==null?void 0:U.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}x()&&(d.current=!1)}},[s.terminals.length,x,k]),e.jsxs("div",{className:"app",onDragOver:L=>{var U;Array.from(((U=L.dataTransfer)==null?void 0:U.types)??[]).includes("Files")&&(L.preventDefault(),f(!0))},onDragLeave:L=>{L.currentTarget.contains(L.relatedTarget)||f(!1)},onDrop:L=>{var ke,Ce;if(f(!1),!Array.from(((ke=L.dataTransfer)==null?void 0:ke.types)??[]).includes("Files"))return;L.preventDefault();const U=Array.from(((Ce=L.dataTransfer)==null?void 0:Ce.files)??[]);if(U.length===0){c("warning",t("foldersNotSupported"));return}const ie=U.filter(be=>Le(be.type)),ve=U.filter(be=>!Le(be.type));ie.length>0&&ce(ie),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(ui,{chat:s,send:i,terminal:a,view:k,plugins:N,onViewChange:L=>{d.current=L==="terminal"&&s.terminals.length===0,d.current&&x()&&(d.current=!1),b(L),h(null)},onOpenPanel:h,onOpenSettings:()=>g(!0),onOpenBgTasks:()=>$(!0),onOpenGlobalSearch:()=>z(!0),sound:Y,onSoundChange:M,onSoundPreview:L=>tt(L,Y),themes:F,theme:H,onThemeChange:se}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(L=>e.jsx(jr,{notice:L,onDismiss:l},L.id))}),e.jsx(Ra,{send:i,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${_}px`,"--right-w":`${w}px`},children:[O&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>h(null)}),e.jsxs("div",{className:`view-pane ${k==="chat"?"":"hidden"}`,children:[e.jsx("div",{className:`panel-drawer drawer-left ${O==="left"?"open":""}`,children:e.jsx(mi,{send:fe,active:!B||O==="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:D}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(Aa,{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:E,onJumpDone:()=>ee(null)},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(Ka,{send:i,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId}),s.dialog&&e.jsx(Ga,{dialog:s.dialog,send:i}),e.jsx(Ha,{send:i,ready:s.ready,streaming:((Vt=s.state)==null?void 0:Vt.isStreaming)??!1,messages:((Gt=s.state)==null?void 0:Gt.messages)??wr,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:w,onResize:S}),e.jsx("div",{className:`panel-drawer drawer-right ${O==="right"?"open":""}`,children:e.jsx(Wi,{send:fe,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((Yt=s.state)==null?void 0:Yt.cwd)??"",onAttach:(L,U,ie,ve)=>{h(null),le(L,U,ie,ve)},onPreview:(L,U)=>{h(null),m({path:L,name:U})},onNotice:(L,U)=>c(L,U)})})]}),e.jsx("div",{className:`view-pane ${k==="terminal"?"":"hidden"}`,children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(br,{chat:s,send:i,terminal:a})})}),e.jsx("div",{className:`view-pane ${k==="git"?"":"hidden"}`,children:e.jsx(Ja,{chat:s,send:i,terminal:a,active:k==="git",onSwitchToTerminal:()=>b("terminal")})}),A.map(L=>{const U=`plugin:${L.info.id}`;return e.jsx("div",{className:`view-pane ${k===U?"":"hidden"}`,children:e.jsx(Qa,{entry:L,send:i})},L.info.id)})]})}),e.jsx(za,{chat:s,send:i}),u&&e.jsx(or,{file:u,content:s.fileContent,send:i,onAddLines:(L,U,ie,ve)=>le(L,U,"lines",!1,{start:ie,end:ve}),onAttach:(L,U,ie)=>le(L,U,ie),onClose:()=>m(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!G&&!q&&e.jsx(Xa,{send:i,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>X(!0)}),q&&e.jsx(tr,{send:i,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>K(!1)}),P&&e.jsx(nr,{chat:s,send:i,terminal:a,onSwitchToTerminal:()=>b("terminal"),onClose:()=>g(!1)}),v&&e.jsx(ar,{servers:s.bgServers,send:i,onClose:()=>$(!1)}),e.jsx(lr,{open:me,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,U)=>{i({type:"switch_session",path:L});const ie=U&&U[0];ee(ie?{path:L,role:ie.role,timestamp:ie.timestamp}:null)},onSwitchProject:L=>{i({type:"set_cwd",path:L})},onPreviewFile:(L,U)=>{m({path:L,name:U})}})]})}hi();gn(hn());wn.createRoot(document.getElementById("root")).render(e.jsx(r.StrictMode,{children:e.jsx(ci,{children:e.jsx(Nr,{})})}));export{gt as F,Es as T,_e as a,Er as b,Tr as c,It as d,Ie as e,we as f,Hn as g,ze as h,De as r,pe as u};
|
|
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"):f?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(Ue,{}):e.jsx(xt,{}))]}),!o&&i&&(u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:s("bridgedVisionDetail")}),(f==null?void 0:f.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:f.dataUrl,alt:a})}),p&&e.jsx("pre",{className:"attachcard-content",children:p})]}):f!=null&&f.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:f.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 ca(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 da({block:t}){const s=me(),[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(si,{})}),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(Ue,{}),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 m=me(),p=nt(t);if(p){const A=c&&a;return e.jsxs("div",{className:"msg-text",children:[A?e.jsx(Yi,{text:p.text}):e.jsx(kt,{text:p.text}),p.truncated&&e.jsx("div",{className:"trunc-note",children:m("truncated")})]})}const f=Qs(t);if(f)return e.jsx(Ji,{thinking:f.thinking,streaming:c&&a,wrap:o});const k=Xs(t);if(k){const A=s.get(k.id),j=i.get(k.id),_={result:A,liveOutput:j==null?void 0:j.text,streaming:c,status:l.get(k.id)};return e.jsx(Zi,{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:m("exitCode",{code:N.exitCode})}),N.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:m("cancelled")})]}),N.output&&e.jsx("pre",{className:"bashblock-output",children:N.output}),N.truncated&&e.jsx("div",{className:"trunc-note",children:m("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 ua(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 pa(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 ma=r.memo(function({message:s,onExpand:i}){const l=me();let c="";for(const f of s.content){const k=nt(f);if(k&&k.text.trim()){const b=Ut(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 f=s.details??{};c=f.name??f.path??""}c.length>90&&(c=`${c.slice(0,90)}…`);let n=0,o=0,u=0,m=0;for(const f of s.content)Qs(f)?n++:Xs(f)?o++:en(f)?u++:Zs(f)&&m++;const p=[];return n&&p.push(`${l("thinking")} ${n}`),o&&p.push(`${l("toolCalls")} ${o}`),u&&p.push(`${l("bashRuns")} ${u}`),m&&p.push(`${l("images")} ${m}`),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((f,k)=>e.jsx("span",{className:"msg-collapsed-chip",children:f},k))})]}),s.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:ha(s.timestamp)}):null,e.jsxs("span",{className:"msg-collapsed-action",children:[e.jsx(Ue,{})," ",l("expandMsg")]})]})});function ha(t){const s=new Date(t),i=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${i}:${l}`}const ga=r.memo(function({id:s,show:i,height:l,containerRef:c,onMeasured:a,lazyRef:n,children:o}){const u=r.useRef(null),m=r.useRef(null);return r.useLayoutEffect(()=>{const p=m.current;if(m.current=i,!i||p!==!1)return;const f=u.current,k=c.current;if(!f||!k)return;const b=f.offsetHeight;a==null||a(s,b);const N=b-l;if(N!==0){const A=f.parentElement;A&&A.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 fa(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 xa(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 va(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 ya=["text","thinking","argumentsText","output","command"];function ka(t){let s=0;for(const i of t.content){i.type==="image"&&(s+=1);for(const l of ya){const c=i[l];typeof c=="string"&&(s+=c.length)}}return s}function ba(t,s,i,l){const c=i.get(t);return c&&c.len===s?c.h:l}function ja(t){if(t.role==="toolResult")return"";const s=[];for(const i of t.content)wa(i,s);return t.errorMessage&&s.push(t.errorMessage),s.join(`
|
|
317
|
+
`)}function wa(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 Na(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 Ca(t,s){const i=s.trim().toLowerCase();if(!i)return[];const l=[];for(const c of t){const a=ja(c);if(!a)continue;const n=Na(a,i);for(let o=0;o<n;o++)l.push({messageId:c.id,occurrence:o})}return l}function Sa(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(),m=(n=o.parentElement)==null?void 0:n.closest("[data-msg-id]");if(!m)continue;const p=m.getAttribute("data-msg-id")??"";let f=u.indexOf(c);for(;f!==-1;){const k=document.createRange();k.setStart(o,f),k.setEnd(o,f+c.length),l.push(k);const b=i.get(p);b?b.push(k):i.set(p,[k]),f=u.indexOf(c,f+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 Ta({containerRef:t,messages:s,open:i,onClose:l,onEnsureExpanded:c}){const a=me(),n=r.useRef(null),[o,u]=r.useState(""),[m,p]=r.useState(0),f=r.useDeferredValue(o),k=i?f.trim():"",b=r.useMemo(()=>i?Ca(s,k):[],[s,k,i]),N=r.useRef(b);N.current=b;const A=r.useRef(m);A.current=m,r.useEffect(()=>{i&&(p(0),requestAnimationFrame(()=>{var w;return(w=n.current)==null?void 0:w.select()}))},[i]),r.useEffect(()=>{if(!i)return;const w=I=>{I.key==="Escape"&&(I.preventDefault(),I.stopPropagation(),l())};return window.addEventListener("keydown",w,!0),()=>window.removeEventListener("keydown",w,!0)},[i,l]),r.useEffect(()=>(i||(He("msg-search",[]),He("msg-search-active",[])),()=>{He("msg-search",[]),He("msg-search-active",[])}),[i]);const j=r.useCallback(w=>{const I=t.current;if(!I)return;const D=I.querySelector(`[data-msg-id="${w}"]`);D&&(D.classList.remove("msg-flash"),D.offsetWidth,D.classList.add("msg-flash"))},[t]);r.useLayoutEffect(()=>{if(!i||!k)return;const w=t.current;if(!w)return;let I=!1,D=0;return D=requestAnimationFrame(()=>{var G;if(I)return;const{byMsg:S,all:O}=Sa(w,k);He("msg-search",O);const h=N.current,B=h[Math.min(A.current,h.length-1)];if(!B)return;const W=(G=S.get(B.messageId))==null?void 0:G[B.occurrence];if(W){He("msg-search-active",[W]);const X=W.startContainer.parentElement??w.querySelector(`[data-msg-id="${B.messageId}"]`);X==null||X.scrollIntoView({block:"center"})}else j(B.messageId)}),()=>{I=!0,cancelAnimationFrame(D)}},[i,k,b,t,j]);const _=r.useCallback(w=>{const I=N.current;if(I.length===0)return;const D=(A.current+w+I.length)%I.length;p(D),c(I[D].messageId)},[c]);if(!i)return null;const y=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:w=>{u(w.target.value),p(0)},onKeyDown:w=>{w.key==="Enter"&&(w.preventDefault(),_(w.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${y===0?"empty":""}`,children:y===0?a("searchNoResults"):`${Math.min(m+1,y)}/${y}`}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchPrev"),disabled:y===0,onClick:()=>_(-1),children:e.jsx(ft,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchNext"),disabled:y===0,onClick:()=>_(1),children:e.jsx(Ue,{})}),e.jsx("button",{type:"button",className:"search-btn",title:a("searchClose"),onClick:l,children:e.jsx(we,{})})]})}function Ea(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 Ma(){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 Ra({send:t,children:s}){const i=me(),[l,c]=r.useState(Ma),[a,n]=r.useState(!1),[o,u]=r.useState(null),[m,p]=r.useState(!1),[f,k]=r.useState(!1),[b,N]=r.useState(!1);r.useEffect(()=>{try{localStorage.setItem(an,JSON.stringify(l))}catch{}},[l]);const A=r.useMemo(()=>{const q=new Map,K=new Set;for(const v of l)v.hidden?K.add(v.id):(at(v)&&!ks(v.id)||at(v))&&q.set(v.id,v);const P=nn.filter(v=>!K.has(v.id)).map(v=>{const $=q.get(v.id);return{id:v.id,icon:($==null?void 0:$.icon)??v.icon,title:($==null?void 0:$.title)??i(v.titleKey),desc:($==null?void 0:$.desc)??i(v.descKey),prompt:($==null?void 0:$.prompt)??i(v.promptKey),builtin:!0}}),g=l.filter(v=>at(v)&&!ks(v.id)).map(v=>({id:v.id,icon:v.icon??"📌",title:v.title??"",desc:v.desc??"",prompt:v.prompt??""}));return[...P,...g]},[l,i]),j=r.useCallback(()=>n(!0),[]),_=r.useCallback(q=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:q}))},[]),y=r.useCallback((q,K=!1)=>{N(K),q?(p(!1),u({...q})):(p(!0),u({id:De(),icon:"📌",title:"",desc:"",prompt:""}))},[]),w=r.useCallback(()=>{n(!1),u(null),N(!1)},[]),I=r.useCallback(()=>{f?(c([]),k(!1)):(k(!0),setTimeout(()=>k(!1),5e3))},[f]),D=r.useCallback(q=>{n(!1),_(q.prompt)},[_]),S=r.useCallback(q=>{n(!1),y(q,!0)},[y]),O=r.useCallback(()=>{n(!1),y(void 0,!0)},[y]),h=r.useCallback(q=>{c(K=>{const P=K.findIndex(g=>g.id===q.id);if(P>=0){const g=[...K];return g[P]=q,g}return[...K,q]}),u(null),b&&(n(!0),N(!1))},[b]),B=r.useCallback(q=>{c(K=>q.builtin?[...K.filter(g=>g.id!==q.id),{id:q.id,hidden:!0}]:K.filter(P=>P.id!==q.id)),u(null),b&&(n(!0),N(!1))},[b]),W=r.useCallback(q=>{c(K=>K.filter(P=>P.id!==q.id||P.hidden)),u(null),b&&(n(!0),N(!1))},[b]),G=r.useMemo(()=>({templates:A,fill:_,openPicker:j,openEdit:y,resetConfirm:f,toggleReset:I}),[A,_,j,y,f,I]),X=o?l.some(q=>q.id===o.id&&!q.hidden&&at(q)):!1;return e.jsxs(rn.Provider,{value:G,children:[s,a&&e.jsx(Ia,{templates:A,resetConfirm:f,onFill:D,onEditTpl:S,onNew:O,onResetToggle:I,onClose:w}),o&&e.jsx(La,{editing:o,isNew:m,hasOverride:X,onDraft:u,onSave:h,onRestore:()=>W(o),onRemove:()=>B(o),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:o.prompt})),w()},onSend:()=>{const q=o.prompt.trim();q&&t({type:"prompt",text:q,queue:!1})&&w()},onClose:w})]})}function Pa(){const t=me(),{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=me();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 Ia({templates:t,resetConfirm:s,onFill:i,onEditTpl:l,onNew:c,onResetToggle:a,onClose:n}){const o=me();return r.useEffect(()=>{const u=m=>{m.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 La({editing:t,isNew:s,hasOverride:i,onDraft:l,onSave:c,onRestore:a,onRemove:n,onFill:o,onSend:u,onClose:m}){const p=me(),f=r.useRef(null);r.useEffect(()=>{const N=A=>{A.key==="Escape"&&m()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[m]),r.useEffect(()=>{const N=f.current;if(!N)return;N.style.height="auto";const A=N.scrollHeight>300;N.style.height=`${Math.min(N.scrollHeight,300)}px`,N.style.overflowY=A?"auto":"hidden"},[t.prompt]);const k=()=>{const N=t.title.trim(),A=t.prompt.trim();if(!N||!A){l({...t,error:p("tpl.required")});return}c({id:t.id,icon:t.icon.trim()||"📌",title:N,desc:t.desc.trim(),prompt:A})},b=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:m,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:m,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:f,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,Da=15,js=30,St=250,ws=1200,Ba=1600;function Ns(t){return t.content.some(s=>s.type==="toolCall")}function Aa({state:t,liveOutputs:s,toolStatuses:i,onEdit:l,onKillBash:c,thinkingWrap:a,toolsWrap:n,jumpTarget:o,onJumpDone:u}){const m=me(),p=r.useRef(null),[f,k]=r.useState(!0),b=r.useRef(!0),N=r.useRef(0),A=r.useRef(0),j=r.useRef(!1),_=r.useRef(0),[y,w]=r.useState(()=>new Set),[I,D]=r.useState(!1),S=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,O=r.useMemo(()=>{const x=new Map;for(const T of t.messages)T.role==="toolResult"&&T.toolCallId&&x.set(T.toolCallId,T);return x},[t.messages]),h=r.useMemo(()=>pa(t.messages),[t.messages]),B=S.length>0?S[S.length-1].id:null,W=t.messages.length>js?Math.max(0,t.messages.length-Da):0,[G,X]=r.useState(()=>new Set),[q,K]=r.useState(()=>new Set),P=r.useRef(new Map),g=r.useRef(new Map),v=r.useRef(new Map),$=r.useRef(0),pe=r.useMemo(()=>{const x=new Map;for(const T of t.messages)x.set(T.id,ka(T));return x},[t.messages]),z=r.useRef(pe);z.current=pe;const E=r.useRef(G);E.current=G;const ee=t.messages.length>js&&!I,Y=r.useRef(ee);Y.current=ee;const M=va(t.messages,P.current,Ba),F=r.useRef(M);F.current=M;const H=r.useCallback(()=>{const x=p.current;if(!x)return;if(!Y.current){X(ge=>ge.size?new Set:ge);return}const T=x.getBoundingClientRect(),Z={top:T.top-ws,bottom:T.bottom+ws},ne=[];for(const[ge,je]of v.current){const Re=je.getBoundingClientRect();ne.push({id:ge,top:Re.top,bottom:Re.bottom}),E.current.has(ge)||oe(ge,Re.bottom-Re.top,z.current.get(ge))}const he=fa(ne,Z,F.current,E.current);for(const ge of he.hide){const je=v.current.get(ge);je&&oe(ge,je.offsetHeight,z.current.get(ge))}X(ge=>xa(ge,he))},[]),se=r.useCallback(()=>{$.current||($.current=requestAnimationFrame(()=>{$.current=0,H()}))},[H]);r.useLayoutEffect(()=>{H()},[H]);const V=r.useRef(I);r.useLayoutEffect(()=>{V.current&&!I&&H(),V.current=I},[I,H]);const oe=r.useCallback((x,T,Z)=>{Z!==void 0&&(g.current.set(x,{h:T,len:Z}),P.current.set(x,T))},[]),re=r.useCallback((x,T)=>{oe(x,T,z.current.get(x))},[oe]),d=r.useCallback(x=>{x&&v.current.set(x.dataset.lazyId??"",x)},[]);r.useEffect(()=>{const x=new Set(t.messages.map(T=>T.id));for(const[T,Z]of v.current)x.has(T)||(v.current.delete(T),P.current.delete(T),g.current.delete(T));X(T=>{let Z=!1;const ne=new Set;for(const he of T)x.has(he)?ne.add(he):Z=!0;return Z?ne:T})},[t.messages,y]),r.useEffect(()=>()=>cancelAnimationFrame($.current),[]);const R=r.useMemo(()=>{const x=[];for(const T of t.messages){if(T.role!=="user")continue;const Z=T.content.map(ge=>{var je;return((je=nt(ge))==null?void 0:je.text)??""}).filter(Boolean).join(" "),ne=Ut(Z),he=ne?ne.userMessage??`skill:${ne.name}`:Z.trim();he&&x.push({id:T.id,text:he})}return x},[t.messages]),le=r.useMemo(()=>{const x=new Map;return R.forEach((T,Z)=>x.set(T.id,Z)),x},[R]),[te,fe]=r.useState(-1),Q=r.useRef(-1),de=r.useRef(R);r.useEffect(()=>{de.current=R},[R]);const xe=r.useCallback(()=>{const x=p.current,T=de.current;if(!x||T.length===0)return;const Z=x.getBoundingClientRect().top,ne=140;let he=-1;for(let ge=0;ge<T.length;ge++){const je=x.querySelector(`[data-msg-id="${T[ge].id}"]`);if(je)if(je.getBoundingClientRect().top<=Z+ne)he=ge;else break}he!==Q.current&&(Q.current=he,fe(he))},[]);r.useEffect(()=>{xe()},[R,xe]);const ce=r.useCallback(x=>{w(T=>T.has(x)?T:new Set(T).add(x))},[]),Se=r.useCallback(x=>{const T=t.messages.findIndex(Z=>Z.id===x);T>=0&&T<W&&!y.has(x)&&ms.flushSync(()=>ce(x))},[t.messages,W,y,ce]);r.useEffect(()=>{const x=T=>{if(!(T.ctrlKey||T.metaKey)||T.key.toLowerCase()!=="f")return;const Z=T.target;Z&&(Z.tagName==="INPUT"||Z.tagName==="TEXTAREA"||Z.isContentEditable)||(T.preventDefault(),D(!0))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[]);const Je=r.useCallback(x=>{w(T=>{if(!T.has(x))return T;const Z=new Set(T);return Z.delete(x),Z})},[]),Te=r.useCallback(x=>{const T=t.messages.findIndex(ne=>ne.id===x);ms.flushSync(()=>{T>=0&&T<W&&!y.has(x)&&ce(x),K(ne=>ne.has(x)?ne:new Set(ne).add(x))});const Z=de.current.findIndex(ne=>ne.id===x);Q.current=Z,fe(Z),requestAnimationFrame(()=>{var he,ge,je;const ne=(he=p.current)==null?void 0:he.querySelector(`[data-msg-id="${x}"]`);ne&&((ge=p.current)==null||ge.querySelectorAll(".msg-flash").forEach(Re=>Re.classList.remove("msg-flash")),ne.scrollIntoView({block:"start"}),ne.classList.remove("msg-flash"),ne.offsetWidth,ne.classList.add("msg-flash"),ne!==((je=p.current)==null?void 0:je.lastElementChild)&&(j.current=!0))})},[t.messages,W,y,ce]),Ee=r.useMemo(()=>{var x;return o?((x=t.messages.find(T=>T.role===o.role&&T.timestamp===o.timestamp))==null?void 0:x.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 x=p.current;if(!x)return;const T=x.scrollTop-N.current,Z=x.scrollHeight-A.current;N.current=x.scrollTop,A.current=x.scrollHeight;const ne=x.scrollHeight-x.scrollTop-x.clientHeight<80,he=Date.now()<_.current,ge=Ea({dSt:T,dSh:Z,escaped:j.current,graceActive:he,stuck:b.current});ge.reassert&&(_.current=Date.now()+St,x.scrollTop=x.scrollHeight),ge.flipEscape&&(j.current=!0),ne&&T>=0&&(j.current=!1),he||(T<0?b.current=ne&&!j.current:ne&&(b.current=!0)),k(b.current),xe(),se()},[xe,se]),Me=r.useRef(!1);r.useEffect(()=>{const x=Me.current;if(Me.current=!!t.isStreaming,x&&!t.isStreaming&&!j.current){const T=()=>{const ne=p.current;ne&&!j.current&&(ne.scrollTop=ne.scrollHeight,b.current=!0,k(!0))};requestAnimationFrame(()=>requestAnimationFrame(T));const Z=setTimeout(T,180);return()=>clearTimeout(Z)}},[t.isStreaming]),r.useEffect(()=>{const x=p.current;x&&b.current&&(x.scrollTop=x.scrollHeight)},[S,t.isStreaming,s]);const Xe=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");r.useEffect(()=>{const x=p.current;x&&b.current&&(x.scrollTop=x.scrollHeight)},[Xe]),r.useEffect(()=>{const x=p.current;if(!x||typeof ResizeObserver>"u")return;const T=new ResizeObserver(()=>{b.current&&!j.current&&(x.scrollTop=x.scrollHeight,k(!0))});return T.observe(x),()=>T.disconnect()},[]),r.useEffect(()=>{const x=p.current;if(!x||typeof MutationObserver>"u")return;let T=!1;const Z=new MutationObserver(()=>{T||(T=!0,requestAnimationFrame(()=>{T=!1;const ne=p.current;ne&&b.current&&!j.current&&(ne.scrollTop=ne.scrollHeight,k(!0))}))});return Z.observe(x,{childList:!0,subtree:!0,characterData:!0}),()=>Z.disconnect()},[]);const Fe=r.useCallback(()=>{if(!p.current)return;b.current=!0,j.current=!1,k(!0),_.current=Date.now()+St;const T=()=>{const Z=p.current;!Z||!b.current||j.current||(_.current=Date.now()+St,Z.scrollTop=Z.scrollHeight)};T(),requestAnimationFrame(()=>requestAnimationFrame(T)),setTimeout(T,120),setTimeout(T,300),setTimeout(T,600)},[]),$e=r.useRef(null);r.useEffect(()=>{const x=$e.current,T=p.current;if(!x||!T)return;const Z=ne=>{ne.preventDefault();const he=x.querySelector(".qn-list");if(he&&he.contains(ne.target)&&he.scrollHeight>he.clientHeight){he.scrollTop+=ne.deltaY;return}T.scrollTop+=ne.deltaY};return x.addEventListener("wheel",Z,{passive:!1}),()=>x.removeEventListener("wheel",Z)},[]);const[Oe,C]=r.useState(0);r.useEffect(()=>{const x=()=>{var T;C(((T=p.current)==null?void 0:T.clientHeight)??0),se()};return x(),window.addEventListener("resize",x),()=>window.removeEventListener("resize",x)},[se]);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${f?"":" anchor-live"}`,ref:p,onScroll:Qe,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(Pa,{})}),t.messages.map((x,T)=>{const Z=T<W,ne=Z&&y.has(x.id);if(Z&&!ne)return x.role==="toolResult"?null:e.jsx(ma,{message:x,onExpand:ce},x.id);const he=x.role==="user"?le.get(x.id):void 0,ge=!ee||M.has(x.id)||q.has(x.id)||!G.has(x.id);return e.jsx(ga,{id:x.id,show:ge,height:ba(x.id,pe.get(x.id)??-1,g.current,sn(x.role,x.customType)),containerRef:p,onMeasured:re,lazyRef:d,children:e.jsx(fs,{message:x,qnIndex:he,qnActive:he!==void 0?he===te:void 0,onJump:Te,toolResults:O,liveOutputs:Ns(x)?s:bs,toolStatuses:i,streaming:t.isStreaming,onKillBash:c,toolsWrap:n,thinkingWrap:a,isLast:x.id===B,onEdit:l,questionAttachments:h.get(x.id),onCollapse:ne?Je:void 0},x.id)},x.id)}),t.streamingMessage&&e.jsx(fs,{message:t.streamingMessage,toolResults:O,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:m("waitingResponse")}),t.queue.steering.map((x,T)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:m("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:x})]})},`q-steer-${T}`)),t.queue.followUp.map((x,T)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:m("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:x})]})},`q-fu-${T}`))]}),!f&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Fe,children:[e.jsx(Ws,{})," ",m("backToBottom")]}),e.jsx(Ta,{containerRef:p,messages:S,open:I,onClose:()=>D(!1),onEnsureExpanded:Se}),R.length>0&&e.jsxs("div",{className:`qn-rail ${ye?"many":""}`,ref:$e,"aria-label":m("questionNavTitle"),style:{"--rail-gap":`${ae}px`},children:[R.map((x,T)=>e.jsx("button",{type:"button",className:`qn-bar ${T===te?"active":""}`,"aria-label":`${T+1}. ${x.text}`,onClick:()=>Te(x.id),children:e.jsxs("span",{className:"qn-bar-text",children:[T+1,". ",x.text]})},x.id)),ye&&e.jsx("div",{className:"qn-list",children:R.map((x,T)=>e.jsxs("button",{type:"button",className:`qn-list-item ${T===te?"active":""}`,"aria-label":`${T+1}. ${x.text}`,onClick:()=>Te(x.id),children:[e.jsx("span",{className:"qn-list-idx",children:T+1}),e.jsx("span",{className:"qn-list-text",children:x.text})]},x.id))})]})]})}const cn="pi-web-model-usage";function _a(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 Fa(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function $a(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?_a(JSON.parse(t)):{}}catch{return{}}}function Oa(t){try{localStorage.setItem(cn,JSON.stringify(t))}catch{}}function Wa(t){const s=Fa(dn(),t);return Oa(s),s}const Ua=["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=me(),u=s==null?void 0:s.model,m=u?`${u.provider}/${u.id}`:null,[p,f]=r.useState(!1),[k,b]=r.useState(!1),[N,A]=r.useState(""),[j,_]=r.useState(null),[y,w]=r.useState({}),I=r.useRef(null),D=r.useRef(null),[S,O]=r.useState(null);r.useEffect(()=>{if(!p){O(null);return}if(i.length===0)return;const g=requestAnimationFrame(()=>{const v=D.current;v&&O(v.offsetWidth)});return()=>cancelAnimationFrame(g)},[p,i.length]),r.useEffect(()=>{p&&w(dn())},[p]),r.useEffect(()=>{p||(A(""),_(null))},[p]);const h=r.useMemo(()=>{const g=new Map;for(const v of i)g.set(v.provider,(g.get(v.provider)??0)+1);return[...g.entries()].sort((v,$)=>v[0].localeCompare($[0])).map(([v,$])=>({name:v,count:$}))},[i]),B=r.useMemo(()=>$a(i,y),[i,y]),W=r.useMemo(()=>{let g=B;j&&(g=g.filter($=>$.provider===j));const v=N.trim().toLowerCase();return v?g.filter($=>$.name.toLowerCase().includes(v)||$.provider.toLowerCase().includes(v)||$.id.toLowerCase().includes(v)):g},[B,N,j]),[G,X]=r.useState(!1),q=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,K=Ua.map(g=>({value:g,label:o(`thinking.${g}`),supported:q?q.has(g):!0})),P=g=>{var v;return((v=K.find($=>$.value===g))==null?void 0:v.label)??g};return r.useEffect(()=>{p&&i.length===0&&!G&&!l&&(X(!0),c({type:"list_models"}))},[p,i.length,G,l,c]),r.useEffect(()=>{i.length>0&&X(!1)},[i.length]),r.useEffect(()=>{var v;if(!p)return;const g=(v=I.current)==null?void 0:v.querySelector(".dd-item.active");g==null||g.scrollIntoView({block:"nearest"})},[p,m,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:f,menuClassName:"dd-menu-model",menuRef:D,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:g=>A(g.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[h.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 ${j===null?"active":""}`,onClick:()=>_(null),children:e.jsx("span",{children:o("allProviders")})}),h.map(g=>e.jsxs("button",{type:"button",className:`dd-provider-item ${j===g.name?"active":""}`,onClick:()=>_(j===g.name?null:g.name),title:`${g.name} · ${g.count}`,children:[e.jsx("span",{className:"dd-provider-name",children:g.name}),e.jsx("span",{className:"dd-provider-count",children:g.count})]},g.name))]}),e.jsxs("div",{className:"dd-model-scroll",ref:I,children:[(G||l)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),i.length===0&&!G&&!l&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),W.length===0&&i.length>0&&e.jsx("div",{className:"dd-loading",children:o("noModelMatches")}),W.map(g=>e.jsx(Ne,{active:m===g.id,onClick:()=>{m!==g.id&&c({type:"set_model",modelId:g.id}),f(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:g.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:g.provider}),(y[g.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:o("modelUsedCount",{n:y[g.id]})}),(g.reasoning||g.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[g.reasoning&&e.jsx("span",{className:"dd-model-badge",children:o("reasoning")}),g.vision&&e.jsx("span",{className:"dd-model-badge",children:o("vision")})]})]})]})},g.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:()=>{f(!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?P(s.thinkingLevel):"—"})})]}),open:k,onOpenChange:b,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("thinkingLevel")}),K.map(g=>e.jsx(Ne,{active:(s==null?void 0:s.thinkingLevel)===g.value,disabled:!g.supported,title:g.supported?void 0:o("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==g.value&&c({type:"set_thinking",level:g.value}),b(!1)},children:g.label},g.value))]})]})}),Ha=r.memo(function({ready:s,streaming:i,messages:l,slashCommands:c,modelState:a,models:n,modelsLoading:o,send:u,attachments:m,onRemoveAttachment:p,onAddImageFiles:f,onAddLocalFiles:k,onNotice:b,onSent:N,onManageModels:A}){const j=me(),{locale:_}=Ot(),{openPicker:y}=ln(),w=d=>_==="en"&&d.descriptionEn?d.descriptionEn:d.description??"",I=d=>_==="en"&&d.argumentHintEn?d.argumentHintEn:d.argumentHint??"",[D,S]=r.useState(""),[O,h]=r.useState(!1),[B,W]=r.useState(null),[G,X]=r.useState(0),[q,K]=r.useState(!1),[P,g]=r.useState(void 0),v=r.useRef(null),$=r.useRef(null),pe=r.useRef(null),z={builtin:j("slashBuiltin"),extension:j("slashExtension"),prompt:j("slashPrompt"),skill:j("slashSkill"),plugin:j("slashPlugin")},E=d=>{const R=d.match(/^\/([^\s]*)$/);if(R&&s){const le=R[1].toLowerCase(),te=c.filter(fe=>fe.name.toLowerCase().startsWith(le));W(te.length>0?te:null),X(0)}else W(null)};r.useEffect(()=>{var R;const d=(R=pe.current)==null?void 0:R.querySelector(".slash-item.active");d==null||d.scrollIntoView({block:"nearest"})},[G,B]);const ee=d=>{var Q;const R=B??[],le=d??R[G%Math.max(R.length,1)];if(!le){W(null);return}const te=D.match(/^\/([^\s]*)([\s\S]*)$/),fe=te?te[2]:"";S(`/${le.name} ${fe}`),W(null),(Q=v.current)==null||Q.focus()},Y=async()=>{const R=[...l].reverse().find(te=>te.role==="assistant"&&te.content.some(fe=>fe.type==="text"&&fe.text)),le=R==null?void 0:R.content.filter(te=>te.type==="text").map(te=>te.text).join(`
|
|
318
|
+
`);if(!le){b("warning",j("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(le),b("info",j("slashCopied"))}catch{b("error",j("slashCopyFailed"))}},M=d=>{if(!d||d.length===0){b("warning",j("foldersNotSupported"));return}const R=Array.from(d).filter(te=>Le(te.type)),le=Array.from(d).filter(te=>!Le(te.type));R.length>0&&f(R),le.length>0&&k(le)},F=d=>{var te;const R=(te=d.clipboardData)==null?void 0:te.items;if(!R)return;const le=[];for(const fe of R)if(fe.kind==="file"&&Le(fe.type)){const Q=fe.getAsFile();Q&&le.push(Q)}le.length!==0&&(d.preventDefault(),f(le))},H=s,se=r.useRef(D);r.useEffect(()=>{se.current=D},[D]),r.useEffect(()=>{E(se.current)},[c]),r.useEffect(()=>{const d=R=>{var te;const le=R.detail;S(le),(te=v.current)==null||te.focus()};return window.addEventListener("pi-web:fill",d),()=>window.removeEventListener("pi-web:fill",d)},[]),r.useEffect(()=>{if(!q)return;const d=R=>{R.key==="Escape"&&K(!1)};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[q]),r.useEffect(()=>{const d=v.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"},[D]);const V=(d=!1)=>{var te,fe,Q,de,xe;const R=D.trim(),le=m.some(ce=>ce.imageData||ce.fileData);if(!(!H||!R&&!le)){if(R==="/help"){const ce=(fe=(te=v.current)==null?void 0:te.closest(".inputbox"))==null?void 0:fe.getBoundingClientRect();g(ce==null?void 0:ce.width),K(!0),S(""),(Q=v.current)==null||Q.focus();return}if(R==="/copy"){S(""),(de=v.current)==null||de.focus(),Y();return}if(u({type:"prompt",text:R,queue:d,attachments:m.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&&Wa(`${ce.provider}/${ce.id}`),(xe=v.current)==null||xe.focus()}}},oe=d=>{if(!d.nativeEvent.isComposing){if(B&&B.length>0)switch(d.key){case"ArrowDown":d.preventDefault(),X(R=>(R+1)%B.length);return;case"ArrowUp":d.preventDefault(),X(R=>(R-1+B.length)%B.length);return;case"Tab":case"Enter":d.preventDefault(),ee();return;case"Escape":d.preventDefault(),W(null);return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),V())}},re=()=>e.jsx("div",{className:"inputbox-actions",children:i?e.jsxs(e.Fragment,{children:[D.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:j("supplementTip"),onClick:()=>V(!0),children:[e.jsx(As,{})," ",j("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:j("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(ut,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:j("sendTip"),disabled:!H||!D.trim()&&!m.some(d=>d.imageData||d.fileData),onClick:()=>V(),children:e.jsx(Os,{})})});return e.jsxs("div",{className:`inputbar${O?" drop-active":""}`,onDragOver:d=>{d.preventDefault(),d.stopPropagation(),h(!0)},onDragLeave:d=>{d.currentTarget.contains(d.relatedTarget)||h(!1)},onDrop:d=>{var R;d.preventDefault(),d.stopPropagation(),h(!1),M(((R=d.dataTransfer)==null?void 0:R.files)??null)},children:[O&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",j("dropHereToAttach")]})}),m.length>0&&e.jsxs("div",{className:"attach-row",children:[m.map(d=>e.jsxs("span",{className:`attach-chip ${d.imageData?"image":d.fileData?"file":d.mode}`,title:d.imageData?j("attachImage",{name:d.name}):d.fileData?j("attachFile",{name:d.name}):d.isDir?j("folderRef",{path:d.path}):d.mode==="reference"?j("refOnly",{path:d.path}):d.mode==="lines"&&d.lines?j("attachLines",{path:d.path,start:d.lines.start,end:d.lines.end}):j("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:j("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:j("attachHint")})]}),B&&B.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:pe,"aria-label":j("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:j("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>W(null),children:"Esc"})]}),B.map((d,R)=>e.jsxs("button",{type:"button",className:`slash-item${R===G?" active":""}`,onMouseEnter:()=>X(R),onClick:()=>ee(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:[w(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(d)})]})]},d.name))]}),q&&e.jsx("div",{className:"modal-backdrop",onClick:()=>K(!1),children:e.jsxs("div",{className:"slash-help",style:P?{width:P}:void 0,onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",j("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>K(!1),children:j("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:j("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:[w(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:v,value:D,rows:1,placeholder:j(H?i?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!H,onChange:d=>{S(d.target.value),E(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:j("uploadFile"),disabled:!H,onClick:()=>{var d;return(d=$.current)==null?void 0:d.click()},children:e.jsx(Wn,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:j("tpl.openPicker"),onClick:y,children:e.jsx(Qn,{})}),e.jsx(qa,{state:a,models:n,modelsLoading:o,send:u,onManageModels:A,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:re()})]})]})]})}),Ka=r.memo(function({goal:s,models:i,modelsLoading:l,activeConversationId:c,send:a}){var G,X,q,K,P,g;const n=me(),o=!s.conversationId||s.conversationId===c,u=s.goal!==null&&o,[m,p]=r.useState(""),[f,k]=r.useState(s.reviewModel??""),[b,N]=r.useState(s.maxRounds),[A,j]=r.useState(s.locked),[_,y]=r.useState(!1),[w,I]=r.useState(!1),[D,S]=r.useState(!0);r.useEffect(()=>{k(s.reviewModel??""),N(s.maxRounds||0),j(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),r.useEffect(()=>{_&&i.length===0&&!w&&!l&&(I(!0),a({type:"list_models"}))},[_,i.length,w,l,a]),r.useEffect(()=>{i.length>0&&I(!1)},[i.length]);const O=()=>{var v;return f?((v=i.find($=>$.id===f))==null?void 0:v.name)??f:n("goalBarUseMainModel")},h=()=>{const v=m.trim();v&&(a({type:"set_goal",goal:v,...f?{reviewModel:f}:{},maxRounds:b,locked:A}),p(""),S(!1))},B=()=>{const v=m.trim();v&&(a({type:"start_goal_wizard",text:v,...f?{wizardModel:f}:{},maxRounds:b,locked:A}),p(""),S(!1))},W=(((G=s.wizard)==null?void 0:G.active)??!1)&&o;return W?e.jsx("div",{className:`goalbar goalbar-active ${W?"wizard":""}`,children:e.jsxs("div",{className:"goalbar-active-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx("span",{className:"goalbar-spin",children:"🔍"})}),e.jsxs("span",{className:"goalbar-text",title:((X=s.wizard)==null?void 0:X.draft)??"",children:[n("goalWizardRunning"),": ",(q=s.wizard)==null?void 0:q.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[n("goalBarRound",{n:(((K=s.wizard)==null?void 0:K.step)??0)+1})," ","/ ",((P=s.wizard)==null?void 0:P.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((g=s.wizard)==null?void 0:g.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,{})})]})}):D?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:m,placeholder:n("goalBarPlaceholder"),onChange:v=>p(v.target.value),onKeyDown:v=>{v.key==="Enter"&&h()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!m.trim(),onClick:h,children:n("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!m.trim(),title:n("goalWizardTip"),onClick:B,children:["🔍 ",n("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n(A?"goalBarLocked":"goalBarUnlocked"),onClick:()=>j(v=>(a({type:"set_goal_prefs",locked:!v}),!v)),children:A?e.jsx(Vn,{}):e.jsx(_n,{})}),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:O()})]}),open:_,onOpenChange:y,direction:"up",children:[e.jsx("div",{className:"dd-header",children:n("goalBarReviewModel")}),(w||l)&&e.jsx("div",{className:"dd-loading",children:n("loading")}),i.length===0&&!w&&!l&&e.jsx("div",{className:"dd-loading",children:n("noModels")}),e.jsx(Ne,{active:f==="",onClick:()=>{k(""),y(!1),a({type:"set_goal_prefs",reviewModel:""})},children:n("goalBarUseMainModel")}),i.map(v=>e.jsx(Ne,{active:f===v.id,onClick:()=>{k(v.id),y(!1),a({type:"set_goal_prefs",reviewModel:v.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:v.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:v.provider})})]})},v.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:v=>{const $=parseInt(v.target.value,10);if(Number.isNaN($)||$<0){N(0);return}N($)},onBlur:()=>a({type:"set_goal_prefs",maxRounds:b}),onKeyDown:v=>{v.key==="Enter"&&(a({type:"set_goal_prefs",maxRounds:b}),v.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:n(A?"goalBarLocked":"goalBarUnlocked")})]})]})});function za({chat:t,send:s}){const i=me(),l=t.state,[c,a]=r.useState(!1),[n,o]=r.useState(""),[u,m]=r.useState(0),p=r.useRef(null),f=t.pathCompletions;if(r.useEffect(()=>{if(!c)return;const h=setTimeout(()=>{s({type:"complete_path",path:n})},150);return()=>clearTimeout(h)},[n,c,s]),r.useEffect(()=>m(0),[f]),r.useEffect(()=>{const h=document.querySelector(`.status-completions .pc-item[data-idx="${u}"]`);h==null||h.scrollIntoView({block:"nearest"})},[u]),!l)return null;const k=l.stats,b=t.ready?"ok":"busy",N=t.ready?i("connected"):i("connecting"),A=k.contextUsage,j=A.tokens!==null&&A.percent!==null?`${Cs(A.tokens)} / ${Cs(A.contextWindow)}`:"—",_=A.percent??null,y=_===null?"":_>=80?"warn":_>=50?"mid":"ok",w=l.queue.steering.length+l.queue.followUp.length,I=()=>{o(l.cwd),a(!0)},D=(h,B)=>{var G;const W=h.includes("\\")?"\\":"/";o(B?`${h}${W}`:h),m(0),(G=p.current)==null||G.focus()},S=h=>{const B=h.trim();B&&B!==l.cwd&&s({type:"set_cwd",path:B}),a(!1)},O=h=>{if(h.key==="ArrowDown")h.preventDefault(),m(B=>Math.min(B+1,f.length-1));else if(h.key==="ArrowUp")h.preventDefault(),m(B=>Math.max(B-1,0));else if(h.key==="Tab"&&f.length>0){h.preventDefault();const B=f[Math.min(u,f.length-1)];D(B.path,B.type==="dir")}else if(h.key==="Enter"&&!h.nativeEvent.isComposing){const B=n.trim();if(B.endsWith("/")||B.endsWith("\\"))S(B);else if(f.some(W=>W.path===B))S(B);else if(f.length>0&&f[u]){h.preventDefault();const W=f[u];D(W.path,W.type==="dir")}else S(B)}else h.key==="Escape"&&(f.length>0?(h.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 ${y}`,children:_!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(_,100)}%`}})}),j]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:i("cumulativeCost"),children:["$",Va(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(h=>h.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"),w>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",w," ",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:h=>o(h.target.value),onKeyDown:O,onBlur:()=>a(!1)}),f.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:h=>h.preventDefault(),children:f.map((h,B)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":B,className:`pc-item ${B===u?"sel":""}`,onMouseEnter:()=>m(B),onClick:()=>D(h.path,h.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:h.type==="dir"?e.jsx(Ge,{}):e.jsx(Fs,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:h.name}),e.jsx("span",{className:"pc-path",children:h.path})]})]})},h.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 Va(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function Ga({dialog:t,send:s}){const i=me(),[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=f=>{f.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]:[],m=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children: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,f)=>e.jsx("button",{type:"button",className:`dialog-option ${f===a?"sel":""}`,onMouseEnter:()=>n(f),onClick:()=>o(p),children:p},f)),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:m}),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:m||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 Ya(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 Ja({chat:t,send:s,terminal:i,active:l,onSwitchToTerminal:c}){var $e,Oe;const a=me(),[n,o]=r.useState(null),[u,m]=r.useState([]),[p,f]=r.useState(""),[k,b]=r.useState(new Map),[N,A]=r.useState("changes"),[j,_]=r.useState([]),[y,w]=r.useState(null),[I,D]=r.useState(""),[S,O]=r.useState(!1),[h,B]=r.useState(null),[W,G]=r.useState(null),[X,q]=r.useState(!1),[K,P]=r.useState(!1),[g,v]=r.useState(!1),[$,pe]=r.useState(null),[z,E]=r.useState(!1),[ee,Y]=r.useState(""),M=r.useRef(0),F=r.useRef(-1),H=r.useRef(-1),se=r.useRef(-1),V=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,P(!1),pe(null),!C.ok){pe(C.error??"查询失败");return}if(C.notRepo){E(!0),o(null),m([]),b(new Map),_([]),w(null),D(""),G(null);return}E(!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(x=>({...x}))},ae=(C.branches??[]).map(x=>({...x})),ye=new Map;for(const[x,T]of Object.entries(C.stats??{}))ye.set(x,{add:T[0],del:T[1]});o(ue),m(ae),b(ye),f(x=>{var T;return ue.detached?x||"":ue.branch&&ae.some(Z=>Z.name===ue.branch)?ue.branch:x&&ae.some(Z=>Z.name===x)?x:((T=ae[0])==null?void 0:T.name)??""}),G(x=>x&&!ue.files.some(T=>T.path===x.file.path)?null:x)}else if(C.reqId===H.current){if(H.current=-1,q(!1),!C.ok){pe(C.error??"查询失败");return}const ue=re.current;if(!ue)return;G({file:ue,staged:C.stagedText??"",worktree:C.worktreeText??"",untracked:!1})}else if(C.reqId===V.current){if(V.current=-1,v(!1),!C.ok){pe(C.error??"查询失败");return}_((C.history??[]).map(ue=>({...ue})))}else if(C.reqId===se.current){if(se.current=-1,O(!1),!C.ok){pe(C.error??"查询失败");return}D(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]),te=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),m([]),b(new Map),_([]),v(!1),V.current=-1,w(null),D(""),G(null),B(null)),oe.current=t.state.cwd,pe(null),le({type:"scm_status"},F)&&(ue||P(!0)))},[t.ready,($e=t.state)==null?void 0:$e.cwd,t.status,le]),fe=r.useCallback(C=>{if(B(C),w(null),re.current=C,C.x==="?"&&C.y==="?"){G({file:C,staged:"",worktree:"",untracked:!0});return}q(!0),pe(null),le({type:"scm_filediff",path:C.path},H)||q(!1)},[le]),Q=r.useCallback(C=>{w(C),B(null),G(null),D(""),O(!0),pe(null),le({type:"scm_commit",hash:C.hash},se)||O(!1)},[le]),de=r.useCallback((C,ue)=>{var x,T;if(!t.ready)return;const ae={name:C,command:ue,cwd:"${pwd}"},ye=t.terminals.find(Z=>Z.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 Z=De();i.create({id:Z,conversationId:t.activeConversationId||((x=t.state)==null?void 0:x.conversationId)||"",title:C,cwd:((T=t.state)==null?void 0:T.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=ee.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}"`),Y("")},[ee,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"},V)||(V.current=-1)},[le]);r.useEffect(()=>{l&&te()},[l,te]),r.useEffect(()=>{N==="history"&&n&&Me()},[N,n,Me]),r.useEffect(()=>{t.scmDirty>0&&l&&te(!1,!0)},[t.scmDirty]),r.useEffect(()=>{if(!l||!t.ready||t.status!=="open")return;const C=setInterval(()=>{document.visibilityState!=="hidden"&&te(!1,!0)},3e4);return()=>clearInterval(C)},[l,t.ready,t.status,te]),r.useEffect(()=>{const C=d.current;if(d.current=t.terminals,!l)return;t.terminals.some(ae=>{var x;return ae.running!==!1?!1:((x=C.find(T=>T.id===ae.id))==null?void 0:x.running)===!0&&/^git /.test(ae.title)})&&t.ready&&t.status==="open"&&(te(!1,!0),N==="history"&&n&&Me())},[t.terminals,l,t.ready,t.status,te,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 x="";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("+++")?x="hdr":ae.startsWith("@@")?x="hunk":ae.startsWith("+")?x="add":ae.startsWith("-")&&(x="del"),e.jsx("div",{className:`scm-diff-line ${x}`,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:()=>{A("changes"),pe(null)},children:a("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":N==="history",className:N==="history"?"active":"",onClick:()=>{A("history"),pe(null)},children:a("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:a("scmRefreshTip"),disabled:K,onClick:()=>te(!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=>f(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:ee,placeholder:a("scmCommitPlaceholder"),disabled:z,onChange:C=>Y(C.target.value),onKeyDown:C=>{C.key==="Enter"&&!C.nativeEvent.isComposing&&xe()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!ee.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")}),j.length>0&&e.jsx("span",{className:"scm-files-count",children:j.length})]}),e.jsx("div",{className:"scm-history-list",children:z?e.jsx("div",{className:"scm-empty",children:a("scmNotGitRepo")}):!n||g?e.jsx("div",{className:"scm-empty",children:t.status==="open"?a("scmLoading"):a("scmConnecting")}):j.length===0?e.jsx("div",{className:"scm-empty",children:a("scmNoHistory")}):j.map(C=>e.jsxs("button",{type:"button",className:`scm-commit ${(y==null?void 0:y.hash)===C.hash?"active":""}`,onClick:()=>Q(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=Ya(C),ae=k.get(C.path);return e.jsxs("div",{className:`scm-file ${(h==null?void 0:h.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"?y?`${y.shortHash} ${y.subject}`:a("scmCommitDetail"):h?h.path:a("scmDiff")}),(N==="history"?S:X)&&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:$}),!y&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmSelectCommitHint")}),y&&S&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmLoading")}),y&&!S&&!$&&I?Fe(I):null]}):e.jsxs(e.Fragment,{children:[$&&e.jsx("div",{className:"scm-error",children:$}),!h&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmSelectFileHint")}),h&&!W&&!$&&e.jsx("div",{className:"scm-empty",children:a("scmLoading")}),h&&W&&W.untracked&&e.jsx("div",{className:"scm-empty",children:a("scmUntrackedNote")}),h&&W&&!W.untracked&&e.jsxs(e.Fragment,{children:[W.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:a("scmStaged")}),Fe(W.staged)]}),W.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:a("scmUnstaged")}),Fe(W.worktree)]}),!W.staged&&!W.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 Qa({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,Ci(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 Xa({send:t,piConfigured:s,piAgentInstalled:i,providers:l,installResult:c,onClose:a}){const n=me(),[o,u]=r.useState(!1),[m,p]=r.useState(""),[f,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;!m&&l.length>0&&p(((I=l.find(D=>!D.configured))==null?void 0:I.id)??l[0].id)},[l,m]);const A=()=>{o||(u(!0),t({type:"install_pi_agent"}))},j=()=>{!f.trim()||b||(N(!0),t({type:"set_provider_api_key",provider:m.trim(),apiKey:f.trim()}),setTimeout(()=>N(!1),3e3))},_=()=>{t({type:"get_state"}),t({type:"list_providers"})},y=l.find(I=>I.id===m),w=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")}),w?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:A,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:m,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))]}),(y==null?void 0:y.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:f,onChange:I=>k(I.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!f.trim()||b||!m,onClick:j,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:A,children:n(o?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:a,children:n("skip")})]})]})})}const Za=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],qt=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),er=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[qt()]});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:[qt()]).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 tr({send:t,providers:s,providerStatus:i,fetchModelsResult:l,refreshProviderResult:c,cloneProviderResult:a,onClose:n}){const o=me(),[u,m]=r.useState(null),[p,f]=r.useState({}),[k,b]=r.useState(null),[N,A]=r.useState({}),[j,_]=r.useState(!1),[y,w]=r.useState(0),[I,D]=r.useState(null),S=r.useRef(0),[O,h]=r.useState({});r.useRef(0);const B=r.useRef(0),[W,G]=r.useState(null),X=r.useRef(0),q=r.useRef(0);r.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const K=()=>{if(!u)return;const E=u.baseUrl.trim();if(!E){D({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(j)return;_(!0),D(null);const ee=y+1;w(ee),t({type:"fetch_models",reqId:ee,baseUrl:E,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};r.useEffect(()=>{var E;if(!(!l||l.reqId===S.current))if(S.current=l.reqId,_(!1),l.ok&&((E=l.models)!=null&&E.length)){const ee=l.models;m(Y=>{if(!Y)return Y;const M=Y.models.map(V=>{var d;if(!V.id.trim())return V;const oe=ee.find(R=>R.id===V.id.trim());if(!oe)return V;const re={...V};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(V=>V.id.trim()).filter(Boolean)),H=ee.filter(V=>!F.has(V.id)).map(V=>{var oe;return{id:V.id,name:V.name??"",reasoning:V.reasoning??!1,input:(oe=V.input)!=null&&oe.includes("image")?"text-image":"text",contextWindow:V.contextWindow?String(V.contextWindow):"",maxTokens:V.maxTokens?String(V.maxTokens):""}}),se=[...M,...H];return se.some(V=>V.id.trim())?{...Y,models:se.filter(V=>V.id.trim())}:Y}),D({ok:!0,text:o("fetchModelsOk",{n:ee.length})})}else D({ok:!1,text:l.error||o("fetchModelsEmpty")})},[l]);const P=E=>{const ee=(p[E.id]??"").trim();!ee||k||(b(E.id),t({type:"set_provider_api_key",provider:E.id,apiKey:ee}),setTimeout(()=>{b(null),f(Y=>({...Y,[E.id]:""})),A(Y=>({...Y,[E.id]:!1})),t({type:"list_providers"})},1500))},g=()=>{if(!u)return;const E=u.providerId.trim(),ee=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})),Y={providerId:E,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:ee};t({type:"save_model_config",providerId:E,config:Y}),n()};r.useEffect(()=>{!c||c.reqId===B.current||(B.current=c.reqId,h({}))},[c]);const v=E=>{if(W)return;G(E.id);const ee=++X.current+Date.now();t({type:"clone_provider",provider:E.id,reqId:ee})};r.useEffect(()=>{!a||a.reqId===q.current||(q.current=a.reqId,G(null),a.ok&&a.config&&m(Ss({...a.config,apiKey:""})))},[a]);const $=E=>{window.confirm(o("clearKeyConfirm",{id:E}))&&t({type:"clear_provider_api_key",provider:E})},pe=E=>{window.confirm(o("deleteProviderConfirm",{id:E.providerId,n:E.models.length}))&&t({type:"delete_model_config",providerId:E.providerId})},z=(E,ee)=>{u&&m({...u,models:u.models.map((Y,M)=>M===E?{...Y,...ee}:Y)})};return e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"modal model-modal",onClick:E=>E.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(E=>E.providerId===u.providerId),onChange:E=>m({...u,providerId:E.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:E=>m({...u,name:E.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:E=>m({...u,api:E.target.value}),children:Za.map(E=>e.jsx("option",{value:E,children:E},E))})]}),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:E=>m({...u,baseUrl:E.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:E=>m({...u,apiKey:E.target.value}),placeholder:o("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:E=>m({...u,authHeader:E.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:j||!u.baseUrl.trim(),title:o("fetchModelsHint"),onClick:K,children:[e.jsx(Ft,{})," ",o(j?"fetchingModels":"fetchModels")]})]})]}),u.models.map((E,ee)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:E.id,onChange:Y=>z(ee,{id:Y.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:E.name,onChange:Y=>z(ee,{name:Y.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:E.input,onChange:Y=>z(ee,{input:Y.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:E.reasoning,onChange:Y=>z(ee,{reasoning:Y.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:E.contextWindow,onChange:Y=>z(ee,{contextWindow:Y.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:E.maxTokens,onChange:Y=>z(ee,{maxTokens:Y.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>m({...u,models:u.models.filter((Y,M)=>M!==ee)}),children:e.jsx(Ie,{})})]},ee)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>m({...u,models:[...u.models,qt()]}),children:[e.jsx(_e,{})," ",o("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>m(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(E=>E.id.trim()),onClick:g,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(E=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:E.name}),e.jsxs("span",{className:"provider-sub",children:[E.id,E.configured&&e.jsx("span",{className:"auth-badge",children:o("configuredBadge")}),E.source&&!E.configured&&e.jsx("span",{className:"auth-badge dim",children:E.source})]})]}),e.jsxs("div",{className:"provider-actions",children:[E.configured&&!N[E.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:()=>A(ee=>({...ee,[E.id]:!0})),children:[e.jsx(It,{})," ",o("replaceKey")]}),E.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>$(E.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[E.id]??"",onChange:ee=>f(Y=>({...Y,[E.id]:ee.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(p[E.id]??"").trim()||k===E.id,onClick:()=>P(E),children:[e.jsx(Gn,{})," ",k===E.id?o("savingKey"):o("saveKey")]})]}),e.jsxs("button",{type:"button",className:"btn sm",disabled:W!==null,title:o("cloneProviderTitle"),onClick:()=>v(E),children:[e.jsx($t,{})," ",W===E.id?o("cloning"):o("cloneProvider")]})]})]},E.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(E=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:E.providerId}),e.jsxs("span",{className:"provider-sub",children:[E.api??"—",E.baseUrl?` · ${E.baseUrl}`:"",E.models.length>0&&` · ${o("modelsCount",{n:E.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:o("edit"),onClick:()=>m(Ss(E)),children:e.jsx(It,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>pe(E),children:e.jsx(Ie,{})})]})]},E.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>m(er()),children:[e.jsx(_e,{})," ",o("addProvider")]})})]})]})})}function sr({plugin:t,send:s}){const i=me(),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})),m=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)},f=()=>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:!m||n,onClick:p,children:i(n?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:f,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=me();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 nr({chat:t,send:s,terminal:i,onSwitchToTerminal:l,onClose:c}){const a=me(),n=t.settings,[o,u]=r.useState("prompt"),m=r.useRef(null);r.useEffect(()=>{var d;(d=m.current)==null||d.scrollTo({top:0})},[o]);const[p,f]=r.useState(""),[k,b]=r.useState("append"),N=r.useRef(!1),[A,j]=r.useState(""),[_,y]=r.useState("append"),w=r.useRef(!1),[I,D]=r.useState(""),S=r.useRef(!1),[O,h]=r.useState(""),[B,W]=r.useState(!1),[G,X]=r.useState(null),[q,K]=r.useState(null);r.useEffect(()=>{n&&(b(n.promptMode),!N.current&&(f(k==="append"||n.customSystemPrompt?n.customSystemPrompt:n.defaultSystemPrompt||""),y(n.visionBridgePromptMode),!w.current&&(j(_==="append"||n.visionBridgePrompt?n.visionBridgePrompt:n.visionBridgeDefaultPrompt||""),S.current||D(n.reviewPrompt))))},[n,k,_]);const[P,g]=r.useState(String((n==null?void 0:n.terminalBashIdleMs)??15e3));if(r.useEffect(()=>{g(String((n==null?void 0:n.terminalBashIdleMs)??15e3))},[n==null?void 0:n.terminalBashIdleMs]),!n)return null;const v=[{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($n,{}),label:a("settingsPresets"),count:n.presets.length}],$=new Set(n.disabledSkills),pe=new Set(n.disabledExtensions),z=d=>s({type:"set_settings",...d}),E=d=>{const R=new Set($);R.has(d.name)?R.delete(d.name):R.add(d.name),z({disabledSkills:[...R]})},ee=new Set(n.disabledPlugins??[]),Y=d=>{const R=new Set(ee);R.has(d.id)?R.delete(d.id):R.add(d.id),z({disabledPlugins:[...R]})},M=d=>{const R=new Set(pe);R.has(d.id)?R.delete(d.id):R.add(d.id),z({disabledExtensions:[...R]})},F=(d,R)=>{var fe,Q;const le={name:d,command:R,cwd:"${pwd}"},te=t.terminals.find(de=>de.title===d);te?(i.restart(te.id),s({type:"run_command",terminalId:te.id,conversationId:te.conversationId,command:le,cols:80,rows:24})):i.create({id:De(),conversationId:t.activeConversationId||((fe=t.state)==null?void 0:fe.conversationId)||"",title:d,cwd:((Q=t.state)==null?void 0:Q.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:le}),l(),c()},H=d=>{X(null),F(`${a("uninstallTitle")} ${d}`,`pi remove npm:${d}`)},se=d=>{K(null),F(`${a("uninstallTitle")} ${d}`,`pi-web-ui uninstall ${d}`)},V=(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:v.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:m,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=>f(d.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":B,onClick:()=>W(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:P,onChange:d=>g(d.target.value),onBlur:()=>{const d=Math.max(0,Math.floor(Number(P)||0));g(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:()=>E(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?G===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("uninstallConfirmHint"),onClick:()=>H(R),children:a("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:a("uninstallHint"),onClick:()=>X(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:!ee.has(d.id)&&!d.error,onToggle:()=>!d.error&&Y(d),action:e.jsxs("div",{className:"set-row-actions",children:[d.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:a("pluginUpdateHint"),onClick:()=>V(d.id,d.source),children:[e.jsx(gt,{}),a("pluginUpdate")]}),q===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:a("pluginUninstallHint"),onClick:()=>se(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(sr,{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=>D(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;y(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:A,onFocus:()=>w.current=!0,onBlur:()=>{w.current=!1;const d=_==="replace"&&n.visionBridgeDefaultPrompt&&A===n.visionBridgeDefaultPrompt?"":A;z({visionBridgePromptMode:_,visionBridgePrompt:d})},onChange:d=>j(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:O,onChange:d=>h(d.target.value),onKeyDown:d=>{d.key==="Enter"&&O.trim()&&(s({type:"save_preset",name:O.trim()}),h(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!O.trim(),onClick:()=>{s({type:"save_preset",name:O.trim()}),h("")},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 ir(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 ar({servers:t,send:s,onClose:i}){const l=me(),[c,a]=r.useState(new Set),n=o=>a(u=>{const m=new Set(u);return m.has(o)?m.delete(o):m.add(o),m});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,m=o.taskId??String(o.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:u?o.plugin: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")," ",ir(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(m)?"open":""}`,title:`${l("bgTaskCommand")}: ${o.command}`,onClick:()=>n(m),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")})]})]},m)})}),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 rr(t,s){return t.toLowerCase().includes(s)}function lr({open:t,send:s,projects:i,cwd:l,fileSearch:c,sessionSearch:a,onClose:n,onSwitchSession:o,onSwitchProject:u,onPreviewFile:m}){const p=me(),f=r.useRef(null),[k,b]=r.useState(""),N=r.useDeferredValue(k),[A,j]=r.useState(0),_=r.useRef(1),y=r.useRef(0),w=r.useRef(null);r.useEffect(()=>{if(!t)return;s({type:"list_sessions"}),s({type:"list_projects"});const g=k.trim();if(g){const v=++_.current;y.current=v,D(!0),s({type:"search_files",reqId:v,query:g}),s({type:"search_sessions",reqId:v,query:g})}requestAnimationFrame(()=>{var v;return(v=f.current)==null?void 0:v.select()})},[t]);const[I,D]=r.useState(!1);r.useEffect(()=>{w.current&&clearTimeout(w.current);const g=N.trim();if(!g){D(!1);return}return w.current=setTimeout(()=>{const v=++_.current;y.current=v,D(!0),s({type:"search_files",reqId:v,query:g}),s({type:"search_sessions",reqId:v,query:g})},300),()=>{w.current&&clearTimeout(w.current)}},[N]);const S=N.trim().toLowerCase(),O=r.useMemo(()=>!S||!a||a.reqId!==y.current||!a.ok?[]:a.results,[a,S]),h=r.useMemo(()=>S?i.filter(g=>rr(g.path,S)).slice(0,10):[],[i,S]),B=r.useMemo(()=>!S||!c||c.reqId!==y.current||!c.ok?[]:c.results,[c,S]);r.useEffect(()=>{c&&c.reqId===y.current&&a&&a.reqId===y.current&&y.current!==0&&D(!1)},[c,a]);const W=!!c&&c.ok&&c.truncated,G=r.useMemo(()=>[...O.map(g=>({kind:"session",path:g.path,anchors:g.anchors})),...h.map(g=>({kind:"project",path:g.path})),...B.filter(g=>g.type==="file").map(g=>({kind:"file",path:g.path,name:g.name}))],[O,h,B]);r.useEffect(()=>{j(0)},[N]);const X=r.useCallback(g=>{if(g)if(g.kind==="session")o(g.path,g.anchors),n();else if(g.kind==="project"){u(g.path),s({type:"list_sessions"}),s({type:"list_projects"});const v=N.trim();if(v){const $=++_.current;y.current=$,D(!0),s({type:"search_files",reqId:$,query:v}),s({type:"search_sessions",reqId:$,query:v})}}else m(g.path,g.name)},[o,u,m,s,N]);r.useEffect(()=>{if(!t)return;const g=v=>{v.key==="Escape"?(v.preventDefault(),v.stopPropagation(),n()):v.key==="ArrowDown"?(v.preventDefault(),j($=>Math.min($+1,G.length-1))):v.key==="ArrowUp"?(v.preventDefault(),j($=>Math.max($-1,0))):v.key==="Enter"&&(v.preventDefault(),X(G[A]))};return window.addEventListener("keydown",g,!0),()=>window.removeEventListener("keydown",g,!0)},[G,A,X,n,t]);const q=O.length+h.length+B.length,K=(g,v,$)=>e.jsxs("div",{className:"gs-section-head",children:[$,e.jsx("span",{children:g}),e.jsx("em",{children:v})]});let P=-1;return t?e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:n,children:e.jsxs("div",{className:"gs-modal",onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(mt,{}),e.jsx("input",{ref:f,type:"text",value:k,placeholder:p("gsPlaceholder"),onChange:g=>b(g.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&&q===0&&!W&&e.jsx("div",{className:"gs-empty",children:p(I?"gsSearching":"gsNoResults")}),O.length>0&&e.jsxs("div",{className:"gs-section",children:[K(p("gsSessions"),O.length,e.jsx(Ve,{})),O.map(g=>{P++;const v=P;return e.jsxs("button",{type:"button",className:v===A?"gs-item active":"gs-item",onMouseEnter:()=>j(v),onClick:()=>X({kind:"session",path:g.path,anchors:g.anchors}),children:[e.jsxs("span",{className:"gs-item-title",children:[g.name||g.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:g.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:g.firstMessage})]},g.path)})]}),h.length>0&&e.jsxs("div",{className:"gs-section",children:[K(p("gsProjects"),h.length,e.jsx(Ge,{})),h.map(g=>{P++;const v=P,$=l&&g.path===l;return e.jsxs("button",{type:"button",className:v===A?"gs-item active":"gs-item",onMouseEnter:()=>j(v),onClick:()=>X({kind:"project",path:g.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[g.path.split(/[\\/]/).pop(),$&&e.jsx("em",{className:"gs-item-meta",children:p("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:g.path})]},g.path)})]}),(B.length>0||S&&W)&&e.jsxs("div",{className:"gs-section",children:[K(p("gsFiles"),B.length,e.jsx($s,{})),B.map(g=>{P++;const v=P;return e.jsxs("button",{type:"button",className:v===A?"gs-item active":"gs-item",disabled:g.type==="dir",title:g.type==="dir"?void 0:p("gsOpenPreview"),onMouseEnter:()=>j(v),onClick:()=>{g.type==="file"&&X({kind:"file",path:g.path,name:g.name})},children:[e.jsx("span",{className:"gs-item-title",children:g.name}),e.jsx("span",{className:"gs-item-sub",children:g.path})]},`${g.type}:${g.path}`)}),W&&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 or({file:t,content:s,send:i,onAddLines:l,onAttach:c,onClose:a}){const n=me(),[o,u]=r.useState(null),[m,p]=r.useState(!1),[f,k]=r.useState(null),[b,N]=r.useState(!1),[A,j]=r.useState(!1),[_,y]=r.useState(!1),[w,I]=r.useState(""),[D,S]=r.useState(!0),O=r.useRef(!1),[h,B]=r.useState(!0),[W,G]=r.useState(!1),[X,q]=r.useState(100),K=r.useRef(0),P=r.useRef(!1),g=r.useRef(null);r.useEffect(()=>{p(!0),u(null),k(null),y(!1),I(""),S(!0),O.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 Q=de=>{if(de.key==="Escape"){se();return}if((de.ctrlKey||de.metaKey)&&de.key.toLowerCase()==="s"&&_){de.preventDefault(),H();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(),E())};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[a,o,_,w]),r.useEffect(()=>{const Q=()=>{P.current=!1,N(!1)};return window.addEventListener("mouseup",Q),()=>window.removeEventListener("mouseup",Q)},[]);const v=r.useMemo(()=>{if(!o)return[];const Q=o.text.split(`
|
|
320
|
+
`);return Q.length>0&&Q[Q.length-1]===""&&Q.pop(),Q.slice(0,Tt)},[o]),$=(o==null?void 0:o.lines)??0,pe=$>Tt,z=(Q,de)=>{if(de){const xe=K.current>0?K.current:Q;k({start:Math.min(xe,Q),end:Math.max(xe,Q)})}else K.current=Q,k({start:Q,end:Q})},E=()=>{v.length!==0&&(K.current=1,k({start:1,end:v.length}))},ee=()=>{f&&(l(t.path,t.name,f.start,f.end),j(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>j(!1),1400))},Y=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,M=()=>{I((o==null?void 0:o.text)??""),y(!1),O.current&&S(!0)},F=()=>{if(_){if(w!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges")))return;M();return}!Y||!o||(O.current=Et(t.name)&&D,Et(t.name)&&S(!1),k(null),I(o.text),y(!0))},H=()=>{!_||!o||!Y||i({type:"write_file",path:t.path,text:w})&&(y(!1),O.current&&S(!0),k(null))},se=()=>{_&&w!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges"))||a()},V=Q=>{q(Math.min(200,Math.max(50,Q)))},oe=f?f.end-f.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),te=le&&D&&!_&&R==="text"&&!re,fe=Q=>yt(Ye(`/api/file?clientId=${encodeURIComponent(Wt())}&path=${encodeURIComponent(Q)}`));return e.jsx("div",{className:`fp-overlay ${W?"fullscreen":""}`,onMouseDown:Q=>{Q.target===Q.currentTarget&&se()},children:e.jsxs("div",{className:`fp ${W?"fullscreen":""}`,style:{"--fp-zoom":X/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&&` · ${cr(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[le&&R==="text"&&!re&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${D?"on":""}`,"data-tip":n(D?"showMarkdownSource":"showMarkdownPreview"),disabled:_,onClick:()=>S(Q=>!Q),children:D?e.jsx(Rt,{}):e.jsx(ei,{})}),R==="text"&&!re&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${_?"on":""}`,"data-tip":n(d?"fileEditTruncated":_?"exitEditFile":"editFile"),disabled:!Y&&!_,onClick:F,children:e.jsx(Pt,{})}),R==="text"&&!re&&!te&&e.jsx("button",{type:"button",className:`fp-attach wrap ${h?"on":""}`,"data-tip":n(h?"disableWrap":"enableWrap"),onClick:()=>B(Q=>!Q),children:e.jsx(Zn,{})}),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:X<=50,onClick:()=>V(X-10),children:e.jsx(Dn,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:n("resetZoom"),onClick:()=>q(100),children:[X,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":n("zoomIn"),disabled:X>=200,onClick:()=>V(X+10),children:e.jsx(Bn,{})})]}),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 ${W?"on":""}`,"data-tip":n(W?"exitFullscreen":"fullscreen"),onClick:()=>G(Q=>!Q),children:W?e.jsx(qn,{}):e.jsx(Kn,{})}),e.jsx("button",{type:"button",className:"fp-close",title:n("close"),onClick:se,children:e.jsx(we,{})})]})]}),d&&R==="text"&&!re&&e.jsx("div",{className:"fp-notice",children:n("previewTruncated")}),m&&!o&&e.jsx("div",{className:"fp-empty",children:n("loading")}),!m&&R==="none"&&!re&&e.jsx("div",{className:"fp-empty",children:n("previewNotSupported")}),!m&&R==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:fe(t.path),alt:t.name})}),!m&&R==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:fe(t.path),controls:!0,preload:"metadata"})}),!m&&te&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(kt,{text:o.text})})}),!m&&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})]}),!m&&_&&R==="text"&&!re&&o&&e.jsx("textarea",{className:`fp-editor ${h?"":"no-wrap"}`,value:w,onChange:Q=>I(Q.target.value),wrap:h?"soft":"off",spellCheck:!1,autoFocus:!0}),!m&&!te&&!_&&R==="text"&&!re&&o&&v.length===0&&e.jsx("div",{className:"fp-empty",children:n("emptyFile")}),!m&&!te&&!_&&R==="text"&&!re&&v.length>0&&e.jsxs("div",{className:`fp-code ${b?"dragging":""} ${h?"":"no-wrap"}`,onMouseDown:Q=>{Q.button===0&&Q.preventDefault()},children:[v.map((Q,de)=>{const xe=de+1,ce=f!==null&&xe>=f.start&&xe<=f.end;return e.jsxs("div",{className:`fp-line ${ce?"sel":""}`,onMouseDown:Se=>{Se.button===0&&(z(xe,Se.shiftKey),P.current=!0,N(!0))},onMouseEnter:()=>{P.current&&z(xe,!0)},children:[e.jsx("span",{className:"fp-num",children:xe}),e.jsx("span",{className:"fp-code-text",children:Q})]},xe)}),pe&&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:w===((o==null?void 0:o.text)??""),onClick:H,children:[e.jsx(On,{})," ",n("saveFile")]})]})]}):!te&&R==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:f?n("selectedRange",{n:oe,start:f.start,end:f.end}):n("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:v.length===0,onClick:E,children:n("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!f,onClick:()=>k(null),children:n("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!f||re,onClick:ee,children:[A?e.jsx(vt,{}):null,n(A?"addedToChat":"addToChat")]})]})]})})]})})}function Et(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function cr(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 dr(t){try{localStorage.setItem(un,JSON.stringify(t))}catch{}}let et=null;function ur(){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 pr=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],mr=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],hr=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],gr=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],fr={question:pr,done:mr,start:hr,error:gr};function xr(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=ur();if(!i)return;const l=Math.max(0,Math.min(1,s.volume/100));for(const c of fr[t])xr(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 vr(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 yr(){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 kr(){const[t,s]=r.useState([]),[i,l]=r.useState(()=>hn());return r.useEffect(()=>{let a=!1;return yr().then(n=>{a||s(n)}),()=>{a=!0}},[]),r.useEffect(()=>{gn(i),vr(i)},[i]),{themes:t,theme:i,switchTheme:a=>l(a===mn?null:a)}}function Er(){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 br=r.lazy(()=>Sn(()=>import("./TerminalPanel-qfBdYdPT.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function jr({notice:t,onDismiss:s}){const i=me(),[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"?ii:t.level==="warning"?ni:Yn;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 wr=[],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=me(),c=r.useCallback(a=>{a.preventDefault();const n=a.clientX,o=s;let u=o;const m=f=>{const k=t==="left"?f.clientX-n:n-f.clientX;u=Math.min(xn,Math.max(fn,Math.round(o+k))),i(u)},p=()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",p),document.body.classList.remove("panel-resizing"),localStorage.setItem(yn(t),String(u))};window.addEventListener("pointermove",m),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 Nr(){var T,Z,ne,he,ge,je,Re,Ht,Kt,zt,Vt,Gt,Yt,Jt;const t=me(),{chat:s,send:i,dismissNotice:l,pushNotice:c,terminal:a}=Ii(),[n,o]=r.useState([]),[u,m]=r.useState(null),[p,f]=r.useState(!1),[k,b]=r.useState("chat"),N=r.useMemo(()=>s.plugins.filter(L=>{var U,ie;return!((ie=(U=s.settings)==null?void 0:U.disabledPlugins)!=null&&ie.includes(L.id))}),[s.plugins,(T=s.settings)==null?void 0:T.disabledPlugins]),[A,j]=r.useState([]);r.useEffect(()=>wi(j),[]),r.useEffect(()=>{Ni(N,s.pluginsEpoch)},[N,s.pluginsEpoch]);const[_,y]=r.useState(()=>Ms("left")),[w,I]=r.useState(()=>Ms("right")),D=r.useCallback(L=>y(L),[]),S=r.useCallback(L=>I(L),[]),[O,h]=r.useState(null),[B,W]=r.useState(()=>window.matchMedia("(max-width: 768px)").matches);r.useEffect(()=>{const L=window.matchMedia("(max-width: 768px)"),U=ie=>W(ie.matches);return L.addEventListener("change",U),()=>L.removeEventListener("change",U)},[]);const[G,X]=r.useState(!1),[q,K]=r.useState(!1),[P,g]=r.useState(!1),[v,$]=r.useState(!1),[pe,z]=r.useState(!1),[E,ee]=r.useState(null);r.useEffect(()=>{if(!E)return;const L=setTimeout(()=>ee(null),15e3);return()=>clearTimeout(L)},[E]),r.useEffect(()=>{const L=U=>{var Be,Qt;const ie=U.detail,ve=(ie==null?void 0:ie.title)||"插件命令",ke=ie==null?void 0:ie.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=De();a.create({id:bt,conversationId:s.activeConversationId||((Be=s.state)==null?void 0:Be.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=U=>{!(U.ctrlKey||U.metaKey)||U.key.toLowerCase()!=="k"||(U.preventDefault(),z(ie=>!ie))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[]);const[Y,M]=r.useState(pn),{themes:F,theme:H,switchTheme:se}=kr(),V=r.useRef(null),oe=r.useRef(null),re=r.useRef(0),d=r.useRef(!1),R=r.useRef(s.terminals);r.useEffect(()=>{dr(Y)},[Y]),r.useEffect(()=>{var U;const L=R.current;R.current=s.terminals;for(const ie of s.terminals){const ve=((U=ie.command)==null?void 0:U.command)??"",ke=L.find(Ce=>Ce.id===ie.id);!(ke!=null&&ke.running)||ie.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 ie;const L=((ie=s.state)==null?void 0:ie.isStreaming)??!1,U=V.current;V.current=L,U!==null&&(!U&&L?tt("start",Y):U&&!L&&tt("done",Y))},[(Z=s.state)==null?void 0:Z.isStreaming,Y]),r.useEffect(()=>{var U;const L=((U=s.dialog)==null?void 0:U.id)??null;L!==null&&L!==oe.current&&tt("question",Y),oe.current=L},[s.dialog,Y]),r.useEffect(()=>{const L=[...s.notices].reverse().find(U=>U.level==="error");L&&L.id!==re.current&&(re.current=L.id,tt("error",Y))},[s.notices,Y]);const le=(L,U,ie,ve=!1,ke)=>{const Ce=`${L}|${ie}|${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:U,mode:ie,isDir:ve,...ke?{lines:ke}:{}}])},te=L=>o(U=>U.filter(ie=>ie.key?ie.key!==L:ie.path!==L)),fe=r.useCallback(L=>(!L.type.startsWith("list_")&&!L.type.startsWith("get_")&&h(null),i(L)),[i]),Q=r.useRef(0),de=r.useRef(0),xe=L=>{var ve;const U=Date.now();(ve=s.state)!=null&&ve.model&&!s.state.model.vision&&U-de.current>1e4&&(de.current=U,c("warning",t("imageNotSupported")));const ie=`paste-${++Q.current}`;o(ke=>[...ke,{path:"",key:ie,name:L.name,mode:"inline",imageData:L.data,mimeType:L.mimeType}])},ce=async L=>{for(const U of L){const ie=await Js(U);if(!ie){c("error",t("imageLoadFailed",{name:U.name}));continue}xe(ie)}},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 U;try{U=(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 ie=`upload-${++Je.current}`;o(ve=>[...ve,{path:"",key:ie,name:L.name,mode:"inline",fileData:U,size:L.size,mimeType:L.type||void 0}])},Ee=async L=>{for(const U of L)Le(U.type)?await ce([U]):await Te(U)},Qe=r.useCallback((L,U,ie)=>{i({type:"edit_message",messageId:L,text:U,attachments:ie})},[i]),Me=r.useCallback(()=>K(!0),[]),Xe=r.useCallback(()=>o([]),[]),Fe=r.useCallback(te,[]),$e=r.useCallback(ce,[ce]),Oe=r.useCallback(Ee,[Ee]),C=(ne=s.state)==null?void 0:ne.model,ue=(he=s.state)==null?void 0:he.thinkingLevel,ae=(ge=s.state)==null?void 0:ge.availableThinkingLevels,ye=r.useMemo(()=>C?{model:C,thinkingLevel:ue??"off",availableThinkingLevels:ae??[]}:null,[C,ue,ae]),x=r.useCallback(()=>{var L,U;return!s.ready||s.terminals.length!==0?!1:(a.create({id:De(),conversationId:s.activeConversationId||((L=s.state)==null?void 0:L.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((U=s.state)==null?void 0:U.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}x()&&(d.current=!1)}},[s.terminals.length,x,k]),e.jsxs("div",{className:"app",onDragOver:L=>{var U;Array.from(((U=L.dataTransfer)==null?void 0:U.types)??[]).includes("Files")&&(L.preventDefault(),f(!0))},onDragLeave:L=>{L.currentTarget.contains(L.relatedTarget)||f(!1)},onDrop:L=>{var ke,Ce;if(f(!1),!Array.from(((ke=L.dataTransfer)==null?void 0:ke.types)??[]).includes("Files"))return;L.preventDefault();const U=Array.from(((Ce=L.dataTransfer)==null?void 0:Ce.files)??[]);if(U.length===0){c("warning",t("foldersNotSupported"));return}const ie=U.filter(be=>Le(be.type)),ve=U.filter(be=>!Le(be.type));ie.length>0&&ce(ie),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(ui,{chat:s,send:i,terminal:a,view:k,plugins:N,onViewChange:L=>{d.current=L==="terminal"&&s.terminals.length===0,d.current&&x()&&(d.current=!1),b(L),h(null)},onOpenPanel:h,onOpenSettings:()=>g(!0),onOpenBgTasks:()=>$(!0),onOpenGlobalSearch:()=>z(!0),sound:Y,onSoundChange:M,onSoundPreview:L=>tt(L,Y),themes:F,theme:H,onThemeChange:se}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(L=>e.jsx(jr,{notice:L,onDismiss:l},L.id))}),e.jsx(Ra,{send:i,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${_}px`,"--right-w":`${w}px`},children:[O&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>h(null)}),e.jsxs("div",{className:`view-pane ${k==="chat"?"":"hidden"}`,children:[e.jsx("div",{className:`panel-drawer drawer-left ${O==="left"?"open":""}`,children:e.jsx(mi,{send:fe,active:!B||O==="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:D}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(Aa,{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:E,onJumpDone:()=>ee(null)},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(Ka,{send:i,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId}),s.dialog&&e.jsx(Ga,{dialog:s.dialog,send:i}),e.jsx(Ha,{send:i,ready:s.ready,streaming:((Vt=s.state)==null?void 0:Vt.isStreaming)??!1,messages:((Gt=s.state)==null?void 0:Gt.messages)??wr,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:w,onResize:S}),e.jsx("div",{className:`panel-drawer drawer-right ${O==="right"?"open":""}`,children:e.jsx(Wi,{send:fe,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((Yt=s.state)==null?void 0:Yt.cwd)??"",onAttach:(L,U,ie,ve)=>{h(null),le(L,U,ie,ve)},onPreview:(L,U)=>{h(null),m({path:L,name:U})},onNotice:(L,U)=>c(L,U)})})]}),e.jsx("div",{className:`view-pane ${k==="terminal"?"":"hidden"}`,children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(br,{chat:s,send:i,terminal:a})})}),e.jsx("div",{className:`view-pane ${k==="git"?"":"hidden"}`,children:e.jsx(Ja,{chat:s,send:i,terminal:a,active:k==="git",onSwitchToTerminal:()=>b("terminal")})}),A.map(L=>{const U=`plugin:${L.info.id}`;return e.jsx("div",{className:`view-pane ${k===U?"":"hidden"}`,children:e.jsx(Qa,{entry:L,send:i})},L.info.id)})]})}),e.jsx(za,{chat:s,send:i}),u&&e.jsx(or,{file:u,content:s.fileContent,send:i,onAddLines:(L,U,ie,ve)=>le(L,U,"lines",!1,{start:ie,end:ve}),onAttach:(L,U,ie)=>le(L,U,ie),onClose:()=>m(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!G&&!q&&e.jsx(Xa,{send:i,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>X(!0)}),q&&e.jsx(tr,{send:i,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>K(!1)}),P&&e.jsx(nr,{chat:s,send:i,terminal:a,onSwitchToTerminal:()=>b("terminal"),onClose:()=>g(!1)}),v&&e.jsx(ar,{servers:s.bgServers,send:i,onClose:()=>$(!1)}),e.jsx(lr,{open:pe,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,U)=>{i({type:"switch_session",path:L});const ie=U&&U[0];ee(ie?{path:L,role:ie.role,timestamp:ie.timestamp}:null)},onSwitchProject:L=>{i({type:"set_cwd",path:L})},onPreviewFile:(L,U)=>{m({path:L,name:U})}})]})}hi();gn(hn());wn.createRoot(document.getElementById("root")).render(e.jsx(r.StrictMode,{children:e.jsx(ci,{children:e.jsx(Nr,{})})}));export{gt as F,Es as T,_e as a,Er as b,Tr as c,It as d,Ie as e,we as f,Hn as g,ze as h,De as r,me as u};
|