pi-web-ui 0.51.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-
|
|
2
|
-
import{R as _e,a as r,j as e,M as Es,b as vn,c as yn}from"./markdown-DRBrS2Nf.js";import{r as Ms}from"./react-C9ovnpIm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))l(c);new MutationObserver(c=>{for(const i of c)if(i.type==="childList")for(const n of i.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&l(n)}).observe(document,{childList:!0,subtree:!0});function a(c){const i={};return c.integrity&&(i.integrity=c.integrity),c.referrerPolicy&&(i.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?i.credentials="include":c.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function l(c){if(c.ep)return;c.ep=!0;const i=a(c);fetch(c.href,i)}})();var et={},Jt;function kn(){if(Jt)return et;Jt=1;var t=Ms();return et.createRoot=t.createRoot,et.hydrateRoot=t.hydrateRoot,et}var bn=kn();const jn="modulepreload",wn=function(t){return"/"+t},Yt={},Rs=function(s,a,l){let c=Promise.resolve();if(a&&a.length>0){let n=function(p){return Promise.all(p.map(h=>Promise.resolve(h).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),u=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));c=n(a.map(p=>{if(p=wn(p),p in Yt)return;Yt[p]=!0;const h=p.endsWith(".css"),g=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${g}`))return;const y=document.createElement("link");if(y.rel=h?"stylesheet":jn,h||(y.as="script"),y.crossOrigin="",y.href=p,u&&y.setAttribute("nonce",u),document.head.appendChild(y),h)return new Promise((b,k)=>{y.addEventListener("load",b),y.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(n){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=n,window.dispatchEvent(o),!o.defaultPrevented)throw n}return c.then(n=>{for(const o of n||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};var Ps={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Qt=_e.createContext&&_e.createContext(Ps),Nn=["attr","size","title"];function Cn(t,s){if(t==null)return{};var a,l,c=Sn(t,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(l=0;l<i.length;l++)a=i[l],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(c[a]=t[a])}return c}function Sn(t,s){if(t==null)return{};var a={};for(var l in t)if({}.hasOwnProperty.call(t,l)){if(s.indexOf(l)!==-1)continue;a[l]=t[l]}return a}function rt(){return rt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var l in a)({}).hasOwnProperty.call(a,l)&&(t[l]=a[l])}return t},rt.apply(null,arguments)}function Xt(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);s&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),a.push.apply(a,l)}return a}function lt(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Xt(Object(a),!0).forEach(function(l){Tn(t,l,a[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):Xt(Object(a)).forEach(function(l){Object.defineProperty(t,l,Object.getOwnPropertyDescriptor(a,l))})}return t}function Tn(t,s,a){return(s=En(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function En(t){var s=Mn(t,"string");return typeof s=="symbol"?s:s+""}function Mn(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var l=a.call(t,s);if(typeof l!="object")return l;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Is(t){return t&&t.map((s,a)=>_e.createElement(s.tag,lt({key:a},s.attr),Is(s.child)))}function Y(t){return s=>_e.createElement(Rn,rt({attr:lt({},t.attr)},s),Is(t.child))}function Rn(t){var s=a=>{var l=t.attr,c=t.size,i=t.title,n=Cn(t,Nn),o=c||a.size||"1em",u;return a.className&&(u=a.className),t.className&&(u=(u?u+" ":"")+t.className),_e.createElement("svg",rt({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},a.attr,l,n,{className:u,style:lt(lt({color:t.color||a.color},a.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&_e.createElement("title",null,i),t.children)};return Qt!==void 0?_e.createElement(Qt.Consumer,null,a=>s(a)):s(Ps)}function Pn(t){return Y({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 In(t){return Y({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 nt(t){return Y({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 ke(t){return Y({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 Ls(t){return Y({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 Ln(t){return Y({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 Ee(t){return Y({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 qe(t){return Y({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 Zt(t){return Y({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 Dn(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"5"},child:[]},{tag:"line",attr:{x1:"12",y1:"1",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"23"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},child:[]},{tag:"line",attr:{x1:"1",y1:"12",x2:"3",y2:"12"},child:[]},{tag:"line",attr:{x1:"21",y1:"12",x2:"23",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},child:[]}]})(t)}function ot(t){return Y({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 Bn(t){return Y({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 ct(t){return Y({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 Ds(t){return Y({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 dt(t){return Y({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 An(t){return Y({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 Bs(t){return Y({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 pt(t){return Y({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 De(t){return Y({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 yr(t){return Y({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 _n(t){return Y({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 es(t){return Y({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 Fn(t){return Y({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 $n(t){return Y({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 Ke(t){return Y({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 On(t){return Y({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 Wn(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"},child:[]}]})(t)}function Hn(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 3 21 3 21 9"},child:[]},{tag:"polyline",attr:{points:"9 21 3 21 3 15"},child:[]},{tag:"line",attr:{x1:"21",y1:"3",x2:"14",y2:"10"},child:[]},{tag:"line",attr:{x1:"3",y1:"21",x2:"10",y2:"14"},child:[]}]})(t)}function Un(t){return Y({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 Ct(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"},child:[]},{tag:"path",attr:{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"},child:[]}]})(t)}function ut(t){return Y({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 qn(t){return Y({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 Kn(t){return Y({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 zn(t){return Y({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 Vn(t){return Y({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 Gn(t){return Y({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 ts(t){return Y({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 it(t){return Y({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 ze(t){return Y({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 As(t){return Y({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 Y({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 St(t){return Y({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 Tt(t){return Y({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 Et(t){return Y({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 Dt(t){return Y({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 Xe(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"4",y:"4",width:"16",height:"16",rx:"2",ry:"2"},child:[]},{tag:"rect",attr:{x:"9",y:"9",width:"6",height:"6"},child:[]},{tag:"line",attr:{x1:"9",y1:"1",x2:"9",y2:"4"},child:[]},{tag:"line",attr:{x1:"15",y1:"1",x2:"15",y2:"4"},child:[]},{tag:"line",attr:{x1:"9",y1:"20",x2:"9",y2:"23"},child:[]},{tag:"line",attr:{x1:"15",y1:"20",x2:"15",y2:"23"},child:[]},{tag:"line",attr:{x1:"20",y1:"9",x2:"23",y2:"9"},child:[]},{tag:"line",attr:{x1:"20",y1:"14",x2:"23",y2:"14"},child:[]},{tag:"line",attr:{x1:"1",y1:"9",x2:"4",y2:"9"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"4",y2:"14"},child:[]}]})(t)}function Jn(t){return Y({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 Bt(t){return Y({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 Yn(t){return Y({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 mt(t){return Y({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 ht(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function Fe(t){return Y({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 gt(t){return Y({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 Qn(t){return Y({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 ss(t){return Y({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 Xn(t){return Y({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 Fs(t){return Y({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 $s(t){return Y({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 Zn(t){return Y({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 ei(t){return Y({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 ti(t){return t.map(s=>`npm i -g ${s}@latest`).join("; ")}function Re(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let a=0;a<16;a++)t[a]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(a=>a.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Le({trigger:t,open:s,onOpenChange:a,children:l,align:c="right",fit:i=!1,direction:n="down",menuClassName:o,menuRef:u,menuStyle:p}){const h=r.useRef(null);return r.useEffect(()=>{if(!s)return;const g=b=>{h.current&&!h.current.contains(b.target)&&a(!1)},y=b=>{b.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y)}},[s,a]),e.jsxs("div",{className:`dropdown ${c} ${i?"fit":""} ${n==="up"?"dd-up":""}`,ref:h,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>a(!s),"aria-expanded":s,children:[t,e.jsx(Fe,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${o??""}`,ref:u,style:p,children:l})]})}function be({active:t,disabled:s=!1,title:a,onClick:l,children:c}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:a,onClick:l,children:c})}const Os="pi-web-ui:lang",si={cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",queueSteerTag:"插队",queueFollowTag:"排队",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",noOptions:"(无选项)",inputPlaceholder:"输入内容",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-web-ui 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",directory:"目录",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",modelUsedCount:"已用 {n} 次",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:同时搜索历史对话、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索文件…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","tpl.title":"提示词模板","tpl.hint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.clickCard":"点击填入输入框","tpl.editTpl":"编辑 / 删除模板","tpl.openPicker":"提示词模板(常用提示词,随时取用)","tpl.pickerTitle":"提示词模板","tpl.pickerHint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.add":"新建模板","tpl.addDesc":"把常用工作流存成模板","tpl.reset":"恢复默认模板","tpl.resetConfirm":"确认恢复默认?","tpl.builtin":"内置","tpl.custom":"自定义","tpl.newTitle":"新建提示词模板","tpl.editTitle":"编辑提示词模板","tpl.fieldIcon":"图标","tpl.fieldTitle":"标题","tpl.fieldTitlePh":"卡片上显示的短标题","tpl.fieldDesc":"说明","tpl.fieldDescPh":"一句话说明,显示在卡片上","tpl.fieldPrompt":"提示词","tpl.fieldPromptPh":"完整提示词 —— 发送给智能体的内容","tpl.required":"标题和提示词不能为空","tpl.save":"保存修改","tpl.fill":"填入输入框","tpl.fillTip":"填入输入框,可再编辑后发送","tpl.sendNow":"直接发送","tpl.sendTip":"立即作为新对话发送","tpl.delete":"删除","tpl.deleteTip":"删除这个自定义模板","tpl.remove":"移出模板库","tpl.removeTip":"把内置模板移出模板库,可在底部「恢复默认模板」找回","tpl.restore":"恢复默认","tpl.restoreTip":"撤掉你的修改,恢复内置默认","tpl.sk.setup":"仓库初始化","tpl.sk.setup.desc":"让仓库了解它的构建与约定","tpl.sk.setup.prompt":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-CgkoEcJf.js","assets/markdown-DRBrS2Nf.js","assets/xterm-D1D2FVe3.js","assets/react-C9ovnpIm.js","assets/TerminalPanel-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{R as _e,a as r,j as e,M as Es,b as vn,c as yn}from"./markdown-DRBrS2Nf.js";import{r as Ms}from"./react-C9ovnpIm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))l(c);new MutationObserver(c=>{for(const i of c)if(i.type==="childList")for(const n of i.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&l(n)}).observe(document,{childList:!0,subtree:!0});function a(c){const i={};return c.integrity&&(i.integrity=c.integrity),c.referrerPolicy&&(i.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?i.credentials="include":c.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function l(c){if(c.ep)return;c.ep=!0;const i=a(c);fetch(c.href,i)}})();var et={},Jt;function kn(){if(Jt)return et;Jt=1;var t=Ms();return et.createRoot=t.createRoot,et.hydrateRoot=t.hydrateRoot,et}var bn=kn();const jn="modulepreload",wn=function(t){return"/"+t},Yt={},Rs=function(s,a,l){let c=Promise.resolve();if(a&&a.length>0){let n=function(p){return Promise.all(p.map(h=>Promise.resolve(h).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),u=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));c=n(a.map(p=>{if(p=wn(p),p in Yt)return;Yt[p]=!0;const h=p.endsWith(".css"),g=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${g}`))return;const y=document.createElement("link");if(y.rel=h?"stylesheet":jn,h||(y.as="script"),y.crossOrigin="",y.href=p,u&&y.setAttribute("nonce",u),document.head.appendChild(y),h)return new Promise((b,k)=>{y.addEventListener("load",b),y.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${p}`)))})}))}function i(n){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=n,window.dispatchEvent(o),!o.defaultPrevented)throw n}return c.then(n=>{for(const o of n||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};var Ps={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Qt=_e.createContext&&_e.createContext(Ps),Nn=["attr","size","title"];function Cn(t,s){if(t==null)return{};var a,l,c=Sn(t,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(l=0;l<i.length;l++)a=i[l],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(c[a]=t[a])}return c}function Sn(t,s){if(t==null)return{};var a={};for(var l in t)if({}.hasOwnProperty.call(t,l)){if(s.indexOf(l)!==-1)continue;a[l]=t[l]}return a}function rt(){return rt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var l in a)({}).hasOwnProperty.call(a,l)&&(t[l]=a[l])}return t},rt.apply(null,arguments)}function Xt(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);s&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),a.push.apply(a,l)}return a}function lt(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?Xt(Object(a),!0).forEach(function(l){Tn(t,l,a[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):Xt(Object(a)).forEach(function(l){Object.defineProperty(t,l,Object.getOwnPropertyDescriptor(a,l))})}return t}function Tn(t,s,a){return(s=En(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function En(t){var s=Mn(t,"string");return typeof s=="symbol"?s:s+""}function Mn(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var l=a.call(t,s);if(typeof l!="object")return l;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Is(t){return t&&t.map((s,a)=>_e.createElement(s.tag,lt({key:a},s.attr),Is(s.child)))}function Y(t){return s=>_e.createElement(Rn,rt({attr:lt({},t.attr)},s),Is(t.child))}function Rn(t){var s=a=>{var l=t.attr,c=t.size,i=t.title,n=Cn(t,Nn),o=c||a.size||"1em",u;return a.className&&(u=a.className),t.className&&(u=(u?u+" ":"")+t.className),_e.createElement("svg",rt({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},a.attr,l,n,{className:u,style:lt(lt({color:t.color||a.color},a.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&_e.createElement("title",null,i),t.children)};return Qt!==void 0?_e.createElement(Qt.Consumer,null,a=>s(a)):s(Ps)}function Pn(t){return Y({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 In(t){return Y({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 nt(t){return Y({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 ke(t){return Y({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 Ls(t){return Y({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 Ln(t){return Y({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 Ee(t){return Y({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 qe(t){return Y({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 Zt(t){return Y({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 Dn(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"5"},child:[]},{tag:"line",attr:{x1:"12",y1:"1",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"23"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},child:[]},{tag:"line",attr:{x1:"1",y1:"12",x2:"3",y2:"12"},child:[]},{tag:"line",attr:{x1:"21",y1:"12",x2:"23",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},child:[]}]})(t)}function ot(t){return Y({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 Bn(t){return Y({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 ct(t){return Y({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 Ds(t){return Y({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 dt(t){return Y({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 An(t){return Y({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 Bs(t){return Y({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 pt(t){return Y({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 De(t){return Y({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 yr(t){return Y({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 _n(t){return Y({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 es(t){return Y({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 Fn(t){return Y({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 $n(t){return Y({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 Ke(t){return Y({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 On(t){return Y({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 Wn(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"},child:[]}]})(t)}function Hn(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 3 21 3 21 9"},child:[]},{tag:"polyline",attr:{points:"9 21 3 21 3 15"},child:[]},{tag:"line",attr:{x1:"21",y1:"3",x2:"14",y2:"10"},child:[]},{tag:"line",attr:{x1:"3",y1:"21",x2:"10",y2:"14"},child:[]}]})(t)}function Un(t){return Y({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 Ct(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"},child:[]},{tag:"path",attr:{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"},child:[]}]})(t)}function ut(t){return Y({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 qn(t){return Y({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 Kn(t){return Y({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 zn(t){return Y({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 Vn(t){return Y({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 Gn(t){return Y({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 ts(t){return Y({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 it(t){return Y({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 ze(t){return Y({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 As(t){return Y({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 Y({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 St(t){return Y({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 Tt(t){return Y({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 Et(t){return Y({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 Dt(t){return Y({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 Xe(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"4",y:"4",width:"16",height:"16",rx:"2",ry:"2"},child:[]},{tag:"rect",attr:{x:"9",y:"9",width:"6",height:"6"},child:[]},{tag:"line",attr:{x1:"9",y1:"1",x2:"9",y2:"4"},child:[]},{tag:"line",attr:{x1:"15",y1:"1",x2:"15",y2:"4"},child:[]},{tag:"line",attr:{x1:"9",y1:"20",x2:"9",y2:"23"},child:[]},{tag:"line",attr:{x1:"15",y1:"20",x2:"15",y2:"23"},child:[]},{tag:"line",attr:{x1:"20",y1:"9",x2:"23",y2:"9"},child:[]},{tag:"line",attr:{x1:"20",y1:"14",x2:"23",y2:"14"},child:[]},{tag:"line",attr:{x1:"1",y1:"9",x2:"4",y2:"9"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"4",y2:"14"},child:[]}]})(t)}function Jn(t){return Y({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 Bt(t){return Y({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 Yn(t){return Y({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 mt(t){return Y({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 ht(t){return Y({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function Fe(t){return Y({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 gt(t){return Y({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 Qn(t){return Y({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 ss(t){return Y({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 Xn(t){return Y({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 Fs(t){return Y({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 $s(t){return Y({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 Zn(t){return Y({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 ei(t){return Y({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 ti(t){return t.map(s=>s.kind==="package"?`pi update npm:${s.name}`:`npm i -g ${s.name}@latest`).join("; ")}function Re(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let a=0;a<16;a++)t[a]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(a=>a.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Le({trigger:t,open:s,onOpenChange:a,children:l,align:c="right",fit:i=!1,direction:n="down",menuClassName:o,menuRef:u,menuStyle:p}){const h=r.useRef(null);return r.useEffect(()=>{if(!s)return;const g=b=>{h.current&&!h.current.contains(b.target)&&a(!1)},y=b=>{b.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",y)}},[s,a]),e.jsxs("div",{className:`dropdown ${c} ${i?"fit":""} ${n==="up"?"dd-up":""}`,ref:h,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>a(!s),"aria-expanded":s,children:[t,e.jsx(Fe,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${o??""}`,ref:u,style:p,children:l})]})}function be({active:t,disabled:s=!1,title:a,onClick:l,children:c}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:a,onClick:l,children:c})}const Os="pi-web-ui:lang",si={cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",queueSteerTag:"插队",queueFollowTag:"排队",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",noOptions:"(无选项)",inputPlaceholder:"输入内容",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-web-ui 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",directory:"目录",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",modelUsedCount:"已用 {n} 次",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:同时搜索历史对话、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索文件…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","tpl.title":"提示词模板","tpl.hint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.clickCard":"点击填入输入框","tpl.editTpl":"编辑 / 删除模板","tpl.openPicker":"提示词模板(常用提示词,随时取用)","tpl.pickerTitle":"提示词模板","tpl.pickerHint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.add":"新建模板","tpl.addDesc":"把常用工作流存成模板","tpl.reset":"恢复默认模板","tpl.resetConfirm":"确认恢复默认?","tpl.builtin":"内置","tpl.custom":"自定义","tpl.newTitle":"新建提示词模板","tpl.editTitle":"编辑提示词模板","tpl.fieldIcon":"图标","tpl.fieldTitle":"标题","tpl.fieldTitlePh":"卡片上显示的短标题","tpl.fieldDesc":"说明","tpl.fieldDescPh":"一句话说明,显示在卡片上","tpl.fieldPrompt":"提示词","tpl.fieldPromptPh":"完整提示词 —— 发送给智能体的内容","tpl.required":"标题和提示词不能为空","tpl.save":"保存修改","tpl.fill":"填入输入框","tpl.fillTip":"填入输入框,可再编辑后发送","tpl.sendNow":"直接发送","tpl.sendTip":"立即作为新对话发送","tpl.delete":"删除","tpl.deleteTip":"删除这个自定义模板","tpl.remove":"移出模板库","tpl.removeTip":"把内置模板移出模板库,可在底部「恢复默认模板」找回","tpl.restore":"恢复默认","tpl.restoreTip":"撤掉你的修改,恢复内置默认","tpl.sk.setup":"仓库初始化","tpl.sk.setup.desc":"让仓库了解它的构建与约定","tpl.sk.setup.prompt":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
|
|
3
3
|
|
|
4
4
|
1. 项目类型、技术栈与目录结构
|
|
5
5
|
2. 构建 / 测试 / 运行 / 格式化的具体命令
|
|
@@ -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…"},Ws=r.createContext(null);function ii(){try{const t=localStorage.getItem(Os);if(t==="zh"||t==="en")return t}catch{}return"zh"}function ai({children:t}){const[s,a]=r.useState(ii),l=r.useCallback(n=>{a(n);try{localStorage.setItem(Os,n)}catch{}},[]),c=r.useCallback((n,o)=>{let u=ni[n];if(s==="zh"&&(u=si[n]),o)for(const[p,h]of Object.entries(o))u=u.replaceAll(`{${p}}`,String(h));return u},[s]);r.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en"},[s]);const i=r.useMemo(()=>({locale:s,setLocale:l,t:c}),[s,l,c]);return e.jsx(Ws.Provider,{value:i,children:t})}function At(){const t=r.useContext(Ws);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function pe(){return At().t}const ri=[{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 ns({settings:t,onChange:s,onPreview:a}){const l=pe(),c=i=>s({...t,...i});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:l("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Ls,{className:"sound-icon"}),e.jsx("span",{children:l("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:i=>c({enabled:i.target.checked})})]}),ri.map(({kind:i,labelKey:n,descKey:o})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:l(n)}),e.jsx("span",{className:"sound-desc",children:l(o)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:l("preview"),disabled:!t.enabled,onClick:u=>{u.preventDefault(),a(i)},children:l("preview")}),e.jsx("input",{type:"checkbox",checked:t[i],disabled:!t.enabled,onChange:u=>c({[i]:u.target.checked})})]})]},i)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:l("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:i=>c({volume:Number(i.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}function li({chat:t,send:s,terminal:a,view:l,plugins:c,onViewChange:i,onOpenPanel:n,onOpenSettings:o,onOpenBgTasks:u,onOpenGlobalSearch:p,sound:h,onSoundChange:g,onSoundPreview:y,themes:b,theme:k,onThemeChange:B}){var te;const{locale:M,setLocale:$,t:x}=At(),[j,P]=r.useState(!1),[D,R]=r.useState(!1),[N,m]=r.useState(!1),[A,W]=r.useState(!1),[ee,ie]=r.useState(!1),H=[{value:"zh",label:x("langZh")},{value:"en",label:x("langEn")}],q=t.ready?x("connected"):t.status==="closed"?x("reconnecting"):x("connecting"),L=t.ready?"ok":"busy",T=()=>{var ne,G;if(!t.ready)return;const S=x("updateTabTitle"),F={name:S,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},z=t.terminals.find(oe=>oe.title===S);z?(a.restart(z.id),s({type:"run_command",terminalId:z.id,conversationId:z.conversationId,command:F,cols:80,rows:24})):a.create({id:Re(),conversationId:t.activeConversationId||((ne=t.state)==null?void 0:ne.conversationId)||"",title:S,cwd:((G=t.state)==null?void 0:G.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:F}),W(!1),ie(!1),i("terminal")},C=(S,F)=>{var G,oe;if(!t.ready||S.length===0)return;const z={name:F,command:ti(S),cwd:"${pwd}"},ne=t.terminals.find(X=>X.title===F);ne?(a.restart(ne.id),s({type:"run_command",terminalId:ne.id,conversationId:ne.conversationId,command:z,cols:80,rows:24})):a.create({id:Re(),conversationId:t.activeConversationId||((G=t.state)==null?void 0:G.conversationId)||"",title:F,cwd:((oe=t.state)==null?void 0:oe.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:z}),W(!1),ie(!1),i("terminal")},K=t.updatesAll??[],me=K.filter(S=>!S.upToDate&&!S.error).length,J=K.filter(S=>!S.upToDate&&!S.error&&S.kind!=="webui"),E=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:x("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:x("checkingUpdate")}):K.length===0?e.jsx("div",{className:"dd-note",children:x("updatesAllUpToDate")}):e.jsx("ul",{className:"dd-all-list",children:K.map(S=>e.jsxs("li",{className:`dd-all-item${S.error?" err":S.upToDate?"":" warn"}`,children:[e.jsx("span",{className:"dd-all-name",title:S.name,children:S.name}),e.jsx("span",{className:"dd-all-kind",children:S.kind==="webui"?x("kindWebUi"):S.kind==="pi-core"?x("kindPiCore"):x("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:S.error?x("updateCheckFailed"):S.upToDate?`v${S.current}`:e.jsxs(e.Fragment,{children:["v",S.current," → v",S.latest]})}),S.kind!=="webui"&&!S.upToDate&&!S.error&&e.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>C([S.name],x("updatePkgTabTitle",{name:S.name})),children:x("updateBtn")})]},`${S.kind}:${S.name}`))}),e.jsxs("div",{className:"dd-actions",children:[J.length>0&&e.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>C(J.map(S=>S.name),x("updateAllTabTitle")),children:x("updateAllBtn")}),e.jsx("button",{type:"button",className:"dd-refresh",style:J.length>0?{flex:1}:void 0,onClick:()=>s({type:"check_updates_all",force:!0}),children:x("updatesAllRefresh")})]})]}),Z=()=>{var S,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:x("currentVersion")}),e.jsxs("b",{children:["v",((S=t.update)==null?void 0:S.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:x("latestVersion")}),e.jsx("b",{children:t.update===null?x("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:x("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:x("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:x("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:x("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:x("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?x("checkingUpdate"):x("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:T,children:x("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:x("openHistory"),onClick:()=>n("left"),children:e.jsx(On,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${L}`,title:q}),e.jsx("span",{className:"conn-label",children:q})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":x("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="chat",className:l==="chat"?"active":"",onClick:()=>i("chat"),children:[e.jsx(Ke,{}),e.jsx("span",{children:x("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="terminal",className:l==="terminal"?"active":"",onClick:()=>i("terminal"),children:[e.jsx(qe,{}),e.jsx("span",{children:x("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="git",className:l==="git"?"active":"",onClick:()=>i("git"),children:[e.jsx(it,{}),e.jsx("span",{children:x("scmTab")})]}),c.map(S=>{const F=S.error?`${S.name}: ${S.error}`:S.description?`${S.name} — ${S.description}`:S.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":l===`plugin:${S.id}`,className:`plugin-tab${l===`plugin:${S.id}`?" active":""}${S.error?" broken":""}`,title:F,onClick:()=>i(`plugin:${S.id}`),children:[S.icon?e.jsx("span",{"aria-hidden":!0,children:S.icon}):null,e.jsx("span",{children:S.name})]},S.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:x("searchGlobalTip"),onClick:p,children:[e.jsx(dt,{}),e.jsx("span",{className:"chip-sub",children:x("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":x("bgTasksTip"),onClick:u,children:[e.jsx(ut,{}),e.jsx("span",{className:"chip-sub",children:x("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:x("settingsTitle"),onClick:o,children:[e.jsx(ct,{}),e.jsx("span",{className:"chip-sub",children:x("settings")})]}),e.jsx(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ls,{}),e.jsx("span",{className:"chip-sub",children:x("sound")})]}),open:j,onOpenChange:P,children:e.jsx(ns,{settings:h,onChange:g,onPreview:y})}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Gn,{}),e.jsx("span",{className:"chip-sub",children:M==="zh"?x("langZh"):"EN"})]}),open:D,onOpenChange:R,children:[e.jsx("div",{className:"dd-header",children:x("language")}),H.map(S=>e.jsx(be,{active:M===S.value,onClick:()=>{$(S.value),R(!1)},children:S.label},S.value))]}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Dn,{}),e.jsx("span",{className:"chip-sub",children:x("theme")})]}),open:N,onOpenChange:m,children:[e.jsx("div",{className:"dd-header",children:x("theme")}),e.jsx(be,{active:k===null,onClick:()=>{B(null),m(!1)},children:x("themeDefault")}),b.map(S=>e.jsx(be,{active:k===S.id,onClick:()=>{B(S.id),m(!1)},children:S.name},S.id))]}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Dt,{}),e.jsxs("span",{className:"chip-sub",children:["v",((te=t.update)==null?void 0:te.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:x("updateAvailable",{version:t.update.latest??""})}),me>0&&e.jsx("span",{className:"update-badge",children:x("updatesAllBadge",{n:me})})]}),open:A,onOpenChange:S=>{W(S),S&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:x("update")}),Z(),E()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:x("githubRepo"),children:e.jsx(ts,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":x("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(De,{}),e.jsx("span",{children:x("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Fn,{}),e.jsx("span",{className:"chip-sub",children:x("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:ee,onOpenChange:S=>{ie(S),S&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:x("sound")}),e.jsx("div",{className:"dd-header",children:x("settings")}),e.jsxs(be,{onClick:()=>{ie(!1),o()},children:[e.jsx(ct,{})," ",x("settingsTitle")]}),e.jsxs(be,{onClick:()=>{ie(!1),p()},children:[e.jsx(dt,{})," ",x("searchGlobal")]}),e.jsxs(be,{onClick:()=>{ie(!1),u()},children:[e.jsx(ut,{})," ",x("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(ns,{settings:h,onChange:g,onPreview:y}),e.jsx("div",{className:"dd-header",children:x("language")}),H.map(S=>e.jsx(be,{active:M===S.value,onClick:()=>$(S.value),children:S.label},S.value)),e.jsx("div",{className:"dd-header",children:x("theme")}),e.jsx(be,{active:k===null,onClick:()=>{B(null),ie(!1)},children:x("themeDefault")}),b.map(S=>e.jsx(be,{active:k===S.id,onClick:()=>{B(S.id),ie(!1)},children:S.name},S.id)),e.jsx("div",{className:"dd-header",children:x("update")}),Z(),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(ts,{})," ",x("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:x("openFiles"),onClick:()=>n("right"),children:e.jsx(ze,{})})]})]})}function is(t){const s=new Date(t),a=new Date;return s.toDateString()===a.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function oi(t,s){const a=new Map;for(const c of t){const i=a.get(c.cwd)??[];i.push(c),a.set(c.cwd,i)}const l=[...a.entries()].map(([c,i])=>({cwd:c,isCurrent:c===s,convs:i}));return l.sort((c,i)=>c.isCurrent?-1:i.isCurrent?1:c.cwd<i.cwd?-1:c.cwd>i.cwd?1:0),l}const ci=r.memo(function({ready:s,status:a,cwd:l,sessionFile:c,conversations:i,sessions:n,projects:o,activeConversationId:u,send:p,active:h}){const g=pe(),y=c,b=l,[k,B]=r.useState(null);r.useEffect(()=>{!h||!s||a!=="open"||l&&(p({type:"list_sessions"}),p({type:"list_projects"}))},[h,s,a,l,p]);const M=j=>{const P=j.name||j.firstMessage.trim();return P.length>0?P:g("emptyChat")},$=j=>j.split(/[\\/]/).pop()||j,x=(j,P,D,R)=>{const N=k===j;return e.jsx("button",{type:"button",className:`lp-del ${N?"confirm":""}`,title:N?D:P,onClick:m=>{m.stopPropagation(),N?(B(null),R()):B(j)},children:N?e.jsx(gt,{}):e.jsx(Ee,{})})};return e.jsxs("aside",{className:"panel panel-left",children:[o.length>0&&e.jsxs("div",{className:"panel-projects",children:[e.jsx("div",{className:"panel-section-title",children:g("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:o.map(j=>{const P=b===j.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>B(D=>D===`proj:${j.path}`?null:D),children:[e.jsxs("button",{type:"button",className:`project-item ${P?"active":""}`,title:j.path,onClick:()=>{P||p({type:"set_cwd",path:j.path})},children:[e.jsx(ze,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:$(j.path)}),e.jsx("span",{className:"project-path",children:j.path})]}),e.jsx("span",{className:"project-time",children:is(j.lastUsed)})]}),x(`proj:${j.path}`,g("deleteProject"),g("deleteProjectConfirm"),()=>p({type:"remove_project",path:j.path}))]},j.path)})})]}),i.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:g("runningConversations")}),oi(i,l).map(j=>e.jsxs("div",{className:"panel-conv-group",children:[!j.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:j.cwd,children:$(j.cwd)}),j.convs.map(P=>{const D=u===P.id;return e.jsxs("button",{type:"button",className:`session-item ${D?"active":""}`,title:`${P.title}${j.isCurrent?"":` — ${j.cwd}`}`,onClick:()=>{D||p({type:"switch_conversation",id:P.id})},children:[e.jsx(Ke,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:P.title}),e.jsx("span",{className:"session-sub",children:D?g("current"):g("messageCount",{n:P.messageCount})})]}),P.isStreaming&&e.jsx("span",{className:"conv-streaming",title:g("streaming")})]},P.id)})]},j.cwd)),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:g("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[n.length===0&&e.jsx("div",{className:"panel-empty",children:g("noHistory")}),n.map(j=>{const P=y===j.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>B(D=>D===`sess:${j.path}`?null:D),children:[e.jsxs("button",{type:"button",className:`session-item ${P?"active":""}`,title:j.path,onClick:()=>{P||p({type:"switch_session",path:j.path})},children:[e.jsx(Ke,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:M(j)}),e.jsxs("span",{className:"session-sub",children:[P?g("current"):g("messageCount",{n:j.messageCount}),j.source==="tui"&&e.jsx("span",{className:"session-src",title:g("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:is(j.modified)})]}),x(`sess:${j.path}`,g("deleteSession"),g("deleteSessionConfirm"),()=>p({type:"delete_session",path:j.path}))]},j.path)})]})]})]})}),Hs="pi-web-ui:token";function di(){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 ui(){try{return localStorage.getItem(Hs)??""}catch{return""}}function ft(t){const s=ui();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}function pi(t,s){const a=s.assistantMessageEvent,l=t.stats.tokens,c=s.usage!==null?{...l,...s.usage}:l,i=c===l?t.stats:{...t.stats,tokens:c};if(a.type!=="text_delta"&&a.type!=="thinking_delta")return i===t.stats?t:{...t,stats:i};const n=a.delta??"";if(!n)return i===t.stats?t:{...t,stats:i};const o=t.streamingMessage??null,u=o&&o.id===s.messageId?o:{id:s.messageId,content:[]},p=[...u.content],h=a.type==="thinking_delta"?"thinking":"text",g=a.contentIndex??p.length-1;return g>=0&&g<p.length&&p[g].type===h?p[g]=h==="thinking"?{type:"thinking",thinking:(p[g].thinking??"")+n}:{type:"text",text:(p[g].text??"")+n}:p.push(h==="thinking"?{type:"thinking",thinking:n}:{type:"text",text:n}),{...t,stats:i,streamingMessage:{...u,id:s.messageId,content:p}}}const Mt="pi-web-ui:plugin-data";function mi(t,s){window.dispatchEvent(new CustomEvent(Mt,{detail:{pluginId:t,payload:s}}))}function hi(t){const s=a=>{const l=a.detail;t(l.pluginId,l.payload)};return window.addEventListener(Mt,s),()=>window.removeEventListener(Mt,s)}const Ue=new Map,Rt=new Set,We=new Set;let as=-1;function Us(){return[...Ue.values()]}function gi(){const t=Us();for(const s of Rt)s(t)}function fi(t){return Rt.add(t),t(Us()),()=>Rt.delete(t)}async function xi(t,s){s!==as&&(as=s,Ue.clear(),We.clear());const a=new Set(t.map(l=>l.id));for(const l of[...Ue.keys()])a.has(l)||Ue.delete(l);for(const l of[...We])a.has(l)||We.delete(l);await Promise.all(t.filter(l=>l.hasClient&&!l.error&&!Ue.has(l.id)&&!We.has(l.id)).map(async l=>{try{const i=(await Rs(()=>import(`/plugins/${encodeURIComponent(l.id)}/client/entry.mjs?e=${s}`),[])).default;i&&typeof i.mount=="function"?Ue.set(l.id,{info:l,module:i}):(We.add(l.id),console.error(`[plugin:${l.id}] entry.mjs 缺少 default.mount`))}catch(c){We.add(l.id),console.error(`[plugin:${l.id}] 客户端加载失败:`,c)}})),gi()}function vi(t,s){return{pluginId:t,send:a=>s({type:"plugin_message",pluginId:t,payload:a}),onData:a=>hi((l,c)=>{l===t&&a(c)})}}const yi=10,yt=2e5,ki=2e5,bi={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 ji(){const t=new Map,s=new Map,a=(l,c)=>`${l}:${c}`;return{write(l,c,i){const n=a(l,c),o=t.get(n);if(o&&o.size>0){for(const h of o)try{h.write(i)}catch{}return}const u=s.get(n)??"",p=u.length+i.length>ki?i:u+i;s.set(n,p)},register(l,c,i){const n=a(l,c);let o=t.get(n);o||(o=new Set,t.set(n,o)),o.add(i);const u=s.get(n);if(u){try{i.write(u)}catch{}s.delete(n)}return()=>{const p=t.get(n);p&&(p.delete(i),p.size===0&&t.delete(n)),s.delete(n)}},clear(){t.clear(),s.clear()}}}function rs(t,s){const a=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&a.add(c.toolCallId),c.role==="bashExecution"&&a.add(`bash-${c.id}`);let l=!1;for(const c of t.keys())a.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function ls(t,s){if(t.size===0)return t;const a=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&a.add(c.toolCallId);let l=!1;for(const c of t.keys())a.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function wi(t,s){var a,l,c,i;switch(s.type){case"status":return{...t,status:s.status,ready:s.status==="open"?t.ready:!1,terminals:s.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:s.serverVersion,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==yi};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:rs(t.liveOutputs,s.state),toolStatuses:ls(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:rs(t.liveOutputs,u),toolStatuses:ls(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>yt?`…[前 ${o.length-yt} 字符已省略]…
|
|
303
|
-
`+o.slice(o.length-yt):o,p=new Map(t.liveOutputs);return p.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:p}}case"message_delta":{const n=t.state;return!n||n.conversationId!==s.msg.conversationId?t:{...t,state:pi(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"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"update_status_all":return{...t,updatesAll:s.items};case"updates_check_started":return{...t,updatesAll:null};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"commands":return{...t,commands:s.commands,commandsPath:s.path};case"slash_commands":return{...t,slashCommands:s.commands};case"goal_status":return{...t,goal:s.status};case"settings":return{...t,settings:s.settings};case"bg_servers":return{...t,bgServers:s.servers};case"plugins":return{...t,plugins:s.plugins,pluginsEpoch:s.epoch};case"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(n=>n.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(a=t.state)!=null&&a.conversationId)&&s.conversationId!==(t.activeConversationId||((l=t.state)==null?void 0:l.conversationId))?t:{...t,terminals:t.terminals.map(n=>n.id===s.terminalId?{...n,running:!1,exitCode:s.exitCode}:n)};case"terminal_restart":return{...t,terminals:t.terminals.map(n=>n.id===s.terminalId?{...n,running:!0,exitCode:null}:n)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(c=t.state)!=null&&c.conversationId)&&s.conversationId!==(t.activeConversationId||((i=t.state)==null?void 0:i.conversationId))?t:{...t,terminals:s.terminals.map(n=>{var o;return{...n,conversationId:s.conversationId??((o=t.state)==null?void 0:o.conversationId)??""}})};default:return t}}const os="pi-web-client-id";let kt=null;function _t(){if(kt)return kt;let t=null;try{t=sessionStorage.getItem(os),t||(t=Re(),sessionStorage.setItem(os,t))}catch{t=t??Re()}return kt=t,t}function Ni(){const t=location.protocol==="https:"?"wss:":"ws:";return ft(`${t}//${location.host}/ws`)}function Ci(){const[t,s]=r.useReducer(wi,{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:bi,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,protocolMismatch:!1}),a=r.useRef(null),l=r.useRef(ji()),c=r.useRef(0),i=r.useRef(null),n=r.useRef(!0),o=r.useRef(0),u=r.useRef(0),p=r.useRef(new Map),h=r.useRef(null),g=()=>{h.current||(h.current=setTimeout(()=>{h.current=null;const R=a.current;R&&R.readyState===WebSocket.OPEN&&R.send(JSON.stringify({type:"get_state"}))},300))},y=(R,N)=>{var W;const m=p.current,A=m.get(R);if(A!==void 0&&N!==A+1){const ee=D.current.chat,ie=ee.activeConversationId||((W=ee.state)==null?void 0:W.conversationId);R===ie&&g()}m.set(R,N)},b=r.useCallback((R,N)=>{const m=++u.current;s({type:"notice",notice:{id:m,level:R,text:N}})},[]),k=r.useCallback(R=>{const N=a.current;return N&&N.readyState===WebSocket.OPEN?(R.type==="check_updates_all"&&R.force===!0&&s({type:"updates_check_started"}),N.send(JSON.stringify(R)),!0):!1},[]),B=r.useCallback(()=>{if(!n.current)return;s({type:"status",status:"connecting"});const R=new WebSocket(Ni());a.current=R,R.onopen=()=>{a.current===R&&(s({type:"status",status:"open"}),c.current=0,o.current=Date.now(),R.send(JSON.stringify({type:"hello",clientId:_t()})))},R.onmessage=N=>{if(a.current!==R)return;o.current=Date.now();let m;try{m=JSON.parse(N.data)}catch{return}switch(m.type){case"ready":s({type:"ready",serverVersion:m.serverVersion,protocolVersion:m.protocolVersion}),R.send(JSON.stringify({type:"get_state"})),R.send(JSON.stringify({type:"list_files"})),R.send(JSON.stringify({type:"list_models"})),R.send(JSON.stringify({type:"list_commands"})),R.send(JSON.stringify({type:"get_commands"})),R.send(JSON.stringify({type:"check_update"})),R.send(JSON.stringify({type:"check_updates_all"}));break;case"snapshot":p.current=new Map,s({type:"snapshot",state:m.state});break;case"snapshot_delta":{const A=D.current.chat.state;(!A||A.conversationId!==m.conversationId||A.rev!==m.baseRev)&&g(),s({type:"snapshot_delta",msg:m});break}case"tool_delta":y(m.conversationId,m.seq),s({type:"tool_delta",toolCallId:m.toolCallId,toolName:m.toolName,delta:m.delta});break;case"tool_status":s({type:"tool_status",status:m});break;case"message_delta":{y(m.conversationId,m.seq),s({type:"message_delta",msg:m});break}case"notice":{const A=++u.current;s({type:"notice",notice:{id:A,level:m.level,text:m.text}});break}case"sessions":s({type:"sessions",sessions:m.sessions});break;case"conversations":s({type:"conversations",conversations:m.conversations,activeId:m.activeId});break;case"projects":s({type:"projects",projects:m.projects});break;case"files":s({type:"files",files:m});break;case"file_changed":s({type:"file_changed",path:m.path});break;case"file_content":s({type:"file_content",content:m});break;case"models":s({type:"models",models:m.models,loading:!1});break;case"models_config":s({type:"models_config",providers:m.providers});break;case"providers_status":s({type:"providers_status",providers:m.providers});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:m.reqId,ok:m.ok,models:m.models,error:m.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:m.reqId,ok:m.ok,added:m.added,total:m.total,error:m.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:m.reqId,ok:m.ok,config:m.config,error:m.error}});break;case"scm_data":s({type:"scm_data",data:m});break;case"search_files_result":s({type:"file_search_result",result:{reqId:m.reqId,ok:m.ok,results:m.results,truncated:m.truncated}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:m});break;case"path_completions":s({type:"path_completions",completions:m.completions});break;case"update_status":s({type:"update_status",status:m});break;case"update_status_all":s({type:"update_status_all",items:m.items});break;case"widgets":s({type:"widgets",widgets:m.widgets});break;case"statuses":s({type:"statuses",statuses:m.statuses});break;case"dialog":s({type:"dialog",dialog:{id:m.id,kind:m.kind,title:m.title,args:m.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"terminal_output":l.current.write(m.conversationId??D.current.chat.activeConversationId,m.terminalId,m.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:m.conversationId,terminalId:m.terminalId,exitCode:m.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:m.conversationId,terminals:m.terminals});break;case"commands":s({type:"commands",commands:m.commands,path:m.path});break;case"slash_commands":s({type:"slash_commands",commands:m.commands});break;case"goal_status":s({type:"goal_status",status:m.status});break;case"settings_state":s({type:"settings",settings:m.settings});break;case"bg_servers":s({type:"bg_servers",servers:m.servers});break;case"plugins":s({type:"plugins",plugins:m.plugins,epoch:m.epoch});break;case"plugin_data":mi(m.pluginId,m.payload);break}},R.onclose=()=>{if(a.current===R&&(a.current=null),l.current.clear(),!n.current||a.current&&a.current!==R)return;s({type:"status",status:"closed"});const N=Math.min(1e3*2**c.current,1e4);c.current+=1,i.current=setTimeout(()=>{i.current=null,B()},N)},R.onerror=()=>{}},[]);r.useEffect(()=>{n.current=!0,B();const R=setInterval(()=>{if(!n.current)return;const N=a.current;N&&N.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&N.close()},5e3);return()=>{var N;n.current=!1,clearInterval(R),i.current&&(clearTimeout(i.current),i.current=null),(N=a.current)==null||N.close(),a.current=null}},[B]);const M=r.useCallback(R=>s({type:"dismiss_notice",id:R}),[]),$=r.useCallback(R=>s({type:"terminal_add",meta:R}),[]),x=r.useCallback(R=>s({type:"terminal_remove",id:R}),[]),j=r.useCallback(R=>s({type:"terminal_restart",terminalId:R}),[]),P=r.useCallback((R,N,m)=>l.current.register(R,N,m),[]),D=r.useRef({chat:t,send:k,pushNotice:b,dismissNotice:M,terminal:{create:$,close:x,register:P,restart:j}});return D.current={chat:t,send:k,pushNotice:b,dismissNotice:M,terminal:{create:$,close:x,register:P,restart:j}},D.current}const Si=200*1024*1024,Ti=/windows/i.test(navigator.userAgent),Ei=/[<>:"/\\|?*\u0000-\u001f]/g,Mi=/[. ]+$/,Ri=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Pi(t){const s=t.replace(Ei,"_").replace(Mi,"");return s?Ri.test(s)?`_${s}`:s:"_"}function cs(t,s=!0){const a=new URLSearchParams({clientId:_t(),path:t,...s?{download:"1"}:{}});return ft(`/api/file?${a}`)}async function Ii(t,s){const a=Ti?Pi(s):s;try{const l=await fetch(cs(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")>Si)return window.location.assign(cs(t)),{ok:!0};const i=await l.blob();return window.showSaveFilePicker&&window.isSecureContext?Li(i,a):Pt(i,a)}catch(l){return{ok:!1,cancelled:!1,error:l instanceof Error?l.message:String(l)}}}async function Li(t,s){let a;const l=window.showSaveFilePicker;if(!l)return Pt(t,s);try{a=await l({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:Pt(t,s)}try{const c=await a.createWritable();return await c.write(t),await c.close(),{ok:!0}}catch(c){return{ok:!1,cancelled:!1,error:c instanceof Error?c.message:String(c)}}}function Pt(t,s){const a=URL.createObjectURL(t),l=document.createElement("a");return l.href=a,l.download=s,document.body.appendChild(l),l.click(),l.remove(),setTimeout(()=>URL.revokeObjectURL(a),1e4),{ok:!0}}const Di=r.memo(function({files:s,fileChanged:a,widgets:l,cwd:c,send:i,onAttach:n,onPreview:o,onNotice:u}){const p=pe(),[h,g]=r.useState(""),[y,b]=r.useState(null),[k,B]=r.useState(!1),M=1e4,$=r.useRef(0),x=r.useRef(void 0),j=r.useCallback((N,m)=>{const A=++$.current;g(N),m!=null&&m.silent||B(!0),i({type:"list_files",path:N===""?void 0:N})||$.current===A&&B(!1)},[i]);r.useEffect(()=>{s&&s.path===h&&B(!1)},[s,h]),r.useEffect(()=>{if(c!==x.current){x.current=c,j("",{silent:!0});return}const N=setInterval(()=>{document.visibilityState!=="hidden"&&j(h,{silent:!0})},M);return()=>clearInterval(N)},[c,h,j]),r.useEffect(()=>{a&&a.path===h&&j(h,{silent:!0})},[a,h,j]);const P=N=>j(N),D=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&j(s.parent)},R=h.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 ${h===""?"active":""}`,onClick:()=>j(""),children:p("rootDir")}),R.map((N,m)=>{const A=R.slice(0,m+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(ht,{}),e.jsx("button",{type:"button",className:`crumb ${A===h?"active":""}`,onClick:()=>j(A),children:N})]},A)})]}),e.jsxs("div",{className:"panel-body",children:[k&&e.jsx("div",{className:"panel-empty",children:p("loading")}),!k&&s&&s.path===h&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:D,children:[e.jsx(ze,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(N=>N.type==="dir"?e.jsxs("div",{className:"file-item dir",children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>P(N.path),children:[e.jsx(ze,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:N.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":p("linkFolderTip"),onClick:()=>n(N.path,N.name,"reference",!0),children:e.jsx(Ct,{})})]},N.path):e.jsxs("div",{className:"file-item file",children:[e.jsxs("button",{type:"button",className:"file-name",title:`${N.path} — ${p("previewFile")}`,onClick:()=>o(N.path,N.name),children:[e.jsx(As,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:N.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":p("downloadFile"),onClick:()=>{Ii(N.path,N.name).then(m=>{m.ok||m.cancelled||u("error",p("downloadFailed",{error:m.error}))})},children:e.jsx(Dt,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":p("attachInlineTip"),onClick:()=>n(N.path,N.name,"inline"),children:e.jsx(De,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":p("referenceTip"),onClick:()=>n(N.path,N.name,"reference"),children:e.jsx(Ct,{})})]},N.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:p("filesTruncated")})]}),!k&&!s&&e.jsx("div",{className:"panel-empty",children:p("noFiles")})]}),l.filter(N=>N.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:l.filter(N=>N.lines.length>0).map(N=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:p("widgetExpand"),onClick:()=>b(N.key),children:[e.jsx("span",{children:N.key}),e.jsx(Hn,{})]}),e.jsx("pre",{className:"widget-lines",children:N.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…"},Ws=r.createContext(null);function ii(){try{const t=localStorage.getItem(Os);if(t==="zh"||t==="en")return t}catch{}return"zh"}function ai({children:t}){const[s,a]=r.useState(ii),l=r.useCallback(n=>{a(n);try{localStorage.setItem(Os,n)}catch{}},[]),c=r.useCallback((n,o)=>{let u=ni[n];if(s==="zh"&&(u=si[n]),o)for(const[p,h]of Object.entries(o))u=u.replaceAll(`{${p}}`,String(h));return u},[s]);r.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en"},[s]);const i=r.useMemo(()=>({locale:s,setLocale:l,t:c}),[s,l,c]);return e.jsx(Ws.Provider,{value:i,children:t})}function At(){const t=r.useContext(Ws);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function pe(){return At().t}const ri=[{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 ns({settings:t,onChange:s,onPreview:a}){const l=pe(),c=i=>s({...t,...i});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:l("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Ls,{className:"sound-icon"}),e.jsx("span",{children:l("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:i=>c({enabled:i.target.checked})})]}),ri.map(({kind:i,labelKey:n,descKey:o})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:l(n)}),e.jsx("span",{className:"sound-desc",children:l(o)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:l("preview"),disabled:!t.enabled,onClick:u=>{u.preventDefault(),a(i)},children:l("preview")}),e.jsx("input",{type:"checkbox",checked:t[i],disabled:!t.enabled,onChange:u=>c({[i]:u.target.checked})})]})]},i)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:l("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:i=>c({volume:Number(i.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}function li({chat:t,send:s,terminal:a,view:l,plugins:c,onViewChange:i,onOpenPanel:n,onOpenSettings:o,onOpenBgTasks:u,onOpenGlobalSearch:p,sound:h,onSoundChange:g,onSoundPreview:y,themes:b,theme:k,onThemeChange:B}){var te;const{locale:E,setLocale:$,t:x}=At(),[j,P]=r.useState(!1),[D,R]=r.useState(!1),[N,m]=r.useState(!1),[A,W]=r.useState(!1),[ee,ie]=r.useState(!1),H=[{value:"zh",label:x("langZh")},{value:"en",label:x("langEn")}],q=t.ready?x("connected"):t.status==="closed"?x("reconnecting"):x("connecting"),L=t.ready?"ok":"busy",S=()=>{var ne,G;if(!t.ready)return;const M=x("updateTabTitle"),F={name:M,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},z=t.terminals.find(oe=>oe.title===M);z?(a.restart(z.id),s({type:"run_command",terminalId:z.id,conversationId:z.conversationId,command:F,cols:80,rows:24})):a.create({id:Re(),conversationId:t.activeConversationId||((ne=t.state)==null?void 0:ne.conversationId)||"",title:M,cwd:((G=t.state)==null?void 0:G.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:F}),W(!1),ie(!1),i("terminal")},C=(M,F)=>{var G,oe;if(!t.ready||M.length===0)return;const z={name:F,command:ti(M),cwd:"${pwd}"},ne=t.terminals.find(X=>X.title===F);ne?(a.restart(ne.id),s({type:"run_command",terminalId:ne.id,conversationId:ne.conversationId,command:z,cols:80,rows:24})):a.create({id:Re(),conversationId:t.activeConversationId||((G=t.state)==null?void 0:G.conversationId)||"",title:F,cwd:((oe=t.state)==null?void 0:oe.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:z}),W(!1),ie(!1),i("terminal")},K=t.updatesAll??[],me=K.filter(M=>!M.upToDate&&!M.error).length,J=K.filter(M=>!M.upToDate&&!M.error&&M.kind!=="webui"),T=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:x("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:x("checkingUpdate")}):K.length===0?e.jsx("div",{className:"dd-note",children:x("updatesAllUpToDate")}):e.jsx("ul",{className:"dd-all-list",children:K.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"?x("kindWebUi"):M.kind==="pi-core"?x("kindPiCore"):x("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:M.error?x("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:()=>C([M],x("updatePkgTabTitle",{name:M.name})),children:x("updateBtn")})]},`${M.kind}:${M.name}`))}),e.jsxs("div",{className:"dd-actions",children:[J.length>0&&e.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>C(J,x("updateAllTabTitle")),children:x("updateAllBtn")}),e.jsx("button",{type:"button",className:"dd-refresh",style:J.length>0?{flex:1}:void 0,onClick:()=>s({type:"check_updates_all",force:!0}),children:x("updatesAllRefresh")})]})]}),Z=()=>{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:x("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:x("latestVersion")}),e.jsx("b",{children:t.update===null?x("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:x("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:x("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:x("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:x("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:x("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?x("checkingUpdate"):x("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:S,children:x("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:x("openHistory"),onClick:()=>n("left"),children:e.jsx(On,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${L}`,title:q}),e.jsx("span",{className:"conn-label",children:q})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":x("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="chat",className:l==="chat"?"active":"",onClick:()=>i("chat"),children:[e.jsx(Ke,{}),e.jsx("span",{children:x("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="terminal",className:l==="terminal"?"active":"",onClick:()=>i("terminal"),children:[e.jsx(qe,{}),e.jsx("span",{children:x("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="git",className:l==="git"?"active":"",onClick:()=>i("git"),children:[e.jsx(it,{}),e.jsx("span",{children:x("scmTab")})]}),c.map(M=>{const F=M.error?`${M.name}: ${M.error}`:M.description?`${M.name} — ${M.description}`:M.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":l===`plugin:${M.id}`,className:`plugin-tab${l===`plugin:${M.id}`?" active":""}${M.error?" broken":""}`,title:F,onClick:()=>i(`plugin:${M.id}`),children:[M.icon?e.jsx("span",{"aria-hidden":!0,children:M.icon}):null,e.jsx("span",{children:M.name})]},M.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:x("searchGlobalTip"),onClick:p,children:[e.jsx(dt,{}),e.jsx("span",{className:"chip-sub",children:x("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":x("bgTasksTip"),onClick:u,children:[e.jsx(ut,{}),e.jsx("span",{className:"chip-sub",children:x("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:x("settingsTitle"),onClick:o,children:[e.jsx(ct,{}),e.jsx("span",{className:"chip-sub",children:x("settings")})]}),e.jsx(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ls,{}),e.jsx("span",{className:"chip-sub",children:x("sound")})]}),open:j,onOpenChange:P,children:e.jsx(ns,{settings:h,onChange:g,onPreview:y})}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Gn,{}),e.jsx("span",{className:"chip-sub",children:E==="zh"?x("langZh"):"EN"})]}),open:D,onOpenChange:R,children:[e.jsx("div",{className:"dd-header",children:x("language")}),H.map(M=>e.jsx(be,{active:E===M.value,onClick:()=>{$(M.value),R(!1)},children:M.label},M.value))]}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Dn,{}),e.jsx("span",{className:"chip-sub",children:x("theme")})]}),open:N,onOpenChange:m,children:[e.jsx("div",{className:"dd-header",children:x("theme")}),e.jsx(be,{active:k===null,onClick:()=>{B(null),m(!1)},children:x("themeDefault")}),b.map(M=>e.jsx(be,{active:k===M.id,onClick:()=>{B(M.id),m(!1)},children:M.name},M.id))]}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Dt,{}),e.jsxs("span",{className:"chip-sub",children:["v",((te=t.update)==null?void 0:te.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:x("updateAvailable",{version:t.update.latest??""})}),me>0&&e.jsx("span",{className:"update-badge",children:x("updatesAllBadge",{n:me})})]}),open:A,onOpenChange:M=>{W(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:x("update")}),Z(),T()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:x("githubRepo"),children:e.jsx(ts,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":x("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(De,{}),e.jsx("span",{children:x("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Fn,{}),e.jsx("span",{className:"chip-sub",children:x("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:ee,onOpenChange:M=>{ie(M),M&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:x("sound")}),e.jsx("div",{className:"dd-header",children:x("settings")}),e.jsxs(be,{onClick:()=>{ie(!1),o()},children:[e.jsx(ct,{})," ",x("settingsTitle")]}),e.jsxs(be,{onClick:()=>{ie(!1),p()},children:[e.jsx(dt,{})," ",x("searchGlobal")]}),e.jsxs(be,{onClick:()=>{ie(!1),u()},children:[e.jsx(ut,{})," ",x("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(ns,{settings:h,onChange:g,onPreview:y}),e.jsx("div",{className:"dd-header",children:x("language")}),H.map(M=>e.jsx(be,{active:E===M.value,onClick:()=>$(M.value),children:M.label},M.value)),e.jsx("div",{className:"dd-header",children:x("theme")}),e.jsx(be,{active:k===null,onClick:()=>{B(null),ie(!1)},children:x("themeDefault")}),b.map(M=>e.jsx(be,{active:k===M.id,onClick:()=>{B(M.id),ie(!1)},children:M.name},M.id)),e.jsx("div",{className:"dd-header",children:x("update")}),Z(),T(),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(ts,{})," ",x("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:x("openFiles"),onClick:()=>n("right"),children:e.jsx(ze,{})})]})]})}function is(t){const s=new Date(t),a=new Date;return s.toDateString()===a.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function oi(t,s){const a=new Map;for(const c of t){const i=a.get(c.cwd)??[];i.push(c),a.set(c.cwd,i)}const l=[...a.entries()].map(([c,i])=>({cwd:c,isCurrent:c===s,convs:i}));return l.sort((c,i)=>c.isCurrent?-1:i.isCurrent?1:c.cwd<i.cwd?-1:c.cwd>i.cwd?1:0),l}const ci=r.memo(function({ready:s,status:a,cwd:l,sessionFile:c,conversations:i,sessions:n,projects:o,activeConversationId:u,send:p,active:h}){const g=pe(),y=c,b=l,[k,B]=r.useState(null);r.useEffect(()=>{!h||!s||a!=="open"||l&&(p({type:"list_sessions"}),p({type:"list_projects"}))},[h,s,a,l,p]);const E=j=>{const P=j.name||j.firstMessage.trim();return P.length>0?P:g("emptyChat")},$=j=>j.split(/[\\/]/).pop()||j,x=(j,P,D,R)=>{const N=k===j;return e.jsx("button",{type:"button",className:`lp-del ${N?"confirm":""}`,title:N?D:P,onClick:m=>{m.stopPropagation(),N?(B(null),R()):B(j)},children:N?e.jsx(gt,{}):e.jsx(Ee,{})})};return e.jsxs("aside",{className:"panel panel-left",children:[o.length>0&&e.jsxs("div",{className:"panel-projects",children:[e.jsx("div",{className:"panel-section-title",children:g("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:o.map(j=>{const P=b===j.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>B(D=>D===`proj:${j.path}`?null:D),children:[e.jsxs("button",{type:"button",className:`project-item ${P?"active":""}`,title:j.path,onClick:()=>{P||p({type:"set_cwd",path:j.path})},children:[e.jsx(ze,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:$(j.path)}),e.jsx("span",{className:"project-path",children:j.path})]}),e.jsx("span",{className:"project-time",children:is(j.lastUsed)})]}),x(`proj:${j.path}`,g("deleteProject"),g("deleteProjectConfirm"),()=>p({type:"remove_project",path:j.path}))]},j.path)})})]}),i.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:g("runningConversations")}),oi(i,l).map(j=>e.jsxs("div",{className:"panel-conv-group",children:[!j.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:j.cwd,children:$(j.cwd)}),j.convs.map(P=>{const D=u===P.id;return e.jsxs("button",{type:"button",className:`session-item ${D?"active":""}`,title:`${P.title}${j.isCurrent?"":` — ${j.cwd}`}`,onClick:()=>{D||p({type:"switch_conversation",id:P.id})},children:[e.jsx(Ke,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:P.title}),e.jsx("span",{className:"session-sub",children:D?g("current"):g("messageCount",{n:P.messageCount})})]}),P.isStreaming&&e.jsx("span",{className:"conv-streaming",title:g("streaming")})]},P.id)})]},j.cwd)),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:g("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[n.length===0&&e.jsx("div",{className:"panel-empty",children:g("noHistory")}),n.map(j=>{const P=y===j.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>B(D=>D===`sess:${j.path}`?null:D),children:[e.jsxs("button",{type:"button",className:`session-item ${P?"active":""}`,title:j.path,onClick:()=>{P||p({type:"switch_session",path:j.path})},children:[e.jsx(Ke,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:E(j)}),e.jsxs("span",{className:"session-sub",children:[P?g("current"):g("messageCount",{n:j.messageCount}),j.source==="tui"&&e.jsx("span",{className:"session-src",title:g("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:is(j.modified)})]}),x(`sess:${j.path}`,g("deleteSession"),g("deleteSessionConfirm"),()=>p({type:"delete_session",path:j.path}))]},j.path)})]})]})]})}),Hs="pi-web-ui:token";function di(){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 ui(){try{return localStorage.getItem(Hs)??""}catch{return""}}function ft(t){const s=ui();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}function pi(t,s){const a=s.assistantMessageEvent,l=t.stats.tokens,c=s.usage!==null?{...l,...s.usage}:l,i=c===l?t.stats:{...t.stats,tokens:c};if(a.type!=="text_delta"&&a.type!=="thinking_delta")return i===t.stats?t:{...t,stats:i};const n=a.delta??"";if(!n)return i===t.stats?t:{...t,stats:i};const o=t.streamingMessage??null,u=o&&o.id===s.messageId?o:{id:s.messageId,content:[]},p=[...u.content],h=a.type==="thinking_delta"?"thinking":"text",g=a.contentIndex??p.length-1;return g>=0&&g<p.length&&p[g].type===h?p[g]=h==="thinking"?{type:"thinking",thinking:(p[g].thinking??"")+n}:{type:"text",text:(p[g].text??"")+n}:p.push(h==="thinking"?{type:"thinking",thinking:n}:{type:"text",text:n}),{...t,stats:i,streamingMessage:{...u,id:s.messageId,content:p}}}const Mt="pi-web-ui:plugin-data";function mi(t,s){window.dispatchEvent(new CustomEvent(Mt,{detail:{pluginId:t,payload:s}}))}function hi(t){const s=a=>{const l=a.detail;t(l.pluginId,l.payload)};return window.addEventListener(Mt,s),()=>window.removeEventListener(Mt,s)}const Ue=new Map,Rt=new Set,We=new Set;let as=-1;function Us(){return[...Ue.values()]}function gi(){const t=Us();for(const s of Rt)s(t)}function fi(t){return Rt.add(t),t(Us()),()=>Rt.delete(t)}async function xi(t,s){s!==as&&(as=s,Ue.clear(),We.clear());const a=new Set(t.map(l=>l.id));for(const l of[...Ue.keys()])a.has(l)||Ue.delete(l);for(const l of[...We])a.has(l)||We.delete(l);await Promise.all(t.filter(l=>l.hasClient&&!l.error&&!Ue.has(l.id)&&!We.has(l.id)).map(async l=>{try{const i=(await Rs(()=>import(`/plugins/${encodeURIComponent(l.id)}/client/entry.mjs?e=${s}`),[])).default;i&&typeof i.mount=="function"?Ue.set(l.id,{info:l,module:i}):(We.add(l.id),console.error(`[plugin:${l.id}] entry.mjs 缺少 default.mount`))}catch(c){We.add(l.id),console.error(`[plugin:${l.id}] 客户端加载失败:`,c)}})),gi()}function vi(t,s){return{pluginId:t,send:a=>s({type:"plugin_message",pluginId:t,payload:a}),onData:a=>hi((l,c)=>{l===t&&a(c)})}}const yi=10,yt=2e5,ki=2e5,bi={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 ji(){const t=new Map,s=new Map,a=(l,c)=>`${l}:${c}`;return{write(l,c,i){const n=a(l,c),o=t.get(n);if(o&&o.size>0){for(const h of o)try{h.write(i)}catch{}return}const u=s.get(n)??"",p=u.length+i.length>ki?i:u+i;s.set(n,p)},register(l,c,i){const n=a(l,c);let o=t.get(n);o||(o=new Set,t.set(n,o)),o.add(i);const u=s.get(n);if(u){try{i.write(u)}catch{}s.delete(n)}return()=>{const p=t.get(n);p&&(p.delete(i),p.size===0&&t.delete(n)),s.delete(n)}},clear(){t.clear(),s.clear()}}}function rs(t,s){const a=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&a.add(c.toolCallId),c.role==="bashExecution"&&a.add(`bash-${c.id}`);let l=!1;for(const c of t.keys())a.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function ls(t,s){if(t.size===0)return t;const a=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&a.add(c.toolCallId);let l=!1;for(const c of t.keys())a.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function wi(t,s){var a,l,c,i;switch(s.type){case"status":return{...t,status:s.status,ready:s.status==="open"?t.ready:!1,terminals:s.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:s.serverVersion,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==yi};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:rs(t.liveOutputs,s.state),toolStatuses:ls(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:rs(t.liveOutputs,u),toolStatuses:ls(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>yt?`…[前 ${o.length-yt} 字符已省略]…
|
|
303
|
+
`+o.slice(o.length-yt):o,p=new Map(t.liveOutputs);return p.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:p}}case"message_delta":{const n=t.state;return!n||n.conversationId!==s.msg.conversationId?t:{...t,state:pi(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"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"update_status_all":return{...t,updatesAll:s.items};case"updates_check_started":return{...t,updatesAll:null};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"commands":return{...t,commands:s.commands,commandsPath:s.path};case"slash_commands":return{...t,slashCommands:s.commands};case"goal_status":return{...t,goal:s.status};case"settings":return{...t,settings:s.settings};case"bg_servers":return{...t,bgServers:s.servers};case"plugins":return{...t,plugins:s.plugins,pluginsEpoch:s.epoch};case"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(n=>n.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(a=t.state)!=null&&a.conversationId)&&s.conversationId!==(t.activeConversationId||((l=t.state)==null?void 0:l.conversationId))?t:{...t,terminals:t.terminals.map(n=>n.id===s.terminalId?{...n,running:!1,exitCode:s.exitCode}:n)};case"terminal_restart":return{...t,terminals:t.terminals.map(n=>n.id===s.terminalId?{...n,running:!0,exitCode:null}:n)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(c=t.state)!=null&&c.conversationId)&&s.conversationId!==(t.activeConversationId||((i=t.state)==null?void 0:i.conversationId))?t:{...t,terminals:s.terminals.map(n=>{var o;return{...n,conversationId:s.conversationId??((o=t.state)==null?void 0:o.conversationId)??""}})};default:return t}}const os="pi-web-client-id";let kt=null;function _t(){if(kt)return kt;let t=null;try{t=sessionStorage.getItem(os),t||(t=Re(),sessionStorage.setItem(os,t))}catch{t=t??Re()}return kt=t,t}function Ni(){const t=location.protocol==="https:"?"wss:":"ws:";return ft(`${t}//${location.host}/ws`)}function Ci(){const[t,s]=r.useReducer(wi,{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:bi,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,protocolMismatch:!1}),a=r.useRef(null),l=r.useRef(ji()),c=r.useRef(0),i=r.useRef(null),n=r.useRef(!0),o=r.useRef(0),u=r.useRef(0),p=r.useRef(new Map),h=r.useRef(null),g=()=>{h.current||(h.current=setTimeout(()=>{h.current=null;const R=a.current;R&&R.readyState===WebSocket.OPEN&&R.send(JSON.stringify({type:"get_state"}))},300))},y=(R,N)=>{var W;const m=p.current,A=m.get(R);if(A!==void 0&&N!==A+1){const ee=D.current.chat,ie=ee.activeConversationId||((W=ee.state)==null?void 0:W.conversationId);R===ie&&g()}m.set(R,N)},b=r.useCallback((R,N)=>{const m=++u.current;s({type:"notice",notice:{id:m,level:R,text:N}})},[]),k=r.useCallback(R=>{const N=a.current;return N&&N.readyState===WebSocket.OPEN?(R.type==="check_updates_all"&&R.force===!0&&s({type:"updates_check_started"}),N.send(JSON.stringify(R)),!0):!1},[]),B=r.useCallback(()=>{if(!n.current)return;s({type:"status",status:"connecting"});const R=new WebSocket(Ni());a.current=R,R.onopen=()=>{a.current===R&&(s({type:"status",status:"open"}),c.current=0,o.current=Date.now(),R.send(JSON.stringify({type:"hello",clientId:_t()})))},R.onmessage=N=>{if(a.current!==R)return;o.current=Date.now();let m;try{m=JSON.parse(N.data)}catch{return}switch(m.type){case"ready":s({type:"ready",serverVersion:m.serverVersion,protocolVersion:m.protocolVersion}),R.send(JSON.stringify({type:"get_state"})),R.send(JSON.stringify({type:"list_files"})),R.send(JSON.stringify({type:"list_models"})),R.send(JSON.stringify({type:"list_commands"})),R.send(JSON.stringify({type:"get_commands"})),R.send(JSON.stringify({type:"check_update"})),R.send(JSON.stringify({type:"check_updates_all"}));break;case"snapshot":p.current=new Map,s({type:"snapshot",state:m.state});break;case"snapshot_delta":{const A=D.current.chat.state;(!A||A.conversationId!==m.conversationId||A.rev!==m.baseRev)&&g(),s({type:"snapshot_delta",msg:m});break}case"tool_delta":y(m.conversationId,m.seq),s({type:"tool_delta",toolCallId:m.toolCallId,toolName:m.toolName,delta:m.delta});break;case"tool_status":s({type:"tool_status",status:m});break;case"message_delta":{y(m.conversationId,m.seq),s({type:"message_delta",msg:m});break}case"notice":{const A=++u.current;s({type:"notice",notice:{id:A,level:m.level,text:m.text}});break}case"sessions":s({type:"sessions",sessions:m.sessions});break;case"conversations":s({type:"conversations",conversations:m.conversations,activeId:m.activeId});break;case"projects":s({type:"projects",projects:m.projects});break;case"files":s({type:"files",files:m});break;case"file_changed":s({type:"file_changed",path:m.path});break;case"file_content":s({type:"file_content",content:m});break;case"models":s({type:"models",models:m.models,loading:!1});break;case"models_config":s({type:"models_config",providers:m.providers});break;case"providers_status":s({type:"providers_status",providers:m.providers});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:m.reqId,ok:m.ok,models:m.models,error:m.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:m.reqId,ok:m.ok,added:m.added,total:m.total,error:m.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:m.reqId,ok:m.ok,config:m.config,error:m.error}});break;case"scm_data":s({type:"scm_data",data:m});break;case"search_files_result":s({type:"file_search_result",result:{reqId:m.reqId,ok:m.ok,results:m.results,truncated:m.truncated}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:m});break;case"path_completions":s({type:"path_completions",completions:m.completions});break;case"update_status":s({type:"update_status",status:m});break;case"update_status_all":s({type:"update_status_all",items:m.items});break;case"widgets":s({type:"widgets",widgets:m.widgets});break;case"statuses":s({type:"statuses",statuses:m.statuses});break;case"dialog":s({type:"dialog",dialog:{id:m.id,kind:m.kind,title:m.title,args:m.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"terminal_output":l.current.write(m.conversationId??D.current.chat.activeConversationId,m.terminalId,m.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:m.conversationId,terminalId:m.terminalId,exitCode:m.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:m.conversationId,terminals:m.terminals});break;case"commands":s({type:"commands",commands:m.commands,path:m.path});break;case"slash_commands":s({type:"slash_commands",commands:m.commands});break;case"goal_status":s({type:"goal_status",status:m.status});break;case"settings_state":s({type:"settings",settings:m.settings});break;case"bg_servers":s({type:"bg_servers",servers:m.servers});break;case"plugins":s({type:"plugins",plugins:m.plugins,epoch:m.epoch});break;case"plugin_data":mi(m.pluginId,m.payload);break}},R.onclose=()=>{if(a.current===R&&(a.current=null),l.current.clear(),!n.current||a.current&&a.current!==R)return;s({type:"status",status:"closed"});const N=Math.min(1e3*2**c.current,1e4);c.current+=1,i.current=setTimeout(()=>{i.current=null,B()},N)},R.onerror=()=>{}},[]);r.useEffect(()=>{n.current=!0,B();const R=setInterval(()=>{if(!n.current)return;const N=a.current;N&&N.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&N.close()},5e3);return()=>{var N;n.current=!1,clearInterval(R),i.current&&(clearTimeout(i.current),i.current=null),(N=a.current)==null||N.close(),a.current=null}},[B]);const E=r.useCallback(R=>s({type:"dismiss_notice",id:R}),[]),$=r.useCallback(R=>s({type:"terminal_add",meta:R}),[]),x=r.useCallback(R=>s({type:"terminal_remove",id:R}),[]),j=r.useCallback(R=>s({type:"terminal_restart",terminalId:R}),[]),P=r.useCallback((R,N,m)=>l.current.register(R,N,m),[]),D=r.useRef({chat:t,send:k,pushNotice:b,dismissNotice:E,terminal:{create:$,close:x,register:P,restart:j}});return D.current={chat:t,send:k,pushNotice:b,dismissNotice:E,terminal:{create:$,close:x,register:P,restart:j}},D.current}const Si=200*1024*1024,Ti=/windows/i.test(navigator.userAgent),Ei=/[<>:"/\\|?*\u0000-\u001f]/g,Mi=/[. ]+$/,Ri=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Pi(t){const s=t.replace(Ei,"_").replace(Mi,"");return s?Ri.test(s)?`_${s}`:s:"_"}function cs(t,s=!0){const a=new URLSearchParams({clientId:_t(),path:t,...s?{download:"1"}:{}});return ft(`/api/file?${a}`)}async function Ii(t,s){const a=Ti?Pi(s):s;try{const l=await fetch(cs(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")>Si)return window.location.assign(cs(t)),{ok:!0};const i=await l.blob();return window.showSaveFilePicker&&window.isSecureContext?Li(i,a):Pt(i,a)}catch(l){return{ok:!1,cancelled:!1,error:l instanceof Error?l.message:String(l)}}}async function Li(t,s){let a;const l=window.showSaveFilePicker;if(!l)return Pt(t,s);try{a=await l({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:Pt(t,s)}try{const c=await a.createWritable();return await c.write(t),await c.close(),{ok:!0}}catch(c){return{ok:!1,cancelled:!1,error:c instanceof Error?c.message:String(c)}}}function Pt(t,s){const a=URL.createObjectURL(t),l=document.createElement("a");return l.href=a,l.download=s,document.body.appendChild(l),l.click(),l.remove(),setTimeout(()=>URL.revokeObjectURL(a),1e4),{ok:!0}}const Di=r.memo(function({files:s,fileChanged:a,widgets:l,cwd:c,send:i,onAttach:n,onPreview:o,onNotice:u}){const p=pe(),[h,g]=r.useState(""),[y,b]=r.useState(null),[k,B]=r.useState(!1),E=1e4,$=r.useRef(0),x=r.useRef(void 0),j=r.useCallback((N,m)=>{const A=++$.current;g(N),m!=null&&m.silent||B(!0),i({type:"list_files",path:N===""?void 0:N})||$.current===A&&B(!1)},[i]);r.useEffect(()=>{s&&s.path===h&&B(!1)},[s,h]),r.useEffect(()=>{if(c!==x.current){x.current=c,j("",{silent:!0});return}const N=setInterval(()=>{document.visibilityState!=="hidden"&&j(h,{silent:!0})},E);return()=>clearInterval(N)},[c,h,j]),r.useEffect(()=>{a&&a.path===h&&j(h,{silent:!0})},[a,h,j]);const P=N=>j(N),D=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&j(s.parent)},R=h.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 ${h===""?"active":""}`,onClick:()=>j(""),children:p("rootDir")}),R.map((N,m)=>{const A=R.slice(0,m+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(ht,{}),e.jsx("button",{type:"button",className:`crumb ${A===h?"active":""}`,onClick:()=>j(A),children:N})]},A)})]}),e.jsxs("div",{className:"panel-body",children:[k&&e.jsx("div",{className:"panel-empty",children:p("loading")}),!k&&s&&s.path===h&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:D,children:[e.jsx(ze,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(N=>N.type==="dir"?e.jsxs("div",{className:"file-item dir",children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>P(N.path),children:[e.jsx(ze,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:N.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":p("linkFolderTip"),onClick:()=>n(N.path,N.name,"reference",!0),children:e.jsx(Ct,{})})]},N.path):e.jsxs("div",{className:"file-item file",children:[e.jsxs("button",{type:"button",className:"file-name",title:`${N.path} — ${p("previewFile")}`,onClick:()=>o(N.path,N.name),children:[e.jsx(As,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:N.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":p("downloadFile"),onClick:()=>{Ii(N.path,N.name).then(m=>{m.ok||m.cancelled||u("error",p("downloadFailed",{error:m.error}))})},children:e.jsx(Dt,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":p("attachInlineTip"),onClick:()=>n(N.path,N.name,"inline"),children:e.jsx(De,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":p("referenceTip"),onClick:()=>n(N.path,N.name,"reference"),children:e.jsx(Ct,{})})]},N.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:p("filesTruncated")})]}),!k&&!s&&e.jsx("div",{className:"panel-empty",children:p("noFiles")})]}),l.filter(N=>N.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:l.filter(N=>N.lines.length>0).map(N=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:p("widgetExpand"),onClick:()=>b(N.key),children:[e.jsx("span",{children:N.key}),e.jsx(Hn,{})]}),e.jsx("pre",{className:"widget-lines",children:N.lines.join(`
|
|
304
304
|
`)})]},N.key))}),y&&(()=>{const N=l.find(m=>m.key===y);return N?e.jsx("div",{className:"modal-backdrop",onClick:()=>b(null),children:e.jsxs("div",{className:"widget-expand",onClick:m=>m.stopPropagation(),children:[e.jsxs("div",{className:"widget-expand-head",children:[e.jsx("span",{className:"widget-expand-title",children:N.key}),e.jsx("button",{type:"button",className:"btn",title:p("close"),onClick:()=>b(null),children:e.jsx(ke,{})})]}),e.jsx("pre",{className:"widget-expand-lines",children:N.lines.join(`
|
|
305
305
|
`)})]})}):null})()]})});var ds=Ms();const qs=r.memo(function({text:s}){const a=pe(),[l,c]=r.useState(!1);return s?e.jsx("button",{type:"button",className:"copy-btn",title:a("copy"),onClick:()=>{navigator.clipboard.writeText(s).then(()=>{c(!0),setTimeout(()=>c(!1),1200)})},children:l?e.jsx(gt,{}):e.jsx(Bt,{})}):null});function Bi(t){const s=l=>{var c;if(typeof l=="string"||typeof l=="number"){const i=String(l);return i===""?[[]]:i.split(`
|
|
306
306
|
`).map(n=>n===""?[]:[n])}if(Array.isArray(l)){let i=[];for(const n of l){const o=s(n);if(i.length===0)i=o;else{const u=o[0]??[];i[i.length-1].push(...u),i.push(...o.slice(1))}}return i}if(l&&typeof l=="object"&&"props"in l){const i=l,n=(c=i.props)==null?void 0:c.children,o={...i.props??{},children:void 0},u=n==null?[]:s(n);return u.length===0?[[r.createElement(i.type,o)]]:u.map(p=>[r.createElement(i.type,o,...p)])}return[[l]]},a=s(t);return a.length>1&&a[a.length-1].length===0&&a.pop(),a}const Ks=[yn],zs=[[vn,{detect:!0,ignoreMissing:!0}]];function Vs({text:t}){return e.jsx(Es,{remarkPlugins:Ks,rehypePlugins:zs,components:{pre:Ai},children:t})}const xt=r.memo(function({text:s}){return e.jsx("div",{className:"md",children:e.jsx(Vs,{text:s})})});function Ai({children:t,...s}){var n;const a=t&&typeof t=="object"&&"props"in t?(n=t.props)==null?void 0:n.children:t,l=Bi(a),c=l.length>1,i=c?`${String(l.length).length+1}ch`:void 0;return e.jsxs("div",{className:"codeblock",children:[e.jsx(qs,{text:It(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:i?{width:i}:void 0,children:u+1}),e.jsx("code",{className:"code-line-body hljs",children:o})]},u))})]})}function It(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(It).join("");if(t&&typeof t=="object"&&"props"in t){const s=t.props;return It(s==null?void 0:s.children)}return""}const _i=/^\s{0,3}(`{3,}|~{3,})/,Fi=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function bt(t){return t.trim()===""}function us(t){const s=_i.exec(t);return s?s[1]:null}function $i(t){const s=t.split(`
|
|
307
307
|
`),a=[];let l=[],c=null;for(let i=0;i<s.length;i++){const n=s[i];if(c!==null){const u=us(n);u&&u[0]===c[0]&&u.length>=c.length&&(c=null),l.push(n);continue}const o=us(n);if(o&&!bt(n)){c=o,l.push(n);continue}if(bt(n)){let u=i;for(;u<s.length&&bt(s[u]);)u++;if(!(u<s.length&&Fi.test(s[u]))&&l.length>0){a.push(l.join(`
|
|
308
308
|
`)),l=[];continue}l.push(n);continue}l.push(n)}return{frozen:a,active:l.join(`
|
|
309
309
|
`),inFence:c!==null}}const Oi=r.memo(function({text:s}){return e.jsx(Es,{remarkPlugins:Ks,rehypePlugins:zs,children:s})}),ps=200;function Wi({text:t,inFence:s}){const[a,l]=r.useState(t),c=r.useRef(0),i=r.useRef(null);return r.useEffect(()=>{if(s)return;const n=Date.now()-c.current,o=()=>{c.current=Date.now(),l(t)};if(n>=ps){o();return}return i.current=setTimeout(o,ps-n),()=>{i.current&&clearTimeout(i.current)}},[t,s]),s?e.jsx("div",{className:"codeblock",children:e.jsx("pre",{children:e.jsx("code",{children:t})})}):e.jsx(Vs,{text:a})}const Hi=r.memo(function({text:s}){const{frozen:a,active:l,inFence:c}=r.useMemo(()=>$i(s),[s]);return e.jsxs("div",{className:"md",children:[a.map((i,n)=>e.jsx(Oi,{text:i},n)),l.length>0&&e.jsx(Wi,{text:l,inFence:c},a.length)]})});function Ui({thinking:t,streaming:s,wrap:a=!0}){const l=pe(),[c,i]=r.useState(null),n=c??a,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:()=>i(!n),children:[n?e.jsx(Fe,{}):e.jsx(ht,{}),e.jsx(Xe,{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 Ki(t){return qi[t]??"🛠"}const zi=r.memo(function({block:s,view:a,onKillBash:l,wrap:c=!0}){var D,R,N,m;const i=pe(),[n,o]=r.useState(c),[u,p]=r.useState(!1),h=!a.result&&a.streaming&&!a.status,g=s.name==="bash"&&h,y=a.result!==void 0,b=!a.result&&!!a.status,k=((D=a.result)==null?void 0:D.isError)??((R=a.status)==null?void 0:R.isError)??!1,B=a.result?a.result.content.map(A=>A.type==="text"?A.text:"").join(""):a.liveOutput??"",
|
|
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:()=>i(!n),children:[n?e.jsx(Fe,{}):e.jsx(ht,{}),e.jsx(Xe,{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 Ki(t){return qi[t]??"🛠"}const zi=r.memo(function({block:s,view:a,onKillBash:l,wrap:c=!0}){var D,R,N,m;const i=pe(),[n,o]=r.useState(c),[u,p]=r.useState(!1),h=!a.result&&a.streaming&&!a.status,g=s.name==="bash"&&h,y=a.result!==void 0,b=!a.result&&!!a.status,k=((D=a.result)==null?void 0:D.isError)??((R=a.status)==null?void 0:R.isError)??!1,B=a.result?a.result.content.map(A=>A.type==="text"?A.text:"").join(""):a.liveOutput??"",E=k?"err":y?"ok":h||b?"run":"idle";let $=i(k?"error":y?"done":h?"running":b?"toolDoneWaitingModel":"toolQueued");const x=b&&((N=a.status)==null?void 0:N.durationMs)!==void 0?Gi(a.status.durationMs):"";b&&x&&($=`${$} · ${x}`);const j=b&&((m=a.status)==null?void 0:m.exitCode)!==void 0?`exit ${a.status.exitCode}`:"",P=()=>{s.argumentsText&&(navigator.clipboard.writeText(s.argumentsText),p(!0),setTimeout(()=>p(!1),1200))};return e.jsxs("div",{className:`toolcall ${E}`,children:[e.jsxs("div",{className:"toolcall-head",children:[e.jsx("span",{className:"toolcall-icon",children:Ki(s.name)}),e.jsx("span",{className:"toolcall-name",children:s.name}),e.jsxs("span",{className:"toolcall-status",children:[$,j&&e.jsx("em",{className:"toolcall-exit",children:j})]}),e.jsx("span",{className:"toolcall-spacer"}),g&&l&&e.jsxs("button",{type:"button",className:"toolcall-kill",title:i("stopBashTip"),onClick:l,children:[e.jsx(ot,{}),e.jsx("span",{children:i("stopBash")})]}),e.jsx("button",{type:"button",className:"toolcall-copy",title:i("copyArgs"),onClick:P,children:u?e.jsx(Qn,{}):e.jsx(Bt,{})}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>o(A=>!A),children:n?e.jsx(Fe,{}):e.jsx(ht,{})})]}),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(Vi,{args:s.argumentsText}):e.jsx("pre",{children:s.argumentsText})}),B.length>0&&e.jsxs("div",{className:"toolcall-output",children:[e.jsxs("div",{className:"toolcall-output-label",children:[i(k?"errorOutput":"output"),(h||b)&&e.jsx("span",{className:"cursor"})]}),e.jsx("pre",{children:B})]}),h&&B.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",i("waitingOutput")]}),b&&B.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",i("waitingModel")]})]})]})});function Vi({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(qe,{className:"termline-icon"}),e.jsx("code",{children:s.command}),typeof s.timeout=="number"&&e.jsxs("span",{className:"termline-timeout",children:["⏱ ",s.timeout,"s"]})]})}function Gi(t){if(t===void 0)return"";const s=t/1e3;if(s<60)return`${s.toFixed(1)}s`;const a=Math.floor(s/60),l=Math.round(s%60);return`${a}m ${String(l).padStart(2,"0")}s`}const Ji=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function Ft(t){var a;const s=t.match(Ji);return s?{name:s[1],location:s[2],content:s[3],userMessage:((a=s[4])==null?void 0:a.trim())||void 0}:null}const Yi=1568,Qi=2*1024*1024;function Me(t){return t.startsWith("image/")&&t!=="image/svg+xml"&&t!=="image/svg"}async function Gs(t){if(!t.type.startsWith("image/"))return null;let s;try{s=await createImageBitmap(t,{imageOrientation:"from-image"})}catch{return null}try{const a=Math.min(1,Yi/Math.max(s.width,s.height)),l=Math.max(1,Math.round(s.width*a)),c=Math.max(1,Math.round(s.height*a)),i=t.type==="image/jpeg"||t.type==="image/jpg"?[["image/jpeg",.85],["image/jpeg",.6],["image/webp",.8]]:[["image/png",1],["image/jpeg",.85],["image/jpeg",.6]];let n=null;for(const[o,u]of i){const p=document.createElement("canvas");p.width=l,p.height=c;const h=p.getContext("2d");if(!h)continue;o!=="image/png"&&(h.fillStyle="#ffffff",h.fillRect(0,0,l,c)),h.drawImage(s,0,0,l,c);const g=p.toDataURL(o,u),y=g.match(/^data:([^;]+);base64,/),b=y?y[1]:o,k=g.replace(/^data:[^;]*;base64,/,""),B=Math.floor(k.length*3/4);if(n={data:k,mimeType:b,name:t.name,size:B},B<=Qi)return n}return n}finally{s.close()}}const Xi=20*1024*1024;function Ze(t){return t.type==="text"&&typeof t.text=="string"?t:null}function Js(t){return t.type==="thinking"&&typeof t.thinking=="string"?t:null}function Ys(t){return t.type==="toolCall"&&typeof t.id=="string"&&typeof t.name=="string"?t:null}function Qs(t){return t.type==="image"&&typeof t.dataUrl=="string"?t:null}function Xs(t){return t.type==="bash"&&typeof t.command=="string"?t:null}function Zi(t){return t.imageData?"image":t.uploadPath?"upload":t.fileData?"file":"path"}function ea(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 a=t.path.split("/").pop()??t.path;return t.mode==="lines"&&t.lines?s("attachLines",{path:a,start:t.lines.start,end:t.lines.end}):t.mode==="reference"?s("refOnly",{path:a}):s("attachContent",{path:a})}const ms=r.memo(function({message:s,toolResults:a,liveOutputs:l,toolStatuses:c,streaming:i,isLast:n,onEdit:o,onKillBash:u,onCollapse:p,questionAttachments:h,qnIndex:g,qnActive:y,onJump:b,thinkingWrap:k,toolsWrap:B}){const E=pe(),[$,x]=r.useState(!1),[j,P]=r.useState(""),[D,R]=r.useState([]),[N,m]=r.useState(!1),[A,W]=r.useState(null),ee=F=>{W(F),window.setTimeout(()=>W(z=>z===F?null:z),4e3)};if(s.role==="toolResult")return null;const ie=s.role==="custom"&&s.customType==="file",H=s.content.map(F=>{var z;return((z=Ze(F))==null?void 0:z.text)??""}).filter(Boolean).join(`
|
|
311
311
|
`),q=s.role==="user"?Ft(H):null,L=q?q.userMessage??`skill:${q.name}`:H.split(`
|
|
312
|
-
`).join(" ").trim(),
|
|
313
|
-
`)),R(h??[]),x(!0)},Z=()=>{const F=j.trim();F&&(o==null||o(s.id,F,D.length>0?D:void 0),x(!1))},te=s.role==="custom"&&(s.customType==="goal-review"||s.customType==="goal-wizard"),
|
|
314
|
-
`).length+1)),onChange:F=>P(F.target.value),onPaste:F=>{var ne;const z=[];for(const G of((ne=F.clipboardData)==null?void 0:ne.items)??[])if(G.kind==="file"&&Me(G.type)){const oe=G.getAsFile();oe&&z.push(oe)}z.length!==0&&(F.preventDefault(),K(z))},onKeyDown:F=>{F.key==="Enter"&&(F.metaKey||F.ctrlKey)?(F.preventDefault(),Z()):F.key==="Escape"&&x(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(zn,{})," ",
|
|
312
|
+
`).join(" ").trim(),S=i&&n&&s.content.length===0,C=s.role==="user"&&!i&&!S&&!!o,K=async F=>{const z=[];for(const ne of F){if(!Me(ne.type))continue;const G=await Gs(ne);G&&z.push({path:"",imageData:G.data,mimeType:G.mimeType,name:G.name})}z.length>0&&R(ne=>[...ne,...z])},me=async F=>{if(F.size>Xi){ee(E("fileTooLarge",{name:F.name,size:20}));return}let z;try{z=(await new Promise((G,oe)=>{const X=new FileReader;X.onload=()=>G(X.result),X.onerror=()=>oe(X.error??new Error("read failed")),X.readAsDataURL(F)})).replace(/^data:[^;]*;base64,/,"")}catch{ee(E("fileLoadFailed",{name:F.name}));return}R(ne=>[...ne,{path:"",fileData:z,name:F.name,size:F.size,mimeType:F.type||void 0}])},J=async F=>{const z=[];for(const ne of F)Me(ne.type)?z.push(ne):me(ne);z.length>0&&await K(z)},T=()=>{P(q?`/skill:${q.name}${q.userMessage?` ${q.userMessage}`:""}`:s.content.map(F=>{var z;return((z=Ze(F))==null?void 0:z.text)??""}).filter(Boolean).join(`
|
|
313
|
+
`)),R(h??[]),x(!0)},Z=()=>{const F=j.trim();F&&(o==null||o(s.id,F,D.length>0?D:void 0),x(!1))},te=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}${te?" 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?E("goalWizardCard"):te?E("goalBarTitle"):s.customType==="file"?E("attachment"):`${E("plugin")} · ${s.customType??E("unknown")}`:Zs(s.role,E)}),s.model&&e.jsx("span",{className:"msg-model",children:s.model}),s.timestamp&&e.jsx("span",{className:"msg-time",children:ia(s.timestamp)}),p&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:E("collapseMsg"),onClick:()=>p(s.id),children:[e.jsx(mt,{})," ",E("collapseMsg")]}),g!==void 0&&b&&e.jsxs("button",{type:"button",className:`qn-tag ${y?"active":""}`,title:`${g+1}. ${L}`,"aria-label":`${g+1}. ${L}`,onClick:()=>b(s.id),children:[e.jsx("span",{className:"qn-tag-bar"}),e.jsx("span",{className:"qn-tag-idx",children:g+1})]})]}),e.jsx("div",{className:"msg-body",children:$?e.jsxs("div",{className:`msg-editor${N?" drag-over":""}`,onDragOver:F=>{F.preventDefault(),F.stopPropagation(),m(!0)},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||m(!1)},onDrop:F=>{var z;F.preventDefault(),F.stopPropagation(),m(!1),J(Array.from(((z=F.dataTransfer)==null?void 0:z.files)??[]))},children:[D.length>0&&e.jsx("div",{className:"msg-editor-images",children:D.map((F,z)=>{var G;const ne=Zi(F);return e.jsxs("span",{className:`msg-editor-img ${ne==="image"?"":"file-chip"}`,title:ea(F,E),children:[ne==="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:ne==="path"?F.mode==="reference"?"🔗":"📎":"📄"}),e.jsx("span",{className:"msg-editor-file-name",children:F.name??((G=F.path)==null?void 0:G.split("/").pop())})]}),e.jsx("button",{type:"button",className:"msg-editor-img-remove",title:E("removeAttachment"),onClick:()=>R(oe=>oe.filter((X,d)=>d!==z)),children:e.jsx(ke,{})})]},`${F.name??F.path??"att"}-${z}`)})}),A&&e.jsx("div",{className:"msg-editor-notice",children:A}),e.jsx("textarea",{className:"msg-editor-input",value:j,autoFocus:!0,placeholder:E("editPlaceholder"),rows:Math.max(2,Math.min(10,j.split(`
|
|
314
|
+
`).length+1)),onChange:F=>P(F.target.value),onPaste:F=>{var ne;const z=[];for(const G of((ne=F.clipboardData)==null?void 0:ne.items)??[])if(G.kind==="file"&&Me(G.type)){const oe=G.getAsFile();oe&&z.push(oe)}z.length!==0&&(F.preventDefault(),K(z))},onKeyDown:F=>{F.key==="Enter"&&(F.metaKey||F.ctrlKey)?(F.preventDefault(),Z()):F.key==="Escape"&&x(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(zn,{})," ",E("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>x(!1),children:E("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!j.trim(),title:E("reaskFromHere"),onClick:Z,children:[e.jsx(Tt,{})," ",E("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),ie?e.jsx(ta,{message:s}):q?e.jsxs(e.Fragment,{children:[e.jsx(na,{block:q}),q.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(xt,{text:q.userMessage})}),s.content.map((F,z)=>F.type==="text"?null:e.jsx(gs,{block:F,toolResults:a,liveOutputs:l,toolStatuses:c,streaming:i,isLast:n,onKillBash:u,toolsWrap:B,thinkingWrap:k},`${s.id}-${z}`))]}):s.content.map((F,z)=>e.jsx(gs,{block:F,toolResults:a,liveOutputs:l,toolStatuses:c,streaming:i,isLast:n,onKillBash:u,toolsWrap:B,thinkingWrap:k},`${s.id}-${z}`)),S&&e.jsxs("div",{className:"thinking-wait",children:[E("thinkingWait"),e.jsx("span",{className:"dot"})]}),i&&n&&!S&&e.jsx("span",{className:"stream-cursor"})]})}),C&&!$&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:E("editReaskTip"),onClick:T,children:[e.jsx(Tt,{})," ",E("editReask")]})})]})});function ta({message:t}){const s=pe(),[a,l]=r.useState(!1),c=t.details??{},i=c.name??c.path??s("attachment"),n=c.type==="folder",o=c.mode==="reference",u=c.mode==="bridged",p=t.content.filter(b=>b.type==="text").map(b=>b.text).join(`
|
|
315
315
|
`),h=sa(p),g=t.content.find(b=>b.type==="image"),y=h.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:i}),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")} · ${hs(c.size)}`:u?s("bridgedVision"):g?s("image"):c.mode==="lines"?s("inlineLinesRange",{start:c.startLine??1,end:c.endLine??c.lines??1}):s("inlineLines",{n:c.lines??y})}),!o&&(a?e.jsx(Fe,{}):e.jsx(ht,{}))]}),!o&&a&&(u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:s("bridgedVisionDetail")}),(g==null?void 0:g.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:g.dataUrl,alt:i})}),h&&e.jsx("pre",{className:"attachcard-content",children:h})]}):g!=null&&g.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:g.dataUrl,alt:i})}):e.jsx("pre",{className:"attachcard-content",children:h})),o&&e.jsx("div",{className:"attachcard-refnote",children:n?s("folderNotExpanded"):s("fileNotExpanded",{size:hs(c.size)})})]})}function hs(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function sa(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 a=t.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return a?a[1].trim():t.trim()}function na({block:t}){const s=pe(),[a,l]=r.useState(!1);return e.jsxs("div",{className:`skillcard${a?" 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(Xn,{})}),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:[a?e.jsx(mt,{}):e.jsx(Fe,{}),s(a?"collapseMsg":"expandMsg")]})]}),a&&e.jsx("div",{className:"skillcard-body",children:e.jsx(xt,{text:t.content})})]})}function gs({block:t,toolResults:s,liveOutputs:a,toolStatuses:l,streaming:c,isLast:i,onKillBash:n,thinkingWrap:o,toolsWrap:u}){const p=pe(),h=Ze(t);if(h){const B=c&&i;return e.jsxs("div",{className:"msg-text",children:[B?e.jsx(Hi,{text:h.text}):e.jsx(xt,{text:h.text}),h.truncated&&e.jsx("div",{className:"trunc-note",children:p("truncated")})]})}const g=Js(t);if(g)return e.jsx(Ui,{thinking:g.thinking,streaming:c&&i,wrap:o});const y=Ys(t);if(y){const B=s.get(y.id),
|
|
317
|
-
`)}function fa(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 xa(t,s){const a=s.trim().toLowerCase();if(!a)return 0;const l=t.toLowerCase();let c=0,i=l.indexOf(a);for(;i!==-1;)c++,i=l.indexOf(a,i+a.length);return c}function va(t,s){const a=s.trim().toLowerCase();if(!a)return[];const l=[];for(const c of t){const i=ga(c);if(!i)continue;const n=xa(i,a);for(let o=0;o<n;o++)l.push({messageId:c.id,occurrence:o})}return l}function ya(t,s){var n;const a=new Map,l=[],c=s.toLowerCase();if(!c)return{byMsg:a,all:l};const i=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(o){const u=o.parentElement;return!u||u.closest(".search-bar")?NodeFilter.FILTER_REJECT:(o.textContent??"").toLowerCase().includes(c)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let o=i.nextNode();o;o=i.nextNode()){const u=(o.textContent??"").toLowerCase(),p=(n=o.parentElement)==null?void 0:n.closest("[data-msg-id]");if(!p)continue;const h=p.getAttribute("data-msg-id")??"";let g=u.indexOf(c);for(;g!==-1;){const y=document.createRange();y.setStart(o,g),y.setEnd(o,g+c.length),l.push(y);const b=a.get(h);b?b.push(y):a.set(h,[y]),g=u.indexOf(c,g+c.length)}}return{byMsg:a,all:l}}function He(t,s){const a=CSS;if(!a.highlights)return;if(s.length===0){a.highlights.delete(t);return}const l=window.Highlight;l&&a.highlights.set(t,new l(...s))}function ka({containerRef:t,messages:s,open:a,onClose:l,onEnsureExpanded:c}){const i=pe(),n=r.useRef(null),[o,u]=r.useState(""),[p,h]=r.useState(0),g=r.useDeferredValue(o),y=a?g.trim():"",b=r.useMemo(()=>a?va(s,y):[],[s,y,a]),k=r.useRef(b);k.current=b;const B=r.useRef(p);B.current=p,r.useEffect(()=>{a&&(h(0),requestAnimationFrame(()=>{var j;return(j=n.current)==null?void 0:j.select()}))},[a]),r.useEffect(()=>{if(!a)return;const j=P=>{P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),l())};return window.addEventListener("keydown",j,!0),()=>window.removeEventListener("keydown",j,!0)},[a,l]),r.useEffect(()=>(a||(He("msg-search",[]),He("msg-search-active",[])),()=>{He("msg-search",[]),He("msg-search-active",[])}),[a]);const M=r.useCallback(j=>{const P=t.current;if(!P)return;const D=P.querySelector(`[data-msg-id="${j}"]`);D&&(D.classList.remove("msg-flash"),D.offsetWidth,D.classList.add("msg-flash"))},[t]);r.useLayoutEffect(()=>{if(!a||!y)return;const j=t.current;if(!j)return;let P=!1,D=0;return D=requestAnimationFrame(()=>{var ee;if(P)return;const{byMsg:R,all:N}=ya(j,y);He("msg-search",N);const m=k.current,A=m[Math.min(B.current,m.length-1)];if(!A)return;const W=(ee=R.get(A.messageId))==null?void 0:ee[A.occurrence];if(W){He("msg-search-active",[W]);const ie=W.startContainer.parentElement??j.querySelector(`[data-msg-id="${A.messageId}"]`);ie==null||ie.scrollIntoView({block:"center"})}else M(A.messageId)}),()=>{P=!0,cancelAnimationFrame(D)}},[a,y,b,t,M]);const $=r.useCallback(j=>{const P=k.current;if(P.length===0)return;const D=(B.current+j+P.length)%P.length;h(D),c(P[D].messageId)},[c]);if(!a)return null;const x=b.length;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:n,className:"search-input",type:"text",value:o,placeholder:i("searchPlaceholder"),onChange:j=>{u(j.target.value),h(0)},onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),$(j.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${x===0?"empty":""}`,children:x===0?i("searchNoResults"):`${Math.min(p+1,x)}/${x}`}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchPrev"),disabled:x===0,onClick:()=>$(-1),children:e.jsx(mt,{})}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchNext"),disabled:x===0,onClick:()=>$(1),children:e.jsx(Fe,{})}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchClose"),onClick:l,children:e.jsx(ke,{})})]})}function ba(t){const{dSt:s,dSh:a,escaped:l,graceActive:c,stuck:i}=t;return c?{flipEscape:!1,reassert:!1}:s>=-4||s<=-500?{flipEscape:!1,reassert:!1}:a<0?{flipEscape:!1,reassert:i&&!l}:{flipEscape:!0,reassert:!1}}const tn=[{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"}],sn="pi-web-ui:prompt-templates";function ja(){try{const t=localStorage.getItem(sn);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(a=>!!a&&typeof a=="object"&&typeof a.id=="string"):[]}catch{return[]}}function xs(t){return tn.some(s=>s.id===t)}function tt(t){return typeof t.title=="string"}const nn=r.createContext(null);function an(){const t=r.useContext(nn);if(!t)throw new Error("useTemplates must be used within TemplateProvider");return t}function wa({send:t,children:s}){const a=pe(),[l,c]=r.useState(ja),[i,n]=r.useState(!1),[o,u]=r.useState(null),[p,h]=r.useState(!1),[g,y]=r.useState(!1),[b,k]=r.useState(!1);r.useEffect(()=>{try{localStorage.setItem(sn,JSON.stringify(l))}catch{}},[l]);const B=r.useMemo(()=>{const H=new Map,q=new Set;for(const C of l)C.hidden?q.add(C.id):(tt(C)&&!xs(C.id)||tt(C))&&H.set(C.id,C);const L=tn.filter(C=>!q.has(C.id)).map(C=>{const K=H.get(C.id);return{id:C.id,icon:(K==null?void 0:K.icon)??C.icon,title:(K==null?void 0:K.title)??a(C.titleKey),desc:(K==null?void 0:K.desc)??a(C.descKey),prompt:(K==null?void 0:K.prompt)??a(C.promptKey),builtin:!0}}),T=l.filter(C=>tt(C)&&!xs(C.id)).map(C=>({id:C.id,icon:C.icon??"📌",title:C.title??"",desc:C.desc??"",prompt:C.prompt??""}));return[...L,...T]},[l,a]),M=r.useCallback(()=>n(!0),[]),$=r.useCallback(H=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:H}))},[]),x=r.useCallback((H,q=!1)=>{k(q),H?(h(!1),u({...H})):(h(!0),u({id:Re(),icon:"📌",title:"",desc:"",prompt:""}))},[]),j=r.useCallback(()=>{n(!1),u(null),k(!1)},[]),P=r.useCallback(()=>{g?(c([]),y(!1)):(y(!0),setTimeout(()=>y(!1),5e3))},[g]),D=r.useCallback(H=>{n(!1),$(H.prompt)},[$]),R=r.useCallback(H=>{n(!1),x(H,!0)},[x]),N=r.useCallback(()=>{n(!1),x(void 0,!0)},[x]),m=r.useCallback(H=>{c(q=>{const L=q.findIndex(T=>T.id===H.id);if(L>=0){const T=[...q];return T[L]=H,T}return[...q,H]}),u(null),b&&(n(!0),k(!1))},[b]),A=r.useCallback(H=>{c(q=>H.builtin?[...q.filter(T=>T.id!==H.id),{id:H.id,hidden:!0}]:q.filter(L=>L.id!==H.id)),u(null),b&&(n(!0),k(!1))},[b]),W=r.useCallback(H=>{c(q=>q.filter(L=>L.id!==H.id||L.hidden)),u(null),b&&(n(!0),k(!1))},[b]),ee=r.useMemo(()=>({templates:B,fill:$,openPicker:M,openEdit:x,resetConfirm:g,toggleReset:P}),[B,$,M,x,g,P]),ie=o?l.some(H=>H.id===o.id&&!H.hidden&&tt(H)):!1;return e.jsxs(nn.Provider,{value:ee,children:[s,i&&e.jsx(Ca,{templates:B,resetConfirm:g,onFill:D,onEditTpl:R,onNew:N,onResetToggle:P,onClose:j}),o&&e.jsx(Sa,{editing:o,isNew:p,hasOverride:ie,onDraft:u,onSave:m,onRestore:()=>W(o),onRemove:()=>A(o),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:o.prompt})),j()},onSend:()=>{const H=o.prompt.trim();H&&t({type:"prompt",text:H,queue:!1})&&j()},onClose:j})]})}function Na(){const t=pe(),{templates:s,fill:a,openEdit:l,toggleReset:c,resetConfirm:i}=an();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(rn,{tpl:n,title:t("tpl.clickCard"),onFill:()=>a(n.prompt),onEdit:()=>l(n),editTitle:t("tpl.editTpl")},n.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>l(),title:t("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(De,{})}),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(Bs,{}),t(i?"tpl.resetConfirm":"tpl.reset")]})})]})}function rn({tpl:t,title:s,onFill:a,onEdit:l,editTitle:c}){const i=pe();return e.jsxs("button",{type:"button",className:"empty-template",title:s,onClick:a,children:[e.jsx("span",{className:"empty-template-icon",children:t.icon}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t.title}),e.jsx("span",{className:"empty-template-desc",children:t.desc})]}),e.jsx("span",{className:"template-card-ops",role:"button",title:c??i("tpl.editTpl"),onClick:n=>{n.stopPropagation(),l()},children:e.jsx(Et,{})})]})}function Ca({templates:t,resetConfirm:s,onFill:a,onEditTpl:l,onNew:c,onResetToggle:i,onClose:n}){const o=pe();return r.useEffect(()=>{const u=p=>{p.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(ke,{})})]}),e.jsx("div",{className:"template-picker-hint",children:o("tpl.pickerHint")}),e.jsxs("div",{className:"template-picker-grid",children:[t.map(u=>e.jsx(rn,{tpl:u,title:o("tpl.clickCard"),onFill:()=>a(u),onEdit:()=>l(u),editTitle:o("tpl.editTpl")},u.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:c,title:o("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(De,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:o("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:o("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"template-picker-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:i,children:[e.jsx(Bs,{}),o(s?"tpl.resetConfirm":"tpl.reset")]})})]})})}function Sa({editing:t,isNew:s,hasOverride:a,onDraft:l,onSave:c,onRestore:i,onRemove:n,onFill:o,onSend:u,onClose:p}){const h=pe(),g=r.useRef(null);r.useEffect(()=>{const k=B=>{B.key==="Escape"&&p()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[p]),r.useEffect(()=>{const k=g.current;if(!k)return;k.style.height="auto";const B=k.scrollHeight>300;k.style.height=`${Math.min(k.scrollHeight,300)}px`,k.style.overflowY=B?"auto":"hidden"},[t.prompt]);const y=()=>{const k=t.title.trim(),B=t.prompt.trim();if(!k||!B){l({...t,error:h("tpl.required")});return}c({id:t.id,icon:t.icon.trim()||"📌",title:k,desc:t.desc.trim(),prompt:B})},b=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:p,children:e.jsxs("div",{className:"modal template-modal",onClick:k=>k.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:h(b?"tpl.builtin":"tpl.custom")}),e.jsx("span",{className:"template-modal-title",children:h(s?"tpl.newTitle":"tpl.editTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:h("close"),onClick:p,children:e.jsx(ke,{})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:h("tpl.fieldIcon")}),e.jsx("input",{className:"template-field-input icon",value:t.icon,maxLength:4,onChange:k=>l({...t,icon:k.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:h("tpl.fieldTitle")}),e.jsx("input",{className:"template-field-input",value:t.title,placeholder:h("tpl.fieldTitlePh"),onChange:k=>l({...t,title:k.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:h("tpl.fieldDesc")}),e.jsx("input",{className:"template-field-input",value:t.desc,placeholder:h("tpl.fieldDescPh"),onChange:k=>l({...t,desc:k.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:h("tpl.fieldPrompt")}),e.jsx("textarea",{ref:g,className:"template-field-prompt",value:t.prompt,placeholder:h("tpl.fieldPromptPh"),onChange:k=>l({...t,prompt:k.target.value})})]}),t.error&&e.jsx("div",{className:"template-error",children:t.error}),e.jsxs("div",{className:"template-modal-actions",children:[e.jsxs("div",{className:"template-modal-actions-left",children:[!s&&b&&a&&e.jsx("button",{type:"button",className:"btn template-btn ghost",title:h("tpl.restoreTip"),onClick:i,children:h("tpl.restore")}),!s&&b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:h("tpl.removeTip"),onClick:n,children:[e.jsx(Ee,{})," ",h("tpl.remove")]}),!s&&!b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:h("tpl.deleteTip"),onClick:n,children:[e.jsx(Ee,{})," ",h("tpl.delete")]})]}),e.jsxs("div",{className:"template-modal-actions-right",children:[e.jsx("button",{type:"button",className:"btn template-btn",onClick:y,children:h("tpl.save")}),e.jsx("button",{type:"button",className:"btn template-btn fill",onClick:o,title:h("tpl.fillTip"),children:h("tpl.fill")}),e.jsxs("button",{type:"button",className:"btn template-btn send",onClick:u,title:h("tpl.sendTip"),children:[e.jsx(Ds,{})," ",h("tpl.sendNow")]})]})]})]})})}const vs=new Map,Ta=15,ys=30,jt=250,ks=1200,Ea=1600;function bs(t){return t.content.some(s=>s.type==="toolCall")}function Ma({state:t,liveOutputs:s,toolStatuses:a,onEdit:l,onKillBash:c,thinkingWrap:i,toolsWrap:n}){const o=pe(),u=r.useRef(null),[p,h]=r.useState(!0),g=r.useRef(!0),y=r.useRef(0),b=r.useRef(0),k=r.useRef(!1),B=r.useRef(0),[M,$]=r.useState(()=>new Set),[x,j]=r.useState(!1),P=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,D=r.useMemo(()=>{const f=new Map;for(const v of t.messages)v.role==="toolResult"&&v.toolCallId&&f.set(v.toolCallId,v);return f},[t.messages]),R=r.useMemo(()=>aa(t.messages),[t.messages]),N=P.length>0?P[P.length-1].id:null,m=t.messages.length>ys?Math.max(0,t.messages.length-Ta):0,[A,W]=r.useState(()=>new Set),[ee,ie]=r.useState(()=>new Set),H=r.useRef(new Map),q=r.useRef(new Map),L=r.useRef(new Map),T=r.useRef(0),C=r.useMemo(()=>{const f=new Map;for(const v of t.messages)f.set(v.id,ma(v));return f},[t.messages]),K=r.useRef(C);K.current=C;const me=r.useRef(A);me.current=A;const J=t.messages.length>ys&&!x,E=r.useRef(J);E.current=J;const Z=ua(t.messages,H.current,Ea),te=r.useRef(Z);te.current=Z;const S=r.useCallback(()=>{const f=u.current;if(!f)return;if(!E.current){W(de=>de.size?new Set:de);return}const v=f.getBoundingClientRect(),V={top:v.top-ks,bottom:v.bottom+ks},O=[];for(const[de,ye]of L.current){const Se=ye.getBoundingClientRect();O.push({id:de,top:Se.top,bottom:Se.bottom}),me.current.has(de)||ne(de,Se.bottom-Se.top,K.current.get(de))}const ae=ca(O,V,te.current,me.current);for(const de of ae.hide){const ye=L.current.get(de);ye&&ne(de,ye.offsetHeight,K.current.get(de))}W(de=>da(de,ae))},[]),F=r.useCallback(()=>{T.current||(T.current=requestAnimationFrame(()=>{T.current=0,S()}))},[S]);r.useLayoutEffect(()=>{S()},[S]);const z=r.useRef(x);r.useLayoutEffect(()=>{z.current&&!x&&S(),z.current=x},[x,S]);const ne=r.useCallback((f,v,V)=>{V!==void 0&&(q.current.set(f,{h:v,len:V}),H.current.set(f,v))},[]),G=r.useCallback((f,v)=>{ne(f,v,K.current.get(f))},[ne]),oe=r.useCallback(f=>{f&&L.current.set(f.dataset.lazyId??"",f)},[]);r.useEffect(()=>{const f=new Set(t.messages.map(v=>v.id));for(const[v,V]of L.current)f.has(v)||(L.current.delete(v),H.current.delete(v),q.current.delete(v));W(v=>{let V=!1;const O=new Set;for(const ae of v)f.has(ae)?O.add(ae):V=!0;return V?O:v})},[t.messages,M]),r.useEffect(()=>()=>cancelAnimationFrame(T.current),[]);const X=r.useMemo(()=>{const f=[];for(const v of t.messages){if(v.role!=="user")continue;const V=v.content.map(de=>{var ye;return((ye=Ze(de))==null?void 0:ye.text)??""}).filter(Boolean).join(" "),O=Ft(V),ae=O?O.userMessage??`skill:${O.name}`:V.trim();ae&&f.push({id:v.id,text:ae})}return f},[t.messages]),d=r.useMemo(()=>{const f=new Map;return X.forEach((v,V)=>f.set(v.id,V)),f},[X]),[I,ce]=r.useState(-1),se=r.useRef(-1),he=r.useRef(X);r.useEffect(()=>{he.current=X},[X]);const Q=r.useCallback(()=>{const f=u.current,v=he.current;if(!f||v.length===0)return;const V=f.getBoundingClientRect().top,O=140;let ae=-1;for(let de=0;de<v.length;de++){const ye=f.querySelector(`[data-msg-id="${v[de].id}"]`);if(ye)if(ye.getBoundingClientRect().top<=V+O)ae=de;else break}ae!==se.current&&(se.current=ae,ce(ae))},[]);r.useEffect(()=>{Q()},[X,Q]);const le=r.useCallback(f=>{$(v=>v.has(f)?v:new Set(v).add(f))},[]),ge=r.useCallback(f=>{const v=t.messages.findIndex(V=>V.id===f);v>=0&&v<m&&!M.has(f)&&ds.flushSync(()=>le(f))},[t.messages,m,M,le]);r.useEffect(()=>{const f=v=>{if(!(v.ctrlKey||v.metaKey)||v.key.toLowerCase()!=="f")return;const V=v.target;V&&(V.tagName==="INPUT"||V.tagName==="TEXTAREA"||V.isContentEditable)||(v.preventDefault(),j(!0))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[]);const ue=r.useCallback(f=>{$(v=>{if(!v.has(f))return v;const V=new Set(v);return V.delete(f),V})},[]),we=r.useCallback(f=>{const v=t.messages.findIndex(O=>O.id===f);ds.flushSync(()=>{v>=0&&v<m&&!M.has(f)&&le(f),ie(O=>O.has(f)?O:new Set(O).add(f))});const V=he.current.findIndex(O=>O.id===f);se.current=V,ce(V),requestAnimationFrame(()=>{var ae,de,ye;const O=(ae=u.current)==null?void 0:ae.querySelector(`[data-msg-id="${f}"]`);O&&((de=u.current)==null||de.querySelectorAll(".msg-flash").forEach(Se=>Se.classList.remove("msg-flash")),O.scrollIntoView({block:"start"}),O.classList.remove("msg-flash"),O.offsetWidth,O.classList.add("msg-flash"),O!==((ye=u.current)==null?void 0:ye.lastElementChild)&&(k.current=!0))})},[t.messages,m,M,le]),Be=r.useCallback(()=>{const f=u.current;if(!f)return;const v=f.scrollTop-y.current,V=f.scrollHeight-b.current;y.current=f.scrollTop,b.current=f.scrollHeight;const O=f.scrollHeight-f.scrollTop-f.clientHeight<80,ae=Date.now()<B.current,de=ba({dSt:v,dSh:V,escaped:k.current,graceActive:ae,stuck:g.current});de.reassert&&(B.current=Date.now()+jt,f.scrollTop=f.scrollHeight),de.flipEscape&&(k.current=!0),O&&v>=0&&(k.current=!1),ae||(v<0?g.current=O&&!k.current:O&&(g.current=!0)),h(g.current),Q(),F()},[Q,F]),$e=r.useRef(!1);r.useEffect(()=>{const f=$e.current;if($e.current=!!t.isStreaming,f&&!t.isStreaming&&!k.current){const v=()=>{const O=u.current;O&&!k.current&&(O.scrollTop=O.scrollHeight,g.current=!0,h(!0))};requestAnimationFrame(()=>requestAnimationFrame(v));const V=setTimeout(v,180);return()=>clearTimeout(V)}},[t.isStreaming]),r.useEffect(()=>{const f=u.current;f&&g.current&&(f.scrollTop=f.scrollHeight)},[P,t.isStreaming,s]);const Ve=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");r.useEffect(()=>{const f=u.current;f&&g.current&&(f.scrollTop=f.scrollHeight)},[Ve]),r.useEffect(()=>{const f=u.current;if(!f||typeof ResizeObserver>"u")return;const v=new ResizeObserver(()=>{g.current&&!k.current&&(f.scrollTop=f.scrollHeight,h(!0))});return v.observe(f),()=>v.disconnect()},[]),r.useEffect(()=>{const f=u.current;if(!f||typeof MutationObserver>"u")return;let v=!1;const V=new MutationObserver(()=>{v||(v=!0,requestAnimationFrame(()=>{v=!1;const O=u.current;O&&g.current&&!k.current&&(O.scrollTop=O.scrollHeight,h(!0))}))});return V.observe(f,{childList:!0,subtree:!0,characterData:!0}),()=>V.disconnect()},[]);const Ge=r.useCallback(()=>{if(!u.current)return;g.current=!0,k.current=!1,h(!0),B.current=Date.now()+jt;const v=()=>{const V=u.current;!V||!g.current||k.current||(B.current=Date.now()+jt,V.scrollTop=V.scrollHeight)};v(),requestAnimationFrame(()=>requestAnimationFrame(v)),setTimeout(v,120),setTimeout(v,300),setTimeout(v,600)},[]),Ce=r.useRef(null);r.useEffect(()=>{const f=Ce.current,v=u.current;if(!f||!v)return;const V=O=>{O.preventDefault();const ae=f.querySelector(".qn-list");if(ae&&ae.contains(O.target)&&ae.scrollHeight>ae.clientHeight){ae.scrollTop+=O.deltaY;return}v.scrollTop+=O.deltaY};return f.addEventListener("wheel",V,{passive:!1}),()=>f.removeEventListener("wheel",V)},[]);const[Oe,Ae]=r.useState(0);r.useEffect(()=>{const f=()=>{var v;Ae(((v=u.current)==null?void 0:v.clientHeight)??0),F()};return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[F]);const Ne=X.length,Pe=r.useMemo(()=>Ne===0?27:Math.max(4,Math.min(27,Math.floor(((Oe||600)-16)/Ne)-3)),[Ne,Oe]),w=Pe<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:`messages${p?"":" anchor-live"}`,ref:u,onScroll:Be,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(Na,{})}),t.messages.map((f,v)=>{const V=v<m,O=V&&M.has(f.id);if(V&&!O)return f.role==="toolResult"?null:e.jsx(ra,{message:f,onExpand:le},f.id);const ae=f.role==="user"?d.get(f.id):void 0,de=!J||Z.has(f.id)||ee.has(f.id)||!A.has(f.id);return e.jsx(oa,{id:f.id,show:de,height:ha(f.id,C.get(f.id)??-1,q.current,en(f.role,f.customType)),containerRef:u,onMeasured:G,lazyRef:oe,children:e.jsx(ms,{message:f,qnIndex:ae,qnActive:ae!==void 0?ae===I:void 0,onJump:we,toolResults:D,liveOutputs:bs(f)?s:vs,toolStatuses:a,streaming:t.isStreaming,onKillBash:c,toolsWrap:n,thinkingWrap:i,isLast:f.id===N,onEdit:l,questionAttachments:R.get(f.id),onCollapse:O?ue:void 0},f.id)},f.id)}),t.streamingMessage&&e.jsx(ms,{message:t.streamingMessage,toolResults:D,liveOutputs:bs(t.streamingMessage)?s:vs,toolStatuses:a,streaming:!0,isLast:!0,onEdit:l,onKillBash:c,toolsWrap:n,thinkingWrap:i},t.streamingMessage.id),t.isStreaming&&P.length===0&&e.jsx("div",{className:"streaming-wait",children:o("waitingResponse")}),t.queue.steering.map((f,v)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:o("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:f})]})},`q-steer-${v}`)),t.queue.followUp.map((f,v)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:o("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:f})]})},`q-fu-${v}`))]}),!p&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Ge,children:[e.jsx($s,{})," ",o("backToBottom")]}),e.jsx(ka,{containerRef:u,messages:P,open:x,onClose:()=>j(!1),onEnsureExpanded:ge}),X.length>0&&e.jsxs("div",{className:`qn-rail ${w?"many":""}`,ref:Ce,"aria-label":o("questionNavTitle"),style:{"--rail-gap":`${Pe}px`},children:[X.map((f,v)=>e.jsx("button",{type:"button",className:`qn-bar ${v===I?"active":""}`,"aria-label":`${v+1}. ${f.text}`,onClick:()=>we(f.id),children:e.jsxs("span",{className:"qn-bar-text",children:[v+1,". ",f.text]})},f.id)),w&&e.jsx("div",{className:"qn-list",children:X.map((f,v)=>e.jsxs("button",{type:"button",className:`qn-list-item ${v===I?"active":""}`,"aria-label":`${v+1}. ${f.text}`,onClick:()=>we(f.id),children:[e.jsx("span",{className:"qn-list-idx",children:v+1}),e.jsx("span",{className:"qn-list-text",children:f.text})]},f.id))})]})]})}const ln="pi-web-model-usage";function Ra(t){if(!t||typeof t!="object")return{};const s={};for(const[a,l]of Object.entries(t)){const c=typeof l=="number"?Math.floor(l):0;Number.isFinite(c)&&c>0&&(s[a]=c)}return s}function Pa(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function Ia(t,s){const a=s;return t.map((l,c)=>({m:l,i:c,count:a[l.id]??0})).sort((l,c)=>c.count-l.count||l.i-c.i).map(l=>l.m)}function on(){try{const t=localStorage.getItem(ln);return t?Ra(JSON.parse(t)):{}}catch{return{}}}function La(t){try{localStorage.setItem(ln,JSON.stringify(t))}catch{}}function Da(t){const s=Pa(on(),t);return La(s),s}const Ba=["off","minimal","low","medium","high","xhigh","max"],Aa=r.memo(function({state:s,models:a,modelsLoading:l,send:c,onManageModels:i,compact:n=!1}){const o=pe(),u=s==null?void 0:s.model,p=u?`${u.provider}/${u.id}`:null,[h,g]=r.useState(!1),[y,b]=r.useState(!1),[k,B]=r.useState(""),[M,$]=r.useState(null),[x,j]=r.useState({}),P=r.useRef(null),D=r.useRef(null),[R,N]=r.useState(null);r.useEffect(()=>{if(!h){N(null);return}if(a.length===0)return;const T=requestAnimationFrame(()=>{const C=D.current;C&&N(C.offsetWidth)});return()=>cancelAnimationFrame(T)},[h,a.length]),r.useEffect(()=>{h&&j(on())},[h]),r.useEffect(()=>{h||(B(""),$(null))},[h]);const m=r.useMemo(()=>{const T=new Map;for(const C of a)T.set(C.provider,(T.get(C.provider)??0)+1);return[...T.entries()].sort((C,K)=>C[0].localeCompare(K[0])).map(([C,K])=>({name:C,count:K}))},[a]),A=r.useMemo(()=>Ia(a,x),[a,x]),W=r.useMemo(()=>{let T=A;M&&(T=T.filter(K=>K.provider===M));const C=k.trim().toLowerCase();return C?T.filter(K=>K.name.toLowerCase().includes(C)||K.provider.toLowerCase().includes(C)||K.id.toLowerCase().includes(C)):T},[A,k,M]),[ee,ie]=r.useState(!1),H=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,q=Ba.map(T=>({value:T,label:o(`thinking.${T}`),supported:H?H.has(T):!0})),L=T=>{var C;return((C=q.find(K=>K.value===T))==null?void 0:C.label)??T};return r.useEffect(()=>{h&&a.length===0&&!ee&&!l&&(ie(!0),c({type:"list_models"}))},[h,a.length,ee,l,c]),r.useEffect(()=>{a.length>0&&ie(!1)},[a.length]),r.useEffect(()=>{var C;if(!h)return;const T=(C=P.current)==null?void 0:C.querySelector(".dd-item.active");T==null||T.scrollIntoView({block:"nearest"})},[h,p,a.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Xe,{}),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:h,onOpenChange:g,menuClassName:"dd-menu-model",menuRef:D,menuStyle:R!=null?{width:R}:void 0,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(dt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:o("searchModels"),value:k,onChange:T=>B(T.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[m.length>1&&e.jsxs("div",{className:"dd-provider-col",children:[e.jsx("div",{className:"dd-provider-head",children:o("providers")}),e.jsx("button",{type:"button",className:`dd-provider-item ${M===null?"active":""}`,onClick:()=>$(null),children:e.jsx("span",{children:o("allProviders")})}),m.map(T=>e.jsxs("button",{type:"button",className:`dd-provider-item ${M===T.name?"active":""}`,onClick:()=>$(M===T.name?null:T.name),title:`${T.name} · ${T.count}`,children:[e.jsx("span",{className:"dd-provider-name",children:T.name}),e.jsx("span",{className:"dd-provider-count",children:T.count})]},T.name))]}),e.jsxs("div",{className:"dd-model-scroll",ref:P,children:[(ee||l)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),a.length===0&&!ee&&!l&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),W.length===0&&a.length>0&&e.jsx("div",{className:"dd-loading",children:o("noModelMatches")}),W.map(T=>e.jsx(be,{active:p===T.id,onClick:()=>{p!==T.id&&c({type:"set_model",modelId:T.id}),g(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:T.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:T.provider}),(x[T.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:o("modelUsedCount",{n:x[T.id]})}),(T.reasoning||T.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[T.reasoning&&e.jsx("span",{className:"dd-model-badge",children:o("reasoning")}),T.vision&&e.jsx("span",{className:"dd-model-badge",children:o("vision")})]})]})]})},T.id))]})]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>c({type:"list_models"}),children:o("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{g(!1),i()},children:o("manageModels")})]})]}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(nt,{}),e.jsx("span",{className:"chip-sub",children:o("thinkingChip",{level:s?L(s.thinkingLevel):"—"})})]}),open:y,onOpenChange:b,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("thinkingLevel")}),q.map(T=>e.jsx(be,{active:(s==null?void 0:s.thinkingLevel)===T.value,disabled:!T.supported,title:T.supported?void 0:o("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==T.value&&c({type:"set_thinking",level:T.value}),b(!1)},children:T.label},T.value))]})]})}),_a=r.memo(function({ready:s,streaming:a,messages:l,slashCommands:c,modelState:i,models:n,modelsLoading:o,send:u,attachments:p,onRemoveAttachment:h,onAddImageFiles:g,onAddLocalFiles:y,onNotice:b,onSent:k,onManageModels:B}){const M=pe(),{locale:$}=At(),{openPicker:x}=an(),j=d=>$==="en"&&d.descriptionEn?d.descriptionEn:d.description??"",P=d=>$==="en"&&d.argumentHintEn?d.argumentHintEn:d.argumentHint??"",[D,R]=r.useState(""),[N,m]=r.useState(!1),[A,W]=r.useState(null),[ee,ie]=r.useState(0),[H,q]=r.useState(!1),[L,T]=r.useState(void 0),C=r.useRef(null),K=r.useRef(null),me=r.useRef(null),J={builtin:M("slashBuiltin"),extension:M("slashExtension"),prompt:M("slashPrompt"),skill:M("slashSkill"),plugin:M("slashPlugin")},E=d=>{const I=d.match(/^\/([^\s]*)$/);if(I&&s){const ce=I[1].toLowerCase(),se=c.filter(he=>he.name.toLowerCase().startsWith(ce));W(se.length>0?se:null),ie(0)}else W(null)};r.useEffect(()=>{var I;const d=(I=me.current)==null?void 0:I.querySelector(".slash-item.active");d==null||d.scrollIntoView({block:"nearest"})},[ee,A]);const Z=d=>{var Q;const I=A??[],ce=d??I[ee%Math.max(I.length,1)];if(!ce){W(null);return}const se=D.match(/^\/([^\s]*)([\s\S]*)$/),he=se?se[2]:"";R(`/${ce.name} ${he}`),W(null),(Q=C.current)==null||Q.focus()},te=async()=>{const I=[...l].reverse().find(se=>se.role==="assistant"&&se.content.some(he=>he.type==="text"&&he.text)),ce=I==null?void 0:I.content.filter(se=>se.type==="text").map(se=>se.text).join(`
|
|
318
|
-
`);if(!ce){b("warning",M("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(ce),b("info",M("slashCopied"))}catch{b("error",M("slashCopyFailed"))}},S=d=>{if(!d||d.length===0){b("warning",M("foldersNotSupported"));return}const I=Array.from(d).filter(se=>Me(se.type)),ce=Array.from(d).filter(se=>!Me(se.type));I.length>0&&g(I),ce.length>0&&y(ce)},F=d=>{var se;const I=(se=d.clipboardData)==null?void 0:se.items;if(!I)return;const ce=[];for(const he of I)if(he.kind==="file"&&Me(he.type)){const Q=he.getAsFile();Q&&ce.push(Q)}ce.length!==0&&(d.preventDefault(),g(ce))},z=s,ne=r.useRef(D);r.useEffect(()=>{ne.current=D},[D]),r.useEffect(()=>{E(ne.current)},[c]),r.useEffect(()=>{const d=I=>{var se;const ce=I.detail;R(ce),(se=C.current)==null||se.focus()};return window.addEventListener("pi-web:fill",d),()=>window.removeEventListener("pi-web:fill",d)},[]),r.useEffect(()=>{if(!H)return;const d=I=>{I.key==="Escape"&&q(!1)};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[H]),r.useEffect(()=>{const d=C.current;if(!d)return;d.style.height="auto";const I=d.scrollHeight>220;d.style.height=`${Math.min(d.scrollHeight,220)}px`,d.style.overflowY=I?"auto":"hidden"},[D]);const G=(d=!1)=>{var se,he,Q,le,ge;const I=D.trim(),ce=p.some(ue=>ue.imageData||ue.fileData);if(!(!z||!I&&!ce)){if(I==="/help"){const ue=(he=(se=C.current)==null?void 0:se.closest(".inputbox"))==null?void 0:he.getBoundingClientRect();T(ue==null?void 0:ue.width),q(!0),R(""),(Q=C.current)==null||Q.focus();return}if(I==="/copy"){R(""),(le=C.current)==null||le.focus(),te();return}if(u({type:"prompt",text:I,queue:d,attachments:p.map(ue=>ue.imageData?{path:"",imageData:ue.imageData,mimeType:ue.mimeType,name:ue.name}:ue.fileData?{path:"",fileData:ue.fileData,mimeType:ue.mimeType,name:ue.name,size:ue.size}:{path:ue.path,mode:ue.mode,...ue.lines?{lines:ue.lines}:{}})})){R(""),k();const ue=i==null?void 0:i.model;ue&&Da(`${ue.provider}/${ue.id}`),(ge=C.current)==null||ge.focus()}}},oe=d=>{if(!d.nativeEvent.isComposing){if(A&&A.length>0)switch(d.key){case"ArrowDown":d.preventDefault(),ie(I=>(I+1)%A.length);return;case"ArrowUp":d.preventDefault(),ie(I=>(I-1+A.length)%A.length);return;case"Tab":case"Enter":d.preventDefault(),Z();return;case"Escape":d.preventDefault(),W(null);return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),G())}},X=()=>e.jsx("div",{className:"inputbox-actions",children:a?e.jsxs(e.Fragment,{children:[D.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:M("supplementTip"),onClick:()=>G(!0),children:[e.jsx(Ds,{})," ",M("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:M("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(ot,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:M("sendTip"),disabled:!z||!D.trim()&&!p.some(d=>d.imageData||d.fileData),onClick:()=>G(),children:e.jsx(Fs,{})})});return e.jsxs("div",{className:`inputbar${N?" drop-active":""}`,onDragOver:d=>{d.preventDefault(),d.stopPropagation(),m(!0)},onDragLeave:d=>{d.currentTarget.contains(d.relatedTarget)||m(!1)},onDrop:d=>{var I;d.preventDefault(),d.stopPropagation(),m(!1),S(((I=d.dataTransfer)==null?void 0:I.files)??null)},children:[N&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",M("dropHereToAttach")]})}),p.length>0&&e.jsxs("div",{className:"attach-row",children:[p.map(d=>e.jsxs("span",{className:`attach-chip ${d.imageData?"image":d.fileData?"file":d.mode}`,title:d.imageData?M("attachImage",{name:d.name}):d.fileData?M("attachFile",{name:d.name}):d.isDir?M("folderRef",{path:d.path}):d.mode==="reference"?M("refOnly",{path:d.path}):d.mode==="lines"&&d.lines?M("attachLines",{path:d.path,start:d.lines.start,end:d.lines.end}):M("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:M("removeAttachment"),onClick:()=>h(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:M("attachHint")})]}),A&&A.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:me,"aria-label":M("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:M("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>W(null),children:"Esc"})]}),A.map((d,I)=>e.jsxs("button",{type:"button",className:`slash-item${I===ee?" active":""}`,onMouseEnter:()=>ie(I),onClick:()=>Z(d),children:[e.jsxs("span",{className:"slash-name",children:["/",d.name]}),e.jsx("span",{className:`slash-source ${d.source}`,children:J[d.source]}),e.jsxs("span",{className:"slash-desc",children:[j(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:P(d)})]})]},d.name))]}),H&&e.jsx("div",{className:"modal-backdrop",onClick:()=>q(!1),children:e.jsxs("div",{className:"slash-help",style:L?{width:L}:void 0,onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",M("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>q(!1),children:M("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:M("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:J[d.source]}),e.jsxs("span",{className:"slash-help-desc",children:[j(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:P(d)})]})]},d.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:K,type:"file",multiple:!0,hidden:!0,onChange:d=>{S(d.target.files),d.target.value=""}}),e.jsx("textarea",{ref:C,value:D,rows:1,placeholder:M(z?a?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!z,onChange:d=>{R(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:M("uploadFile"),disabled:!z,onClick:()=>{var d;return(d=K.current)==null?void 0:d.click()},children:e.jsx(_n,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:M("tpl.openPicker"),onClick:x,children:e.jsx(Vn,{})}),e.jsx(Aa,{state:i,models:n,modelsLoading:o,send:u,onManageModels:B,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:X()})]})]})]})}),Fa=r.memo(function({goal:s,models:a,modelsLoading:l,activeConversationId:c,send:i}){var ee,ie,H,q,L,T;const n=pe(),o=!s.conversationId||s.conversationId===c,u=s.goal!==null&&o,[p,h]=r.useState(""),[g,y]=r.useState(s.reviewModel??""),[b,k]=r.useState(s.maxRounds),[B,M]=r.useState(s.locked),[$,x]=r.useState(!1),[j,P]=r.useState(!1),[D,R]=r.useState(!0);r.useEffect(()=>{y(s.reviewModel??""),k(s.maxRounds||0),M(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),r.useEffect(()=>{$&&a.length===0&&!j&&!l&&(P(!0),i({type:"list_models"}))},[$,a.length,j,l,i]),r.useEffect(()=>{a.length>0&&P(!1)},[a.length]);const N=()=>{var C;return g?((C=a.find(K=>K.id===g))==null?void 0:C.name)??g:n("goalBarUseMainModel")},m=()=>{const C=p.trim();C&&(i({type:"set_goal",goal:C,...g?{reviewModel:g}:{},maxRounds:b,locked:B}),h(""),R(!1))},A=()=>{const C=p.trim();C&&(i({type:"start_goal_wizard",text:C,...g?{wizardModel:g}:{},maxRounds:b,locked:B}),h(""),R(!1))},W=(((ee=s.wizard)==null?void 0:ee.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:((ie=s.wizard)==null?void 0:ie.draft)??"",children:[n("goalWizardRunning"),": ",(H=s.wizard)==null?void 0:H.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[n("goalBarRound",{n:(((q=s.wizard)==null?void 0:q.step)??0)+1})," ","/ ",((L=s.wizard)==null?void 0:L.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((T=s.wizard)==null?void 0:T.status)||n("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:n("goalBarClear"),onClick:()=>{i({type:"clear_goal"}),R(!0)},children:e.jsx(ke,{})})]})}):u?e.jsx("div",{className:`goalbar goalbar-active ${s.reviewing?"reviewing":""}`,children:e.jsxs("div",{className:"goalbar-active-row",children:[e.jsx("span",{className:"goalbar-icon",children:s.reviewing?e.jsx("span",{className:"goalbar-spin",children:"◌"}):"🎯"}),e.jsx("span",{className:"goalbar-text",title:s.goal??"",children:s.goal}),s.reviewing?e.jsxs("span",{className:"goalbar-chip reviewing",children:[n("goalBarReviewing")," ",n("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?n("goalBarPassed"):s.verdict==="fail"?n("goalBarFailed"):`${n("goalBarRound",{n:s.round||1})} · ${s.locked?n("goalBarLocked"):n("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:s.status}),e.jsx("button",{type:"button",className:"goalbar-x",title:n("goalBarClear"),disabled:s.reviewing,onClick:()=>{i({type:"clear_goal"}),R(!0)},children:e.jsx(ke,{})})]})}):D?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:n("goalBarPlaceholder"),onClick:()=>R(!1),children:[e.jsx(Zt,{})," ",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(Zt,{})}),e.jsx("input",{className:"goalbar-input",value:p,placeholder:n("goalBarPlaceholder"),onChange:C=>h(C.target.value),onKeyDown:C=>{C.key==="Enter"&&m()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!p.trim(),onClick:m,children:n("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!p.trim(),title:n("goalWizardTip"),onClick:A,children:["🔍 ",n("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n(B?"goalBarLocked":"goalBarUnlocked"),onClick:()=>M(C=>(i({type:"set_goal_prefs",locked:!C}),!C)),children:B?e.jsx(Un,{}):e.jsx(Ln,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n("goalBarClear"),onClick:()=>R(!0),children:e.jsx(mt,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[e.jsxs(Le,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[n("goalBarReviewModel"),": ",e.jsx("b",{children:N()})]}),open:$,onOpenChange:x,direction:"up",children:[e.jsx("div",{className:"dd-header",children:n("goalBarReviewModel")}),(j||l)&&e.jsx("div",{className:"dd-loading",children:n("loading")}),a.length===0&&!j&&!l&&e.jsx("div",{className:"dd-loading",children:n("noModels")}),e.jsx(be,{active:g==="",onClick:()=>{y(""),x(!1),i({type:"set_goal_prefs",reviewModel:""})},children:n("goalBarUseMainModel")}),a.map(C=>e.jsx(be,{active:g===C.id,onClick:()=>{y(C.id),x(!1),i({type:"set_goal_prefs",reviewModel:C.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:C.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:C.provider})})]})},C.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>i({type:"list_models"}),children:n("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:n("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:n("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:b,placeholder:n("goalBarUnlimitedShort"),onChange:C=>{const K=parseInt(C.target.value,10);if(Number.isNaN(K)||K<0){k(0);return}k(K)},onBlur:()=>i({type:"set_goal_prefs",maxRounds:b}),onKeyDown:C=>{C.key==="Enter"&&(i({type:"set_goal_prefs",maxRounds:b}),C.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:n(B?"goalBarLocked":"goalBarUnlocked")})]})]})});function $a({chat:t,send:s}){const a=pe(),l=t.state,[c,i]=r.useState(!1),[n,o]=r.useState(""),[u,p]=r.useState(0),h=r.useRef(null),g=t.pathCompletions;if(r.useEffect(()=>{if(!c)return;const m=setTimeout(()=>{s({type:"complete_path",path:n})},150);return()=>clearTimeout(m)},[n,c,s]),r.useEffect(()=>p(0),[g]),r.useEffect(()=>{const m=document.querySelector(`.status-completions .pc-item[data-idx="${u}"]`);m==null||m.scrollIntoView({block:"nearest"})},[u]),!l)return null;const y=l.stats,b=t.ready?"ok":"busy",k=t.ready?a("connected"):a("connecting"),B=y.contextUsage,M=B.tokens!==null&&B.percent!==null?`${js(B.tokens)} / ${js(B.contextWindow)}`:"—",$=B.percent??null,x=$===null?"":$>=80?"warn":$>=50?"mid":"ok",j=l.queue.steering.length+l.queue.followUp.length,P=()=>{o(l.cwd),i(!0)},D=(m,A)=>{var ee;const W=m.includes("\\")?"\\":"/";o(A?`${m}${W}`:m),p(0),(ee=h.current)==null||ee.focus()},R=m=>{const A=m.trim();A&&A!==l.cwd&&s({type:"set_cwd",path:A}),i(!1)},N=m=>{if(m.key==="ArrowDown")m.preventDefault(),p(A=>Math.min(A+1,g.length-1));else if(m.key==="ArrowUp")m.preventDefault(),p(A=>Math.max(A-1,0));else if(m.key==="Tab"&&g.length>0){m.preventDefault();const A=g[Math.min(u,g.length-1)];D(A.path,A.type==="dir")}else if(m.key==="Enter"&&!m.nativeEvent.isComposing){const A=n.trim();if(A.endsWith("/")||A.endsWith("\\"))R(A);else if(g.some(W=>W.path===A))R(A);else if(g.length>0&&g[u]){m.preventDefault();const W=g[u];D(W.path,W.type==="dir")}else R(A)}else m.key==="Escape"&&(g.length>0?(m.stopPropagation(),s({type:"complete_path",path:""})):i(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${b}`,title:k}),e.jsx("span",{className:"status-item",children:k}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-ctx",title:a("contextUsage"),children:[a("context"),e.jsx("span",{className:`ctx-bar ${x}`,children:$!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min($,100)}%`}})}),M]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:a("cumulativeCost"),children:["$",Oa(y.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:a("sessionMessages"),children:[a("messages")," ",y.totalMessages]}),t.statuses.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsx("span",{className:"status-item ext-status",title:a("pluginStatus"),children:t.statuses.map(m=>m.text).join(" · ")})]}),l.isStreaming&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item working",children:[e.jsx("span",{className:"working-spin"}),a("working"),j>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",j," ",a("queued")]})]})]}),c?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:h,className:"status-cwd-input",value:n,autoFocus:!0,placeholder:a("enterPath"),onChange:m=>o(m.target.value),onKeyDown:N,onBlur:()=>i(!1)}),g.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:m=>m.preventDefault(),children:g.map((m,A)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":A,className:`pc-item ${A===u?"sel":""}`,onMouseEnter:()=>p(A),onClick:()=>D(m.path,m.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:m.type==="dir"?e.jsx(ze,{}):e.jsx(As,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:m.name}),e.jsx("span",{className:"pc-path",children:m.path})]})]})},m.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:a("cwdTip",{path:l.cwd}),onClick:P,children:["📁 ",l.cwd]})]})}function js(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function Oa(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function Wa({dialog:t,send:s}){const a=pe(),[l,c]=r.useState(""),[i,n]=r.useState(0),o=h=>{s({type:"dialog_response",id:t.id,value:h})};r.useEffect(()=>{c(""),n(0);const h=g=>{g.key==="Escape"&&o(null)};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[t.id]);const u=Array.isArray(t.args[0])?t.args[0]:[],p=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:a("pluginRequest")}),t.title&&t.title!==a("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:a("cancel"),onClick:()=>o(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[u.map((h,g)=>e.jsx("button",{type:"button",className:`dialog-option ${g===i?"sel":""}`,onMouseEnter:()=>n(g),onClick:()=>o(h),children:h},g)),u.length===0&&e.jsx("div",{className:"dialog-hint",children:a("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:p}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(!1),children:a("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(!0),children:a("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:l,placeholder:p||a("inputPlaceholder"),autoFocus:!0,onChange:h=>c(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.nativeEvent.isComposing&&o(l)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(null),children:a("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(l),children:a("ok")})]})]})]})}function Ha(t){if(t.x==="?"&&t.y==="?")return"untracked";const s=t.x!==" "&&t.x!=="?",a=t.y!==" "&&t.y!=="?";return s&&a?"both":s?"staged":"unstaged"}function Ua({chat:t,send:s,terminal:a,active:l,onSwitchToTerminal:c}){var Ne,Pe;const i=pe(),[n,o]=r.useState(null),[u,p]=r.useState([]),[h,g]=r.useState(""),[y,b]=r.useState(new Map),[k,B]=r.useState("changes"),[M,$]=r.useState([]),[x,j]=r.useState(null),[P,D]=r.useState(""),[R,N]=r.useState(!1),[m,A]=r.useState(null),[W,ee]=r.useState(null),[ie,H]=r.useState(!1),[q,L]=r.useState(!1),[T,C]=r.useState(!1),[K,me]=r.useState(null),[J,E]=r.useState(!1),[Z,te]=r.useState(""),S=r.useRef(0),F=r.useRef(-1),z=r.useRef(-1),ne=r.useRef(-1),G=r.useRef(-1),oe=r.useRef(void 0),X=r.useRef(null),d=r.useRef([]),I=r.useCallback(w=>{if(w.reqId===F.current){if(F.current=-1,L(!1),me(null),!w.ok){me(w.error??"查询失败");return}if(w.notRepo){E(!0),o(null),p([]),b(new Map),$([]),j(null),D(""),ee(null);return}E(!1);const f={branch:w.branch??"",detached:!!w.detached,upstream:w.upstream??null,ahead:w.ahead??0,behind:w.behind??0,upstreamGone:!!w.upstreamGone,files:(w.files??[]).map(O=>({...O}))},v=(w.branches??[]).map(O=>({...O})),V=new Map;for(const[O,ae]of Object.entries(w.stats??{}))V.set(O,{add:ae[0],del:ae[1]});o(f),p(v),b(V),g(O=>{var ae;return f.detached?O||"":f.branch&&v.some(de=>de.name===f.branch)?f.branch:O&&v.some(de=>de.name===O)?O:((ae=v[0])==null?void 0:ae.name)??""}),ee(O=>O&&!f.files.some(ae=>ae.path===O.file.path)?null:O)}else if(w.reqId===z.current){if(z.current=-1,H(!1),!w.ok){me(w.error??"查询失败");return}const f=X.current;if(!f)return;ee({file:f,staged:w.stagedText??"",worktree:w.worktreeText??"",untracked:!1})}else if(w.reqId===G.current){if(G.current=-1,C(!1),!w.ok){me(w.error??"查询失败");return}$((w.history??[]).map(f=>({...f})))}else if(w.reqId===ne.current){if(ne.current=-1,N(!1),!w.ok){me(w.error??"查询失败");return}D(w.text??"")}},[]);r.useEffect(()=>{const w=t.scmData;w&&w.type==="scm_data"&&I(w)},[t.scmData,I]);const ce=r.useCallback((w,f)=>{if(!t.ready||t.status!=="open")return!1;const v=++S.current;return s({...w,reqId:v})?(f.current=v,!0):(S.current-=1,!1)},[t.ready,t.status,s]),se=r.useCallback((w=!1,f=!1)=>{var v;!t.ready||t.status!=="open"||(v=t.state)!=null&&v.cwd&&(oe.current!==void 0&&oe.current!==t.state.cwd&&(o(null),p([]),b(new Map),$([]),C(!1),G.current=-1,j(null),D(""),ee(null),A(null)),oe.current=t.state.cwd,me(null),ce({type:"scm_status"},F)&&(f||L(!0)))},[t.ready,(Ne=t.state)==null?void 0:Ne.cwd,t.status,ce]),he=r.useCallback(w=>{if(A(w),j(null),X.current=w,w.x==="?"&&w.y==="?"){ee({file:w,staged:"",worktree:"",untracked:!0});return}H(!0),me(null),ce({type:"scm_filediff",path:w.path},z)||H(!1)},[ce]),Q=r.useCallback(w=>{j(w),A(null),ee(null),D(""),N(!0),me(null),ce({type:"scm_commit",hash:w.hash},ne)||N(!1)},[ce]),le=r.useCallback((w,f)=>{var O,ae;if(!t.ready)return;const v={name:w,command:f,cwd:"${pwd}"},V=t.terminals.find(de=>de.title===w);if(V)a.restart(V.id),s({type:"run_command",terminalId:V.id,conversationId:V.conversationId,command:v,cols:80,rows:24});else{const de=Re();a.create({id:de,conversationId:t.activeConversationId||((O=t.state)==null?void 0:O.conversationId)||"",title:w,cwd:((ae=t.state)==null?void 0:ae.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:v})}c()},[t.ready,(Pe=t.state)==null?void 0:Pe.cwd,t.terminals,c,s,a]),ge=r.useCallback(()=>{const w=Z.trim();if(!w||J)return;const f=w.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");le("git commit",`git add -A && git commit -m "${f}"`),te("")},[Z,J,le]),ue=w=>`'${w.replace(/'/g,"'\\''")}`,we=r.useCallback(w=>{J||le("git add",`git add -- ${ue(w.path)}`)},[J,le]),Be=r.useCallback(w=>{J||le("git reset",`git reset HEAD -- ${ue(w.path)}`)},[J,le]),$e=r.useCallback(()=>{if(!h||J)return;const w=u.find(f=>f.name===h);if(w!=null&&w.remote&&typeof w.remote=="string"){const f=h.slice(w.remote.length+1);le("git checkout",`git checkout -b ${f} ${h} || git checkout ${h}`)}else le("git checkout",`git checkout ${h}`)},[h,u,J,le]),Ve=r.useCallback(()=>le("git push","git push"),[le]),Ge=r.useCallback(()=>le("git pull","git pull"),[le]),Ce=r.useCallback(()=>{ce({type:"scm_history"},G)||(G.current=-1)},[ce]);r.useEffect(()=>{l&&se()},[l,se]),r.useEffect(()=>{k==="history"&&n&&Ce()},[k,n,Ce]),r.useEffect(()=>{t.scmDirty>0&&l&&se(!1,!0)},[t.scmDirty]),r.useEffect(()=>{if(!l||!t.ready||t.status!=="open")return;const w=setInterval(()=>{document.visibilityState!=="hidden"&&se(!1,!0)},3e4);return()=>clearInterval(w)},[l,t.ready,t.status,se]),r.useEffect(()=>{const w=d.current;if(d.current=t.terminals,!l)return;t.terminals.some(v=>{var O;return v.running!==!1?!1:((O=w.find(ae=>ae.id===v.id))==null?void 0:O.running)===!0&&/^git /.test(v.title)})&&t.ready&&t.status==="open"&&(se(!1,!0),k==="history"&&n&&Ce())},[t.terminals,l,t.ready,t.status,se,k,n,Ce]);const Oe={staged:i("scmStaged"),unstaged:i("scmUnstaged"),untracked:i("scmUntracked"),both:i("scmStagedUnstaged")},Ae=w=>{const f=w.split(`
|
|
319
|
-
`);return e.jsx("pre",{className:"scm-diff-pre",children:f.map((v,V)=>{let O="";return v.startsWith("diff --git")||v.startsWith("index ")||v.startsWith("new file")||v.startsWith("deleted file")||v.startsWith("old mode")||v.startsWith("new mode")||v.startsWith("similarity index")||v.startsWith("rename ")||v.startsWith("copy ")||v.startsWith("Binary files")||v.startsWith("---")||v.startsWith("+++")?O="hdr":v.startsWith("@@")?O="hunk":v.startsWith("+")?O="add":v.startsWith("-")&&(O="del"),e.jsx("div",{className:`scm-diff-line ${O}`,children:v||" "},V)})})};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(it,{}),i("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":k==="changes",className:k==="changes"?"active":"",onClick:()=>{B("changes"),me(null)},children:i("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":k==="history",className:k==="history"?"active":"",onClick:()=>{B("history"),me(null)},children:i("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:i("scmRefreshTip"),disabled:q,onClick:()=>se(!0),children:e.jsx(pt,{className:q?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:i("scmCurrentBranch"),children:[e.jsx(it,{}),n?n.detached?i("scmDetached"):n.branch:"…",(n==null?void 0:n.upstream)&&e.jsx("span",{className:"scm-upstream",children:n.upstreamGone?i("scmUpstreamGone"):n.ahead>0||n.behind>0?i("scmAheadBehind",{ahead:n.ahead,behind:n.behind}):n.upstream})]}),e.jsxs("select",{className:"scm-select",value:h,disabled:J||u.length===0,title:i("scmSwitchBranch"),onChange:w=>g(w.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:i("scmSelectBranch")}),u.filter(w=>!w.remote).map(w=>e.jsx("option",{value:w.name,children:w.current?`* ${w.name}`:w.name},w.name)),u.some(w=>w.remote)&&e.jsx("optgroup",{label:i("scmRemoteBranches"),children:u.filter(w=>w.remote).map(w=>e.jsx("option",{value:w.name,children:w.name},w.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!h||h===(n==null?void 0:n.branch)||J,title:i("scmSwitchBranchTip",{branch:h}),onClick:$e,children:[e.jsx(it,{}),i("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!n||n.detached||J,title:i("scmPushTip"),onClick:Ve,children:[e.jsx(Fs,{}),i("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!n||n.detached||J,title:i("scmPullTip"),onClick:Ge,children:[e.jsx($s,{}),i("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:Z,placeholder:i("scmCommitPlaceholder"),disabled:J,onChange:w=>te(w.target.value),onKeyDown:w=>{w.key==="Enter"&&!w.nativeEvent.isComposing&&ge()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!Z.trim()||J,title:i("scmCommitTip"),onClick:ge,children:[e.jsx(gt,{}),i("scmCommit")]})]})]}),e.jsxs("div",{className:"scm-body",children:[k==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmHistory")}),M.length>0&&e.jsx("span",{className:"scm-files-count",children:M.length})]}),e.jsx("div",{className:"scm-history-list",children:J?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):!n||T?e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")}):M.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoHistory")}):M.map(w=>e.jsxs("button",{type:"button",className:`scm-commit ${(x==null?void 0:x.hash)===w.hash?"active":""}`,onClick:()=>Q(w),title:w.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:w.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:w.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[w.shortHash," · ",w.author," · ",w.date]}),w.decorations&&e.jsx("span",{className:"scm-commit-refs",children:w.decorations})]})]},w.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmChanges")}),n&&n.files.length>0&&e.jsx("span",{className:"scm-files-count",children:n.files.length})]}),e.jsx("div",{className:"scm-files-list",children:J?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):n?n.files.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoChanges")}):n.files.map(w=>{const f=Ha(w),v=y.get(w.path);return e.jsxs("div",{className:`scm-file ${(m==null?void 0:m.path)===w.path?"active":""}`,title:Oe[f],onClick:()=>he(w),children:[e.jsx("span",{className:`scm-file-xy ${f==="untracked"?"q":"x"}`,children:w.x!==" "?w.x:" "}),e.jsx("span",{className:`scm-file-xy ${f==="untracked"?"q":"y"}`,children:w.y!==" "?w.y:" "}),e.jsx("span",{className:"scm-file-path",children:w.path}),v&&(v.add>0||v.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[v.add>0&&e.jsxs("span",{className:"add",children:["+",v.add]}),v.del>0&&e.jsxs("span",{className:"del",children:["-",v.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(w.y!==" "||f==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:i("scmStageTip",{path:w.path}),onClick:V=>{V.stopPropagation(),we(w)},children:"+"}),f==="staged"||f==="both"?e.jsx("button",{type:"button",className:"scm-act",title:i("scmUnstageTip",{path:w.path}),onClick:V=>{V.stopPropagation(),Be(w)},children:"−"}):null]})]},w.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:k==="history"?x?`${x.shortHash} ${x.subject}`:i("scmCommitDetail"):m?m.path:i("scmDiff")}),(k==="history"?R:ie)&&e.jsx("span",{className:"scm-diff-loading",children:i("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:k==="history"?e.jsxs(e.Fragment,{children:[K&&e.jsx("div",{className:"scm-error",children:K}),!x&&!K&&e.jsx("div",{className:"scm-empty",children:i("scmSelectCommitHint")}),x&&R&&!K&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),x&&!R&&!K&&P?Ae(P):null]}):e.jsxs(e.Fragment,{children:[K&&e.jsx("div",{className:"scm-error",children:K}),!m&&!K&&e.jsx("div",{className:"scm-empty",children:i("scmSelectFileHint")}),m&&!W&&!K&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),m&&W&&W.untracked&&e.jsx("div",{className:"scm-empty",children:i("scmUntrackedNote")}),m&&W&&!W.untracked&&e.jsxs(e.Fragment,{children:[W.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmStaged")}),Ae(W.staged)]}),W.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmUnstaged")}),Ae(W.worktree)]}),!W.staged&&!W.worktree&&e.jsx("div",{className:"scm-empty",children:i("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(qe,{}),e.jsx("span",{children:i("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:c,children:i("scmViewTerminal")})]})]})}function qa({entry:t,send:s}){const a=r.useRef(null);return r.useEffect(()=>{const l=a.current;if(!l)return;let c;try{c=t.module.mount(l,vi(t.info.id,i=>s(i)))}catch(i){console.error(`[plugin:${t.info.id}] mount failed:`,i),l.textContent=`插件 ${t.info.name} 挂载失败`}return()=>{if(typeof c=="function")try{c()}catch(i){console.error(`[plugin:${t.info.id}] cleanup failed:`,i)}l.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:a})}function Ka({send:t,piConfigured:s,piAgentInstalled:a,providers:l,installResult:c,onClose:i}){const n=pe(),[o,u]=r.useState(!1),[p,h]=r.useState(""),[g,y]=r.useState(""),[b,k]=r.useState(!1);r.useEffect(()=>{t({type:"list_providers"})},[t]),r.useEffect(()=>{s&&i()},[s,i]),r.useEffect(()=>{c&&u(!1)},[c]),r.useEffect(()=>{var P;!p&&l.length>0&&h(((P=l.find(D=>!D.configured))==null?void 0:P.id)??l[0].id)},[l,p]);const B=()=>{o||(u(!0),t({type:"install_pi_agent"}))},M=()=>{!g.trim()||b||(k(!0),t({type:"set_provider_api_key",provider:p.trim(),apiKey:g.trim()}),setTimeout(()=>k(!1),3e3))},$=()=>{t({type:"get_state"}),t({type:"list_providers"})},x=l.find(P=>P.id===p),j=c!==null&&!c.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":n("close"),onClick:i,children:e.jsx(ke,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(Xe,{className:"modal-head-icon"}),e.jsx("h2",{children:n("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:n("setupDesc")}),j?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:n("installFailed")}),e.jsx("pre",{className:"setup-detail",children:c.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:B,children:n("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:n("skip")})]})]}):a||c!=null&&c.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:c!=null&&c.ok?n("installDone"):n("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:n("provider")}),e.jsxs("select",{value:p,onChange:P=>h(P.target.value),children:[l.length===0&&e.jsx("option",{value:"",children:n("loading")}),l.map(P=>e.jsxs("option",{value:P.id,children:[P.name,"(",P.id,")",P.configured?` · ${n("configured")}`:""]},P.id))]}),(x==null?void 0:x.configured)&&e.jsx("div",{className:"field-hint",children:n("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:n("apiKey")}),e.jsx("input",{type:"password",value:g,onChange:P=>y(P.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!g.trim()||b||!p,onClick:M,children:n(b?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:$,children:[e.jsx(pt,{})," ",n("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:B,children:n(o?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:n("skip")})]})]})})}const za=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],$t=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),Va=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[$t()]});function ws(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:[$t()]).map(s=>{var a;return{id:s.id,name:s.name??"",reasoning:s.reasoning??!1,input:(a=s.input)!=null&&a.includes("image")?"text-image":"text",contextWindow:s.contextWindow?String(s.contextWindow):"",maxTokens:s.maxTokens?String(s.maxTokens):""}})}}function Ga({send:t,providers:s,providerStatus:a,fetchModelsResult:l,refreshProviderResult:c,cloneProviderResult:i,onClose:n}){const o=pe(),[u,p]=r.useState(null),[h,g]=r.useState({}),[y,b]=r.useState(null),[k,B]=r.useState({}),[M,$]=r.useState(!1),[x,j]=r.useState(0),[P,D]=r.useState(null),R=r.useRef(0),[N,m]=r.useState({});r.useRef(0);const A=r.useRef(0),[W,ee]=r.useState(null),ie=r.useRef(0),H=r.useRef(0);r.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const q=()=>{if(!u)return;const E=u.baseUrl.trim();if(!E){D({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(M)return;$(!0),D(null);const Z=x+1;j(Z),t({type:"fetch_models",reqId:Z,baseUrl:E,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};r.useEffect(()=>{var E;if(!(!l||l.reqId===R.current))if(R.current=l.reqId,$(!1),l.ok&&((E=l.models)!=null&&E.length)){const Z=l.models;p(te=>{if(!te)return te;const S=te.models.map(G=>{var d;if(!G.id.trim())return G;const oe=Z.find(I=>I.id===G.id.trim());if(!oe)return G;const X={...G};return!X.name&&oe.name&&(X.name=oe.name),!X.contextWindow&&oe.contextWindow&&(X.contextWindow=String(oe.contextWindow)),!X.maxTokens&&oe.maxTokens&&(X.maxTokens=String(oe.maxTokens)),X.input==="text"&&((d=oe.input)!=null&&d.includes("image"))&&(X.input="text-image"),!X.reasoning&&oe.reasoning&&(X.reasoning=!0),X}),F=new Set(S.map(G=>G.id.trim()).filter(Boolean)),z=Z.filter(G=>!F.has(G.id)).map(G=>{var oe;return{id:G.id,name:G.name??"",reasoning:G.reasoning??!1,input:(oe=G.input)!=null&&oe.includes("image")?"text-image":"text",contextWindow:G.contextWindow?String(G.contextWindow):"",maxTokens:G.maxTokens?String(G.maxTokens):""}}),ne=[...S,...z];return ne.some(G=>G.id.trim())?{...te,models:ne.filter(G=>G.id.trim())}:te}),D({ok:!0,text:o("fetchModelsOk",{n:Z.length})})}else D({ok:!1,text:l.error||o("fetchModelsEmpty")})},[l]);const L=E=>{const Z=(h[E.id]??"").trim();!Z||y||(b(E.id),t({type:"set_provider_api_key",provider:E.id,apiKey:Z}),setTimeout(()=>{b(null),g(te=>({...te,[E.id]:""})),B(te=>({...te,[E.id]:!1})),t({type:"list_providers"})},1500))},T=()=>{if(!u)return;const E=u.providerId.trim(),Z=u.models.filter(S=>S.id.trim()).map(S=>({id:S.id.trim(),name:S.name.trim()||void 0,reasoning:S.reasoning||void 0,input:S.input==="text-image"?["text","image"]:void 0,contextWindow:S.contextWindow?Number(S.contextWindow):void 0,maxTokens:S.maxTokens?Number(S.maxTokens):void 0})),te={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:Z};t({type:"save_model_config",providerId:E,config:te}),n()};r.useEffect(()=>{!c||c.reqId===A.current||(A.current=c.reqId,m({}))},[c]);const C=E=>{if(W)return;ee(E.id);const Z=++ie.current+Date.now();t({type:"clone_provider",provider:E.id,reqId:Z})};r.useEffect(()=>{!i||i.reqId===H.current||(H.current=i.reqId,ee(null),i.ok&&i.config&&p(ws({...i.config,apiKey:""})))},[i]);const K=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})},J=(E,Z)=>{u&&p({...u,models:u.models.map((te,S)=>S===E?{...te,...Z}:te)})};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(ke,{})}),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=>p({...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=>p({...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=>p({...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=>p({...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=>p({...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=>p({...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:[P&&e.jsx("span",{className:`fetch-msg ${P.ok?"ok":"err"}`,title:P.text,children:P.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:M||!u.baseUrl.trim(),title:o("fetchModelsHint"),onClick:q,children:[e.jsx(Dt,{})," ",o(M?"fetchingModels":"fetchModels")]})]})]}),u.models.map((E,Z)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:E.id,onChange:te=>J(Z,{id:te.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:E.name,onChange:te=>J(Z,{name:te.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:E.input,onChange:te=>J(Z,{input:te.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:te=>J(Z,{reasoning:te.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:E.contextWindow,onChange:te=>J(Z,{contextWindow:te.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:E.maxTokens,onChange:te=>J(Z,{maxTokens:te.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>p({...u,models:u.models.filter((te,S)=>S!==Z)}),children:e.jsx(Ee,{})})]},Z)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>p({...u,models:[...u.models,$t()]}),children:[e.jsx(De,{})," ",o("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>p(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(E=>E.id.trim()),onClick:T,children:o("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-section-title",children:[o("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:o("hintKeyOnly")})]}),e.jsxs("div",{className:"provider-list",children:[a.length===0&&e.jsx("div",{className:"dd-loading",children:o("loading")}),a.map(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&&!k[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:()=>B(Z=>({...Z,[E.id]:!0})),children:[e.jsx(Et,{})," ",o("replaceKey")]}),E.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>K(E.id),children:[e.jsx(Ee,{})," ",o("clearKey")]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"password",className:"key-input",placeholder:o("pasteKey"),value:h[E.id]??"",onChange:Z=>g(te=>({...te,[E.id]:Z.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(h[E.id]??"").trim()||y===E.id,onClick:()=>L(E),children:[e.jsx(qn,{})," ",y===E.id?o("savingKey"):o("saveKey")]})]}),e.jsxs("button",{type:"button",className:"btn sm",disabled:W!==null,title:o("cloneProviderTitle"),onClick:()=>C(E),children:[e.jsx(Bt,{})," ",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:()=>p(ws(E)),children:e.jsx(Et,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>me(E),children:e.jsx(Ee,{})})]})]},E.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>p(Va()),children:[e.jsx(De,{})," ",o("addProvider")]})})]})]})})}function Ja({plugin:t,send:s}){const a=pe(),l=t.settingsSchema??[],[c,i]=r.useState(()=>({...t.settingsValues??{}})),[n,o]=r.useState(!1);if(l.length===0)return null;const u=(y,b)=>i(k=>({...k,[y]:b})),p=l.some(y=>{var b;return c[y.key]!==((b=t.settingsValues)==null?void 0:b[y.key])}),h=()=>{o(!0),s({type:"plugin_settings",pluginId:t.id,values:c}),setTimeout(()=>o(!1),800)},g=()=>i({...t.settingsValues??{}});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:l.map(y=>e.jsxs("label",{className:"plugin-settings-field",title:y.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:y.label}),y.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!c[y.key],onChange:b=>u(y.key,b.target.checked)}):y.type==="select"?e.jsx("select",{value:String(c[y.key]??""),onChange:b=>u(y.key,b.target.value),children:(y.options??[]).map(b=>e.jsx("option",{value:b,children:b},b))}):e.jsx("input",{type:y.type==="password"?"password":y.type==="number"?"number":"text",value:String(c[y.key]??""),min:y.min,max:y.max,onChange:b=>u(y.key,y.type==="number"?Number(b.target.value):b.target.value)})]},y.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!p||n,onClick:h,children:a(n?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:g,children:a("pluginSettingsReset")})]})]})}function at({text:t}){const s=r.useRef(null),[a,l]=r.useState(!1),c=()=>{var n;const i=(n=s.current)==null?void 0:n.getBoundingClientRect();i&&l(window.innerWidth-i.right<340)};return e.jsxs("span",{ref:s,className:`set-tip${a?" flip":""}`,tabIndex:0,"aria-label":t,onMouseEnter:c,onFocus:c,children:["?",e.jsx("span",{className:"set-tip-bubble",role:"tooltip",children:t})]})}function Te({title:t,subtitle:s,tip:a,enabled:l,onToggle:c,action:i}){const n=pe();return e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[t,a&&e.jsx(at,{text:a})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),i,e.jsx("button",{type:"button",className:`set-switch ${l?"on":""}`,role:"switch","aria-checked":l,title:n(l?"settingsEnabled":"settingsDisabled"),onClick:c,children:e.jsx("span",{className:"set-switch-knob"})})]})}function Ya({chat:t,send:s,terminal:a,onSwitchToTerminal:l,onClose:c}){const i=pe(),n=t.settings,[o,u]=r.useState("prompt"),p=r.useRef(null);r.useEffect(()=>{var d;(d=p.current)==null||d.scrollTo({top:0})},[o]);const[h,g]=r.useState(""),[y,b]=r.useState("append"),k=r.useRef(!1),[B,M]=r.useState(""),[$,x]=r.useState("append"),j=r.useRef(!1),[P,D]=r.useState(""),R=r.useRef(!1),[N,m]=r.useState(""),[A,W]=r.useState(!1),[ee,ie]=r.useState(null),[H,q]=r.useState(null);r.useEffect(()=>{n&&(b(n.promptMode),!k.current&&(g(y==="append"||n.customSystemPrompt?n.customSystemPrompt:n.defaultSystemPrompt||""),x(n.visionBridgePromptMode),!j.current&&(M($==="append"||n.visionBridgePrompt?n.visionBridgePrompt:n.visionBridgeDefaultPrompt||""),R.current||D(n.reviewPrompt))))},[n,y,$]);const[L,T]=r.useState(String((n==null?void 0:n.terminalBashIdleMs)??15e3));if(r.useEffect(()=>{T(String((n==null?void 0:n.terminalBashIdleMs)??15e3))},[n==null?void 0:n.terminalBashIdleMs]),!n)return null;const C=[{id:"prompt",icon:e.jsx(_s,{}),label:i("settingsSystemPrompt")},{id:"terminal",icon:e.jsx(qe,{}),label:i("settingsTerminalTools")},{id:"display",icon:e.jsx(Ke,{}),label:i("settingsMessageDisplay")},{id:"skills",icon:e.jsx(Xe,{}),label:i("settingsSkills"),count:n.skills.length},{id:"extensions",icon:e.jsx(es,{}),label:i("settingsExtensions"),count:n.extensions.length},{id:"plugins",icon:e.jsx(ss,{}),label:i("settingsUiPlugins"),count:t.plugins.length},{id:"review",icon:e.jsx(nt,{}),label:i("settingsReview"),count:n.reviewSkills.length},{id:"vision",icon:e.jsx(St,{}),label:i("settingsVisionBridge")},{id:"presets",icon:e.jsx(Bn,{}),label:i("settingsPresets"),count:n.presets.length}],K=new Set(n.disabledSkills),me=new Set(n.disabledExtensions),J=d=>s({type:"set_settings",...d}),E=d=>{const I=new Set(K);I.has(d.name)?I.delete(d.name):I.add(d.name),J({disabledSkills:[...I]})},Z=new Set(n.disabledPlugins??[]),te=d=>{const I=new Set(Z);I.has(d.id)?I.delete(d.id):I.add(d.id),J({disabledPlugins:[...I]})},S=d=>{const I=new Set(me);I.has(d.id)?I.delete(d.id):I.add(d.id),J({disabledExtensions:[...I]})},F=(d,I)=>{var he,Q;const ce={name:d,command:I,cwd:"${pwd}"},se=t.terminals.find(le=>le.title===d);se?(a.restart(se.id),s({type:"run_command",terminalId:se.id,conversationId:se.conversationId,command:ce,cols:80,rows:24})):a.create({id:Re(),conversationId:t.activeConversationId||((he=t.state)==null?void 0:he.conversationId)||"",title:d,cwd:((Q=t.state)==null?void 0:Q.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:ce}),l(),c()},z=d=>{ie(null),F(`${i("uninstallTitle")} ${d}`,`pi remove npm:${d}`)},ne=d=>{q(null),F(`${i("uninstallTitle")} ${d}`,`pi-web-ui uninstall ${d}`)},G=(d,I)=>{F(`${i("pluginUpdate")} ${d}`,`pi-web-ui install ${I} --name ${d} --force`)},oe=d=>{const I=new Set(n.reviewSkills.filter(ce=>!ce.enabled).map(ce=>ce.name));I.has(d.name)?I.delete(d.name):I.add(d.name),J({reviewDisabledSkills:[...I]})},X=()=>{const d=y==="replace"&&n.defaultSystemPrompt&&h===n.defaultSystemPrompt?"":h;J({promptMode:y,customSystemPrompt:d})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal settings-modal",onClick:d=>d.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:c,children:e.jsx(ke,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(ct,{className:"modal-head-icon"}),e.jsx("h2",{children:i("settingsTitle")}),e.jsx(at,{text:i("settingsDesc")})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-rail","aria-label":i("settingsTitle"),children:C.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:p,children:[o==="prompt"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(nt,{className:"set-section-icon"}),i("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:y,onChange:d=>{const I=d.target.value;b(I),J({promptMode:I})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]}),e.jsx(at,{text:i(y==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:i("promptPlaceholder"),value:h,onFocus:()=>k.current=!0,onBlur:()=>{k.current=!1,X()},onChange:d=>g(d.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":A,onClick:()=>W(d=>!d),children:[i("settingsViewPrompt")," ",A?"▴":"▾"]}),A&&e.jsxs("div",{className:"set-prompt-view",children:[e.jsxs("div",{className:"set-prompt-view-head",children:[e.jsx("span",{children:i("settingsViewPromptHint")}),e.jsx(qs,{text:n.effectiveSystemPrompt})]}),n.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:n.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:i("settingsViewPromptEmpty")})]})]}),o==="terminal"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(qe,{className:"set-section-icon"}),i("settingsTerminalTools")]}),e.jsx(Te,{title:i("terminalToolsEnabled"),tip:i("settingsTerminalToolsDesc"),enabled:n.terminalToolsEnabled,onToggle:()=>J({terminalToolsEnabled:!n.terminalToolsEnabled})}),!n.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:i("terminalToolsOffHint")}),e.jsx(Te,{title:i("terminalBashTakeover"),tip:i("terminalBashTakeoverDesc"),enabled:n.terminalBash,onToggle:()=>J({terminalBash:!n.terminalBash})}),n.terminalBash&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:i("terminalBashIdleMs")}),e.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:L,onChange:d=>T(d.target.value),onBlur:()=>{const d=Math.max(0,Math.floor(Number(L)||0));T(String(d)),d!==n.terminalBashIdleMs&&J({terminalBashIdleMs:d})}})]})]}),o==="display"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ke,{className:"set-section-icon"}),i("settingsMessageDisplay")]}),e.jsx(Te,{title:i("thinkingWrap"),tip:i("thinkingWrapDesc"),enabled:n.thinkingWrap??!0,onToggle:()=>J({thinkingWrap:!(n.thinkingWrap??!0)})}),e.jsx(Te,{title:i("toolsWrap"),tip:i("toolsWrapDesc"),enabled:n.toolsWrap??!0,onToggle:()=>J({toolsWrap:!(n.toolsWrap??!0)})})]}),o==="skills"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Xe,{className:"set-section-icon"}),i("settingsSkills"),e.jsx("span",{className:"set-count",children:n.skills.length})]}),n.skills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:n.skills.map(d=>e.jsx(Te,{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(es,{className:"set-section-icon"}),i("settingsExtensions"),e.jsx("span",{className:"set-count",children:n.extensions.length})]}),n.extensions.length===0?e.jsx("p",{className:"set-empty",children:i("noExtensions")}):e.jsx("div",{className:"set-list",children:n.extensions.map(d=>{const I=d.id.startsWith("npm:")?d.id.slice(4):null;return e.jsx(Te,{title:d.name,subtitle:d.path,enabled:d.enabled,onToggle:()=>S(d),action:I?ee===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>z(I),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("uninstallHint"),onClick:()=>ie(d.id),children:[e.jsx(Ee,{}),i("uninstallExt")]}):void 0},d.id)})})]}),o==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ss,{className:"set-section-icon"}),i("settingsUiPlugins"),e.jsx("span",{className:"set-count",children:t.plugins.length})]}),t.plugins.length===0?e.jsx("p",{className:"set-empty",children:i("noUiPlugins")}):e.jsx("div",{className:"set-list",children:t.plugins.map(d=>{var I;return e.jsxs(e.Fragment,{children:[e.jsx(Te,{title:`${d.icon?`${d.icon} `:""}${d.name}`,subtitle:(d.error?`${d.id} · ${d.error}`:d.source?`${d.id} · ${d.source}`:`${d.id} · ${i("uiPluginNoSource")}`)+((I=d.permissions)!=null&&I.length?` · ${i("uiPluginPerms")}: ${d.permissions.join(", ")}`:""),enabled:!Z.has(d.id)&&!d.error,onToggle:()=>!d.error&&te(d),action:e.jsxs("div",{className:"set-row-actions",children:[d.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>G(d.id,d.source),children:[e.jsx(pt,{}),i("pluginUpdate")]}),H===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>ne(d.id),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>q(d.id),children:[e.jsx(Ee,{}),i("uninstallExt")]})]})},d.id),d.settingsSchema&&d.settingsSchema.length>0&&e.jsx(Ja,{plugin:d,send:s})]})})})]}),o==="review"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(nt,{className:"set-section-icon"}),i("settingsReview"),e.jsx(at,{text:i("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:n.reviewSkills.length})]}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:i("reviewPromptPlaceholder"),value:P,onFocus:()=>R.current=!0,onBlur:()=>{R.current=!1,J({reviewPrompt:P})},onChange:d=>D(d.target.value)}),e.jsx("div",{className:"set-field-label",children:i("settingsReviewSkills")}),n.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:n.reviewSkills.map(d=>e.jsx(Te,{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(St,{className:"set-section-icon"}),i("settingsVisionBridge")]}),e.jsx(Te,{title:i("visionBridgeEnabled"),tip:i("settingsVisionBridgeDesc"),enabled:n.visionBridgeEnabled,onToggle:()=>J({visionBridgeEnabled:!n.visionBridgeEnabled})}),!n.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:i("visionBridgeOffHint")}),n.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:n.visionBridgeModel??"",onChange:d=>J({visionBridgeModel:d.target.value||null}),children:[e.jsx("option",{value:"",children:i("visionBridgeAuto")}),n.visionModels.map(d=>e.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),n.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:$,onChange:d=>{const I=d.target.value;x(I),J({visionBridgePromptMode:I})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]})]}),n.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:i("visionBridgePromptPlaceholder"),value:B,onFocus:()=>j.current=!0,onBlur:()=>{j.current=!1;const d=$==="replace"&&n.visionBridgeDefaultPrompt&&B===n.visionBridgeDefaultPrompt?"":B;J({visionBridgePromptMode:$,visionBridgePrompt:d})},onChange:d=>M(d.target.value)}),n.visionBridgeEnabled&&(n.visionModels.length===0?e.jsx("p",{className:"set-hint",children:i("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:i("visionBridgeCurrent",{model:n.visionBridgeModel??i("visionBridgeAuto")})}))]}),o==="presets"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ct,{className:"set-section-icon"}),i("settingsPresets"),e.jsx("span",{className:"set-count",children:n.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:i("presetNamePlaceholder"),value:N,onChange:d=>m(d.target.value),onKeyDown:d=>{d.key==="Enter"&&N.trim()&&(s({type:"save_preset",name:N.trim()}),m(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!N.trim(),onClick:()=>{s({type:"save_preset",name:N.trim()}),m("")},children:[e.jsx(De,{})," ",i("saveAsPreset")]})]}),n.presets.length===0?e.jsx("p",{className:"set-empty",children:i("noPresets")}):e.jsx("div",{className:"set-list",children:n.presets.map(d=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:d.name}),e.jsxs("div",{className:"set-row-desc",children:[d.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend"),d.disabledSkills.length>0&&` · ${i("settingsSkills")} ${d.disabledSkills.length}`,d.disabledExtensions.length>0&&` · ${i("settingsExtensions")} ${d.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:d.name}),children:i("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("deletePreset"),onClick:()=>s({type:"delete_preset",name:d.name}),children:e.jsx(Ee,{})})]})]},d.name))})]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:c,children:i("close")})})]})})}function Qa(t,s){const a=Math.max(0,Date.now()-t),l=Math.floor(a/6e4);if(l<1)return s("bgTaskJustNow");if(l<60)return s("bgTaskMinutes",{n:l});const c=Math.floor(l/60);return c<24?s("bgTaskHours",{n:c}):s("bgTaskDays",{n:Math.floor(c/24)})}function Xa({servers:t,send:s,onClose:a}){const l=pe(),[c,i]=r.useState(new Set),n=o=>i(u=>{const p=new Set(u);return p.has(o)?p.delete(o):p.add(o),p});return r.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"bg-task-modal",onClick:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(ut,{})," ",l("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:l("close"),onClick:a,children:e.jsx(ke,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(ut,{}),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,p=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")," ",Qa(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(p)?"open":""}`,title:`${l("bgTaskCommand")}: ${o.command}`,onClick:()=>n(p),children:[e.jsx(qe,{}),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(ot,{}),e.jsx("span",{children:l("bgTaskStop")})]})]},p)})}),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(pt,{}),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(ot,{}),e.jsx("span",{children:l("bgTaskStopAll")})]})]})]})})}function st(t,s){return t.toLowerCase().includes(s)}function Za({send:t,sessions:s,projects:a,cwd:l,fileSearch:c,onClose:i,onSwitchSession:n,onSwitchProject:o,onPreviewFile:u}){const p=pe(),h=r.useRef(null),[g,y]=r.useState(""),b=r.useDeferredValue(g),[k,B]=r.useState(0),M=r.useRef(1),$=r.useRef(0),x=r.useRef(null);r.useEffect(()=>{t({type:"list_sessions"}),t({type:"list_projects"}),requestAnimationFrame(()=>{var L;return(L=h.current)==null?void 0:L.focus()})},[]);const[j,P]=r.useState(!1);r.useEffect(()=>{x.current&&clearTimeout(x.current);const L=b.trim();if(L)return x.current=setTimeout(()=>{const T=++M.current;$.current=T,P(!0),t({type:"search_files",reqId:T,query:L})},300),()=>{x.current&&clearTimeout(x.current)}},[b]);const D=b.trim().toLowerCase(),R=r.useMemo(()=>D?s.filter(L=>st(L.firstMessage??"",D)||st(L.name??"",D)||st(L.path.split(/[\\/]/).pop()??"",D)).slice(0,20):[],[s,D]),N=r.useMemo(()=>D?a.filter(L=>st(L.path,D)).slice(0,10):[],[a,D]),m=r.useMemo(()=>!D||!c||c.reqId!==$.current||!c.ok?[]:c.results,[c,D]);r.useEffect(()=>{c&&c.reqId===$.current&&$.current!==0&&P(!1)},[c]);const A=!!c&&c.ok&&c.truncated,W=r.useMemo(()=>[...R.map(L=>({kind:"session",path:L.path})),...N.map(L=>({kind:"project",path:L.path})),...m.filter(L=>L.type==="file").map(L=>({kind:"file",path:L.path,name:L.name}))],[R,N,m]);r.useEffect(()=>{B(0)},[b]);const ee=r.useCallback(L=>{L&&(L.kind==="session"?n(L.path):L.kind==="project"?o(L.path):u(L.path,L.name),i())},[n,o,u,i]);r.useEffect(()=>{const L=T=>{T.key==="Escape"?(T.preventDefault(),T.stopPropagation(),i()):T.key==="ArrowDown"?(T.preventDefault(),B(C=>Math.min(C+1,W.length-1))):T.key==="ArrowUp"?(T.preventDefault(),B(C=>Math.max(C-1,0))):T.key==="Enter"&&(T.preventDefault(),ee(W[k]))};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[W,k,ee,i]);const ie=R.length+N.length+m.length,H=(L,T,C)=>e.jsxs("div",{className:"gs-section-head",children:[C,e.jsx("span",{children:L}),e.jsx("em",{children:T})]});let q=-1;return e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:i,children:e.jsxs("div",{className:"gs-modal",onClick:L=>L.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(dt,{}),e.jsx("input",{ref:h,type:"text",value:g,placeholder:p("gsPlaceholder"),onChange:L=>y(L.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:p("close"),onClick:i,children:e.jsx(ke,{})})]}),e.jsxs("div",{className:"gs-results",children:[!D&&e.jsx("div",{className:"gs-empty",children:p("gsHint")}),D&&ie===0&&!A&&e.jsx("div",{className:"gs-empty",children:p(j?"gsSearching":"gsNoResults")}),R.length>0&&e.jsxs("div",{className:"gs-section",children:[H(p("gsSessions"),R.length,e.jsx(Ke,{})),R.map(L=>{q++;const T=q;return e.jsxs("button",{type:"button",className:T===k?"gs-item active":"gs-item",onMouseEnter:()=>B(T),onClick:()=>ee({kind:"session",path:L.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[L.name||L.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:L.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:L.firstMessage})]},L.path)})]}),N.length>0&&e.jsxs("div",{className:"gs-section",children:[H(p("gsProjects"),N.length,e.jsx(ze,{})),N.map(L=>{q++;const T=q,C=l&&L.path===l;return e.jsxs("button",{type:"button",className:T===k?"gs-item active":"gs-item",onMouseEnter:()=>B(T),onClick:()=>ee({kind:"project",path:L.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[L.path.split(/[\\/]/).pop(),C&&e.jsx("em",{className:"gs-item-meta",children:p("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:L.path})]},L.path)})]}),(m.length>0||D&&A)&&e.jsxs("div",{className:"gs-section",children:[H(p("gsFiles"),m.length,e.jsx(_s,{})),m.map(L=>{q++;const T=q;return e.jsxs("button",{type:"button",className:T===k?"gs-item active":"gs-item",disabled:L.type==="dir",title:L.type==="dir"?void 0:p("gsOpenPreview"),onMouseEnter:()=>B(T),onClick:()=>{L.type==="file"&&ee({kind:"file",path:L.path,name:L.name})},children:[e.jsx("span",{className:"gs-item-title",children:L.name}),e.jsx("span",{className:"gs-item-sub",children:L.path})]},`${L.type}:${L.path}`)}),A&&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")]})]})]})})}const wt=5e3;function er({file:t,content:s,send:a,onAddLines:l,onAttach:c,onClose:i}){const n=pe(),[o,u]=r.useState(null),[p,h]=r.useState(!1),[g,y]=r.useState(null),[b,k]=r.useState(!1),[B,M]=r.useState(!1),[$,x]=r.useState(!1),[j,P]=r.useState(""),[D,R]=r.useState(!0),N=r.useRef(!1),[m,A]=r.useState(!0),[W,ee]=r.useState(!1),[ie,H]=r.useState(100),q=r.useRef(0),L=r.useRef(!1),T=r.useRef(null);r.useEffect(()=>{h(!0),u(null),y(null),x(!1),P(""),R(!0),N.current=!1,a({type:"read_file",path:t.path})},[t.path,a]),r.useEffect(()=>{s&&s.path===t.path&&(u(s),$||P(s.text),h(!1))},[s,$,t.path]),r.useEffect(()=>{const Q=le=>{if(le.key==="Escape"){ne();return}if((le.ctrlKey||le.metaKey)&&le.key.toLowerCase()==="s"&&$){le.preventDefault(),z();return}const ge=le.target,ue=ge&&(ge.tagName==="INPUT"||ge.tagName==="TEXTAREA"||ge.isContentEditable);(le.ctrlKey||le.metaKey)&&le.key.toLowerCase()==="a"&&!ue&&(le.preventDefault(),E())};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[i,o,$,j]),r.useEffect(()=>{const Q=()=>{L.current=!1,k(!1)};return window.addEventListener("mouseup",Q),()=>window.removeEventListener("mouseup",Q)},[]);const C=r.useMemo(()=>{if(!o)return[];const Q=o.text.split(`
|
|
320
|
-
`);return Q.length>0&&Q[Q.length-1]===""&&Q.pop(),Q.slice(0,wt)},[o]),K=(o==null?void 0:o.lines)??0,me=K>wt,J=(Q,le)=>{if(le){const ge=q.current>0?q.current:Q;y({start:Math.min(ge,Q),end:Math.max(ge,Q)})}else q.current=Q,y({start:Q,end:Q})},E=()=>{C.length!==0&&(q.current=1,y({start:1,end:C.length}))},Z=()=>{g&&(l(t.path,t.name,g.start,g.end),M(!0),T.current&&clearTimeout(T.current),T.current=setTimeout(()=>M(!1),1400))},te=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,S=()=>{P((o==null?void 0:o.text)??""),x(!1),N.current&&R(!0)},F=()=>{if($){if(j!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges")))return;S();return}!te||!o||(N.current=Nt(t.name)&&D,Nt(t.name)&&R(!1),y(null),P(o.text),x(!0))},z=()=>{!$||!o||!te||a({type:"write_file",path:t.path,text:j})&&(x(!1),N.current&&R(!0),y(null))},ne=()=>{$&&j!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges"))||i()},G=Q=>{H(Math.min(200,Math.max(50,Q)))},oe=g?g.end-g.start+1:0,X=(o==null?void 0:o.binary)??!1,d=(o==null?void 0:o.truncated)??!1,I=(o==null?void 0:o.kind)??"text",ce=Nt(t.name),se=ce&&D&&!$&&I==="text"&&!X,he=Q=>ft(`/api/file?clientId=${encodeURIComponent(_t())}&path=${encodeURIComponent(Q)}`);return e.jsx("div",{className:`fp-overlay ${W?"fullscreen":""}`,onMouseDown:Q=>{Q.target===Q.currentTarget&&ne()},children:e.jsxs("div",{className:`fp ${W?"fullscreen":""}`,style:{"--fp-zoom":ie/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&&I==="text"&&!X&&n("fileLines",{n:K}),o&&` · ${tr(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[ce&&I==="text"&&!X&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${D?"on":""}`,"data-tip":n(D?"showMarkdownSource":"showMarkdownPreview"),disabled:$,onClick:()=>R(Q=>!Q),children:D?e.jsx(St,{}):e.jsx(Yn,{})}),I==="text"&&!X&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${$?"on":""}`,"data-tip":n(d?"fileEditTruncated":$?"exitEditFile":"editFile"),disabled:!te&&!$,onClick:F,children:e.jsx(Tt,{})}),I==="text"&&!X&&!se&&e.jsx("button",{type:"button",className:`fp-attach wrap ${m?"on":""}`,"data-tip":n(m?"disableWrap":"enableWrap"),onClick:()=>A(Q=>!Q),children:e.jsx(Jn,{})}),I==="text"&&o&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":n("zoomOut"),disabled:ie<=50,onClick:()=>G(ie-10),children:e.jsx(Pn,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:n("resetZoom"),onClick:()=>H(100),children:[ie,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":n("zoomIn"),disabled:ie>=200,onClick:()=>G(ie+10),children:e.jsx(In,{})})]}),I!=="video"&&I!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":n("attachInlineTip"),onClick:()=>c(t.path,t.name,"inline"),children:e.jsx(De,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":n("referenceTip"),onClick:()=>c(t.path,t.name,"reference"),children:e.jsx(Ct,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${W?"on":""}`,"data-tip":n(W?"exitFullscreen":"fullscreen"),onClick:()=>ee(Q=>!Q),children:W?e.jsx($n,{}):e.jsx(Wn,{})}),e.jsx("button",{type:"button",className:"fp-close",title:n("close"),onClick:ne,children:e.jsx(ke,{})})]})]}),d&&I==="text"&&!X&&e.jsx("div",{className:"fp-notice",children:n("previewTruncated")}),p&&!o&&e.jsx("div",{className:"fp-empty",children:n("loading")}),!p&&I==="none"&&!X&&e.jsx("div",{className:"fp-empty",children:n("previewNotSupported")}),!p&&I==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:he(t.path),alt:t.name})}),!p&&I==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:he(t.path),controls:!0,preload:"metadata"})}),!p&&se&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(xt,{text:o.text})})}),!p&&X&&I!=="image"&&I!=="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})]}),!p&&$&&I==="text"&&!X&&o&&e.jsx("textarea",{className:`fp-editor ${m?"":"no-wrap"}`,value:j,onChange:Q=>P(Q.target.value),wrap:m?"soft":"off",spellCheck:!1,autoFocus:!0}),!p&&!se&&!$&&I==="text"&&!X&&o&&C.length===0&&e.jsx("div",{className:"fp-empty",children:n("emptyFile")}),!p&&!se&&!$&&I==="text"&&!X&&C.length>0&&e.jsxs("div",{className:`fp-code ${b?"dragging":""} ${m?"":"no-wrap"}`,onMouseDown:Q=>{Q.button===0&&Q.preventDefault()},children:[C.map((Q,le)=>{const ge=le+1,ue=g!==null&&ge>=g.start&&ge<=g.end;return e.jsxs("div",{className:`fp-line ${ue?"sel":""}`,onMouseDown:we=>{we.button===0&&(J(ge,we.shiftKey),L.current=!0,k(!0))},onMouseEnter:()=>{L.current&&J(ge,!0)},children:[e.jsx("span",{className:"fp-num",children:ge}),e.jsx("span",{className:"fp-code-text",children:Q})]},ge)}),me&&e.jsx("div",{className:"fp-lines-note",children:n("previewLinesTruncated",{n:wt})})]}),e.jsx("div",{className:"fp-foot",children:$?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:n("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:F,children:n("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:j===((o==null?void 0:o.text)??""),onClick:z,children:[e.jsx(An,{})," ",n("saveFile")]})]})]}):!se&&I==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:g?n("selectedRange",{n:oe,start:g.start,end:g.end}):n("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:C.length===0,onClick:E,children:n("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!g,onClick:()=>y(null),children:n("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!g||X,onClick:Z,children:[B?e.jsx(gt,{}):null,n(B?"addedToChat":"addToChat")]})]})]})})]})})}function Nt(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function tr(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const cn="pi-web-sounds",Je={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function dn(){try{const t=localStorage.getItem(cn);if(!t)return{...Je};const s=JSON.parse(t),a={...Je,...s};for(const l of["enabled","question","done","start","error"])typeof a[l]!="boolean"&&(a[l]=Je[l]);return typeof a.volume!="number"||!Number.isFinite(a.volume)?a.volume=Je.volume:a.volume=Math.round(Math.max(0,Math.min(100,a.volume))/5)*5,a}catch{return{...Je}}}function sr(t){try{localStorage.setItem(cn,JSON.stringify(t))}catch{}}let Ye=null;function nr(){try{if(!Ye){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;Ye=new t}return Ye.state==="suspended"&&Ye.resume(),Ye}catch{return null}}const ir=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],ar=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],rr=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],lr=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],or={question:ir,done:ar,start:rr,error:lr};function cr(t,s,a){const l=t.createOscillator(),c=t.createGain();l.type=s.type,l.frequency.value=s.freq;const i=t.currentTime+s.start,n=Math.max(1e-4,s.peak*a);c.gain.setValueAtTime(1e-4,i),c.gain.exponentialRampToValueAtTime(n,i+.012),c.gain.exponentialRampToValueAtTime(1e-4,i+s.dur),l.connect(c),c.connect(t.destination),l.start(i),l.stop(i+s.dur+.05)}function Qe(t,s=dn()){if(!s.enabled||!s[t])return;const a=nr();if(!a)return;const l=Math.max(0,Math.min(1,s.volume/100));for(const c of or[t])cr(a,c,l)}const Lt="pi-web-ui:theme",un="dark",Ns="theme-stylesheet",Cs="pi-web-ui:theme-change";function pn(){try{const t=localStorage.getItem(Lt);if(t&&t!==un)return t}catch{}return null}function dr(t){try{t?localStorage.setItem(Lt,t):localStorage.removeItem(Lt)}catch{}}function mn(t){let s=document.getElementById(Ns);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(Cs));return}s||(s=document.createElement("link"),s.id=Ns,s.rel="stylesheet",document.head.appendChild(s)),s.href=`/themes/${encodeURIComponent(t)}.css`,s.onload=()=>window.dispatchEvent(new CustomEvent(Cs))}async function ur(){try{const t=await fetch(ft("/api/themes"));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function pr(){const[t,s]=r.useState([]),[a,l]=r.useState(()=>pn());return r.useEffect(()=>{let i=!1;return ur().then(n=>{i||s(n)}),()=>{i=!0}},[]),r.useEffect(()=>{mn(a),dr(a)},[a]),{themes:t,theme:a,switchTheme:i=>l(i===un?null:i)}}function kr(){const t=getComputedStyle(document.documentElement),s=(a,l)=>t.getPropertyValue(a).trim()||l;return{background:s("--term-bg","#0b0d12"),foreground:s("--term-fg","#e6e8ef"),cursor:s("--term-cursor","#8b5cf6"),cursorAccent:s("--term-cursor-accent","#0b0d12"),selectionBackground:s("--term-selection","rgba(139, 92, 246, 0.35)"),black:s("--term-black","#1a1d26"),red:s("--term-red","#f87171"),green:s("--term-green","#34d399"),yellow:s("--term-yellow","#fbbf24"),blue:s("--term-blue","#60a5fa"),magenta:s("--term-magenta","#c084fc"),cyan:s("--term-cyan","#22d3ee"),white:s("--term-white","#e6e8ef"),brightBlack:s("--term-bright-black","#6b7284"),brightRed:s("--term-bright-red","#f87171"),brightGreen:s("--term-bright-green","#34d399"),brightYellow:s("--term-bright-yellow","#fbbf24"),brightBlue:s("--term-bright-blue","#60a5fa"),brightMagenta:s("--term-bright-magenta","#c084fc"),brightCyan:s("--term-bright-cyan","#22d3ee"),brightWhite:s("--term-bright-white","#ffffff")}}const mr=r.lazy(()=>Rs(()=>import("./TerminalPanel-uB-DaBC5.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function hr({notice:t,onDismiss:s}){const a=pe(),[l,c]=r.useState(!1);r.useEffect(()=>{if(l)return;const n=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(n)},[l,t.id,t.level,s]);const i=t.level==="error"?ei:t.level==="warning"?Zn:Kn;return e.jsxs("div",{className:`notice notice-${t.level}${l?" paused":""}`,role:"status",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[e.jsx(i,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:t.text}),e.jsx("button",{type:"button",className:"notice-close",title:a("close"),onClick:()=>s(t.id),children:e.jsx(ke,{})})]})}const gr=[],hn=180,gn=520,fn=240,xn=t=>`pi-web-ui:${t}-panel-width`;function Ss(t){const s=Number(localStorage.getItem(xn(t)));return Number.isFinite(s)&&s>=hn&&s<=gn?s:fn}function Ts({side:t,width:s,onResize:a}){const l=pe(),c=r.useCallback(i=>{i.preventDefault();const n=i.clientX,o=s;let u=o;const p=g=>{const y=t==="left"?g.clientX-n:n-g.clientX;u=Math.min(gn,Math.max(hn,Math.round(o+y))),a(u)},h=()=>{window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",h),document.body.classList.remove("panel-resizing"),localStorage.setItem(xn(t),String(u))};window.addEventListener("pointermove",p),window.addEventListener("pointerup",h),document.body.classList.add("panel-resizing")},[t,s,a]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:l("dragToResize"),onPointerDown:c,onDoubleClick:()=>a(fn)})}function fr(){var V,O,ae,de,ye,Se,Ot,Wt,Ht,Ut,qt,Kt,zt,Vt;const t=pe(),{chat:s,send:a,dismissNotice:l,pushNotice:c,terminal:i}=Ci(),[n,o]=r.useState([]),[u,p]=r.useState(null),[h,g]=r.useState(!1),[y,b]=r.useState("chat"),k=r.useMemo(()=>s.plugins.filter(_=>{var U,re;return!((re=(U=s.settings)==null?void 0:U.disabledPlugins)!=null&&re.includes(_.id))}),[s.plugins,(V=s.settings)==null?void 0:V.disabledPlugins]),[B,M]=r.useState([]);r.useEffect(()=>fi(M),[]),r.useEffect(()=>{xi(k,s.pluginsEpoch)},[k,s.pluginsEpoch]);const[$,x]=r.useState(()=>Ss("left")),[j,P]=r.useState(()=>Ss("right")),D=r.useCallback(_=>x(_),[]),R=r.useCallback(_=>P(_),[]),[N,m]=r.useState(null),[A,W]=r.useState(()=>window.matchMedia("(max-width: 768px)").matches);r.useEffect(()=>{const _=window.matchMedia("(max-width: 768px)"),U=re=>W(re.matches);return _.addEventListener("change",U),()=>_.removeEventListener("change",U)},[]);const[ee,ie]=r.useState(!1),[H,q]=r.useState(!1),[L,T]=r.useState(!1),[C,K]=r.useState(!1),[me,J]=r.useState(!1);r.useEffect(()=>{const _=U=>{var Ie,Gt;const re=U.detail,fe=(re==null?void 0:re.title)||"插件命令",xe=re==null?void 0:re.command;if(!xe||!s.ready)return;const je={name:fe,command:xe,cwd:"${pwd}"},ve=s.terminals.find(vt=>vt.title===fe);if(ve)i.restart(ve.id),a({type:"run_command",terminalId:ve.id,conversationId:ve.conversationId,command:je,cols:80,rows:24});else{const vt=Re();i.create({id:vt,conversationId:s.activeConversationId||((Ie=s.state)==null?void 0:Ie.conversationId)||"",title:fe,cwd:((Gt=s.state)==null?void 0:Gt.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:je})}b("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",_),()=>window.removeEventListener("pi-web-ui:plugin-run-command",_)},[s,i,a]),r.useEffect(()=>{const _=U=>{!(U.ctrlKey||U.metaKey)||U.key.toLowerCase()!=="k"||(U.preventDefault(),J(re=>!re))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[]);const[E,Z]=r.useState(dn),{themes:te,theme:S,switchTheme:F}=pr(),z=r.useRef(null),ne=r.useRef(null),G=r.useRef(0),oe=r.useRef(!1),X=r.useRef(s.terminals);r.useEffect(()=>{sr(E)},[E]),r.useEffect(()=>{var U;const _=X.current;X.current=s.terminals;for(const re of s.terminals){const fe=((U=re.command)==null?void 0:U.command)??"",xe=_.find(je=>je.id===re.id);!(xe!=null&&xe.running)||re.running||(fe.startsWith("pi remove ")?a({type:"extensions_reload"}):fe.startsWith("pi-web-ui install ")||fe.startsWith("pi-web-ui uninstall ")?a({type:"plugins_reload"}):fe.startsWith("npm i -g ")&&(a({type:"extensions_reload"}),a({type:"plugins_reload"}),a({type:"check_updates_all",force:!0})))}},[s.terminals,a]),r.useEffect(()=>{var re;const _=((re=s.state)==null?void 0:re.isStreaming)??!1,U=z.current;z.current=_,U!==null&&(!U&&_?Qe("start",E):U&&!_&&Qe("done",E))},[(O=s.state)==null?void 0:O.isStreaming,E]),r.useEffect(()=>{var U;const _=((U=s.dialog)==null?void 0:U.id)??null;_!==null&&_!==ne.current&&Qe("question",E),ne.current=_},[s.dialog,E]),r.useEffect(()=>{const _=[...s.notices].reverse().find(U=>U.level==="error");_&&_.id!==G.current&&(G.current=_.id,Qe("error",E))},[s.notices,E]);const d=(_,U,re,fe=!1,xe)=>{const je=`${_}|${re}|${xe?`${xe.start}-${xe.end}`:""}`;o(ve=>ve.some(Ie=>`${Ie.path}|${Ie.mode}|${Ie.lines?`${Ie.lines.start}-${Ie.lines.end}`:""}`===je)?ve:[...ve,{path:_,name:U,mode:re,isDir:fe,...xe?{lines:xe}:{}}])},I=_=>o(U=>U.filter(re=>re.key?re.key!==_:re.path!==_)),ce=r.useCallback(_=>(!_.type.startsWith("list_")&&!_.type.startsWith("get_")&&m(null),a(_)),[a]),se=r.useRef(0),he=r.useRef(0),Q=_=>{var fe;const U=Date.now();(fe=s.state)!=null&&fe.model&&!s.state.model.vision&&U-he.current>1e4&&(he.current=U,c("warning",t("imageNotSupported")));const re=`paste-${++se.current}`;o(xe=>[...xe,{path:"",key:re,name:_.name,mode:"inline",imageData:_.data,mimeType:_.mimeType}])},le=async _=>{for(const U of _){const re=await Gs(U);if(!re){c("error",t("imageLoadFailed",{name:U.name}));continue}Q(re)}},ge=20*1024*1024,ue=r.useRef(0),we=async _=>{if(_.size>ge){c("warning",t("fileTooLarge",{name:_.name,size:ge/1024/1024}));return}let U;try{U=(await new Promise((xe,je)=>{const ve=new FileReader;ve.onload=()=>xe(ve.result),ve.onerror=()=>je(ve.error??new Error("read failed")),ve.readAsDataURL(_)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",t("fileLoadFailed",{name:_.name}));return}const re=`upload-${++ue.current}`;o(fe=>[...fe,{path:"",key:re,name:_.name,mode:"inline",fileData:U,size:_.size,mimeType:_.type||void 0}])},Be=async _=>{for(const U of _)Me(U.type)?await le([U]):await we(U)},$e=r.useCallback((_,U,re)=>{a({type:"edit_message",messageId:_,text:U,attachments:re})},[a]),Ve=r.useCallback(()=>q(!0),[]),Ge=r.useCallback(()=>o([]),[]),Ce=r.useCallback(I,[]),Oe=r.useCallback(le,[le]),Ae=r.useCallback(Be,[Be]),Ne=(ae=s.state)==null?void 0:ae.model,Pe=(de=s.state)==null?void 0:de.thinkingLevel,w=(ye=s.state)==null?void 0:ye.availableThinkingLevels,f=r.useMemo(()=>Ne?{model:Ne,thinkingLevel:Pe??"off",availableThinkingLevels:w??[]}:null,[Ne,Pe,w]),v=r.useCallback(()=>{var _,U;return!s.ready||s.terminals.length!==0?!1:(i.create({id:Re(),conversationId:s.activeConversationId||((_=s.state)==null?void 0:_.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,(Se=s.state)==null?void 0:Se.cwd,s.terminals.length,t,i]);return r.useEffect(()=>{if(oe.current){if(y!=="terminal"||s.terminals.length!==0){oe.current=!1;return}v()&&(oe.current=!1)}},[s.terminals.length,v,y]),e.jsxs("div",{className:"app",onDragOver:_=>{var U;Array.from(((U=_.dataTransfer)==null?void 0:U.types)??[]).includes("Files")&&(_.preventDefault(),g(!0))},onDragLeave:_=>{_.currentTarget.contains(_.relatedTarget)||g(!1)},onDrop:_=>{var xe,je;if(g(!1),!Array.from(((xe=_.dataTransfer)==null?void 0:xe.types)??[]).includes("Files"))return;_.preventDefault();const U=Array.from(((je=_.dataTransfer)==null?void 0:je.files)??[]);if(U.length===0){c("warning",t("foldersNotSupported"));return}const re=U.filter(ve=>Me(ve.type)),fe=U.filter(ve=>!Me(ve.type));re.length>0&&le(re),fe.length>0&&Be(fe)},children:[h&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(li,{chat:s,send:a,terminal:i,view:y,plugins:k,onViewChange:_=>{oe.current=_==="terminal"&&s.terminals.length===0,oe.current&&v()&&(oe.current=!1),b(_),m(null)},onOpenPanel:m,onOpenSettings:()=>T(!0),onOpenBgTasks:()=>K(!0),onOpenGlobalSearch:()=>J(!0),sound:E,onSoundChange:Z,onSoundPreview:_=>Qe(_,E),themes:te,theme:S,onThemeChange:F}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(_=>e.jsx(hr,{notice:_,onDismiss:l},_.id))}),e.jsx(wa,{send:a,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${$}px`,"--right-w":`${j}px`},children:[N&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>m(null)}),e.jsxs("div",{className:`view-pane ${y==="chat"?"":"hidden"}`,children:[e.jsx("div",{className:`panel-drawer drawer-left ${N==="left"?"open":""}`,children:e.jsx(ci,{send:ce,active:!A||N==="left",ready:s.ready,status:s.status,cwd:((Ot=s.state)==null?void 0:Ot.cwd)??"",sessionFile:((Wt=s.state)==null?void 0:Wt.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!A&&e.jsx(Ts,{side:"left",width:$,onResize:D}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(Ma,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:$e,onKillBash:()=>a({type:"abort_bash"}),thinkingWrap:((Ht=s.settings)==null?void 0:Ht.thinkingWrap)??!0,toolsWrap:((Ut=s.settings)==null?void 0:Ut.toolsWrap)??!0},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(Fa,{send:a,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId}),s.dialog&&e.jsx(Wa,{dialog:s.dialog,send:a}),e.jsx(_a,{send:a,ready:s.ready,streaming:((qt=s.state)==null?void 0:qt.isStreaming)??!1,messages:((Kt=s.state)==null?void 0:Kt.messages)??gr,slashCommands:s.slashCommands,modelState:f,models:s.models,modelsLoading:s.modelsLoading,attachments:n,onRemoveAttachment:Ce,onAddImageFiles:Oe,onAddLocalFiles:Ae,onNotice:c,onManageModels:Ve,onSent:Ge})]}),!A&&e.jsx(Ts,{side:"right",width:j,onResize:R}),e.jsx("div",{className:`panel-drawer drawer-right ${N==="right"?"open":""}`,children:e.jsx(Di,{send:ce,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((zt=s.state)==null?void 0:zt.cwd)??"",onAttach:(_,U,re,fe)=>{m(null),d(_,U,re,fe)},onPreview:(_,U)=>{m(null),p({path:_,name:U})},onNotice:(_,U)=>c(_,U)})})]}),e.jsx("div",{className:`view-pane ${y==="terminal"?"":"hidden"}`,children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(mr,{chat:s,send:a,terminal:i})})}),e.jsx("div",{className:`view-pane ${y==="git"?"":"hidden"}`,children:e.jsx(Ua,{chat:s,send:a,terminal:i,active:y==="git",onSwitchToTerminal:()=>b("terminal")})}),B.map(_=>{const U=`plugin:${_.info.id}`;return e.jsx("div",{className:`view-pane ${y===U?"":"hidden"}`,children:e.jsx(qa,{entry:_,send:a})},_.info.id)})]})}),e.jsx($a,{chat:s,send:a}),u&&e.jsx(er,{file:u,content:s.fileContent,send:a,onAddLines:(_,U,re,fe)=>d(_,U,"lines",!1,{start:re,end:fe}),onAttach:(_,U,re)=>d(_,U,re),onClose:()=>p(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!ee&&!H&&e.jsx(Ka,{send:a,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>ie(!0)}),H&&e.jsx(Ga,{send:a,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>q(!1)}),L&&e.jsx(Ya,{chat:s,send:a,terminal:i,onSwitchToTerminal:()=>b("terminal"),onClose:()=>T(!1)}),C&&e.jsx(Xa,{servers:s.bgServers,send:a,onClose:()=>K(!1)}),me&&e.jsx(Za,{send:a,sessions:s.sessions,projects:s.projects,cwd:((Vt=s.state)==null?void 0:Vt.cwd)??"",fileSearch:s.fileSearch,onClose:()=>J(!1),onSwitchSession:_=>{a({type:"switch_session",path:_})},onSwitchProject:_=>{a({type:"set_cwd",path:_})},onPreviewFile:(_,U)=>{p({path:_,name:U})}})]})}di();mn(pn());bn.createRoot(document.getElementById("root")).render(e.jsx(r.StrictMode,{children:e.jsx(ai,{children:e.jsx(fr,{})})}));export{pt as F,Cs as T,De as a,kr as b,yr as c,Et as d,Ee as e,ke as f,On as g,qe as h,Re 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:i}),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")} · ${hs(c.size)}`:u?s("bridgedVision"):g?s("image"):c.mode==="lines"?s("inlineLinesRange",{start:c.startLine??1,end:c.endLine??c.lines??1}):s("inlineLines",{n:c.lines??y})}),!o&&(a?e.jsx(Fe,{}):e.jsx(ht,{}))]}),!o&&a&&(u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:s("bridgedVisionDetail")}),(g==null?void 0:g.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:g.dataUrl,alt:i})}),h&&e.jsx("pre",{className:"attachcard-content",children:h})]}):g!=null&&g.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:g.dataUrl,alt:i})}):e.jsx("pre",{className:"attachcard-content",children:h})),o&&e.jsx("div",{className:"attachcard-refnote",children:n?s("folderNotExpanded"):s("fileNotExpanded",{size:hs(c.size)})})]})}function hs(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function sa(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 a=t.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return a?a[1].trim():t.trim()}function na({block:t}){const s=pe(),[a,l]=r.useState(!1);return e.jsxs("div",{className:`skillcard${a?" 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(Xn,{})}),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:[a?e.jsx(mt,{}):e.jsx(Fe,{}),s(a?"collapseMsg":"expandMsg")]})]}),a&&e.jsx("div",{className:"skillcard-body",children:e.jsx(xt,{text:t.content})})]})}function gs({block:t,toolResults:s,liveOutputs:a,toolStatuses:l,streaming:c,isLast:i,onKillBash:n,thinkingWrap:o,toolsWrap:u}){const p=pe(),h=Ze(t);if(h){const B=c&&i;return e.jsxs("div",{className:"msg-text",children:[B?e.jsx(Hi,{text:h.text}):e.jsx(xt,{text:h.text}),h.truncated&&e.jsx("div",{className:"trunc-note",children:p("truncated")})]})}const g=Js(t);if(g)return e.jsx(Ui,{thinking:g.thinking,streaming:c&&i,wrap:o});const y=Ys(t);if(y){const B=s.get(y.id),E=a.get(y.id),$={result:B,liveOutput:E==null?void 0:E.text,streaming:c,status:l.get(y.id)};return e.jsx(zi,{block:y,view:$,onKillBash:n,wrap:u})}const b=Qs(t);if(b&&b.dataUrl)return e.jsx("div",{className:"msg-image",children:e.jsx("img",{src:b.dataUrl,alt:"attachment"})});const k=Xs(t);return k?e.jsxs("div",{className:"bashblock",children:[e.jsxs("div",{className:"bashblock-command",children:[e.jsx("span",{className:"bashblock-prompt",children:"$"}),e.jsx("code",{children:k.command}),k.exitCode!==void 0&&e.jsx("span",{className:`bashblock-exit ${k.exitCode===0?"ok":"err"}`,children:p("exitCode",{code:k.exitCode})}),k.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:p("cancelled")})]}),k.output&&e.jsx("pre",{className:"bashblock-output",children:k.output}),k.truncated&&e.jsx("div",{className:"trunc-note",children:p("outputTruncated")})]}):null}function Zs(t,s){switch(t){case"user":return s("role.user");case"assistant":return s("role.assistant");case"toolResult":return s("role.tool");case"bashExecution":return s("role.bash");case"branchSummary":return s("role.branch");case"compactionSummary":return s("role.compaction");default:return t}}function ia(t){const s=new Date(t),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${a}:${l}`}function fs(t,s,a){let l=!1;for(const c of s){const i=c;if(i.type!=="image"||typeof i.dataUrl!="string"||!i.dataUrl.startsWith("data:"))continue;const n=i.dataUrl.match(/^data:([^;]*);base64,(.+)$/);n&&(l=!0,t.push({path:"",imageData:n[2],mimeType:n[1]||"image/png",name:a??`image.${(n[1]||"image/png").split("/")[1]??"png"}`}))}return l}function aa(t){const s=new Map;for(let a=0;a<t.length;a++){const l=t[a];if(l.role!=="user"||!l.id)continue;const c=[];fs(c,l.content);for(let i=a+1;i<t.length&&t[i].role==="custom"&&t[i].customType==="file";i++){const n=t[i].details??{};if(!fs(c,t[i].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 ra=r.memo(function({message:s,onExpand:a}){const l=pe();let c="";for(const g of s.content){const y=Ze(g);if(y&&y.text.trim()){const b=Ft(y.text);b?c=`skill:${b.name}`+(b.userMessage?` · ${b.userMessage.replace(/\s+/g," ").trim()}`:""):c=y.text.replace(/\s+/g," ").trim();break}}if(!c&&s.role==="custom"&&s.customType==="file"){const g=s.details??{};c=g.name??g.path??""}c.length>90&&(c=`${c.slice(0,90)}…`);let n=0,o=0,u=0,p=0;for(const g of s.content)Js(g)?n++:Ys(g)?o++:Xs(g)?u++:Qs(g)&&p++;const h=[];return n&&h.push(`${l("thinking")} ${n}`),o&&h.push(`${l("toolCalls")} ${o}`),u&&h.push(`${l("bashRuns")} ${u}`),p&&h.push(`${l("images")} ${p}`),e.jsxs("button",{type:"button",className:"msg-collapsed","data-msg-id":s.id,title:`${l("expandMsg")} · ${c||h.join(" · ")||s.role}`,onClick:()=>a(s.id),children:[e.jsx("span",{className:`msg-collapsed-role role-${s.role}`,children:s.role==="custom"&&s.customType==="file"?l("attachment"):Zs(s.role,l)}),e.jsxs("span",{className:"msg-collapsed-body",children:[c&&e.jsx("span",{className:"msg-collapsed-preview",children:c}),h.length>0&&e.jsx("span",{className:"msg-collapsed-chips",children:h.map((g,y)=>e.jsx("span",{className:"msg-collapsed-chip",children:g},y))})]}),s.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:la(s.timestamp)}):null,e.jsxs("span",{className:"msg-collapsed-action",children:[e.jsx(Fe,{})," ",l("expandMsg")]})]})});function la(t){const s=new Date(t),a=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${a}:${l}`}const oa=r.memo(function({id:s,show:a,height:l,containerRef:c,onMeasured:i,lazyRef:n,children:o}){const u=r.useRef(null),p=r.useRef(null);return r.useLayoutEffect(()=>{const h=p.current;if(p.current=a,!a||h!==!1)return;const g=u.current,y=c.current;if(!g||!y)return;const b=g.offsetHeight;i==null||i(s,b);const k=b-l;if(k!==0){const B=g.parentElement;B&&B.getBoundingClientRect().bottom<=y.getBoundingClientRect().top&&(y.scrollTop+=k)}},[a]),a?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 ca(t,s,a,l){const c=[],i=[];let n=0;for(const o of t){if(a.has(o.id))continue;o.top<s.bottom&&o.bottom>s.top?l.has(o.id)&&c.push(o.id):l.has(o.id)||(i.push(o.id),o.bottom<=s.top&&(n+=o.bottom-o.top))}return{show:c,hide:i,shrinkAbove:n}}function da(t,s){if(s.show.length===0&&s.hide.length===0)return t;const a=new Set(t);for(const l of s.show)a.delete(l);for(const l of s.hide)a.add(l);return a}function ua(t,s,a){const l=new Set;let c=0;for(let i=t.length-1;i>=0&&!(i<t.length-1&&c>=a);i--){const n=t[i];l.add(n.id),c+=s.get(n.id)??en(n.role,n.customType)}return l}function en(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 pa=["text","thinking","argumentsText","output","command"];function ma(t){let s=0;for(const a of t.content){a.type==="image"&&(s+=1);for(const l of pa){const c=a[l];typeof c=="string"&&(s+=c.length)}}return s}function ha(t,s,a,l){const c=a.get(t);return c&&c.len===s?c.h:l}function ga(t){if(t.role==="toolResult")return"";const s=[];for(const a of t.content)fa(a,s);return t.errorMessage&&s.push(t.errorMessage),s.join(`
|
|
317
|
+
`)}function fa(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 xa(t,s){const a=s.trim().toLowerCase();if(!a)return 0;const l=t.toLowerCase();let c=0,i=l.indexOf(a);for(;i!==-1;)c++,i=l.indexOf(a,i+a.length);return c}function va(t,s){const a=s.trim().toLowerCase();if(!a)return[];const l=[];for(const c of t){const i=ga(c);if(!i)continue;const n=xa(i,a);for(let o=0;o<n;o++)l.push({messageId:c.id,occurrence:o})}return l}function ya(t,s){var n;const a=new Map,l=[],c=s.toLowerCase();if(!c)return{byMsg:a,all:l};const i=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(o){const u=o.parentElement;return!u||u.closest(".search-bar")?NodeFilter.FILTER_REJECT:(o.textContent??"").toLowerCase().includes(c)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let o=i.nextNode();o;o=i.nextNode()){const u=(o.textContent??"").toLowerCase(),p=(n=o.parentElement)==null?void 0:n.closest("[data-msg-id]");if(!p)continue;const h=p.getAttribute("data-msg-id")??"";let g=u.indexOf(c);for(;g!==-1;){const y=document.createRange();y.setStart(o,g),y.setEnd(o,g+c.length),l.push(y);const b=a.get(h);b?b.push(y):a.set(h,[y]),g=u.indexOf(c,g+c.length)}}return{byMsg:a,all:l}}function He(t,s){const a=CSS;if(!a.highlights)return;if(s.length===0){a.highlights.delete(t);return}const l=window.Highlight;l&&a.highlights.set(t,new l(...s))}function ka({containerRef:t,messages:s,open:a,onClose:l,onEnsureExpanded:c}){const i=pe(),n=r.useRef(null),[o,u]=r.useState(""),[p,h]=r.useState(0),g=r.useDeferredValue(o),y=a?g.trim():"",b=r.useMemo(()=>a?va(s,y):[],[s,y,a]),k=r.useRef(b);k.current=b;const B=r.useRef(p);B.current=p,r.useEffect(()=>{a&&(h(0),requestAnimationFrame(()=>{var j;return(j=n.current)==null?void 0:j.select()}))},[a]),r.useEffect(()=>{if(!a)return;const j=P=>{P.key==="Escape"&&(P.preventDefault(),P.stopPropagation(),l())};return window.addEventListener("keydown",j,!0),()=>window.removeEventListener("keydown",j,!0)},[a,l]),r.useEffect(()=>(a||(He("msg-search",[]),He("msg-search-active",[])),()=>{He("msg-search",[]),He("msg-search-active",[])}),[a]);const E=r.useCallback(j=>{const P=t.current;if(!P)return;const D=P.querySelector(`[data-msg-id="${j}"]`);D&&(D.classList.remove("msg-flash"),D.offsetWidth,D.classList.add("msg-flash"))},[t]);r.useLayoutEffect(()=>{if(!a||!y)return;const j=t.current;if(!j)return;let P=!1,D=0;return D=requestAnimationFrame(()=>{var ee;if(P)return;const{byMsg:R,all:N}=ya(j,y);He("msg-search",N);const m=k.current,A=m[Math.min(B.current,m.length-1)];if(!A)return;const W=(ee=R.get(A.messageId))==null?void 0:ee[A.occurrence];if(W){He("msg-search-active",[W]);const ie=W.startContainer.parentElement??j.querySelector(`[data-msg-id="${A.messageId}"]`);ie==null||ie.scrollIntoView({block:"center"})}else E(A.messageId)}),()=>{P=!0,cancelAnimationFrame(D)}},[a,y,b,t,E]);const $=r.useCallback(j=>{const P=k.current;if(P.length===0)return;const D=(B.current+j+P.length)%P.length;h(D),c(P[D].messageId)},[c]);if(!a)return null;const x=b.length;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:n,className:"search-input",type:"text",value:o,placeholder:i("searchPlaceholder"),onChange:j=>{u(j.target.value),h(0)},onKeyDown:j=>{j.key==="Enter"&&(j.preventDefault(),$(j.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${x===0?"empty":""}`,children:x===0?i("searchNoResults"):`${Math.min(p+1,x)}/${x}`}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchPrev"),disabled:x===0,onClick:()=>$(-1),children:e.jsx(mt,{})}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchNext"),disabled:x===0,onClick:()=>$(1),children:e.jsx(Fe,{})}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchClose"),onClick:l,children:e.jsx(ke,{})})]})}function ba(t){const{dSt:s,dSh:a,escaped:l,graceActive:c,stuck:i}=t;return c?{flipEscape:!1,reassert:!1}:s>=-4||s<=-500?{flipEscape:!1,reassert:!1}:a<0?{flipEscape:!1,reassert:i&&!l}:{flipEscape:!0,reassert:!1}}const tn=[{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"}],sn="pi-web-ui:prompt-templates";function ja(){try{const t=localStorage.getItem(sn);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(a=>!!a&&typeof a=="object"&&typeof a.id=="string"):[]}catch{return[]}}function xs(t){return tn.some(s=>s.id===t)}function tt(t){return typeof t.title=="string"}const nn=r.createContext(null);function an(){const t=r.useContext(nn);if(!t)throw new Error("useTemplates must be used within TemplateProvider");return t}function wa({send:t,children:s}){const a=pe(),[l,c]=r.useState(ja),[i,n]=r.useState(!1),[o,u]=r.useState(null),[p,h]=r.useState(!1),[g,y]=r.useState(!1),[b,k]=r.useState(!1);r.useEffect(()=>{try{localStorage.setItem(sn,JSON.stringify(l))}catch{}},[l]);const B=r.useMemo(()=>{const H=new Map,q=new Set;for(const C of l)C.hidden?q.add(C.id):(tt(C)&&!xs(C.id)||tt(C))&&H.set(C.id,C);const L=tn.filter(C=>!q.has(C.id)).map(C=>{const K=H.get(C.id);return{id:C.id,icon:(K==null?void 0:K.icon)??C.icon,title:(K==null?void 0:K.title)??a(C.titleKey),desc:(K==null?void 0:K.desc)??a(C.descKey),prompt:(K==null?void 0:K.prompt)??a(C.promptKey),builtin:!0}}),S=l.filter(C=>tt(C)&&!xs(C.id)).map(C=>({id:C.id,icon:C.icon??"📌",title:C.title??"",desc:C.desc??"",prompt:C.prompt??""}));return[...L,...S]},[l,a]),E=r.useCallback(()=>n(!0),[]),$=r.useCallback(H=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:H}))},[]),x=r.useCallback((H,q=!1)=>{k(q),H?(h(!1),u({...H})):(h(!0),u({id:Re(),icon:"📌",title:"",desc:"",prompt:""}))},[]),j=r.useCallback(()=>{n(!1),u(null),k(!1)},[]),P=r.useCallback(()=>{g?(c([]),y(!1)):(y(!0),setTimeout(()=>y(!1),5e3))},[g]),D=r.useCallback(H=>{n(!1),$(H.prompt)},[$]),R=r.useCallback(H=>{n(!1),x(H,!0)},[x]),N=r.useCallback(()=>{n(!1),x(void 0,!0)},[x]),m=r.useCallback(H=>{c(q=>{const L=q.findIndex(S=>S.id===H.id);if(L>=0){const S=[...q];return S[L]=H,S}return[...q,H]}),u(null),b&&(n(!0),k(!1))},[b]),A=r.useCallback(H=>{c(q=>H.builtin?[...q.filter(S=>S.id!==H.id),{id:H.id,hidden:!0}]:q.filter(L=>L.id!==H.id)),u(null),b&&(n(!0),k(!1))},[b]),W=r.useCallback(H=>{c(q=>q.filter(L=>L.id!==H.id||L.hidden)),u(null),b&&(n(!0),k(!1))},[b]),ee=r.useMemo(()=>({templates:B,fill:$,openPicker:E,openEdit:x,resetConfirm:g,toggleReset:P}),[B,$,E,x,g,P]),ie=o?l.some(H=>H.id===o.id&&!H.hidden&&tt(H)):!1;return e.jsxs(nn.Provider,{value:ee,children:[s,i&&e.jsx(Ca,{templates:B,resetConfirm:g,onFill:D,onEditTpl:R,onNew:N,onResetToggle:P,onClose:j}),o&&e.jsx(Sa,{editing:o,isNew:p,hasOverride:ie,onDraft:u,onSave:m,onRestore:()=>W(o),onRemove:()=>A(o),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:o.prompt})),j()},onSend:()=>{const H=o.prompt.trim();H&&t({type:"prompt",text:H,queue:!1})&&j()},onClose:j})]})}function Na(){const t=pe(),{templates:s,fill:a,openEdit:l,toggleReset:c,resetConfirm:i}=an();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(rn,{tpl:n,title:t("tpl.clickCard"),onFill:()=>a(n.prompt),onEdit:()=>l(n),editTitle:t("tpl.editTpl")},n.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>l(),title:t("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(De,{})}),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(Bs,{}),t(i?"tpl.resetConfirm":"tpl.reset")]})})]})}function rn({tpl:t,title:s,onFill:a,onEdit:l,editTitle:c}){const i=pe();return e.jsxs("button",{type:"button",className:"empty-template",title:s,onClick:a,children:[e.jsx("span",{className:"empty-template-icon",children:t.icon}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t.title}),e.jsx("span",{className:"empty-template-desc",children:t.desc})]}),e.jsx("span",{className:"template-card-ops",role:"button",title:c??i("tpl.editTpl"),onClick:n=>{n.stopPropagation(),l()},children:e.jsx(Et,{})})]})}function Ca({templates:t,resetConfirm:s,onFill:a,onEditTpl:l,onNew:c,onResetToggle:i,onClose:n}){const o=pe();return r.useEffect(()=>{const u=p=>{p.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(ke,{})})]}),e.jsx("div",{className:"template-picker-hint",children:o("tpl.pickerHint")}),e.jsxs("div",{className:"template-picker-grid",children:[t.map(u=>e.jsx(rn,{tpl:u,title:o("tpl.clickCard"),onFill:()=>a(u),onEdit:()=>l(u),editTitle:o("tpl.editTpl")},u.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:c,title:o("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(De,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:o("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:o("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"template-picker-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:i,children:[e.jsx(Bs,{}),o(s?"tpl.resetConfirm":"tpl.reset")]})})]})})}function Sa({editing:t,isNew:s,hasOverride:a,onDraft:l,onSave:c,onRestore:i,onRemove:n,onFill:o,onSend:u,onClose:p}){const h=pe(),g=r.useRef(null);r.useEffect(()=>{const k=B=>{B.key==="Escape"&&p()};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)},[p]),r.useEffect(()=>{const k=g.current;if(!k)return;k.style.height="auto";const B=k.scrollHeight>300;k.style.height=`${Math.min(k.scrollHeight,300)}px`,k.style.overflowY=B?"auto":"hidden"},[t.prompt]);const y=()=>{const k=t.title.trim(),B=t.prompt.trim();if(!k||!B){l({...t,error:h("tpl.required")});return}c({id:t.id,icon:t.icon.trim()||"📌",title:k,desc:t.desc.trim(),prompt:B})},b=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:p,children:e.jsxs("div",{className:"modal template-modal",onClick:k=>k.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:h(b?"tpl.builtin":"tpl.custom")}),e.jsx("span",{className:"template-modal-title",children:h(s?"tpl.newTitle":"tpl.editTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:h("close"),onClick:p,children:e.jsx(ke,{})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:h("tpl.fieldIcon")}),e.jsx("input",{className:"template-field-input icon",value:t.icon,maxLength:4,onChange:k=>l({...t,icon:k.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:h("tpl.fieldTitle")}),e.jsx("input",{className:"template-field-input",value:t.title,placeholder:h("tpl.fieldTitlePh"),onChange:k=>l({...t,title:k.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:h("tpl.fieldDesc")}),e.jsx("input",{className:"template-field-input",value:t.desc,placeholder:h("tpl.fieldDescPh"),onChange:k=>l({...t,desc:k.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:h("tpl.fieldPrompt")}),e.jsx("textarea",{ref:g,className:"template-field-prompt",value:t.prompt,placeholder:h("tpl.fieldPromptPh"),onChange:k=>l({...t,prompt:k.target.value})})]}),t.error&&e.jsx("div",{className:"template-error",children:t.error}),e.jsxs("div",{className:"template-modal-actions",children:[e.jsxs("div",{className:"template-modal-actions-left",children:[!s&&b&&a&&e.jsx("button",{type:"button",className:"btn template-btn ghost",title:h("tpl.restoreTip"),onClick:i,children:h("tpl.restore")}),!s&&b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:h("tpl.removeTip"),onClick:n,children:[e.jsx(Ee,{})," ",h("tpl.remove")]}),!s&&!b&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:h("tpl.deleteTip"),onClick:n,children:[e.jsx(Ee,{})," ",h("tpl.delete")]})]}),e.jsxs("div",{className:"template-modal-actions-right",children:[e.jsx("button",{type:"button",className:"btn template-btn",onClick:y,children:h("tpl.save")}),e.jsx("button",{type:"button",className:"btn template-btn fill",onClick:o,title:h("tpl.fillTip"),children:h("tpl.fill")}),e.jsxs("button",{type:"button",className:"btn template-btn send",onClick:u,title:h("tpl.sendTip"),children:[e.jsx(Ds,{})," ",h("tpl.sendNow")]})]})]})]})})}const vs=new Map,Ta=15,ys=30,jt=250,ks=1200,Ea=1600;function bs(t){return t.content.some(s=>s.type==="toolCall")}function Ma({state:t,liveOutputs:s,toolStatuses:a,onEdit:l,onKillBash:c,thinkingWrap:i,toolsWrap:n}){const o=pe(),u=r.useRef(null),[p,h]=r.useState(!0),g=r.useRef(!0),y=r.useRef(0),b=r.useRef(0),k=r.useRef(!1),B=r.useRef(0),[E,$]=r.useState(()=>new Set),[x,j]=r.useState(!1),P=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,D=r.useMemo(()=>{const f=new Map;for(const v of t.messages)v.role==="toolResult"&&v.toolCallId&&f.set(v.toolCallId,v);return f},[t.messages]),R=r.useMemo(()=>aa(t.messages),[t.messages]),N=P.length>0?P[P.length-1].id:null,m=t.messages.length>ys?Math.max(0,t.messages.length-Ta):0,[A,W]=r.useState(()=>new Set),[ee,ie]=r.useState(()=>new Set),H=r.useRef(new Map),q=r.useRef(new Map),L=r.useRef(new Map),S=r.useRef(0),C=r.useMemo(()=>{const f=new Map;for(const v of t.messages)f.set(v.id,ma(v));return f},[t.messages]),K=r.useRef(C);K.current=C;const me=r.useRef(A);me.current=A;const J=t.messages.length>ys&&!x,T=r.useRef(J);T.current=J;const Z=ua(t.messages,H.current,Ea),te=r.useRef(Z);te.current=Z;const M=r.useCallback(()=>{const f=u.current;if(!f)return;if(!T.current){W(de=>de.size?new Set:de);return}const v=f.getBoundingClientRect(),V={top:v.top-ks,bottom:v.bottom+ks},O=[];for(const[de,ye]of L.current){const Se=ye.getBoundingClientRect();O.push({id:de,top:Se.top,bottom:Se.bottom}),me.current.has(de)||ne(de,Se.bottom-Se.top,K.current.get(de))}const ae=ca(O,V,te.current,me.current);for(const de of ae.hide){const ye=L.current.get(de);ye&&ne(de,ye.offsetHeight,K.current.get(de))}W(de=>da(de,ae))},[]),F=r.useCallback(()=>{S.current||(S.current=requestAnimationFrame(()=>{S.current=0,M()}))},[M]);r.useLayoutEffect(()=>{M()},[M]);const z=r.useRef(x);r.useLayoutEffect(()=>{z.current&&!x&&M(),z.current=x},[x,M]);const ne=r.useCallback((f,v,V)=>{V!==void 0&&(q.current.set(f,{h:v,len:V}),H.current.set(f,v))},[]),G=r.useCallback((f,v)=>{ne(f,v,K.current.get(f))},[ne]),oe=r.useCallback(f=>{f&&L.current.set(f.dataset.lazyId??"",f)},[]);r.useEffect(()=>{const f=new Set(t.messages.map(v=>v.id));for(const[v,V]of L.current)f.has(v)||(L.current.delete(v),H.current.delete(v),q.current.delete(v));W(v=>{let V=!1;const O=new Set;for(const ae of v)f.has(ae)?O.add(ae):V=!0;return V?O:v})},[t.messages,E]),r.useEffect(()=>()=>cancelAnimationFrame(S.current),[]);const X=r.useMemo(()=>{const f=[];for(const v of t.messages){if(v.role!=="user")continue;const V=v.content.map(de=>{var ye;return((ye=Ze(de))==null?void 0:ye.text)??""}).filter(Boolean).join(" "),O=Ft(V),ae=O?O.userMessage??`skill:${O.name}`:V.trim();ae&&f.push({id:v.id,text:ae})}return f},[t.messages]),d=r.useMemo(()=>{const f=new Map;return X.forEach((v,V)=>f.set(v.id,V)),f},[X]),[I,ce]=r.useState(-1),se=r.useRef(-1),he=r.useRef(X);r.useEffect(()=>{he.current=X},[X]);const Q=r.useCallback(()=>{const f=u.current,v=he.current;if(!f||v.length===0)return;const V=f.getBoundingClientRect().top,O=140;let ae=-1;for(let de=0;de<v.length;de++){const ye=f.querySelector(`[data-msg-id="${v[de].id}"]`);if(ye)if(ye.getBoundingClientRect().top<=V+O)ae=de;else break}ae!==se.current&&(se.current=ae,ce(ae))},[]);r.useEffect(()=>{Q()},[X,Q]);const le=r.useCallback(f=>{$(v=>v.has(f)?v:new Set(v).add(f))},[]),ge=r.useCallback(f=>{const v=t.messages.findIndex(V=>V.id===f);v>=0&&v<m&&!E.has(f)&&ds.flushSync(()=>le(f))},[t.messages,m,E,le]);r.useEffect(()=>{const f=v=>{if(!(v.ctrlKey||v.metaKey)||v.key.toLowerCase()!=="f")return;const V=v.target;V&&(V.tagName==="INPUT"||V.tagName==="TEXTAREA"||V.isContentEditable)||(v.preventDefault(),j(!0))};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[]);const ue=r.useCallback(f=>{$(v=>{if(!v.has(f))return v;const V=new Set(v);return V.delete(f),V})},[]),we=r.useCallback(f=>{const v=t.messages.findIndex(O=>O.id===f);ds.flushSync(()=>{v>=0&&v<m&&!E.has(f)&&le(f),ie(O=>O.has(f)?O:new Set(O).add(f))});const V=he.current.findIndex(O=>O.id===f);se.current=V,ce(V),requestAnimationFrame(()=>{var ae,de,ye;const O=(ae=u.current)==null?void 0:ae.querySelector(`[data-msg-id="${f}"]`);O&&((de=u.current)==null||de.querySelectorAll(".msg-flash").forEach(Se=>Se.classList.remove("msg-flash")),O.scrollIntoView({block:"start"}),O.classList.remove("msg-flash"),O.offsetWidth,O.classList.add("msg-flash"),O!==((ye=u.current)==null?void 0:ye.lastElementChild)&&(k.current=!0))})},[t.messages,m,E,le]),Be=r.useCallback(()=>{const f=u.current;if(!f)return;const v=f.scrollTop-y.current,V=f.scrollHeight-b.current;y.current=f.scrollTop,b.current=f.scrollHeight;const O=f.scrollHeight-f.scrollTop-f.clientHeight<80,ae=Date.now()<B.current,de=ba({dSt:v,dSh:V,escaped:k.current,graceActive:ae,stuck:g.current});de.reassert&&(B.current=Date.now()+jt,f.scrollTop=f.scrollHeight),de.flipEscape&&(k.current=!0),O&&v>=0&&(k.current=!1),ae||(v<0?g.current=O&&!k.current:O&&(g.current=!0)),h(g.current),Q(),F()},[Q,F]),$e=r.useRef(!1);r.useEffect(()=>{const f=$e.current;if($e.current=!!t.isStreaming,f&&!t.isStreaming&&!k.current){const v=()=>{const O=u.current;O&&!k.current&&(O.scrollTop=O.scrollHeight,g.current=!0,h(!0))};requestAnimationFrame(()=>requestAnimationFrame(v));const V=setTimeout(v,180);return()=>clearTimeout(V)}},[t.isStreaming]),r.useEffect(()=>{const f=u.current;f&&g.current&&(f.scrollTop=f.scrollHeight)},[P,t.isStreaming,s]);const Ve=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");r.useEffect(()=>{const f=u.current;f&&g.current&&(f.scrollTop=f.scrollHeight)},[Ve]),r.useEffect(()=>{const f=u.current;if(!f||typeof ResizeObserver>"u")return;const v=new ResizeObserver(()=>{g.current&&!k.current&&(f.scrollTop=f.scrollHeight,h(!0))});return v.observe(f),()=>v.disconnect()},[]),r.useEffect(()=>{const f=u.current;if(!f||typeof MutationObserver>"u")return;let v=!1;const V=new MutationObserver(()=>{v||(v=!0,requestAnimationFrame(()=>{v=!1;const O=u.current;O&&g.current&&!k.current&&(O.scrollTop=O.scrollHeight,h(!0))}))});return V.observe(f,{childList:!0,subtree:!0,characterData:!0}),()=>V.disconnect()},[]);const Ge=r.useCallback(()=>{if(!u.current)return;g.current=!0,k.current=!1,h(!0),B.current=Date.now()+jt;const v=()=>{const V=u.current;!V||!g.current||k.current||(B.current=Date.now()+jt,V.scrollTop=V.scrollHeight)};v(),requestAnimationFrame(()=>requestAnimationFrame(v)),setTimeout(v,120),setTimeout(v,300),setTimeout(v,600)},[]),Ce=r.useRef(null);r.useEffect(()=>{const f=Ce.current,v=u.current;if(!f||!v)return;const V=O=>{O.preventDefault();const ae=f.querySelector(".qn-list");if(ae&&ae.contains(O.target)&&ae.scrollHeight>ae.clientHeight){ae.scrollTop+=O.deltaY;return}v.scrollTop+=O.deltaY};return f.addEventListener("wheel",V,{passive:!1}),()=>f.removeEventListener("wheel",V)},[]);const[Oe,Ae]=r.useState(0);r.useEffect(()=>{const f=()=>{var v;Ae(((v=u.current)==null?void 0:v.clientHeight)??0),F()};return f(),window.addEventListener("resize",f),()=>window.removeEventListener("resize",f)},[F]);const Ne=X.length,Pe=r.useMemo(()=>Ne===0?27:Math.max(4,Math.min(27,Math.floor(((Oe||600)-16)/Ne)-3)),[Ne,Oe]),w=Pe<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:`messages${p?"":" anchor-live"}`,ref:u,onScroll:Be,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(Na,{})}),t.messages.map((f,v)=>{const V=v<m,O=V&&E.has(f.id);if(V&&!O)return f.role==="toolResult"?null:e.jsx(ra,{message:f,onExpand:le},f.id);const ae=f.role==="user"?d.get(f.id):void 0,de=!J||Z.has(f.id)||ee.has(f.id)||!A.has(f.id);return e.jsx(oa,{id:f.id,show:de,height:ha(f.id,C.get(f.id)??-1,q.current,en(f.role,f.customType)),containerRef:u,onMeasured:G,lazyRef:oe,children:e.jsx(ms,{message:f,qnIndex:ae,qnActive:ae!==void 0?ae===I:void 0,onJump:we,toolResults:D,liveOutputs:bs(f)?s:vs,toolStatuses:a,streaming:t.isStreaming,onKillBash:c,toolsWrap:n,thinkingWrap:i,isLast:f.id===N,onEdit:l,questionAttachments:R.get(f.id),onCollapse:O?ue:void 0},f.id)},f.id)}),t.streamingMessage&&e.jsx(ms,{message:t.streamingMessage,toolResults:D,liveOutputs:bs(t.streamingMessage)?s:vs,toolStatuses:a,streaming:!0,isLast:!0,onEdit:l,onKillBash:c,toolsWrap:n,thinkingWrap:i},t.streamingMessage.id),t.isStreaming&&P.length===0&&e.jsx("div",{className:"streaming-wait",children:o("waitingResponse")}),t.queue.steering.map((f,v)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:o("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:f})]})},`q-steer-${v}`)),t.queue.followUp.map((f,v)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:o("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:f})]})},`q-fu-${v}`))]}),!p&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Ge,children:[e.jsx($s,{})," ",o("backToBottom")]}),e.jsx(ka,{containerRef:u,messages:P,open:x,onClose:()=>j(!1),onEnsureExpanded:ge}),X.length>0&&e.jsxs("div",{className:`qn-rail ${w?"many":""}`,ref:Ce,"aria-label":o("questionNavTitle"),style:{"--rail-gap":`${Pe}px`},children:[X.map((f,v)=>e.jsx("button",{type:"button",className:`qn-bar ${v===I?"active":""}`,"aria-label":`${v+1}. ${f.text}`,onClick:()=>we(f.id),children:e.jsxs("span",{className:"qn-bar-text",children:[v+1,". ",f.text]})},f.id)),w&&e.jsx("div",{className:"qn-list",children:X.map((f,v)=>e.jsxs("button",{type:"button",className:`qn-list-item ${v===I?"active":""}`,"aria-label":`${v+1}. ${f.text}`,onClick:()=>we(f.id),children:[e.jsx("span",{className:"qn-list-idx",children:v+1}),e.jsx("span",{className:"qn-list-text",children:f.text})]},f.id))})]})]})}const ln="pi-web-model-usage";function Ra(t){if(!t||typeof t!="object")return{};const s={};for(const[a,l]of Object.entries(t)){const c=typeof l=="number"?Math.floor(l):0;Number.isFinite(c)&&c>0&&(s[a]=c)}return s}function Pa(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function Ia(t,s){const a=s;return t.map((l,c)=>({m:l,i:c,count:a[l.id]??0})).sort((l,c)=>c.count-l.count||l.i-c.i).map(l=>l.m)}function on(){try{const t=localStorage.getItem(ln);return t?Ra(JSON.parse(t)):{}}catch{return{}}}function La(t){try{localStorage.setItem(ln,JSON.stringify(t))}catch{}}function Da(t){const s=Pa(on(),t);return La(s),s}const Ba=["off","minimal","low","medium","high","xhigh","max"],Aa=r.memo(function({state:s,models:a,modelsLoading:l,send:c,onManageModels:i,compact:n=!1}){const o=pe(),u=s==null?void 0:s.model,p=u?`${u.provider}/${u.id}`:null,[h,g]=r.useState(!1),[y,b]=r.useState(!1),[k,B]=r.useState(""),[E,$]=r.useState(null),[x,j]=r.useState({}),P=r.useRef(null),D=r.useRef(null),[R,N]=r.useState(null);r.useEffect(()=>{if(!h){N(null);return}if(a.length===0)return;const S=requestAnimationFrame(()=>{const C=D.current;C&&N(C.offsetWidth)});return()=>cancelAnimationFrame(S)},[h,a.length]),r.useEffect(()=>{h&&j(on())},[h]),r.useEffect(()=>{h||(B(""),$(null))},[h]);const m=r.useMemo(()=>{const S=new Map;for(const C of a)S.set(C.provider,(S.get(C.provider)??0)+1);return[...S.entries()].sort((C,K)=>C[0].localeCompare(K[0])).map(([C,K])=>({name:C,count:K}))},[a]),A=r.useMemo(()=>Ia(a,x),[a,x]),W=r.useMemo(()=>{let S=A;E&&(S=S.filter(K=>K.provider===E));const C=k.trim().toLowerCase();return C?S.filter(K=>K.name.toLowerCase().includes(C)||K.provider.toLowerCase().includes(C)||K.id.toLowerCase().includes(C)):S},[A,k,E]),[ee,ie]=r.useState(!1),H=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,q=Ba.map(S=>({value:S,label:o(`thinking.${S}`),supported:H?H.has(S):!0})),L=S=>{var C;return((C=q.find(K=>K.value===S))==null?void 0:C.label)??S};return r.useEffect(()=>{h&&a.length===0&&!ee&&!l&&(ie(!0),c({type:"list_models"}))},[h,a.length,ee,l,c]),r.useEffect(()=>{a.length>0&&ie(!1)},[a.length]),r.useEffect(()=>{var C;if(!h)return;const S=(C=P.current)==null?void 0:C.querySelector(".dd-item.active");S==null||S.scrollIntoView({block:"nearest"})},[h,p,a.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Xe,{}),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:h,onOpenChange:g,menuClassName:"dd-menu-model",menuRef:D,menuStyle:R!=null?{width:R}:void 0,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(dt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:o("searchModels"),value:k,onChange:S=>B(S.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[m.length>1&&e.jsxs("div",{className:"dd-provider-col",children:[e.jsx("div",{className:"dd-provider-head",children:o("providers")}),e.jsx("button",{type:"button",className:`dd-provider-item ${E===null?"active":""}`,onClick:()=>$(null),children:e.jsx("span",{children:o("allProviders")})}),m.map(S=>e.jsxs("button",{type:"button",className:`dd-provider-item ${E===S.name?"active":""}`,onClick:()=>$(E===S.name?null:S.name),title:`${S.name} · ${S.count}`,children:[e.jsx("span",{className:"dd-provider-name",children:S.name}),e.jsx("span",{className:"dd-provider-count",children:S.count})]},S.name))]}),e.jsxs("div",{className:"dd-model-scroll",ref:P,children:[(ee||l)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),a.length===0&&!ee&&!l&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),W.length===0&&a.length>0&&e.jsx("div",{className:"dd-loading",children:o("noModelMatches")}),W.map(S=>e.jsx(be,{active:p===S.id,onClick:()=>{p!==S.id&&c({type:"set_model",modelId:S.id}),g(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:S.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:S.provider}),(x[S.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:o("modelUsedCount",{n:x[S.id]})}),(S.reasoning||S.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[S.reasoning&&e.jsx("span",{className:"dd-model-badge",children:o("reasoning")}),S.vision&&e.jsx("span",{className:"dd-model-badge",children:o("vision")})]})]})]})},S.id))]})]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>c({type:"list_models"}),children:o("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{g(!1),i()},children:o("manageModels")})]})]}),e.jsxs(Le,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(nt,{}),e.jsx("span",{className:"chip-sub",children:o("thinkingChip",{level:s?L(s.thinkingLevel):"—"})})]}),open:y,onOpenChange:b,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("thinkingLevel")}),q.map(S=>e.jsx(be,{active:(s==null?void 0:s.thinkingLevel)===S.value,disabled:!S.supported,title:S.supported?void 0:o("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==S.value&&c({type:"set_thinking",level:S.value}),b(!1)},children:S.label},S.value))]})]})}),_a=r.memo(function({ready:s,streaming:a,messages:l,slashCommands:c,modelState:i,models:n,modelsLoading:o,send:u,attachments:p,onRemoveAttachment:h,onAddImageFiles:g,onAddLocalFiles:y,onNotice:b,onSent:k,onManageModels:B}){const E=pe(),{locale:$}=At(),{openPicker:x}=an(),j=d=>$==="en"&&d.descriptionEn?d.descriptionEn:d.description??"",P=d=>$==="en"&&d.argumentHintEn?d.argumentHintEn:d.argumentHint??"",[D,R]=r.useState(""),[N,m]=r.useState(!1),[A,W]=r.useState(null),[ee,ie]=r.useState(0),[H,q]=r.useState(!1),[L,S]=r.useState(void 0),C=r.useRef(null),K=r.useRef(null),me=r.useRef(null),J={builtin:E("slashBuiltin"),extension:E("slashExtension"),prompt:E("slashPrompt"),skill:E("slashSkill"),plugin:E("slashPlugin")},T=d=>{const I=d.match(/^\/([^\s]*)$/);if(I&&s){const ce=I[1].toLowerCase(),se=c.filter(he=>he.name.toLowerCase().startsWith(ce));W(se.length>0?se:null),ie(0)}else W(null)};r.useEffect(()=>{var I;const d=(I=me.current)==null?void 0:I.querySelector(".slash-item.active");d==null||d.scrollIntoView({block:"nearest"})},[ee,A]);const Z=d=>{var Q;const I=A??[],ce=d??I[ee%Math.max(I.length,1)];if(!ce){W(null);return}const se=D.match(/^\/([^\s]*)([\s\S]*)$/),he=se?se[2]:"";R(`/${ce.name} ${he}`),W(null),(Q=C.current)==null||Q.focus()},te=async()=>{const I=[...l].reverse().find(se=>se.role==="assistant"&&se.content.some(he=>he.type==="text"&&he.text)),ce=I==null?void 0:I.content.filter(se=>se.type==="text").map(se=>se.text).join(`
|
|
318
|
+
`);if(!ce){b("warning",E("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(ce),b("info",E("slashCopied"))}catch{b("error",E("slashCopyFailed"))}},M=d=>{if(!d||d.length===0){b("warning",E("foldersNotSupported"));return}const I=Array.from(d).filter(se=>Me(se.type)),ce=Array.from(d).filter(se=>!Me(se.type));I.length>0&&g(I),ce.length>0&&y(ce)},F=d=>{var se;const I=(se=d.clipboardData)==null?void 0:se.items;if(!I)return;const ce=[];for(const he of I)if(he.kind==="file"&&Me(he.type)){const Q=he.getAsFile();Q&&ce.push(Q)}ce.length!==0&&(d.preventDefault(),g(ce))},z=s,ne=r.useRef(D);r.useEffect(()=>{ne.current=D},[D]),r.useEffect(()=>{T(ne.current)},[c]),r.useEffect(()=>{const d=I=>{var se;const ce=I.detail;R(ce),(se=C.current)==null||se.focus()};return window.addEventListener("pi-web:fill",d),()=>window.removeEventListener("pi-web:fill",d)},[]),r.useEffect(()=>{if(!H)return;const d=I=>{I.key==="Escape"&&q(!1)};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[H]),r.useEffect(()=>{const d=C.current;if(!d)return;d.style.height="auto";const I=d.scrollHeight>220;d.style.height=`${Math.min(d.scrollHeight,220)}px`,d.style.overflowY=I?"auto":"hidden"},[D]);const G=(d=!1)=>{var se,he,Q,le,ge;const I=D.trim(),ce=p.some(ue=>ue.imageData||ue.fileData);if(!(!z||!I&&!ce)){if(I==="/help"){const ue=(he=(se=C.current)==null?void 0:se.closest(".inputbox"))==null?void 0:he.getBoundingClientRect();S(ue==null?void 0:ue.width),q(!0),R(""),(Q=C.current)==null||Q.focus();return}if(I==="/copy"){R(""),(le=C.current)==null||le.focus(),te();return}if(u({type:"prompt",text:I,queue:d,attachments:p.map(ue=>ue.imageData?{path:"",imageData:ue.imageData,mimeType:ue.mimeType,name:ue.name}:ue.fileData?{path:"",fileData:ue.fileData,mimeType:ue.mimeType,name:ue.name,size:ue.size}:{path:ue.path,mode:ue.mode,...ue.lines?{lines:ue.lines}:{}})})){R(""),k();const ue=i==null?void 0:i.model;ue&&Da(`${ue.provider}/${ue.id}`),(ge=C.current)==null||ge.focus()}}},oe=d=>{if(!d.nativeEvent.isComposing){if(A&&A.length>0)switch(d.key){case"ArrowDown":d.preventDefault(),ie(I=>(I+1)%A.length);return;case"ArrowUp":d.preventDefault(),ie(I=>(I-1+A.length)%A.length);return;case"Tab":case"Enter":d.preventDefault(),Z();return;case"Escape":d.preventDefault(),W(null);return}d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),G())}},X=()=>e.jsx("div",{className:"inputbox-actions",children:a?e.jsxs(e.Fragment,{children:[D.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:E("supplementTip"),onClick:()=>G(!0),children:[e.jsx(Ds,{})," ",E("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:E("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(ot,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:E("sendTip"),disabled:!z||!D.trim()&&!p.some(d=>d.imageData||d.fileData),onClick:()=>G(),children:e.jsx(Fs,{})})});return e.jsxs("div",{className:`inputbar${N?" drop-active":""}`,onDragOver:d=>{d.preventDefault(),d.stopPropagation(),m(!0)},onDragLeave:d=>{d.currentTarget.contains(d.relatedTarget)||m(!1)},onDrop:d=>{var I;d.preventDefault(),d.stopPropagation(),m(!1),M(((I=d.dataTransfer)==null?void 0:I.files)??null)},children:[N&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",E("dropHereToAttach")]})}),p.length>0&&e.jsxs("div",{className:"attach-row",children:[p.map(d=>e.jsxs("span",{className:`attach-chip ${d.imageData?"image":d.fileData?"file":d.mode}`,title:d.imageData?E("attachImage",{name:d.name}):d.fileData?E("attachFile",{name:d.name}):d.isDir?E("folderRef",{path:d.path}):d.mode==="reference"?E("refOnly",{path:d.path}):d.mode==="lines"&&d.lines?E("attachLines",{path:d.path,start:d.lines.start,end:d.lines.end}):E("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:E("removeAttachment"),onClick:()=>h(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:E("attachHint")})]}),A&&A.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:me,"aria-label":E("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:E("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>W(null),children:"Esc"})]}),A.map((d,I)=>e.jsxs("button",{type:"button",className:`slash-item${I===ee?" active":""}`,onMouseEnter:()=>ie(I),onClick:()=>Z(d),children:[e.jsxs("span",{className:"slash-name",children:["/",d.name]}),e.jsx("span",{className:`slash-source ${d.source}`,children:J[d.source]}),e.jsxs("span",{className:"slash-desc",children:[j(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:P(d)})]})]},d.name))]}),H&&e.jsx("div",{className:"modal-backdrop",onClick:()=>q(!1),children:e.jsxs("div",{className:"slash-help",style:L?{width:L}:void 0,onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",E("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>q(!1),children:E("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:E("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:J[d.source]}),e.jsxs("span",{className:"slash-help-desc",children:[j(d),d.argumentHint&&e.jsx("span",{className:"slash-hint",children:P(d)})]})]},d.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:K,type:"file",multiple:!0,hidden:!0,onChange:d=>{M(d.target.files),d.target.value=""}}),e.jsx("textarea",{ref:C,value:D,rows:1,placeholder:E(z?a?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!z,onChange:d=>{R(d.target.value),T(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:E("uploadFile"),disabled:!z,onClick:()=>{var d;return(d=K.current)==null?void 0:d.click()},children:e.jsx(_n,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:E("tpl.openPicker"),onClick:x,children:e.jsx(Vn,{})}),e.jsx(Aa,{state:i,models:n,modelsLoading:o,send:u,onManageModels:B,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:X()})]})]})]})}),Fa=r.memo(function({goal:s,models:a,modelsLoading:l,activeConversationId:c,send:i}){var ee,ie,H,q,L,S;const n=pe(),o=!s.conversationId||s.conversationId===c,u=s.goal!==null&&o,[p,h]=r.useState(""),[g,y]=r.useState(s.reviewModel??""),[b,k]=r.useState(s.maxRounds),[B,E]=r.useState(s.locked),[$,x]=r.useState(!1),[j,P]=r.useState(!1),[D,R]=r.useState(!0);r.useEffect(()=>{y(s.reviewModel??""),k(s.maxRounds||0),E(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),r.useEffect(()=>{$&&a.length===0&&!j&&!l&&(P(!0),i({type:"list_models"}))},[$,a.length,j,l,i]),r.useEffect(()=>{a.length>0&&P(!1)},[a.length]);const N=()=>{var C;return g?((C=a.find(K=>K.id===g))==null?void 0:C.name)??g:n("goalBarUseMainModel")},m=()=>{const C=p.trim();C&&(i({type:"set_goal",goal:C,...g?{reviewModel:g}:{},maxRounds:b,locked:B}),h(""),R(!1))},A=()=>{const C=p.trim();C&&(i({type:"start_goal_wizard",text:C,...g?{wizardModel:g}:{},maxRounds:b,locked:B}),h(""),R(!1))},W=(((ee=s.wizard)==null?void 0:ee.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:((ie=s.wizard)==null?void 0:ie.draft)??"",children:[n("goalWizardRunning"),": ",(H=s.wizard)==null?void 0:H.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[n("goalBarRound",{n:(((q=s.wizard)==null?void 0:q.step)??0)+1})," ","/ ",((L=s.wizard)==null?void 0:L.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((S=s.wizard)==null?void 0:S.status)||n("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:n("goalBarClear"),onClick:()=>{i({type:"clear_goal"}),R(!0)},children:e.jsx(ke,{})})]})}):u?e.jsx("div",{className:`goalbar goalbar-active ${s.reviewing?"reviewing":""}`,children:e.jsxs("div",{className:"goalbar-active-row",children:[e.jsx("span",{className:"goalbar-icon",children:s.reviewing?e.jsx("span",{className:"goalbar-spin",children:"◌"}):"🎯"}),e.jsx("span",{className:"goalbar-text",title:s.goal??"",children:s.goal}),s.reviewing?e.jsxs("span",{className:"goalbar-chip reviewing",children:[n("goalBarReviewing")," ",n("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?n("goalBarPassed"):s.verdict==="fail"?n("goalBarFailed"):`${n("goalBarRound",{n:s.round||1})} · ${s.locked?n("goalBarLocked"):n("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:s.status}),e.jsx("button",{type:"button",className:"goalbar-x",title:n("goalBarClear"),disabled:s.reviewing,onClick:()=>{i({type:"clear_goal"}),R(!0)},children:e.jsx(ke,{})})]})}):D?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:n("goalBarPlaceholder"),onClick:()=>R(!1),children:[e.jsx(Zt,{})," ",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(Zt,{})}),e.jsx("input",{className:"goalbar-input",value:p,placeholder:n("goalBarPlaceholder"),onChange:C=>h(C.target.value),onKeyDown:C=>{C.key==="Enter"&&m()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!p.trim(),onClick:m,children:n("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!p.trim(),title:n("goalWizardTip"),onClick:A,children:["🔍 ",n("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n(B?"goalBarLocked":"goalBarUnlocked"),onClick:()=>E(C=>(i({type:"set_goal_prefs",locked:!C}),!C)),children:B?e.jsx(Un,{}):e.jsx(Ln,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:n("goalBarClear"),onClick:()=>R(!0),children:e.jsx(mt,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[e.jsxs(Le,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[n("goalBarReviewModel"),": ",e.jsx("b",{children:N()})]}),open:$,onOpenChange:x,direction:"up",children:[e.jsx("div",{className:"dd-header",children:n("goalBarReviewModel")}),(j||l)&&e.jsx("div",{className:"dd-loading",children:n("loading")}),a.length===0&&!j&&!l&&e.jsx("div",{className:"dd-loading",children:n("noModels")}),e.jsx(be,{active:g==="",onClick:()=>{y(""),x(!1),i({type:"set_goal_prefs",reviewModel:""})},children:n("goalBarUseMainModel")}),a.map(C=>e.jsx(be,{active:g===C.id,onClick:()=>{y(C.id),x(!1),i({type:"set_goal_prefs",reviewModel:C.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:C.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:C.provider})})]})},C.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>i({type:"list_models"}),children:n("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:n("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:n("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:b,placeholder:n("goalBarUnlimitedShort"),onChange:C=>{const K=parseInt(C.target.value,10);if(Number.isNaN(K)||K<0){k(0);return}k(K)},onBlur:()=>i({type:"set_goal_prefs",maxRounds:b}),onKeyDown:C=>{C.key==="Enter"&&(i({type:"set_goal_prefs",maxRounds:b}),C.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:n(B?"goalBarLocked":"goalBarUnlocked")})]})]})});function $a({chat:t,send:s}){const a=pe(),l=t.state,[c,i]=r.useState(!1),[n,o]=r.useState(""),[u,p]=r.useState(0),h=r.useRef(null),g=t.pathCompletions;if(r.useEffect(()=>{if(!c)return;const m=setTimeout(()=>{s({type:"complete_path",path:n})},150);return()=>clearTimeout(m)},[n,c,s]),r.useEffect(()=>p(0),[g]),r.useEffect(()=>{const m=document.querySelector(`.status-completions .pc-item[data-idx="${u}"]`);m==null||m.scrollIntoView({block:"nearest"})},[u]),!l)return null;const y=l.stats,b=t.ready?"ok":"busy",k=t.ready?a("connected"):a("connecting"),B=y.contextUsage,E=B.tokens!==null&&B.percent!==null?`${js(B.tokens)} / ${js(B.contextWindow)}`:"—",$=B.percent??null,x=$===null?"":$>=80?"warn":$>=50?"mid":"ok",j=l.queue.steering.length+l.queue.followUp.length,P=()=>{o(l.cwd),i(!0)},D=(m,A)=>{var ee;const W=m.includes("\\")?"\\":"/";o(A?`${m}${W}`:m),p(0),(ee=h.current)==null||ee.focus()},R=m=>{const A=m.trim();A&&A!==l.cwd&&s({type:"set_cwd",path:A}),i(!1)},N=m=>{if(m.key==="ArrowDown")m.preventDefault(),p(A=>Math.min(A+1,g.length-1));else if(m.key==="ArrowUp")m.preventDefault(),p(A=>Math.max(A-1,0));else if(m.key==="Tab"&&g.length>0){m.preventDefault();const A=g[Math.min(u,g.length-1)];D(A.path,A.type==="dir")}else if(m.key==="Enter"&&!m.nativeEvent.isComposing){const A=n.trim();if(A.endsWith("/")||A.endsWith("\\"))R(A);else if(g.some(W=>W.path===A))R(A);else if(g.length>0&&g[u]){m.preventDefault();const W=g[u];D(W.path,W.type==="dir")}else R(A)}else m.key==="Escape"&&(g.length>0?(m.stopPropagation(),s({type:"complete_path",path:""})):i(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${b}`,title:k}),e.jsx("span",{className:"status-item",children:k}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-ctx",title:a("contextUsage"),children:[a("context"),e.jsx("span",{className:`ctx-bar ${x}`,children:$!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min($,100)}%`}})}),E]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:a("cumulativeCost"),children:["$",Oa(y.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:a("sessionMessages"),children:[a("messages")," ",y.totalMessages]}),t.statuses.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsx("span",{className:"status-item ext-status",title:a("pluginStatus"),children:t.statuses.map(m=>m.text).join(" · ")})]}),l.isStreaming&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item working",children:[e.jsx("span",{className:"working-spin"}),a("working"),j>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",j," ",a("queued")]})]})]}),c?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:h,className:"status-cwd-input",value:n,autoFocus:!0,placeholder:a("enterPath"),onChange:m=>o(m.target.value),onKeyDown:N,onBlur:()=>i(!1)}),g.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:m=>m.preventDefault(),children:g.map((m,A)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":A,className:`pc-item ${A===u?"sel":""}`,onMouseEnter:()=>p(A),onClick:()=>D(m.path,m.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:m.type==="dir"?e.jsx(ze,{}):e.jsx(As,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:m.name}),e.jsx("span",{className:"pc-path",children:m.path})]})]})},m.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:a("cwdTip",{path:l.cwd}),onClick:P,children:["📁 ",l.cwd]})]})}function js(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function Oa(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function Wa({dialog:t,send:s}){const a=pe(),[l,c]=r.useState(""),[i,n]=r.useState(0),o=h=>{s({type:"dialog_response",id:t.id,value:h})};r.useEffect(()=>{c(""),n(0);const h=g=>{g.key==="Escape"&&o(null)};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[t.id]);const u=Array.isArray(t.args[0])?t.args[0]:[],p=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:a("pluginRequest")}),t.title&&t.title!==a("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:a("cancel"),onClick:()=>o(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[u.map((h,g)=>e.jsx("button",{type:"button",className:`dialog-option ${g===i?"sel":""}`,onMouseEnter:()=>n(g),onClick:()=>o(h),children:h},g)),u.length===0&&e.jsx("div",{className:"dialog-hint",children:a("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:p}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(!1),children:a("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(!0),children:a("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:l,placeholder:p||a("inputPlaceholder"),autoFocus:!0,onChange:h=>c(h.target.value),onKeyDown:h=>{h.key==="Enter"&&!h.nativeEvent.isComposing&&o(l)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(null),children:a("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(l),children:a("ok")})]})]})]})}function Ha(t){if(t.x==="?"&&t.y==="?")return"untracked";const s=t.x!==" "&&t.x!=="?",a=t.y!==" "&&t.y!=="?";return s&&a?"both":s?"staged":"unstaged"}function Ua({chat:t,send:s,terminal:a,active:l,onSwitchToTerminal:c}){var Ne,Pe;const i=pe(),[n,o]=r.useState(null),[u,p]=r.useState([]),[h,g]=r.useState(""),[y,b]=r.useState(new Map),[k,B]=r.useState("changes"),[E,$]=r.useState([]),[x,j]=r.useState(null),[P,D]=r.useState(""),[R,N]=r.useState(!1),[m,A]=r.useState(null),[W,ee]=r.useState(null),[ie,H]=r.useState(!1),[q,L]=r.useState(!1),[S,C]=r.useState(!1),[K,me]=r.useState(null),[J,T]=r.useState(!1),[Z,te]=r.useState(""),M=r.useRef(0),F=r.useRef(-1),z=r.useRef(-1),ne=r.useRef(-1),G=r.useRef(-1),oe=r.useRef(void 0),X=r.useRef(null),d=r.useRef([]),I=r.useCallback(w=>{if(w.reqId===F.current){if(F.current=-1,L(!1),me(null),!w.ok){me(w.error??"查询失败");return}if(w.notRepo){T(!0),o(null),p([]),b(new Map),$([]),j(null),D(""),ee(null);return}T(!1);const f={branch:w.branch??"",detached:!!w.detached,upstream:w.upstream??null,ahead:w.ahead??0,behind:w.behind??0,upstreamGone:!!w.upstreamGone,files:(w.files??[]).map(O=>({...O}))},v=(w.branches??[]).map(O=>({...O})),V=new Map;for(const[O,ae]of Object.entries(w.stats??{}))V.set(O,{add:ae[0],del:ae[1]});o(f),p(v),b(V),g(O=>{var ae;return f.detached?O||"":f.branch&&v.some(de=>de.name===f.branch)?f.branch:O&&v.some(de=>de.name===O)?O:((ae=v[0])==null?void 0:ae.name)??""}),ee(O=>O&&!f.files.some(ae=>ae.path===O.file.path)?null:O)}else if(w.reqId===z.current){if(z.current=-1,H(!1),!w.ok){me(w.error??"查询失败");return}const f=X.current;if(!f)return;ee({file:f,staged:w.stagedText??"",worktree:w.worktreeText??"",untracked:!1})}else if(w.reqId===G.current){if(G.current=-1,C(!1),!w.ok){me(w.error??"查询失败");return}$((w.history??[]).map(f=>({...f})))}else if(w.reqId===ne.current){if(ne.current=-1,N(!1),!w.ok){me(w.error??"查询失败");return}D(w.text??"")}},[]);r.useEffect(()=>{const w=t.scmData;w&&w.type==="scm_data"&&I(w)},[t.scmData,I]);const ce=r.useCallback((w,f)=>{if(!t.ready||t.status!=="open")return!1;const v=++M.current;return s({...w,reqId:v})?(f.current=v,!0):(M.current-=1,!1)},[t.ready,t.status,s]),se=r.useCallback((w=!1,f=!1)=>{var v;!t.ready||t.status!=="open"||(v=t.state)!=null&&v.cwd&&(oe.current!==void 0&&oe.current!==t.state.cwd&&(o(null),p([]),b(new Map),$([]),C(!1),G.current=-1,j(null),D(""),ee(null),A(null)),oe.current=t.state.cwd,me(null),ce({type:"scm_status"},F)&&(f||L(!0)))},[t.ready,(Ne=t.state)==null?void 0:Ne.cwd,t.status,ce]),he=r.useCallback(w=>{if(A(w),j(null),X.current=w,w.x==="?"&&w.y==="?"){ee({file:w,staged:"",worktree:"",untracked:!0});return}H(!0),me(null),ce({type:"scm_filediff",path:w.path},z)||H(!1)},[ce]),Q=r.useCallback(w=>{j(w),A(null),ee(null),D(""),N(!0),me(null),ce({type:"scm_commit",hash:w.hash},ne)||N(!1)},[ce]),le=r.useCallback((w,f)=>{var O,ae;if(!t.ready)return;const v={name:w,command:f,cwd:"${pwd}"},V=t.terminals.find(de=>de.title===w);if(V)a.restart(V.id),s({type:"run_command",terminalId:V.id,conversationId:V.conversationId,command:v,cols:80,rows:24});else{const de=Re();a.create({id:de,conversationId:t.activeConversationId||((O=t.state)==null?void 0:O.conversationId)||"",title:w,cwd:((ae=t.state)==null?void 0:ae.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:v})}c()},[t.ready,(Pe=t.state)==null?void 0:Pe.cwd,t.terminals,c,s,a]),ge=r.useCallback(()=>{const w=Z.trim();if(!w||J)return;const f=w.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");le("git commit",`git add -A && git commit -m "${f}"`),te("")},[Z,J,le]),ue=w=>`'${w.replace(/'/g,"'\\''")}`,we=r.useCallback(w=>{J||le("git add",`git add -- ${ue(w.path)}`)},[J,le]),Be=r.useCallback(w=>{J||le("git reset",`git reset HEAD -- ${ue(w.path)}`)},[J,le]),$e=r.useCallback(()=>{if(!h||J)return;const w=u.find(f=>f.name===h);if(w!=null&&w.remote&&typeof w.remote=="string"){const f=h.slice(w.remote.length+1);le("git checkout",`git checkout -b ${f} ${h} || git checkout ${h}`)}else le("git checkout",`git checkout ${h}`)},[h,u,J,le]),Ve=r.useCallback(()=>le("git push","git push"),[le]),Ge=r.useCallback(()=>le("git pull","git pull"),[le]),Ce=r.useCallback(()=>{ce({type:"scm_history"},G)||(G.current=-1)},[ce]);r.useEffect(()=>{l&&se()},[l,se]),r.useEffect(()=>{k==="history"&&n&&Ce()},[k,n,Ce]),r.useEffect(()=>{t.scmDirty>0&&l&&se(!1,!0)},[t.scmDirty]),r.useEffect(()=>{if(!l||!t.ready||t.status!=="open")return;const w=setInterval(()=>{document.visibilityState!=="hidden"&&se(!1,!0)},3e4);return()=>clearInterval(w)},[l,t.ready,t.status,se]),r.useEffect(()=>{const w=d.current;if(d.current=t.terminals,!l)return;t.terminals.some(v=>{var O;return v.running!==!1?!1:((O=w.find(ae=>ae.id===v.id))==null?void 0:O.running)===!0&&/^git /.test(v.title)})&&t.ready&&t.status==="open"&&(se(!1,!0),k==="history"&&n&&Ce())},[t.terminals,l,t.ready,t.status,se,k,n,Ce]);const Oe={staged:i("scmStaged"),unstaged:i("scmUnstaged"),untracked:i("scmUntracked"),both:i("scmStagedUnstaged")},Ae=w=>{const f=w.split(`
|
|
319
|
+
`);return e.jsx("pre",{className:"scm-diff-pre",children:f.map((v,V)=>{let O="";return v.startsWith("diff --git")||v.startsWith("index ")||v.startsWith("new file")||v.startsWith("deleted file")||v.startsWith("old mode")||v.startsWith("new mode")||v.startsWith("similarity index")||v.startsWith("rename ")||v.startsWith("copy ")||v.startsWith("Binary files")||v.startsWith("---")||v.startsWith("+++")?O="hdr":v.startsWith("@@")?O="hunk":v.startsWith("+")?O="add":v.startsWith("-")&&(O="del"),e.jsx("div",{className:`scm-diff-line ${O}`,children:v||" "},V)})})};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(it,{}),i("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":k==="changes",className:k==="changes"?"active":"",onClick:()=>{B("changes"),me(null)},children:i("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":k==="history",className:k==="history"?"active":"",onClick:()=>{B("history"),me(null)},children:i("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:i("scmRefreshTip"),disabled:q,onClick:()=>se(!0),children:e.jsx(pt,{className:q?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:i("scmCurrentBranch"),children:[e.jsx(it,{}),n?n.detached?i("scmDetached"):n.branch:"…",(n==null?void 0:n.upstream)&&e.jsx("span",{className:"scm-upstream",children:n.upstreamGone?i("scmUpstreamGone"):n.ahead>0||n.behind>0?i("scmAheadBehind",{ahead:n.ahead,behind:n.behind}):n.upstream})]}),e.jsxs("select",{className:"scm-select",value:h,disabled:J||u.length===0,title:i("scmSwitchBranch"),onChange:w=>g(w.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:i("scmSelectBranch")}),u.filter(w=>!w.remote).map(w=>e.jsx("option",{value:w.name,children:w.current?`* ${w.name}`:w.name},w.name)),u.some(w=>w.remote)&&e.jsx("optgroup",{label:i("scmRemoteBranches"),children:u.filter(w=>w.remote).map(w=>e.jsx("option",{value:w.name,children:w.name},w.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!h||h===(n==null?void 0:n.branch)||J,title:i("scmSwitchBranchTip",{branch:h}),onClick:$e,children:[e.jsx(it,{}),i("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!n||n.detached||J,title:i("scmPushTip"),onClick:Ve,children:[e.jsx(Fs,{}),i("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!n||n.detached||J,title:i("scmPullTip"),onClick:Ge,children:[e.jsx($s,{}),i("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:Z,placeholder:i("scmCommitPlaceholder"),disabled:J,onChange:w=>te(w.target.value),onKeyDown:w=>{w.key==="Enter"&&!w.nativeEvent.isComposing&&ge()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!Z.trim()||J,title:i("scmCommitTip"),onClick:ge,children:[e.jsx(gt,{}),i("scmCommit")]})]})]}),e.jsxs("div",{className:"scm-body",children:[k==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmHistory")}),E.length>0&&e.jsx("span",{className:"scm-files-count",children:E.length})]}),e.jsx("div",{className:"scm-history-list",children:J?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):!n||S?e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")}):E.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoHistory")}):E.map(w=>e.jsxs("button",{type:"button",className:`scm-commit ${(x==null?void 0:x.hash)===w.hash?"active":""}`,onClick:()=>Q(w),title:w.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:w.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:w.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[w.shortHash," · ",w.author," · ",w.date]}),w.decorations&&e.jsx("span",{className:"scm-commit-refs",children:w.decorations})]})]},w.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmChanges")}),n&&n.files.length>0&&e.jsx("span",{className:"scm-files-count",children:n.files.length})]}),e.jsx("div",{className:"scm-files-list",children:J?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):n?n.files.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoChanges")}):n.files.map(w=>{const f=Ha(w),v=y.get(w.path);return e.jsxs("div",{className:`scm-file ${(m==null?void 0:m.path)===w.path?"active":""}`,title:Oe[f],onClick:()=>he(w),children:[e.jsx("span",{className:`scm-file-xy ${f==="untracked"?"q":"x"}`,children:w.x!==" "?w.x:" "}),e.jsx("span",{className:`scm-file-xy ${f==="untracked"?"q":"y"}`,children:w.y!==" "?w.y:" "}),e.jsx("span",{className:"scm-file-path",children:w.path}),v&&(v.add>0||v.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[v.add>0&&e.jsxs("span",{className:"add",children:["+",v.add]}),v.del>0&&e.jsxs("span",{className:"del",children:["-",v.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(w.y!==" "||f==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:i("scmStageTip",{path:w.path}),onClick:V=>{V.stopPropagation(),we(w)},children:"+"}),f==="staged"||f==="both"?e.jsx("button",{type:"button",className:"scm-act",title:i("scmUnstageTip",{path:w.path}),onClick:V=>{V.stopPropagation(),Be(w)},children:"−"}):null]})]},w.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:k==="history"?x?`${x.shortHash} ${x.subject}`:i("scmCommitDetail"):m?m.path:i("scmDiff")}),(k==="history"?R:ie)&&e.jsx("span",{className:"scm-diff-loading",children:i("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:k==="history"?e.jsxs(e.Fragment,{children:[K&&e.jsx("div",{className:"scm-error",children:K}),!x&&!K&&e.jsx("div",{className:"scm-empty",children:i("scmSelectCommitHint")}),x&&R&&!K&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),x&&!R&&!K&&P?Ae(P):null]}):e.jsxs(e.Fragment,{children:[K&&e.jsx("div",{className:"scm-error",children:K}),!m&&!K&&e.jsx("div",{className:"scm-empty",children:i("scmSelectFileHint")}),m&&!W&&!K&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),m&&W&&W.untracked&&e.jsx("div",{className:"scm-empty",children:i("scmUntrackedNote")}),m&&W&&!W.untracked&&e.jsxs(e.Fragment,{children:[W.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmStaged")}),Ae(W.staged)]}),W.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmUnstaged")}),Ae(W.worktree)]}),!W.staged&&!W.worktree&&e.jsx("div",{className:"scm-empty",children:i("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(qe,{}),e.jsx("span",{children:i("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:c,children:i("scmViewTerminal")})]})]})}function qa({entry:t,send:s}){const a=r.useRef(null);return r.useEffect(()=>{const l=a.current;if(!l)return;let c;try{c=t.module.mount(l,vi(t.info.id,i=>s(i)))}catch(i){console.error(`[plugin:${t.info.id}] mount failed:`,i),l.textContent=`插件 ${t.info.name} 挂载失败`}return()=>{if(typeof c=="function")try{c()}catch(i){console.error(`[plugin:${t.info.id}] cleanup failed:`,i)}l.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:a})}function Ka({send:t,piConfigured:s,piAgentInstalled:a,providers:l,installResult:c,onClose:i}){const n=pe(),[o,u]=r.useState(!1),[p,h]=r.useState(""),[g,y]=r.useState(""),[b,k]=r.useState(!1);r.useEffect(()=>{t({type:"list_providers"})},[t]),r.useEffect(()=>{s&&i()},[s,i]),r.useEffect(()=>{c&&u(!1)},[c]),r.useEffect(()=>{var P;!p&&l.length>0&&h(((P=l.find(D=>!D.configured))==null?void 0:P.id)??l[0].id)},[l,p]);const B=()=>{o||(u(!0),t({type:"install_pi_agent"}))},E=()=>{!g.trim()||b||(k(!0),t({type:"set_provider_api_key",provider:p.trim(),apiKey:g.trim()}),setTimeout(()=>k(!1),3e3))},$=()=>{t({type:"get_state"}),t({type:"list_providers"})},x=l.find(P=>P.id===p),j=c!==null&&!c.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":n("close"),onClick:i,children:e.jsx(ke,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(Xe,{className:"modal-head-icon"}),e.jsx("h2",{children:n("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:n("setupDesc")}),j?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:n("installFailed")}),e.jsx("pre",{className:"setup-detail",children:c.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:B,children:n("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:n("skip")})]})]}):a||c!=null&&c.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:c!=null&&c.ok?n("installDone"):n("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:n("provider")}),e.jsxs("select",{value:p,onChange:P=>h(P.target.value),children:[l.length===0&&e.jsx("option",{value:"",children:n("loading")}),l.map(P=>e.jsxs("option",{value:P.id,children:[P.name,"(",P.id,")",P.configured?` · ${n("configured")}`:""]},P.id))]}),(x==null?void 0:x.configured)&&e.jsx("div",{className:"field-hint",children:n("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:n("apiKey")}),e.jsx("input",{type:"password",value:g,onChange:P=>y(P.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!g.trim()||b||!p,onClick:E,children:n(b?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:$,children:[e.jsx(pt,{})," ",n("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:B,children:n(o?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:n("skip")})]})]})})}const za=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],$t=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),Va=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[$t()]});function ws(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:[$t()]).map(s=>{var a;return{id:s.id,name:s.name??"",reasoning:s.reasoning??!1,input:(a=s.input)!=null&&a.includes("image")?"text-image":"text",contextWindow:s.contextWindow?String(s.contextWindow):"",maxTokens:s.maxTokens?String(s.maxTokens):""}})}}function Ga({send:t,providers:s,providerStatus:a,fetchModelsResult:l,refreshProviderResult:c,cloneProviderResult:i,onClose:n}){const o=pe(),[u,p]=r.useState(null),[h,g]=r.useState({}),[y,b]=r.useState(null),[k,B]=r.useState({}),[E,$]=r.useState(!1),[x,j]=r.useState(0),[P,D]=r.useState(null),R=r.useRef(0),[N,m]=r.useState({});r.useRef(0);const A=r.useRef(0),[W,ee]=r.useState(null),ie=r.useRef(0),H=r.useRef(0);r.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const q=()=>{if(!u)return;const T=u.baseUrl.trim();if(!T){D({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(E)return;$(!0),D(null);const Z=x+1;j(Z),t({type:"fetch_models",reqId:Z,baseUrl:T,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};r.useEffect(()=>{var T;if(!(!l||l.reqId===R.current))if(R.current=l.reqId,$(!1),l.ok&&((T=l.models)!=null&&T.length)){const Z=l.models;p(te=>{if(!te)return te;const M=te.models.map(G=>{var d;if(!G.id.trim())return G;const oe=Z.find(I=>I.id===G.id.trim());if(!oe)return G;const X={...G};return!X.name&&oe.name&&(X.name=oe.name),!X.contextWindow&&oe.contextWindow&&(X.contextWindow=String(oe.contextWindow)),!X.maxTokens&&oe.maxTokens&&(X.maxTokens=String(oe.maxTokens)),X.input==="text"&&((d=oe.input)!=null&&d.includes("image"))&&(X.input="text-image"),!X.reasoning&&oe.reasoning&&(X.reasoning=!0),X}),F=new Set(M.map(G=>G.id.trim()).filter(Boolean)),z=Z.filter(G=>!F.has(G.id)).map(G=>{var oe;return{id:G.id,name:G.name??"",reasoning:G.reasoning??!1,input:(oe=G.input)!=null&&oe.includes("image")?"text-image":"text",contextWindow:G.contextWindow?String(G.contextWindow):"",maxTokens:G.maxTokens?String(G.maxTokens):""}}),ne=[...M,...z];return ne.some(G=>G.id.trim())?{...te,models:ne.filter(G=>G.id.trim())}:te}),D({ok:!0,text:o("fetchModelsOk",{n:Z.length})})}else D({ok:!1,text:l.error||o("fetchModelsEmpty")})},[l]);const L=T=>{const Z=(h[T.id]??"").trim();!Z||y||(b(T.id),t({type:"set_provider_api_key",provider:T.id,apiKey:Z}),setTimeout(()=>{b(null),g(te=>({...te,[T.id]:""})),B(te=>({...te,[T.id]:!1})),t({type:"list_providers"})},1500))},S=()=>{if(!u)return;const T=u.providerId.trim(),Z=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})),te={providerId:T,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:Z};t({type:"save_model_config",providerId:T,config:te}),n()};r.useEffect(()=>{!c||c.reqId===A.current||(A.current=c.reqId,m({}))},[c]);const C=T=>{if(W)return;ee(T.id);const Z=++ie.current+Date.now();t({type:"clone_provider",provider:T.id,reqId:Z})};r.useEffect(()=>{!i||i.reqId===H.current||(H.current=i.reqId,ee(null),i.ok&&i.config&&p(ws({...i.config,apiKey:""})))},[i]);const K=T=>{window.confirm(o("clearKeyConfirm",{id:T}))&&t({type:"clear_provider_api_key",provider:T})},me=T=>{window.confirm(o("deleteProviderConfirm",{id:T.providerId,n:T.models.length}))&&t({type:"delete_model_config",providerId:T.providerId})},J=(T,Z)=>{u&&p({...u,models:u.models.map((te,M)=>M===T?{...te,...Z}:te)})};return e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"modal model-modal",onClick:T=>T.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:n,children:e.jsx(ke,{})}),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(T=>T.providerId===u.providerId),onChange:T=>p({...u,providerId:T.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:T=>p({...u,name:T.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:T=>p({...u,api:T.target.value}),children:za.map(T=>e.jsx("option",{value:T,children:T},T))})]}),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:T=>p({...u,baseUrl:T.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:T=>p({...u,apiKey:T.target.value}),placeholder:o("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:T=>p({...u,authHeader:T.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:[P&&e.jsx("span",{className:`fetch-msg ${P.ok?"ok":"err"}`,title:P.text,children:P.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:E||!u.baseUrl.trim(),title:o("fetchModelsHint"),onClick:q,children:[e.jsx(Dt,{})," ",o(E?"fetchingModels":"fetchModels")]})]})]}),u.models.map((T,Z)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:T.id,onChange:te=>J(Z,{id:te.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:T.name,onChange:te=>J(Z,{name:te.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:T.input,onChange:te=>J(Z,{input:te.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:T.reasoning,onChange:te=>J(Z,{reasoning:te.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:T.contextWindow,onChange:te=>J(Z,{contextWindow:te.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:T.maxTokens,onChange:te=>J(Z,{maxTokens:te.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>p({...u,models:u.models.filter((te,M)=>M!==Z)}),children:e.jsx(Ee,{})})]},Z)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>p({...u,models:[...u.models,$t()]}),children:[e.jsx(De,{})," ",o("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>p(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(T=>T.id.trim()),onClick:S,children:o("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-section-title",children:[o("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:o("hintKeyOnly")})]}),e.jsxs("div",{className:"provider-list",children:[a.length===0&&e.jsx("div",{className:"dd-loading",children:o("loading")}),a.map(T=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:T.name}),e.jsxs("span",{className:"provider-sub",children:[T.id,T.configured&&e.jsx("span",{className:"auth-badge",children:o("configuredBadge")}),T.source&&!T.configured&&e.jsx("span",{className:"auth-badge dim",children:T.source})]})]}),e.jsxs("div",{className:"provider-actions",children:[T.configured&&!k[T.id]?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"auth-badge",children:o("keyReady")}),e.jsxs("button",{type:"button",className:"btn sm",title:o("replaceKeyTitle"),onClick:()=>B(Z=>({...Z,[T.id]:!0})),children:[e.jsx(Et,{})," ",o("replaceKey")]}),T.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>K(T.id),children:[e.jsx(Ee,{})," ",o("clearKey")]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"password",className:"key-input",placeholder:o("pasteKey"),value:h[T.id]??"",onChange:Z=>g(te=>({...te,[T.id]:Z.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(h[T.id]??"").trim()||y===T.id,onClick:()=>L(T),children:[e.jsx(qn,{})," ",y===T.id?o("savingKey"):o("saveKey")]})]}),e.jsxs("button",{type:"button",className:"btn sm",disabled:W!==null,title:o("cloneProviderTitle"),onClick:()=>C(T),children:[e.jsx(Bt,{})," ",W===T.id?o("cloning"):o("cloneProvider")]})]})]},T.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(T=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:T.providerId}),e.jsxs("span",{className:"provider-sub",children:[T.api??"—",T.baseUrl?` · ${T.baseUrl}`:"",T.models.length>0&&` · ${o("modelsCount",{n:T.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:o("edit"),onClick:()=>p(ws(T)),children:e.jsx(Et,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>me(T),children:e.jsx(Ee,{})})]})]},T.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>p(Va()),children:[e.jsx(De,{})," ",o("addProvider")]})})]})]})})}function Ja({plugin:t,send:s}){const a=pe(),l=t.settingsSchema??[],[c,i]=r.useState(()=>({...t.settingsValues??{}})),[n,o]=r.useState(!1);if(l.length===0)return null;const u=(y,b)=>i(k=>({...k,[y]:b})),p=l.some(y=>{var b;return c[y.key]!==((b=t.settingsValues)==null?void 0:b[y.key])}),h=()=>{o(!0),s({type:"plugin_settings",pluginId:t.id,values:c}),setTimeout(()=>o(!1),800)},g=()=>i({...t.settingsValues??{}});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:l.map(y=>e.jsxs("label",{className:"plugin-settings-field",title:y.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:y.label}),y.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!c[y.key],onChange:b=>u(y.key,b.target.checked)}):y.type==="select"?e.jsx("select",{value:String(c[y.key]??""),onChange:b=>u(y.key,b.target.value),children:(y.options??[]).map(b=>e.jsx("option",{value:b,children:b},b))}):e.jsx("input",{type:y.type==="password"?"password":y.type==="number"?"number":"text",value:String(c[y.key]??""),min:y.min,max:y.max,onChange:b=>u(y.key,y.type==="number"?Number(b.target.value):b.target.value)})]},y.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!p||n,onClick:h,children:a(n?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:g,children:a("pluginSettingsReset")})]})]})}function at({text:t}){const s=r.useRef(null),[a,l]=r.useState(!1),c=()=>{var n;const i=(n=s.current)==null?void 0:n.getBoundingClientRect();i&&l(window.innerWidth-i.right<340)};return e.jsxs("span",{ref:s,className:`set-tip${a?" flip":""}`,tabIndex:0,"aria-label":t,onMouseEnter:c,onFocus:c,children:["?",e.jsx("span",{className:"set-tip-bubble",role:"tooltip",children:t})]})}function Te({title:t,subtitle:s,tip:a,enabled:l,onToggle:c,action:i}){const n=pe();return e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[t,a&&e.jsx(at,{text:a})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),i,e.jsx("button",{type:"button",className:`set-switch ${l?"on":""}`,role:"switch","aria-checked":l,title:n(l?"settingsEnabled":"settingsDisabled"),onClick:c,children:e.jsx("span",{className:"set-switch-knob"})})]})}function Ya({chat:t,send:s,terminal:a,onSwitchToTerminal:l,onClose:c}){const i=pe(),n=t.settings,[o,u]=r.useState("prompt"),p=r.useRef(null);r.useEffect(()=>{var d;(d=p.current)==null||d.scrollTo({top:0})},[o]);const[h,g]=r.useState(""),[y,b]=r.useState("append"),k=r.useRef(!1),[B,E]=r.useState(""),[$,x]=r.useState("append"),j=r.useRef(!1),[P,D]=r.useState(""),R=r.useRef(!1),[N,m]=r.useState(""),[A,W]=r.useState(!1),[ee,ie]=r.useState(null),[H,q]=r.useState(null);r.useEffect(()=>{n&&(b(n.promptMode),!k.current&&(g(y==="append"||n.customSystemPrompt?n.customSystemPrompt:n.defaultSystemPrompt||""),x(n.visionBridgePromptMode),!j.current&&(E($==="append"||n.visionBridgePrompt?n.visionBridgePrompt:n.visionBridgeDefaultPrompt||""),R.current||D(n.reviewPrompt))))},[n,y,$]);const[L,S]=r.useState(String((n==null?void 0:n.terminalBashIdleMs)??15e3));if(r.useEffect(()=>{S(String((n==null?void 0:n.terminalBashIdleMs)??15e3))},[n==null?void 0:n.terminalBashIdleMs]),!n)return null;const C=[{id:"prompt",icon:e.jsx(_s,{}),label:i("settingsSystemPrompt")},{id:"terminal",icon:e.jsx(qe,{}),label:i("settingsTerminalTools")},{id:"display",icon:e.jsx(Ke,{}),label:i("settingsMessageDisplay")},{id:"skills",icon:e.jsx(Xe,{}),label:i("settingsSkills"),count:n.skills.length},{id:"extensions",icon:e.jsx(es,{}),label:i("settingsExtensions"),count:n.extensions.length},{id:"plugins",icon:e.jsx(ss,{}),label:i("settingsUiPlugins"),count:t.plugins.length},{id:"review",icon:e.jsx(nt,{}),label:i("settingsReview"),count:n.reviewSkills.length},{id:"vision",icon:e.jsx(St,{}),label:i("settingsVisionBridge")},{id:"presets",icon:e.jsx(Bn,{}),label:i("settingsPresets"),count:n.presets.length}],K=new Set(n.disabledSkills),me=new Set(n.disabledExtensions),J=d=>s({type:"set_settings",...d}),T=d=>{const I=new Set(K);I.has(d.name)?I.delete(d.name):I.add(d.name),J({disabledSkills:[...I]})},Z=new Set(n.disabledPlugins??[]),te=d=>{const I=new Set(Z);I.has(d.id)?I.delete(d.id):I.add(d.id),J({disabledPlugins:[...I]})},M=d=>{const I=new Set(me);I.has(d.id)?I.delete(d.id):I.add(d.id),J({disabledExtensions:[...I]})},F=(d,I)=>{var he,Q;const ce={name:d,command:I,cwd:"${pwd}"},se=t.terminals.find(le=>le.title===d);se?(a.restart(se.id),s({type:"run_command",terminalId:se.id,conversationId:se.conversationId,command:ce,cols:80,rows:24})):a.create({id:Re(),conversationId:t.activeConversationId||((he=t.state)==null?void 0:he.conversationId)||"",title:d,cwd:((Q=t.state)==null?void 0:Q.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:ce}),l(),c()},z=d=>{ie(null),F(`${i("uninstallTitle")} ${d}`,`pi remove npm:${d}`)},ne=d=>{q(null),F(`${i("uninstallTitle")} ${d}`,`pi-web-ui uninstall ${d}`)},G=(d,I)=>{F(`${i("pluginUpdate")} ${d}`,`pi-web-ui install ${I} --name ${d} --force`)},oe=d=>{const I=new Set(n.reviewSkills.filter(ce=>!ce.enabled).map(ce=>ce.name));I.has(d.name)?I.delete(d.name):I.add(d.name),J({reviewDisabledSkills:[...I]})},X=()=>{const d=y==="replace"&&n.defaultSystemPrompt&&h===n.defaultSystemPrompt?"":h;J({promptMode:y,customSystemPrompt:d})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal settings-modal",onClick:d=>d.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:c,children:e.jsx(ke,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(ct,{className:"modal-head-icon"}),e.jsx("h2",{children:i("settingsTitle")}),e.jsx(at,{text:i("settingsDesc")})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-rail","aria-label":i("settingsTitle"),children:C.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:p,children:[o==="prompt"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(nt,{className:"set-section-icon"}),i("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:y,onChange:d=>{const I=d.target.value;b(I),J({promptMode:I})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]}),e.jsx(at,{text:i(y==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:i("promptPlaceholder"),value:h,onFocus:()=>k.current=!0,onBlur:()=>{k.current=!1,X()},onChange:d=>g(d.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":A,onClick:()=>W(d=>!d),children:[i("settingsViewPrompt")," ",A?"▴":"▾"]}),A&&e.jsxs("div",{className:"set-prompt-view",children:[e.jsxs("div",{className:"set-prompt-view-head",children:[e.jsx("span",{children:i("settingsViewPromptHint")}),e.jsx(qs,{text:n.effectiveSystemPrompt})]}),n.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:n.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:i("settingsViewPromptEmpty")})]})]}),o==="terminal"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(qe,{className:"set-section-icon"}),i("settingsTerminalTools")]}),e.jsx(Te,{title:i("terminalToolsEnabled"),tip:i("settingsTerminalToolsDesc"),enabled:n.terminalToolsEnabled,onToggle:()=>J({terminalToolsEnabled:!n.terminalToolsEnabled})}),!n.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:i("terminalToolsOffHint")}),e.jsx(Te,{title:i("terminalBashTakeover"),tip:i("terminalBashTakeoverDesc"),enabled:n.terminalBash,onToggle:()=>J({terminalBash:!n.terminalBash})}),n.terminalBash&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:i("terminalBashIdleMs")}),e.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:L,onChange:d=>S(d.target.value),onBlur:()=>{const d=Math.max(0,Math.floor(Number(L)||0));S(String(d)),d!==n.terminalBashIdleMs&&J({terminalBashIdleMs:d})}})]})]}),o==="display"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ke,{className:"set-section-icon"}),i("settingsMessageDisplay")]}),e.jsx(Te,{title:i("thinkingWrap"),tip:i("thinkingWrapDesc"),enabled:n.thinkingWrap??!0,onToggle:()=>J({thinkingWrap:!(n.thinkingWrap??!0)})}),e.jsx(Te,{title:i("toolsWrap"),tip:i("toolsWrapDesc"),enabled:n.toolsWrap??!0,onToggle:()=>J({toolsWrap:!(n.toolsWrap??!0)})})]}),o==="skills"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Xe,{className:"set-section-icon"}),i("settingsSkills"),e.jsx("span",{className:"set-count",children:n.skills.length})]}),n.skills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:n.skills.map(d=>e.jsx(Te,{title:d.name,subtitle:d.description,enabled:d.enabled,onToggle:()=>T(d)},d.name))})]}),o==="extensions"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(es,{className:"set-section-icon"}),i("settingsExtensions"),e.jsx("span",{className:"set-count",children:n.extensions.length})]}),n.extensions.length===0?e.jsx("p",{className:"set-empty",children:i("noExtensions")}):e.jsx("div",{className:"set-list",children:n.extensions.map(d=>{const I=d.id.startsWith("npm:")?d.id.slice(4):null;return e.jsx(Te,{title:d.name,subtitle:d.path,enabled:d.enabled,onToggle:()=>M(d),action:I?ee===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>z(I),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("uninstallHint"),onClick:()=>ie(d.id),children:[e.jsx(Ee,{}),i("uninstallExt")]}):void 0},d.id)})})]}),o==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ss,{className:"set-section-icon"}),i("settingsUiPlugins"),e.jsx("span",{className:"set-count",children:t.plugins.length})]}),t.plugins.length===0?e.jsx("p",{className:"set-empty",children:i("noUiPlugins")}):e.jsx("div",{className:"set-list",children:t.plugins.map(d=>{var I;return e.jsxs(e.Fragment,{children:[e.jsx(Te,{title:`${d.icon?`${d.icon} `:""}${d.name}`,subtitle:(d.error?`${d.id} · ${d.error}`:d.source?`${d.id} · ${d.source}`:`${d.id} · ${i("uiPluginNoSource")}`)+((I=d.permissions)!=null&&I.length?` · ${i("uiPluginPerms")}: ${d.permissions.join(", ")}`:""),enabled:!Z.has(d.id)&&!d.error,onToggle:()=>!d.error&&te(d),action:e.jsxs("div",{className:"set-row-actions",children:[d.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>G(d.id,d.source),children:[e.jsx(pt,{}),i("pluginUpdate")]}),H===d.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>ne(d.id),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>q(d.id),children:[e.jsx(Ee,{}),i("uninstallExt")]})]})},d.id),d.settingsSchema&&d.settingsSchema.length>0&&e.jsx(Ja,{plugin:d,send:s})]})})})]}),o==="review"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(nt,{className:"set-section-icon"}),i("settingsReview"),e.jsx(at,{text:i("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:n.reviewSkills.length})]}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:i("reviewPromptPlaceholder"),value:P,onFocus:()=>R.current=!0,onBlur:()=>{R.current=!1,J({reviewPrompt:P})},onChange:d=>D(d.target.value)}),e.jsx("div",{className:"set-field-label",children:i("settingsReviewSkills")}),n.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:n.reviewSkills.map(d=>e.jsx(Te,{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(St,{className:"set-section-icon"}),i("settingsVisionBridge")]}),e.jsx(Te,{title:i("visionBridgeEnabled"),tip:i("settingsVisionBridgeDesc"),enabled:n.visionBridgeEnabled,onToggle:()=>J({visionBridgeEnabled:!n.visionBridgeEnabled})}),!n.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:i("visionBridgeOffHint")}),n.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:n.visionBridgeModel??"",onChange:d=>J({visionBridgeModel:d.target.value||null}),children:[e.jsx("option",{value:"",children:i("visionBridgeAuto")}),n.visionModels.map(d=>e.jsx("option",{value:`${d.provider}/${d.id}`,children:d.label},`${d.provider}/${d.id}`))]})]}),n.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:$,onChange:d=>{const I=d.target.value;x(I),J({visionBridgePromptMode:I})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]})]}),n.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:i("visionBridgePromptPlaceholder"),value:B,onFocus:()=>j.current=!0,onBlur:()=>{j.current=!1;const d=$==="replace"&&n.visionBridgeDefaultPrompt&&B===n.visionBridgeDefaultPrompt?"":B;J({visionBridgePromptMode:$,visionBridgePrompt:d})},onChange:d=>E(d.target.value)}),n.visionBridgeEnabled&&(n.visionModels.length===0?e.jsx("p",{className:"set-hint",children:i("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:i("visionBridgeCurrent",{model:n.visionBridgeModel??i("visionBridgeAuto")})}))]}),o==="presets"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ct,{className:"set-section-icon"}),i("settingsPresets"),e.jsx("span",{className:"set-count",children:n.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:i("presetNamePlaceholder"),value:N,onChange:d=>m(d.target.value),onKeyDown:d=>{d.key==="Enter"&&N.trim()&&(s({type:"save_preset",name:N.trim()}),m(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!N.trim(),onClick:()=>{s({type:"save_preset",name:N.trim()}),m("")},children:[e.jsx(De,{})," ",i("saveAsPreset")]})]}),n.presets.length===0?e.jsx("p",{className:"set-empty",children:i("noPresets")}):e.jsx("div",{className:"set-list",children:n.presets.map(d=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:d.name}),e.jsxs("div",{className:"set-row-desc",children:[d.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend"),d.disabledSkills.length>0&&` · ${i("settingsSkills")} ${d.disabledSkills.length}`,d.disabledExtensions.length>0&&` · ${i("settingsExtensions")} ${d.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:d.name}),children:i("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("deletePreset"),onClick:()=>s({type:"delete_preset",name:d.name}),children:e.jsx(Ee,{})})]})]},d.name))})]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:c,children:i("close")})})]})})}function Qa(t,s){const a=Math.max(0,Date.now()-t),l=Math.floor(a/6e4);if(l<1)return s("bgTaskJustNow");if(l<60)return s("bgTaskMinutes",{n:l});const c=Math.floor(l/60);return c<24?s("bgTaskHours",{n:c}):s("bgTaskDays",{n:Math.floor(c/24)})}function Xa({servers:t,send:s,onClose:a}){const l=pe(),[c,i]=r.useState(new Set),n=o=>i(u=>{const p=new Set(u);return p.has(o)?p.delete(o):p.add(o),p});return r.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"bg-task-modal",onClick:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(ut,{})," ",l("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:l("close"),onClick:a,children:e.jsx(ke,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(ut,{}),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,p=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")," ",Qa(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(p)?"open":""}`,title:`${l("bgTaskCommand")}: ${o.command}`,onClick:()=>n(p),children:[e.jsx(qe,{}),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(ot,{}),e.jsx("span",{children:l("bgTaskStop")})]})]},p)})}),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(pt,{}),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(ot,{}),e.jsx("span",{children:l("bgTaskStopAll")})]})]})]})})}function st(t,s){return t.toLowerCase().includes(s)}function Za({send:t,sessions:s,projects:a,cwd:l,fileSearch:c,onClose:i,onSwitchSession:n,onSwitchProject:o,onPreviewFile:u}){const p=pe(),h=r.useRef(null),[g,y]=r.useState(""),b=r.useDeferredValue(g),[k,B]=r.useState(0),E=r.useRef(1),$=r.useRef(0),x=r.useRef(null);r.useEffect(()=>{t({type:"list_sessions"}),t({type:"list_projects"}),requestAnimationFrame(()=>{var L;return(L=h.current)==null?void 0:L.focus()})},[]);const[j,P]=r.useState(!1);r.useEffect(()=>{x.current&&clearTimeout(x.current);const L=b.trim();if(L)return x.current=setTimeout(()=>{const S=++E.current;$.current=S,P(!0),t({type:"search_files",reqId:S,query:L})},300),()=>{x.current&&clearTimeout(x.current)}},[b]);const D=b.trim().toLowerCase(),R=r.useMemo(()=>D?s.filter(L=>st(L.firstMessage??"",D)||st(L.name??"",D)||st(L.path.split(/[\\/]/).pop()??"",D)).slice(0,20):[],[s,D]),N=r.useMemo(()=>D?a.filter(L=>st(L.path,D)).slice(0,10):[],[a,D]),m=r.useMemo(()=>!D||!c||c.reqId!==$.current||!c.ok?[]:c.results,[c,D]);r.useEffect(()=>{c&&c.reqId===$.current&&$.current!==0&&P(!1)},[c]);const A=!!c&&c.ok&&c.truncated,W=r.useMemo(()=>[...R.map(L=>({kind:"session",path:L.path})),...N.map(L=>({kind:"project",path:L.path})),...m.filter(L=>L.type==="file").map(L=>({kind:"file",path:L.path,name:L.name}))],[R,N,m]);r.useEffect(()=>{B(0)},[b]);const ee=r.useCallback(L=>{L&&(L.kind==="session"?n(L.path):L.kind==="project"?o(L.path):u(L.path,L.name),i())},[n,o,u,i]);r.useEffect(()=>{const L=S=>{S.key==="Escape"?(S.preventDefault(),S.stopPropagation(),i()):S.key==="ArrowDown"?(S.preventDefault(),B(C=>Math.min(C+1,W.length-1))):S.key==="ArrowUp"?(S.preventDefault(),B(C=>Math.max(C-1,0))):S.key==="Enter"&&(S.preventDefault(),ee(W[k]))};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[W,k,ee,i]);const ie=R.length+N.length+m.length,H=(L,S,C)=>e.jsxs("div",{className:"gs-section-head",children:[C,e.jsx("span",{children:L}),e.jsx("em",{children:S})]});let q=-1;return e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:i,children:e.jsxs("div",{className:"gs-modal",onClick:L=>L.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(dt,{}),e.jsx("input",{ref:h,type:"text",value:g,placeholder:p("gsPlaceholder"),onChange:L=>y(L.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:p("close"),onClick:i,children:e.jsx(ke,{})})]}),e.jsxs("div",{className:"gs-results",children:[!D&&e.jsx("div",{className:"gs-empty",children:p("gsHint")}),D&&ie===0&&!A&&e.jsx("div",{className:"gs-empty",children:p(j?"gsSearching":"gsNoResults")}),R.length>0&&e.jsxs("div",{className:"gs-section",children:[H(p("gsSessions"),R.length,e.jsx(Ke,{})),R.map(L=>{q++;const S=q;return e.jsxs("button",{type:"button",className:S===k?"gs-item active":"gs-item",onMouseEnter:()=>B(S),onClick:()=>ee({kind:"session",path:L.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[L.name||L.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:L.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:L.firstMessage})]},L.path)})]}),N.length>0&&e.jsxs("div",{className:"gs-section",children:[H(p("gsProjects"),N.length,e.jsx(ze,{})),N.map(L=>{q++;const S=q,C=l&&L.path===l;return e.jsxs("button",{type:"button",className:S===k?"gs-item active":"gs-item",onMouseEnter:()=>B(S),onClick:()=>ee({kind:"project",path:L.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[L.path.split(/[\\/]/).pop(),C&&e.jsx("em",{className:"gs-item-meta",children:p("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:L.path})]},L.path)})]}),(m.length>0||D&&A)&&e.jsxs("div",{className:"gs-section",children:[H(p("gsFiles"),m.length,e.jsx(_s,{})),m.map(L=>{q++;const S=q;return e.jsxs("button",{type:"button",className:S===k?"gs-item active":"gs-item",disabled:L.type==="dir",title:L.type==="dir"?void 0:p("gsOpenPreview"),onMouseEnter:()=>B(S),onClick:()=>{L.type==="file"&&ee({kind:"file",path:L.path,name:L.name})},children:[e.jsx("span",{className:"gs-item-title",children:L.name}),e.jsx("span",{className:"gs-item-sub",children:L.path})]},`${L.type}:${L.path}`)}),A&&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")]})]})]})})}const wt=5e3;function er({file:t,content:s,send:a,onAddLines:l,onAttach:c,onClose:i}){const n=pe(),[o,u]=r.useState(null),[p,h]=r.useState(!1),[g,y]=r.useState(null),[b,k]=r.useState(!1),[B,E]=r.useState(!1),[$,x]=r.useState(!1),[j,P]=r.useState(""),[D,R]=r.useState(!0),N=r.useRef(!1),[m,A]=r.useState(!0),[W,ee]=r.useState(!1),[ie,H]=r.useState(100),q=r.useRef(0),L=r.useRef(!1),S=r.useRef(null);r.useEffect(()=>{h(!0),u(null),y(null),x(!1),P(""),R(!0),N.current=!1,a({type:"read_file",path:t.path})},[t.path,a]),r.useEffect(()=>{s&&s.path===t.path&&(u(s),$||P(s.text),h(!1))},[s,$,t.path]),r.useEffect(()=>{const Q=le=>{if(le.key==="Escape"){ne();return}if((le.ctrlKey||le.metaKey)&&le.key.toLowerCase()==="s"&&$){le.preventDefault(),z();return}const ge=le.target,ue=ge&&(ge.tagName==="INPUT"||ge.tagName==="TEXTAREA"||ge.isContentEditable);(le.ctrlKey||le.metaKey)&&le.key.toLowerCase()==="a"&&!ue&&(le.preventDefault(),T())};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[i,o,$,j]),r.useEffect(()=>{const Q=()=>{L.current=!1,k(!1)};return window.addEventListener("mouseup",Q),()=>window.removeEventListener("mouseup",Q)},[]);const C=r.useMemo(()=>{if(!o)return[];const Q=o.text.split(`
|
|
320
|
+
`);return Q.length>0&&Q[Q.length-1]===""&&Q.pop(),Q.slice(0,wt)},[o]),K=(o==null?void 0:o.lines)??0,me=K>wt,J=(Q,le)=>{if(le){const ge=q.current>0?q.current:Q;y({start:Math.min(ge,Q),end:Math.max(ge,Q)})}else q.current=Q,y({start:Q,end:Q})},T=()=>{C.length!==0&&(q.current=1,y({start:1,end:C.length}))},Z=()=>{g&&(l(t.path,t.name,g.start,g.end),E(!0),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>E(!1),1400))},te=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,M=()=>{P((o==null?void 0:o.text)??""),x(!1),N.current&&R(!0)},F=()=>{if($){if(j!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges")))return;M();return}!te||!o||(N.current=Nt(t.name)&&D,Nt(t.name)&&R(!1),y(null),P(o.text),x(!0))},z=()=>{!$||!o||!te||a({type:"write_file",path:t.path,text:j})&&(x(!1),N.current&&R(!0),y(null))},ne=()=>{$&&j!==((o==null?void 0:o.text)??"")&&!window.confirm(n("discardFileChanges"))||i()},G=Q=>{H(Math.min(200,Math.max(50,Q)))},oe=g?g.end-g.start+1:0,X=(o==null?void 0:o.binary)??!1,d=(o==null?void 0:o.truncated)??!1,I=(o==null?void 0:o.kind)??"text",ce=Nt(t.name),se=ce&&D&&!$&&I==="text"&&!X,he=Q=>ft(`/api/file?clientId=${encodeURIComponent(_t())}&path=${encodeURIComponent(Q)}`);return e.jsx("div",{className:`fp-overlay ${W?"fullscreen":""}`,onMouseDown:Q=>{Q.target===Q.currentTarget&&ne()},children:e.jsxs("div",{className:`fp ${W?"fullscreen":""}`,style:{"--fp-zoom":ie/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&&I==="text"&&!X&&n("fileLines",{n:K}),o&&` · ${tr(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[ce&&I==="text"&&!X&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${D?"on":""}`,"data-tip":n(D?"showMarkdownSource":"showMarkdownPreview"),disabled:$,onClick:()=>R(Q=>!Q),children:D?e.jsx(St,{}):e.jsx(Yn,{})}),I==="text"&&!X&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${$?"on":""}`,"data-tip":n(d?"fileEditTruncated":$?"exitEditFile":"editFile"),disabled:!te&&!$,onClick:F,children:e.jsx(Tt,{})}),I==="text"&&!X&&!se&&e.jsx("button",{type:"button",className:`fp-attach wrap ${m?"on":""}`,"data-tip":n(m?"disableWrap":"enableWrap"),onClick:()=>A(Q=>!Q),children:e.jsx(Jn,{})}),I==="text"&&o&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":n("zoomOut"),disabled:ie<=50,onClick:()=>G(ie-10),children:e.jsx(Pn,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:n("resetZoom"),onClick:()=>H(100),children:[ie,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":n("zoomIn"),disabled:ie>=200,onClick:()=>G(ie+10),children:e.jsx(In,{})})]}),I!=="video"&&I!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":n("attachInlineTip"),onClick:()=>c(t.path,t.name,"inline"),children:e.jsx(De,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":n("referenceTip"),onClick:()=>c(t.path,t.name,"reference"),children:e.jsx(Ct,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${W?"on":""}`,"data-tip":n(W?"exitFullscreen":"fullscreen"),onClick:()=>ee(Q=>!Q),children:W?e.jsx($n,{}):e.jsx(Wn,{})}),e.jsx("button",{type:"button",className:"fp-close",title:n("close"),onClick:ne,children:e.jsx(ke,{})})]})]}),d&&I==="text"&&!X&&e.jsx("div",{className:"fp-notice",children:n("previewTruncated")}),p&&!o&&e.jsx("div",{className:"fp-empty",children:n("loading")}),!p&&I==="none"&&!X&&e.jsx("div",{className:"fp-empty",children:n("previewNotSupported")}),!p&&I==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:he(t.path),alt:t.name})}),!p&&I==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:he(t.path),controls:!0,preload:"metadata"})}),!p&&se&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(xt,{text:o.text})})}),!p&&X&&I!=="image"&&I!=="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})]}),!p&&$&&I==="text"&&!X&&o&&e.jsx("textarea",{className:`fp-editor ${m?"":"no-wrap"}`,value:j,onChange:Q=>P(Q.target.value),wrap:m?"soft":"off",spellCheck:!1,autoFocus:!0}),!p&&!se&&!$&&I==="text"&&!X&&o&&C.length===0&&e.jsx("div",{className:"fp-empty",children:n("emptyFile")}),!p&&!se&&!$&&I==="text"&&!X&&C.length>0&&e.jsxs("div",{className:`fp-code ${b?"dragging":""} ${m?"":"no-wrap"}`,onMouseDown:Q=>{Q.button===0&&Q.preventDefault()},children:[C.map((Q,le)=>{const ge=le+1,ue=g!==null&&ge>=g.start&&ge<=g.end;return e.jsxs("div",{className:`fp-line ${ue?"sel":""}`,onMouseDown:we=>{we.button===0&&(J(ge,we.shiftKey),L.current=!0,k(!0))},onMouseEnter:()=>{L.current&&J(ge,!0)},children:[e.jsx("span",{className:"fp-num",children:ge}),e.jsx("span",{className:"fp-code-text",children:Q})]},ge)}),me&&e.jsx("div",{className:"fp-lines-note",children:n("previewLinesTruncated",{n:wt})})]}),e.jsx("div",{className:"fp-foot",children:$?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:n("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:F,children:n("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:j===((o==null?void 0:o.text)??""),onClick:z,children:[e.jsx(An,{})," ",n("saveFile")]})]})]}):!se&&I==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:g?n("selectedRange",{n:oe,start:g.start,end:g.end}):n("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:C.length===0,onClick:T,children:n("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!g,onClick:()=>y(null),children:n("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!g||X,onClick:Z,children:[B?e.jsx(gt,{}):null,n(B?"addedToChat":"addToChat")]})]})]})})]})})}function Nt(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function tr(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const cn="pi-web-sounds",Je={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function dn(){try{const t=localStorage.getItem(cn);if(!t)return{...Je};const s=JSON.parse(t),a={...Je,...s};for(const l of["enabled","question","done","start","error"])typeof a[l]!="boolean"&&(a[l]=Je[l]);return typeof a.volume!="number"||!Number.isFinite(a.volume)?a.volume=Je.volume:a.volume=Math.round(Math.max(0,Math.min(100,a.volume))/5)*5,a}catch{return{...Je}}}function sr(t){try{localStorage.setItem(cn,JSON.stringify(t))}catch{}}let Ye=null;function nr(){try{if(!Ye){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;Ye=new t}return Ye.state==="suspended"&&Ye.resume(),Ye}catch{return null}}const ir=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],ar=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],rr=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],lr=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],or={question:ir,done:ar,start:rr,error:lr};function cr(t,s,a){const l=t.createOscillator(),c=t.createGain();l.type=s.type,l.frequency.value=s.freq;const i=t.currentTime+s.start,n=Math.max(1e-4,s.peak*a);c.gain.setValueAtTime(1e-4,i),c.gain.exponentialRampToValueAtTime(n,i+.012),c.gain.exponentialRampToValueAtTime(1e-4,i+s.dur),l.connect(c),c.connect(t.destination),l.start(i),l.stop(i+s.dur+.05)}function Qe(t,s=dn()){if(!s.enabled||!s[t])return;const a=nr();if(!a)return;const l=Math.max(0,Math.min(1,s.volume/100));for(const c of or[t])cr(a,c,l)}const Lt="pi-web-ui:theme",un="dark",Ns="theme-stylesheet",Cs="pi-web-ui:theme-change";function pn(){try{const t=localStorage.getItem(Lt);if(t&&t!==un)return t}catch{}return null}function dr(t){try{t?localStorage.setItem(Lt,t):localStorage.removeItem(Lt)}catch{}}function mn(t){let s=document.getElementById(Ns);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(Cs));return}s||(s=document.createElement("link"),s.id=Ns,s.rel="stylesheet",document.head.appendChild(s)),s.href=`/themes/${encodeURIComponent(t)}.css`,s.onload=()=>window.dispatchEvent(new CustomEvent(Cs))}async function ur(){try{const t=await fetch(ft("/api/themes"));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function pr(){const[t,s]=r.useState([]),[a,l]=r.useState(()=>pn());return r.useEffect(()=>{let i=!1;return ur().then(n=>{i||s(n)}),()=>{i=!0}},[]),r.useEffect(()=>{mn(a),dr(a)},[a]),{themes:t,theme:a,switchTheme:i=>l(i===un?null:i)}}function kr(){const t=getComputedStyle(document.documentElement),s=(a,l)=>t.getPropertyValue(a).trim()||l;return{background:s("--term-bg","#0b0d12"),foreground:s("--term-fg","#e6e8ef"),cursor:s("--term-cursor","#8b5cf6"),cursorAccent:s("--term-cursor-accent","#0b0d12"),selectionBackground:s("--term-selection","rgba(139, 92, 246, 0.35)"),black:s("--term-black","#1a1d26"),red:s("--term-red","#f87171"),green:s("--term-green","#34d399"),yellow:s("--term-yellow","#fbbf24"),blue:s("--term-blue","#60a5fa"),magenta:s("--term-magenta","#c084fc"),cyan:s("--term-cyan","#22d3ee"),white:s("--term-white","#e6e8ef"),brightBlack:s("--term-bright-black","#6b7284"),brightRed:s("--term-bright-red","#f87171"),brightGreen:s("--term-bright-green","#34d399"),brightYellow:s("--term-bright-yellow","#fbbf24"),brightBlue:s("--term-bright-blue","#60a5fa"),brightMagenta:s("--term-bright-magenta","#c084fc"),brightCyan:s("--term-bright-cyan","#22d3ee"),brightWhite:s("--term-bright-white","#ffffff")}}const mr=r.lazy(()=>Rs(()=>import("./TerminalPanel-CgkoEcJf.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function hr({notice:t,onDismiss:s}){const a=pe(),[l,c]=r.useState(!1);r.useEffect(()=>{if(l)return;const n=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(n)},[l,t.id,t.level,s]);const i=t.level==="error"?ei:t.level==="warning"?Zn:Kn;return e.jsxs("div",{className:`notice notice-${t.level}${l?" paused":""}`,role:"status",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[e.jsx(i,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:t.text}),e.jsx("button",{type:"button",className:"notice-close",title:a("close"),onClick:()=>s(t.id),children:e.jsx(ke,{})})]})}const gr=[],hn=180,gn=520,fn=240,xn=t=>`pi-web-ui:${t}-panel-width`;function Ss(t){const s=Number(localStorage.getItem(xn(t)));return Number.isFinite(s)&&s>=hn&&s<=gn?s:fn}function Ts({side:t,width:s,onResize:a}){const l=pe(),c=r.useCallback(i=>{i.preventDefault();const n=i.clientX,o=s;let u=o;const p=g=>{const y=t==="left"?g.clientX-n:n-g.clientX;u=Math.min(gn,Math.max(hn,Math.round(o+y))),a(u)},h=()=>{window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",h),document.body.classList.remove("panel-resizing"),localStorage.setItem(xn(t),String(u))};window.addEventListener("pointermove",p),window.addEventListener("pointerup",h),document.body.classList.add("panel-resizing")},[t,s,a]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:l("dragToResize"),onPointerDown:c,onDoubleClick:()=>a(fn)})}function fr(){var V,O,ae,de,ye,Se,Ot,Wt,Ht,Ut,qt,Kt,zt,Vt;const t=pe(),{chat:s,send:a,dismissNotice:l,pushNotice:c,terminal:i}=Ci(),[n,o]=r.useState([]),[u,p]=r.useState(null),[h,g]=r.useState(!1),[y,b]=r.useState("chat"),k=r.useMemo(()=>s.plugins.filter(_=>{var U,re;return!((re=(U=s.settings)==null?void 0:U.disabledPlugins)!=null&&re.includes(_.id))}),[s.plugins,(V=s.settings)==null?void 0:V.disabledPlugins]),[B,E]=r.useState([]);r.useEffect(()=>fi(E),[]),r.useEffect(()=>{xi(k,s.pluginsEpoch)},[k,s.pluginsEpoch]);const[$,x]=r.useState(()=>Ss("left")),[j,P]=r.useState(()=>Ss("right")),D=r.useCallback(_=>x(_),[]),R=r.useCallback(_=>P(_),[]),[N,m]=r.useState(null),[A,W]=r.useState(()=>window.matchMedia("(max-width: 768px)").matches);r.useEffect(()=>{const _=window.matchMedia("(max-width: 768px)"),U=re=>W(re.matches);return _.addEventListener("change",U),()=>_.removeEventListener("change",U)},[]);const[ee,ie]=r.useState(!1),[H,q]=r.useState(!1),[L,S]=r.useState(!1),[C,K]=r.useState(!1),[me,J]=r.useState(!1);r.useEffect(()=>{const _=U=>{var Ie,Gt;const re=U.detail,fe=(re==null?void 0:re.title)||"插件命令",xe=re==null?void 0:re.command;if(!xe||!s.ready)return;const je={name:fe,command:xe,cwd:"${pwd}"},ve=s.terminals.find(vt=>vt.title===fe);if(ve)i.restart(ve.id),a({type:"run_command",terminalId:ve.id,conversationId:ve.conversationId,command:je,cols:80,rows:24});else{const vt=Re();i.create({id:vt,conversationId:s.activeConversationId||((Ie=s.state)==null?void 0:Ie.conversationId)||"",title:fe,cwd:((Gt=s.state)==null?void 0:Gt.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:je})}b("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",_),()=>window.removeEventListener("pi-web-ui:plugin-run-command",_)},[s,i,a]),r.useEffect(()=>{const _=U=>{!(U.ctrlKey||U.metaKey)||U.key.toLowerCase()!=="k"||(U.preventDefault(),J(re=>!re))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[]);const[T,Z]=r.useState(dn),{themes:te,theme:M,switchTheme:F}=pr(),z=r.useRef(null),ne=r.useRef(null),G=r.useRef(0),oe=r.useRef(!1),X=r.useRef(s.terminals);r.useEffect(()=>{sr(T)},[T]),r.useEffect(()=>{var U;const _=X.current;X.current=s.terminals;for(const re of s.terminals){const fe=((U=re.command)==null?void 0:U.command)??"",xe=_.find(je=>je.id===re.id);!(xe!=null&&xe.running)||re.running||(fe.startsWith("pi remove ")?a({type:"extensions_reload"}):fe.startsWith("pi-web-ui install ")||fe.startsWith("pi-web-ui uninstall ")?a({type:"plugins_reload"}):fe.startsWith("npm i -g ")&&(a({type:"extensions_reload"}),a({type:"plugins_reload"}),a({type:"check_updates_all",force:!0})))}},[s.terminals,a]),r.useEffect(()=>{var re;const _=((re=s.state)==null?void 0:re.isStreaming)??!1,U=z.current;z.current=_,U!==null&&(!U&&_?Qe("start",T):U&&!_&&Qe("done",T))},[(O=s.state)==null?void 0:O.isStreaming,T]),r.useEffect(()=>{var U;const _=((U=s.dialog)==null?void 0:U.id)??null;_!==null&&_!==ne.current&&Qe("question",T),ne.current=_},[s.dialog,T]),r.useEffect(()=>{const _=[...s.notices].reverse().find(U=>U.level==="error");_&&_.id!==G.current&&(G.current=_.id,Qe("error",T))},[s.notices,T]);const d=(_,U,re,fe=!1,xe)=>{const je=`${_}|${re}|${xe?`${xe.start}-${xe.end}`:""}`;o(ve=>ve.some(Ie=>`${Ie.path}|${Ie.mode}|${Ie.lines?`${Ie.lines.start}-${Ie.lines.end}`:""}`===je)?ve:[...ve,{path:_,name:U,mode:re,isDir:fe,...xe?{lines:xe}:{}}])},I=_=>o(U=>U.filter(re=>re.key?re.key!==_:re.path!==_)),ce=r.useCallback(_=>(!_.type.startsWith("list_")&&!_.type.startsWith("get_")&&m(null),a(_)),[a]),se=r.useRef(0),he=r.useRef(0),Q=_=>{var fe;const U=Date.now();(fe=s.state)!=null&&fe.model&&!s.state.model.vision&&U-he.current>1e4&&(he.current=U,c("warning",t("imageNotSupported")));const re=`paste-${++se.current}`;o(xe=>[...xe,{path:"",key:re,name:_.name,mode:"inline",imageData:_.data,mimeType:_.mimeType}])},le=async _=>{for(const U of _){const re=await Gs(U);if(!re){c("error",t("imageLoadFailed",{name:U.name}));continue}Q(re)}},ge=20*1024*1024,ue=r.useRef(0),we=async _=>{if(_.size>ge){c("warning",t("fileTooLarge",{name:_.name,size:ge/1024/1024}));return}let U;try{U=(await new Promise((xe,je)=>{const ve=new FileReader;ve.onload=()=>xe(ve.result),ve.onerror=()=>je(ve.error??new Error("read failed")),ve.readAsDataURL(_)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",t("fileLoadFailed",{name:_.name}));return}const re=`upload-${++ue.current}`;o(fe=>[...fe,{path:"",key:re,name:_.name,mode:"inline",fileData:U,size:_.size,mimeType:_.type||void 0}])},Be=async _=>{for(const U of _)Me(U.type)?await le([U]):await we(U)},$e=r.useCallback((_,U,re)=>{a({type:"edit_message",messageId:_,text:U,attachments:re})},[a]),Ve=r.useCallback(()=>q(!0),[]),Ge=r.useCallback(()=>o([]),[]),Ce=r.useCallback(I,[]),Oe=r.useCallback(le,[le]),Ae=r.useCallback(Be,[Be]),Ne=(ae=s.state)==null?void 0:ae.model,Pe=(de=s.state)==null?void 0:de.thinkingLevel,w=(ye=s.state)==null?void 0:ye.availableThinkingLevels,f=r.useMemo(()=>Ne?{model:Ne,thinkingLevel:Pe??"off",availableThinkingLevels:w??[]}:null,[Ne,Pe,w]),v=r.useCallback(()=>{var _,U;return!s.ready||s.terminals.length!==0?!1:(i.create({id:Re(),conversationId:s.activeConversationId||((_=s.state)==null?void 0:_.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,(Se=s.state)==null?void 0:Se.cwd,s.terminals.length,t,i]);return r.useEffect(()=>{if(oe.current){if(y!=="terminal"||s.terminals.length!==0){oe.current=!1;return}v()&&(oe.current=!1)}},[s.terminals.length,v,y]),e.jsxs("div",{className:"app",onDragOver:_=>{var U;Array.from(((U=_.dataTransfer)==null?void 0:U.types)??[]).includes("Files")&&(_.preventDefault(),g(!0))},onDragLeave:_=>{_.currentTarget.contains(_.relatedTarget)||g(!1)},onDrop:_=>{var xe,je;if(g(!1),!Array.from(((xe=_.dataTransfer)==null?void 0:xe.types)??[]).includes("Files"))return;_.preventDefault();const U=Array.from(((je=_.dataTransfer)==null?void 0:je.files)??[]);if(U.length===0){c("warning",t("foldersNotSupported"));return}const re=U.filter(ve=>Me(ve.type)),fe=U.filter(ve=>!Me(ve.type));re.length>0&&le(re),fe.length>0&&Be(fe)},children:[h&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(li,{chat:s,send:a,terminal:i,view:y,plugins:k,onViewChange:_=>{oe.current=_==="terminal"&&s.terminals.length===0,oe.current&&v()&&(oe.current=!1),b(_),m(null)},onOpenPanel:m,onOpenSettings:()=>S(!0),onOpenBgTasks:()=>K(!0),onOpenGlobalSearch:()=>J(!0),sound:T,onSoundChange:Z,onSoundPreview:_=>Qe(_,T),themes:te,theme:M,onThemeChange:F}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(_=>e.jsx(hr,{notice:_,onDismiss:l},_.id))}),e.jsx(wa,{send:a,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${$}px`,"--right-w":`${j}px`},children:[N&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>m(null)}),e.jsxs("div",{className:`view-pane ${y==="chat"?"":"hidden"}`,children:[e.jsx("div",{className:`panel-drawer drawer-left ${N==="left"?"open":""}`,children:e.jsx(ci,{send:ce,active:!A||N==="left",ready:s.ready,status:s.status,cwd:((Ot=s.state)==null?void 0:Ot.cwd)??"",sessionFile:((Wt=s.state)==null?void 0:Wt.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!A&&e.jsx(Ts,{side:"left",width:$,onResize:D}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(Ma,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:$e,onKillBash:()=>a({type:"abort_bash"}),thinkingWrap:((Ht=s.settings)==null?void 0:Ht.thinkingWrap)??!0,toolsWrap:((Ut=s.settings)==null?void 0:Ut.toolsWrap)??!0},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(Fa,{send:a,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId}),s.dialog&&e.jsx(Wa,{dialog:s.dialog,send:a}),e.jsx(_a,{send:a,ready:s.ready,streaming:((qt=s.state)==null?void 0:qt.isStreaming)??!1,messages:((Kt=s.state)==null?void 0:Kt.messages)??gr,slashCommands:s.slashCommands,modelState:f,models:s.models,modelsLoading:s.modelsLoading,attachments:n,onRemoveAttachment:Ce,onAddImageFiles:Oe,onAddLocalFiles:Ae,onNotice:c,onManageModels:Ve,onSent:Ge})]}),!A&&e.jsx(Ts,{side:"right",width:j,onResize:R}),e.jsx("div",{className:`panel-drawer drawer-right ${N==="right"?"open":""}`,children:e.jsx(Di,{send:ce,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((zt=s.state)==null?void 0:zt.cwd)??"",onAttach:(_,U,re,fe)=>{m(null),d(_,U,re,fe)},onPreview:(_,U)=>{m(null),p({path:_,name:U})},onNotice:(_,U)=>c(_,U)})})]}),e.jsx("div",{className:`view-pane ${y==="terminal"?"":"hidden"}`,children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(mr,{chat:s,send:a,terminal:i})})}),e.jsx("div",{className:`view-pane ${y==="git"?"":"hidden"}`,children:e.jsx(Ua,{chat:s,send:a,terminal:i,active:y==="git",onSwitchToTerminal:()=>b("terminal")})}),B.map(_=>{const U=`plugin:${_.info.id}`;return e.jsx("div",{className:`view-pane ${y===U?"":"hidden"}`,children:e.jsx(qa,{entry:_,send:a})},_.info.id)})]})}),e.jsx($a,{chat:s,send:a}),u&&e.jsx(er,{file:u,content:s.fileContent,send:a,onAddLines:(_,U,re,fe)=>d(_,U,"lines",!1,{start:re,end:fe}),onAttach:(_,U,re)=>d(_,U,re),onClose:()=>p(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!ee&&!H&&e.jsx(Ka,{send:a,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>ie(!0)}),H&&e.jsx(Ga,{send:a,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>q(!1)}),L&&e.jsx(Ya,{chat:s,send:a,terminal:i,onSwitchToTerminal:()=>b("terminal"),onClose:()=>S(!1)}),C&&e.jsx(Xa,{servers:s.bgServers,send:a,onClose:()=>K(!1)}),me&&e.jsx(Za,{send:a,sessions:s.sessions,projects:s.projects,cwd:((Vt=s.state)==null?void 0:Vt.cwd)??"",fileSearch:s.fileSearch,onClose:()=>J(!1),onSwitchSession:_=>{a({type:"switch_session",path:_})},onSwitchProject:_=>{a({type:"set_cwd",path:_})},onPreviewFile:(_,U)=>{p({path:_,name:U})}})]})}di();mn(pn());bn.createRoot(document.getElementById("root")).render(e.jsx(r.StrictMode,{children:e.jsx(ai,{children:e.jsx(fr,{})})}));export{pt as F,Cs as T,De as a,kr as b,yr as c,Et as d,Ee as e,ke as f,On as g,qe as h,Re as r,pe as u};
|