pi-web-ui 0.62.0 → 0.62.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-
|
|
2
|
-
import{R as qe,a as r,j as e,M as Hs,b as Dn,c as Bn}from"./markdown-DRBrS2Nf.js";import{r as Ks}from"./react-C9ovnpIm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))a(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&a(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function a(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();var ct={},os;function _n(){if(os)return ct;os=1;var t=Ks();return ct.createRoot=t.createRoot,ct.hydrateRoot=t.hydrateRoot,ct}var An=_n();const $n="modulepreload",Fn=function(t){return"/"+t},cs={},Hn=function(s,n,a){let o=Promise.resolve();if(n&&n.length>0){let i=function(u){return Promise.all(u.map(f=>Promise.resolve(f).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=i(n.map(u=>{if(u=Fn(u),u in cs)return;cs[u]=!0;const f=u.endsWith(".css"),h=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const x=document.createElement("link");if(x.rel=f?"stylesheet":$n,f||(x.as="script"),x.crossOrigin="",x.href=u,d&&x.setAttribute("nonce",d),document.head.appendChild(x),f)return new Promise((v,T)=>{x.addEventListener("load",v),x.addEventListener("error",()=>T(new Error(`Unable to preload CSS for ${u}`)))})}))}function l(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return o.then(i=>{for(const c of i||[])c.status==="rejected"&&l(c.reason);return s().catch(l)})};var Os={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ds=qe.createContext&&qe.createContext(Os),Kn=["attr","size","title"];function On(t,s){if(t==null)return{};var n,a,o=Wn(t,s);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(a=0;a<l.length;a++)n=l[a],s.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}function Wn(t,s){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(s.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function mt(){return mt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},mt.apply(null,arguments)}function us(t,s){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);s&&(a=a.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,a)}return n}function ht(t){for(var s=1;s<arguments.length;s++){var n=arguments[s]!=null?arguments[s]:{};s%2?us(Object(n),!0).forEach(function(a){Un(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):us(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function Un(t,s,n){return(s=qn(s))in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function qn(t){var s=zn(t,"string");return typeof s=="symbol"?s:s+""}function zn(t,s){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,s);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Ws(t){return t&&t.map((s,n)=>qe.createElement(s.tag,ht({key:n},s.attr),Ws(s.child)))}function te(t){return s=>qe.createElement(Vn,mt({attr:ht({},t.attr)},s),Ws(t.child))}function Vn(t){var s=n=>{var a=t.attr,o=t.size,l=t.title,i=On(t,Kn),c=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),qe.createElement("svg",mt({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,a,i,{className:d,style:ht(ht({color:t.color||n.color},n.style),t.style),height:c,width:c,xmlns:"http://www.w3.org/2000/svg"}),l&&qe.createElement("title",null,l),t.children)};return ds!==void 0?qe.createElement(ds.Consumer,null,n=>s(n)):s(Os)}function Gn(t){return te({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 Qn(t){return te({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 ut(t){return te({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 Se(t){return te({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 Us(t){return te({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 Yn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"17 8 12 3 7 8"},child:[]},{tag:"line",attr:{x1:"12",y1:"3",x2:"12",y2:"15"},child:[]}]})(t)}function Jn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 9.9-1"},child:[]}]})(t)}function Ie(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(t)}function Je(t){return te({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 ps(t){return te({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 Xn(t){return te({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 gt(t){return te({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 Zn(t){return te({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 ft(t){return te({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 qs(t){return te({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 xt(t){return te({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 ei(t){return te({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 zs(t){return te({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 at(t){return te({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 Ae(t){return te({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 te({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 ti(t){return te({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 ms(t){return te({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 si(t){return te({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 ni(t){return te({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 Xe(t){return te({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 ii(t){return te({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 ai(t){return te({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 ri(t){return te({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 li(t){return te({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 Dt(t){return te({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 vt(t){return te({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 oi(t){return te({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 ci(t){return te({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 di(t){return te({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 ui(t){return te({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 hs(t){return te({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 pt(t){return te({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 te({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 Vs(t){return te({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 Gs(t){return te({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 Bt(t){return te({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 _t(t){return te({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 Qs(t){return te({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 Wt(t){return te({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 rt(t){return te({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 pi(t){return te({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 Ys(t){return te({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 mi(t){return te({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 Js(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"13 17 18 12 13 7"},child:[]},{tag:"polyline",attr:{points:"6 17 11 12 6 7"},child:[]}]})(t)}function Xs(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"11 17 6 12 11 7"},child:[]},{tag:"polyline",attr:{points:"18 17 13 12 18 7"},child:[]}]})(t)}function yt(t){return te({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 kt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function ze(t){return te({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 ot(t){return te({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 hi(t){return te({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 Nt(t){return te({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 gi(t){return te({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 Zs(t){return te({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 en(t){return te({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 fi(t){return te({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 xi(t){return te({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 vi(t){return t.map(s=>s.kind==="package"?`pi update npm:${s.name}`:`npm i -g ${s.name}@latest`).join("; ")}function Fe(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(n=>n.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Ke({trigger:t,open:s,onOpenChange:n,children:a,align:o="right",fit:l=!1,direction:i="down",menuClassName:c,menuRef:d,menuStyle:u}){const f=r.useRef(null);return r.useEffect(()=>{if(!s)return;const h=v=>{f.current&&!f.current.contains(v.target)&&n(!1)},x=v=>{v.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",h),document.addEventListener("keydown",x),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",x)}},[s,n]),e.jsxs("div",{className:`dropdown ${o} ${l?"fit":""} ${i==="up"?"dd-up":""}`,ref:f,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!s),"aria-expanded":s,children:[t,e.jsx(ze,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${c??""}`,ref:d,style:u,children:a})]})}function Te({active:t,disabled:s=!1,title:n,onClick:a,children:o}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:n,onClick:a,children:o})}const tn="pi-web-ui:lang",yi={cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",collapsePanel:"收起面板",expandPanel:"展开面板",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",engineBadge:"引擎",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",cacheHit:"缓存命中",cacheHitTip:"缓存读取 {read} · 缓存写入 {write} · 未命中 {miss}(共 {input} 输入 token)",tps:"t/s",rateTip:"实时生成速率(估算)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",queueSteerTag:"插队",queueFollowTag:"排队",queueRemoveTip:"移除此排队消息",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",uploadToFolder:"上传文件到此文件夹",uploadToCurrentDir:"上传文件到当前目录",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",modelQuestion:"模型提问",modelQuestionCustom:"补充回答(可选)",modelQuestionSubmit:"提交回答",noOptions:"(无选项)",inputPlaceholder:"输入内容",questionTimeout:"⏳ 剩余 {s} 秒,超时将自动取消",questionTimeoutExpired:"提问已超时,正在恢复对话…",modelNoVision:"当前模型 {name} 不支持图片,请切换到 DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH 引擎使用运行时内置技能(dsh-skill),暂不支持在设置面板启停",dshExtensionsNote:"DSH 引擎无 pi 扩展体系,能力由运行时内置(MCP/subagent/goal/plan/skill 等)",dshReviewPromptNote:"DSH 无独立审查会话:此指令将随目标轮次附加到系统提示词,供模型在目标轮次中遵守",dshVisionHiddenNote:"DSH 引擎直接支持图片输入(仅 DeepSeek V4 Flash Vision (exp) 模型),无需视觉桥转写",dshNoReviewModel:"DSH 无独立审查模型:目标由模型自判定完成/受阻,轮次上限即自动迭代次数",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-web-ui 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",directory:"目录",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",modelUsedCount:"已用 {n} 次",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:搜索历史对话全文(含 AI 回复)、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","tpl.title":"提示词模板","tpl.hint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.clickCard":"点击填入输入框","tpl.editTpl":"编辑 / 删除模板","tpl.openPicker":"提示词模板(常用提示词,随时取用)","tpl.pickerTitle":"提示词模板","tpl.pickerHint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.add":"新建模板","tpl.addDesc":"把常用工作流存成模板","tpl.reset":"恢复默认模板","tpl.resetConfirm":"确认恢复默认?","tpl.builtin":"内置","tpl.custom":"自定义","tpl.newTitle":"新建提示词模板","tpl.editTitle":"编辑提示词模板","tpl.fieldIcon":"图标","tpl.fieldTitle":"标题","tpl.fieldTitlePh":"卡片上显示的短标题","tpl.fieldDesc":"说明","tpl.fieldDescPh":"一句话说明,显示在卡片上","tpl.fieldPrompt":"提示词","tpl.fieldPromptPh":"完整提示词 —— 发送给智能体的内容","tpl.required":"标题和提示词不能为空","tpl.save":"保存修改","tpl.fill":"填入输入框","tpl.fillTip":"填入输入框,可再编辑后发送","tpl.sendNow":"直接发送","tpl.sendTip":"立即作为新对话发送","tpl.delete":"删除","tpl.deleteTip":"删除这个自定义模板","tpl.remove":"移出模板库","tpl.removeTip":"把内置模板移出模板库,可在底部「恢复默认模板」找回","tpl.restore":"恢复默认","tpl.restoreTip":"撤掉你的修改,恢复内置默认","tpl.sk.setup":"仓库初始化","tpl.sk.setup.desc":"让仓库了解它的构建与约定","tpl.sk.setup.prompt":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-CrduzEDu.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 Ue,a as r,j as e,M as Ks,b as Bn,c as _n}from"./markdown-DRBrS2Nf.js";import{r as Os}from"./react-C9ovnpIm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))a(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const i of l.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&a(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function a(o){if(o.ep)return;o.ep=!0;const l=n(o);fetch(o.href,l)}})();var ct={},os;function An(){if(os)return ct;os=1;var t=Os();return ct.createRoot=t.createRoot,ct.hydrateRoot=t.hydrateRoot,ct}var $n=An();const Fn="modulepreload",Hn=function(t){return"/"+t},cs={},Kn=function(s,n,a){let o=Promise.resolve();if(n&&n.length>0){let i=function(u){return Promise.all(u.map(f=>Promise.resolve(f).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));o=i(n.map(u=>{if(u=Hn(u),u in cs)return;cs[u]=!0;const f=u.endsWith(".css"),h=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const x=document.createElement("link");if(x.rel=f?"stylesheet":Fn,f||(x.as="script"),x.crossOrigin="",x.href=u,d&&x.setAttribute("nonce",d),document.head.appendChild(x),f)return new Promise((v,S)=>{x.addEventListener("load",v),x.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${u}`)))})}))}function l(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return o.then(i=>{for(const c of i||[])c.status==="rejected"&&l(c.reason);return s().catch(l)})};var Ws={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ds=Ue.createContext&&Ue.createContext(Ws),On=["attr","size","title"];function Wn(t,s){if(t==null)return{};var n,a,o=Un(t,s);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(a=0;a<l.length;a++)n=l[a],s.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(o[n]=t[n])}return o}function Un(t,s){if(t==null)return{};var n={};for(var a in t)if({}.hasOwnProperty.call(t,a)){if(s.indexOf(a)!==-1)continue;n[a]=t[a]}return n}function mt(){return mt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var a in n)({}).hasOwnProperty.call(n,a)&&(t[a]=n[a])}return t},mt.apply(null,arguments)}function us(t,s){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(t);s&&(a=a.filter(function(o){return Object.getOwnPropertyDescriptor(t,o).enumerable})),n.push.apply(n,a)}return n}function ht(t){for(var s=1;s<arguments.length;s++){var n=arguments[s]!=null?arguments[s]:{};s%2?us(Object(n),!0).forEach(function(a){qn(t,a,n[a])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):us(Object(n)).forEach(function(a){Object.defineProperty(t,a,Object.getOwnPropertyDescriptor(n,a))})}return t}function qn(t,s,n){return(s=zn(s))in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function zn(t){var s=Vn(t,"string");return typeof s=="symbol"?s:s+""}function Vn(t,s){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var a=n.call(t,s);if(typeof a!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Us(t){return t&&t.map((s,n)=>Ue.createElement(s.tag,ht({key:n},s.attr),Us(s.child)))}function te(t){return s=>Ue.createElement(Gn,mt({attr:ht({},t.attr)},s),Us(t.child))}function Gn(t){var s=n=>{var a=t.attr,o=t.size,l=t.title,i=Wn(t,On),c=o||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),Ue.createElement("svg",mt({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,a,i,{className:d,style:ht(ht({color:t.color||n.color},n.style),t.style),height:c,width:c,xmlns:"http://www.w3.org/2000/svg"}),l&&Ue.createElement("title",null,l),t.children)};return ds!==void 0?Ue.createElement(ds.Consumer,null,n=>s(n)):s(Ws)}function Qn(t){return te({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 Yn(t){return te({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 ut(t){return te({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 Te(t){return te({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 qs(t){return te({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 Jn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"17 8 12 3 7 8"},child:[]},{tag:"line",attr:{x1:"12",y1:"3",x2:"12",y2:"15"},child:[]}]})(t)}function Xn(t){return te({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 Le(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(t)}function Je(t){return te({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 ps(t){return te({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 Zn(t){return te({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 gt(t){return te({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 ei(t){return te({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 ft(t){return te({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 zs(t){return te({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 xt(t){return te({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 ti(t){return te({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 Vs(t){return te({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 at(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"polyline",attr:{points:"1 20 1 14 7 14"},child:[]},{tag:"path",attr:{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"},child:[]}]})(t)}function $e(t){return te({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 Jr(t){return te({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 si(t){return te({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 ms(t){return te({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 ni(t){return te({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 ii(t){return te({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 Xe(t){return te({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 ai(t){return te({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 ri(t){return te({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 li(t){return te({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 oi(t){return te({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 Dt(t){return te({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 vt(t){return te({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 ci(t){return te({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 di(t){return te({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 ui(t){return te({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 pi(t){return te({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 hs(t){return te({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 pt(t){return te({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 te({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 Gs(t){return te({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 Qs(t){return te({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 Bt(t){return te({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 _t(t){return te({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 Ys(t){return te({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 Wt(t){return te({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 rt(t){return te({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 mi(t){return te({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 Js(t){return te({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 hi(t){return te({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 Xs(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"13 17 18 12 13 7"},child:[]},{tag:"polyline",attr:{points:"6 17 11 12 6 7"},child:[]}]})(t)}function Zs(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"11 17 6 12 11 7"},child:[]},{tag:"polyline",attr:{points:"18 17 13 12 18 7"},child:[]}]})(t)}function yt(t){return te({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 kt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function qe(t){return te({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 ot(t){return te({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 gi(t){return te({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 Nt(t){return te({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 fi(t){return te({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 en(t){return te({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 tn(t){return te({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 xi(t){return te({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 vi(t){return te({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 yi(t){return t.map(s=>s.kind==="package"?`pi update npm:${s.name}`:`npm i -g ${s.name}@latest`).join("; ")}function He(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(n=>n.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function We({trigger:t,open:s,onOpenChange:n,children:a,align:o="right",fit:l=!1,direction:i="down",menuClassName:c,menuRef:d,menuStyle:u}){const f=r.useRef(null);return r.useEffect(()=>{if(!s)return;const h=v=>{f.current&&!f.current.contains(v.target)&&n(!1)},x=v=>{v.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",h),document.addEventListener("keydown",x),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",x)}},[s,n]),e.jsxs("div",{className:`dropdown ${o} ${l?"fit":""} ${i==="up"?"dd-up":""}`,ref:f,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!s),"aria-expanded":s,children:[t,e.jsx(qe,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${c??""}`,ref:d,style:u,children:a})]})}function Ee({active:t,disabled:s=!1,title:n,onClick:a,children:o}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:n,onClick:a,children:o})}const sn="pi-web-ui:lang",ki={cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",collapsePanel:"收起面板",expandPanel:"展开面板",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",engineBadge:"引擎",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",cacheHit:"缓存命中",cacheHitTip:"缓存读取 {read} · 缓存写入 {write} · 未命中 {miss}(共 {input} 输入 token)",tps:"t/s",rateTip:"实时生成速率(估算)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",queueSteerTag:"插队",queueFollowTag:"排队",queueRemoveTip:"移除此排队消息",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",uploadToFolder:"上传文件到此文件夹",uploadToCurrentDir:"上传文件到当前目录",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",modelQuestion:"模型提问",modelQuestionCustom:"补充回答(可选)",modelQuestionSubmit:"提交回答",noOptions:"(无选项)",inputPlaceholder:"输入内容",questionTimeout:"⏳ 剩余 {s} 秒,超时将自动取消",questionTimeoutExpired:"提问已超时,正在恢复对话…",modelNoVision:"当前模型 {name} 不支持图片,请切换到 DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH 引擎使用运行时内置技能(dsh-skill),暂不支持在设置面板启停",dshExtensionsNote:"DSH 引擎无 pi 扩展体系,能力由运行时内置(MCP/subagent/goal/plan/skill 等)",dshReviewPromptNote:"DSH 无独立审查会话:此指令将随目标轮次附加到系统提示词,供模型在目标轮次中遵守",dshVisionHiddenNote:"DSH 引擎直接支持图片输入(仅 DeepSeek V4 Flash Vision (exp) 模型),无需视觉桥转写",dshNoReviewModel:"DSH 无独立审查模型:目标由模型自判定完成/受阻,轮次上限即自动迭代次数",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-web-ui 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",directory:"目录",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",modelUsedCount:"已用 {n} 次",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:搜索历史对话全文(含 AI 回复)、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","tpl.title":"提示词模板","tpl.hint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.clickCard":"点击填入输入框","tpl.editTpl":"编辑 / 删除模板","tpl.openPicker":"提示词模板(常用提示词,随时取用)","tpl.pickerTitle":"提示词模板","tpl.pickerHint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.add":"新建模板","tpl.addDesc":"把常用工作流存成模板","tpl.reset":"恢复默认模板","tpl.resetConfirm":"确认恢复默认?","tpl.builtin":"内置","tpl.custom":"自定义","tpl.newTitle":"新建提示词模板","tpl.editTitle":"编辑提示词模板","tpl.fieldIcon":"图标","tpl.fieldTitle":"标题","tpl.fieldTitlePh":"卡片上显示的短标题","tpl.fieldDesc":"说明","tpl.fieldDescPh":"一句话说明,显示在卡片上","tpl.fieldPrompt":"提示词","tpl.fieldPromptPh":"完整提示词 —— 发送给智能体的内容","tpl.required":"标题和提示词不能为空","tpl.save":"保存修改","tpl.fill":"填入输入框","tpl.fillTip":"填入输入框,可再编辑后发送","tpl.sendNow":"直接发送","tpl.sendTip":"立即作为新对话发送","tpl.delete":"删除","tpl.deleteTip":"删除这个自定义模板","tpl.remove":"移出模板库","tpl.removeTip":"把内置模板移出模板库,可在底部「恢复默认模板」找回","tpl.restore":"恢复默认","tpl.restoreTip":"撤掉你的修改,恢复内置默认","tpl.sk.setup":"仓库初始化","tpl.sk.setup.desc":"让仓库了解它的构建与约定","tpl.sk.setup.prompt":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
|
|
3
3
|
|
|
4
4
|
1. 项目类型、技术栈与目录结构
|
|
5
5
|
2. 构建 / 测试 / 运行 / 格式化的具体命令
|
|
@@ -149,7 +149,7 @@ import{R as qe,a as r,j as e,M as Hs,b as Dn,c as Bn}from"./markdown-DRBrS2Nf.js
|
|
|
149
149
|
2. 用最小实现让测试通过
|
|
150
150
|
3. 重构并保持测试通过
|
|
151
151
|
|
|
152
|
-
避免三种反模式:与实现耦合的测试、空洞断言(永远为真)、横向切片(只测表面)。每步汇报并运行测试。`,error:"出错",done:"完成",running:"执行中…",toolQueued:"排队中",copyArgs:"复制参数",errorOutput:"错误输出",output:"输出",waitingOutput:"等待输出…",toolDoneWaitingModel:"已结束 · 等模型",waitingModel:"等待模型响应…",thinkingNow:"思考中",thinkingPreview:"思考:{preview}",commands:"命令",newCommand:"新建命令",newTerminal:"新建终端",name:"名称",command:"命令",cwdHint:"(${pwd} = 当前工作目录)",noCommands:"还没有命令,点 + 添加一个",clickToRun:"点击运行",edit:"编辑",delete:"删除",confirmQ:"确认?",builtinTerminal:"内置终端",termEmptySub:"点击左侧命令运行,或点右侧 + 新建终端",noTerminal:"暂无终端",exited:"(已退出{code})",closeTerminal:"关闭终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",aiBashGroup:"终端接管 bash",exampleName:"例如:启动开发服务器",exampleCommand:"例如:npm run dev",scmTab:"Git",scmTitle:"源代码管理",scmRefreshTip:"重新查询 Git 状态与差异",scmCurrentBranch:"当前分支",scmUpstreamGone:"上游已删除",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"分离 HEAD",scmSelectBranch:"选择分支…",scmRemoteBranches:"远程分支",scmStageTip:"暂存 {path}",scmUnstageTip:"取消暂存 {path}",scmSwitch:"切换",scmSwitchBranch:"切换分支",scmSwitchBranchTip:"在终端中执行 git checkout {branch}",scmPush:"推送",scmPushTip:"在终端中执行 git push",scmPull:"拉取",scmPullTip:"在终端中执行 git pull",scmCommit:"提交",scmCommitTip:'在终端中执行 git add -A && git commit -m "…"(提交全部更改,含未跟踪)',scmCommitPlaceholder:"输入提交信息…",scmChanges:"更改",scmHistory:"提交树",scmCommitDetail:"提交详情",scmSelectCommitHint:"点击左侧提交查看详情",scmNoHistory:"暂无提交记录",scmNoChanges:"工作区干净,没有更改",scmNotGitRepo:"当前目录不是 Git 仓库",scmLoading:"查询中…",scmConnecting:"等待连接…",scmDiff:"差异",scmSelectFileHint:"点击左侧文件查看差异",scmNoDiff:"(无差异)",scmStaged:"已暂存",scmUnstaged:"未暂存",scmStagedUnstaged:"已暂存 + 未暂存",scmUntracked:"未跟踪",scmUntrackedNote:"未跟踪文件:差异不显示,提交时会一并包含",scmQueryFailed:"Git 查询失败:{error}",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"只需填入 API 密钥",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",cloneProvider:"添加密钥",cloning:"添加中",cloneProviderTitle:"为该供应商添加第二把密钥(自动复制 baseUrl 与模型列表,可改名后保存)",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",addKey:"添加密钥",addKeyPlaceholder:"粘贴密钥值…",keyNamePh:"名称(可留空,如 备用)",noKeyYet:"尚无密钥,添加一把即可用",activateKey:"设为当前",removeKey:"移除",removeKeyConfirm:"确定移除该密钥?移除后需重新配置才能使用。",customProviders:"自定义服务商",customDesc:"用于 Ollama / vLLM / 兼容 OpenAI 的代理等,写入 pi 的 models.json,保存后热重载、立即生效。",noCustomProviders:"还没有自定义服务商",modelsCount:"{n} 个模型",addProvider:"新增服务商",providerId:"服务商 ID",providerIdHint:"(必填,如 ollama / my-proxy)",displayName:"显示名",displayNamePh:"我的代理",apiType:"API 类型",baseUrlHint:"(OpenAI 兼容端点)",apiKeyHint:"sk-…(可留空,用 auth.json 的密钥)",authHeader:"自动添加 Authorization 请求头",modelsTitle:"模型",modelIdReq:"模型 ID(必填)",text:"文本",textImage:"文本+图片",contextWindow:"上下文",maxOutput:"最大输出",removeModel:"移除模型",addModel:"添加模型",deleteProviderConfirm:"删除服务商 {id} 及其 {n} 个模型?",fetchModels:"自动获取模型列表",fetchModelsHint:"从 baseUrl 的 /models 接口自动拉取模型 ID(服务端请求,不受 CORS 限制)",fetchingModels:"获取中…",fetchModelsOk:"已获取 {n} 个模型",fetchModelsEmpty:"接口未返回任何模型",fetchModelsErr:"获取失败:{msg}",fetchModelsNeedBaseUrl:"请先填写 baseUrl 再获取",goalBarTitle:"目标",goalBarPlaceholder:"设定一个目标,agent 完成后自动审查…",goalBarSet:"开始",goalBarClear:"取消",goalBarLocked:"锁定:应用到后续所有回合",goalBarUnlocked:"仅本回合(改完自动清除)",goalBarReviewModel:"审查模型",goalBarUseMainModel:"使用主模型",goalBarMaxRounds:"最大轮数",goalBarMaxRoundsTip:"最大审查重改轮数;0 或不填 = 不限(持续改到通过)",goalBarUnlimitedShort:"不限",goalBarReviewing:"审查中…",goalBarRound:"第 {n} 轮",goalBarActive:"目标生效中",goalBarPassed:"已通过",goalBarFailed:"未通过",goalBarStatusPending:"等待生成…",goalWizardBtn:"AI 提炼",goalWizardTip:"让 AI 通过问卷调研细化需求,收敛为目标",goalWizardRunning:"目标调研中",goalWizardAnswer:"回答",goalWizardCard:"目标调研",settings:"设置",settingsTitle:"设置",settingsDesc:"修改立即生效:系统提示词、技能与插件开关会重建当前会话;审查提示词与审查技能只影响后续目标审查(回复进行中则主会话变更自动延迟)。",settingsSystemPrompt:"系统提示词",settingsPromptMode:"模式",promptModeAppend:"追加",promptModeReplace:"替换",promptAppendHint:"追加模式:自定义内容拼接到默认系统提示词末尾(推荐,保留默认行为约束)。",promptReplaceHint:"替换模式:完全用自定义内容替换系统提示词(项目上下文与技能段仍会自动附加)。切换后输入框会显示原本的默认提示词,可直接修改;不改动失焦则仍使用默认。",promptPlaceholder:"输入自定义系统提示词…(失焦后自动应用)",settingsViewPrompt:"查看当前完整提示词",settingsViewPromptHint:"当前会话实际生效的完整系统提示词(含自定义追加/替换内容、项目上下文、技能说明与工具引导),只读。",settingsViewPromptEmpty:"会话尚未就绪,暂无系统提示词。",settingsSkills:"技能",settingsReview:"目标审查",settingsReviewDesc:"为独立的目标审查会话配置额外提示词和技能;不会改变主会话设置。",settingsReviewSkills:"审查可用技能",reviewPromptPlaceholder:"输入审查自定义提示词…(失焦后自动应用)",reviewPromptHint:"这些内容会追加到审查任务中;审查仍会强制要求输出 pass/fail JSON。技能开关仅对审查生效。",settingsVisionBridge:"视觉桥",settingsVisionBridgeDesc:"当前模型不支持识图时,把图片交给已配置的视觉模型转写为文字证据,再让模型回答",visionBridgeEnabled:"启用视觉桥",visionBridgeModel:"转写模型",visionBridgeAuto:"自动选择(按顺序)",visionBridgeNoModels:"未找到已配置的视觉模型:在模型配置里添加任意支持图片的模型(如 qwen-vl、GLM-4V、Gemini)即可自动启用",visionBridgeOffHint:"已关闭:图片将原样发送,纯文本模型可能看不到图片内容",visionBridgeCurrent:"当前转写模型:{model}",visionBridgePromptMode:"转写提示词",settingsTerminalTools:"终端工具",terminalToolsEnabled:"启用持久终端工具",settingsTerminalToolsDesc:"让 AI 在交互式程序(REPL/vim)、长驻服务、需要持续观察输出或你要求在可见终端操作时,使用内置终端;普通命令仍走一次性 bash 工具",terminalToolsOffHint:"已关闭:AI 无法使用 terminal_* 工具,也不会收到相关使用引导",settingsMessageDisplay:"消息显示",thinkingWrap:"完整显示思考",thinkingWrapDesc:"开启:思考内容始终完整展开并自动换行(流式推理过程也实时可见);关闭:折叠成一行摘要,流式中一行实时显示最新文本",toolsWrap:"完整显示工具",toolsWrapDesc:"开启:工具调用始终完整展开显示参数和输出;关闭:默认折叠,点击展开",terminalBashTakeover:"终端接管 bash",terminalBashTakeoverDesc:"此开关决定 bash 是否覆盖为终端版:关 = 原生 SDK bash(纯进程、不开终端);开 = 跑进可见终端,且 persist 参数在本开关的基础上决定一次性(false,命令跑完进程退出、输出留档)还是持久(true,shell 状态跨调用保留、静默自动转后台并通知 AI)",terminalBashIdleMs:"静默转后台阈值(毫秒)",terminalBashIdleMsDesc:"持久终端模式下,命令连续无输出达到该时长即不再阻塞等待,转入后台继续运行并通知 AI;0 = 一直等到命令结束(默认 15000)",visionBridgePromptPlaceholder:"输入自定义转写提示词…(留空 = 使用内置默认提示词,失焦后自动应用)",visionBridgePromptAppendHint:"追加模式:自定义内容拼接到内置转写提示词末尾(推荐,保留默认的逐字转写约束)。",visionBridgePromptReplaceHint:"替换模式:完全用自定义内容替换内置转写提示词。切换后输入框会显示内置默认提示词,可直接修改;不改动失焦则仍使用默认。",uninstallExt:"卸载",uninstallConfirm:"确认卸载?",uninstallConfirmHint:"再次点击确认,将在终端执行 pi remove",uninstallHint:"通过可见终端执行 pi remove 卸载此包,完成后自动刷新列表",uninstallTitle:"卸载",pluginUpdate:"更新",pluginUpdateHint:"从安装来源重新拉取并覆盖安装(保留 config.json 配置),完成后自动重载插件列表",pluginUninstallHint:"在可见终端执行 pi-web-ui uninstall 卸载此插件(再次点击确认),完成后自动刷新列表",settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",dshPatches:"DSH 用户补丁",dshPatchesDesc:"启动时按文件名序加载的 Cordis patch(<dataDir>/dsh-patches/*.yml)。新增/修改后点「重扫」重启运行时生效;失败的文件会被跳过并打印到运行时 stderr。",dshPatchesRescan:"重扫",dshPatchesRescanHint:"重新扫描补丁目录并重启 DSH 运行时使新补丁生效",dshPatchesEmpty:"未放置补丁文件",dshPatchesPath:"补丁目录:",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},ki={cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",collapsePanel:"Collapse panel",expandPanel:"Expand panel",dragToResize:"Drag to resize · double-click to reset",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",githubRepo:"GitHub repository (xing-shuyin/pi-web-ui)",copy:"Copy",viewSwitch:"Switch view",chat:"Chat",terminal:"Terminal",selectModel:"Select model",availableModels:"Available models",allProviders:"All",providers:"Providers",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",engineBadge:"Engine",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",cacheHit:"Cache hit",cacheHitTip:"read {read} · write {write} · miss {miss} (of {input} input tokens)",tps:"t/s",rateTip:"Live generation rate (estimated)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",placeholderStreaming:"The agent is working… press Enter to steer, or click Queue to send after the reply finishes",placeholderIdle:"Message pi — Enter to send, / for commands",placeholderConnecting:"Connecting to server…",stopAgent:"Stop agent",stop:"Stop",bgTasks:"Background tasks",bgTasksTip:"Servers the AI started in the background (npm run dev & etc.) — stop them individually or all at once; they survive the conversation",bgTasksEmpty:"No background tasks",bgTasksDesc:"Processes the AI started that are still listening (detected by port)",bgTaskPort:"Port",bgTaskPid:"PID",bgTaskSince:"Started",bgTaskStop:"Stop",bgTaskStopAll:"Stop all",bgTaskRefresh:"Refresh",bgTaskJustNow:"just now",bgTaskMinutes:"{n} min ago",bgTaskHours:"{n} hr ago",bgTaskDays:"{n} days ago",stopBash:"Stop",stopBashTip:"Stop the running bash command (conversation continues)",supplement:"Queue",supplementTip:"Add to queue: sent only after the whole run finishes (no interruption)",queueSteerTag:"Steer",queueFollowTag:"Queued",queueRemoveTip:"Remove this queued message",sendTip:"Send (Enter)",slashCommands:"Commands",slashMenuHint:"↑↓ select · Enter/Tab complete",slashHelpTitle:"pi commands",slashHelpHint:"Type / anytime to open the command list",slashLoading:"Loading commands… (available once connected)",slashBuiltin:"Builtin",slashExtension:"Extension",slashPrompt:"Template",slashSkill:"Skill",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",historySessions:"History",openHistory:"History",openFiles:"Files",streaming:"Streaming…",noHistory:"No previous chats",current:"Current",messageCount:"{n} messages",tuiTip:"Chat in the pi terminal (TUI)",deleteProject:"Remove from recent projects",deleteProjectConfirm:"Confirm remove",deleteSession:"Delete this chat transcript permanently",deleteSessionConfirm:"Confirm delete",emptyChat:"Empty chat",editReask:"Edit & re-ask",editReaskTip:"Edit this question and re-ask from here (forks a new conversation; the original is kept)",reaskFromHere:"Re-ask from here",editPlaceholder:"Edit the question…",editHint:"⌘/Ctrl+Enter to submit · Esc to cancel",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-web-ui",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-web-ui",updateTerminalHint:"Clicking runs npm i -g pi-web-ui@latest in a visible terminal; restart the service afterwards to take effect (pi-web-ui server restart).",updatesAllTitle:"Component updates",updatesAllBadge:"{n} updates",updatesAllUpToDate:"All components up to date",kindWebUi:"Web UI",kindPiCore:"Core",kindPackage:"Package",updatesAllRefresh:"Re-check all",updateCheckFailed:"Check failed",updateBtn:"Update",updateAllBtn:"Update all",updatePkgTabTitle:"Update {name}",updateAllTabTitle:"Update all components",rootDir:"Root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",previewFile:"Preview",downloadFile:"Download file",downloadFailed:"Download failed: {error}",uploadToFolder:"Upload files to this folder",uploadToCurrentDir:"Upload files to current directory",protocolMismatch:"Page version differs from the server (the app was just updated). Refresh the page to restore full functionality.",selectLinesHint:"Click a line to select; drag or Shift+click for a range",enableWrap:"Enable line wrap",disableWrap:"Disable line wrap",selectedRange:"Selected {n} lines (lines {start}-{end})",fileLines:"{n} lines",selectAll:"Select all",clearSelection:"Clear",addToChat:"Add to chat",addedToChat:"Added",previewTruncated:"⚠ File too large — previewing the first 512KB",previewLinesTruncated:"… too many lines — showing the first {n}",binaryFile:"🔣 Binary file — first 4KB shown as hex",binaryHexTruncated:" (file larger — download for the full file)",previewNotSupported:"This file type can't be previewed (only images / videos / text)",emptyFile:"(empty file)",editFile:"Edit file",exitEditFile:"Exit editing",saveFile:"Save file",discardFileChanges:"Discard unsaved changes?",fileSaved:"Saved",fileEditTruncated:"The preview is incomplete, so this file can't be edited",showMarkdownSource:"Show Markdown source",showMarkdownPreview:"Show Markdown preview",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",zoomIn:"Increase font size",zoomOut:"Decrease font size",resetZoom:"Reset zoom",pluginRequest:"Plugin request",modelQuestion:"Model question",modelQuestionCustom:"Custom answer (optional)",modelQuestionSubmit:"Submit answer",questionTimeout:"⏳ {s}s left — auto-cancels on timeout",questionTimeoutExpired:"Question timed out, resuming conversation…",modelNoVision:"Current model {name} doesn't support images — switch to DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH uses runtime-built-in skills (dsh-skill); toggling is not supported in settings yet",dshExtensionsNote:"DSH has no pi extension system; capabilities are runtime-built-in (MCP/subagent/goal/plan/skill…)",dshReviewPromptNote:"DSH has no separate reviewer: this text is appended to the system prompt for goal rounds",dshVisionHiddenNote:"DSH supports real image input (DeepSeek V4 Flash Vision (exp) only) — no vision bridge needed",dshNoReviewModel:"DSH has no separate reviewer model — the model self-certifies goal completion; max rounds = auto-iteration count",noOptions:"(no options)",inputPlaceholder:"Enter content",soundHeader:"Sound notifications",enableSound:"Enable sound",preview:"Preview",volume:"Volume","sound.question":"Question popup","sound.question.desc":"When ask_user_question appears","sound.done":"Reply finished","sound.done.desc":"When the agent finishes a turn","sound.start":"Reply started","sound.start.desc":"When the agent starts a new turn","sound.error":"Error","sound.error.desc":"When an error notice appears",setupTitle:"pi agent config not detected",setupDesc:"pi-web-ui needs pi's config directory (~/.pi/agent) and at least one API key to run the agent. pi has built-in providers such as openai, anthropic, and deepseek — just pick one and enter a key, no terminal needed.",installFailed:"✖ pi agent installation failed:",retryInstall:"Retry install",skip:"Skip",installDone:"✅ pi agent CLI installed. Pick a provider and enter an API key to start chatting:",cliReadyHint:"✅ pi agent CLI already installed locally. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",directory:"Directory",waitingResponse:"Waiting for model response…",backToBottom:"Back to bottom",questionNavTitle:"Questions",searchPlaceholder:"Search in conversation…",searchNoResults:"No results",searchModels:"Filter models…",noModelMatches:"No matching models",modelUsedCount:"used {n}×",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search full conversation text (AI replies included), recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching…",gsTruncated:"Too many matches — showing a subset",gsCurrentProject:"current",gsOpenPreview:"Open file preview",gsNavigate:"select",gsOpen:"open",gsCloseHint:"close",bgTaskCommand:"Command",searchPrev:"Previous (Shift+Enter)",searchNext:"Next (Enter)",searchClose:"Close (Esc)",questionNavTip:"All questions in this conversation — hover to expand, click to jump","tpl.title":"Prompt templates","tpl.hint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.clickCard":"Click to fill the input","tpl.editTpl":"Edit / delete template","tpl.openPicker":"Prompt templates (reusable prompts, anytime)","tpl.pickerTitle":"Prompt templates","tpl.pickerHint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.add":"New template","tpl.addDesc":"Save a workflow you use often","tpl.reset":"Restore defaults","tpl.resetConfirm":"Restore defaults?","tpl.builtin":"Built-in","tpl.custom":"Custom","tpl.newTitle":"New prompt template","tpl.editTitle":"Edit prompt template","tpl.fieldIcon":"Icon","tpl.fieldTitle":"Title","tpl.fieldTitlePh":"Short title shown on the card","tpl.fieldDesc":"Description","tpl.fieldDescPh":"One-liner shown on the card","tpl.fieldPrompt":"Prompt","tpl.fieldPromptPh":"The full prompt sent to the agent","tpl.required":"Title and prompt are required","tpl.save":"Save","tpl.fill":"Fill input","tpl.fillTip":"Fill the input so you can tweak it before sending","tpl.sendNow":"Send now","tpl.sendTip":"Send immediately as a new conversation","tpl.delete":"Delete","tpl.deleteTip":"Delete this custom template","tpl.remove":"Remove from library","tpl.removeTip":"Remove this built-in template; restore later via “Restore defaults”","tpl.restore":"Restore default","tpl.restoreTip":"Discard your edits and restore the built-in default","tpl.sk.setup":"Repo setup","tpl.sk.setup.desc":"Give the repo a baseline that other workflows can use","tpl.sk.setup.prompt":`Scan this repository and build the baseline context other workflows rely on, then report concisely:
|
|
152
|
+
避免三种反模式:与实现耦合的测试、空洞断言(永远为真)、横向切片(只测表面)。每步汇报并运行测试。`,error:"出错",done:"完成",running:"执行中…",toolQueued:"排队中",copyArgs:"复制参数",errorOutput:"错误输出",output:"输出",waitingOutput:"等待输出…",toolDoneWaitingModel:"已结束 · 等模型",waitingModel:"等待模型响应…",thinkingNow:"思考中",thinkingPreview:"思考:{preview}",commands:"命令",newCommand:"新建命令",newTerminal:"新建终端",name:"名称",command:"命令",cwdHint:"(${pwd} = 当前工作目录)",noCommands:"还没有命令,点 + 添加一个",clickToRun:"点击运行",edit:"编辑",delete:"删除",confirmQ:"确认?",builtinTerminal:"内置终端",termEmptySub:"点击左侧命令运行,或点右侧 + 新建终端",noTerminal:"暂无终端",exited:"(已退出{code})",closeTerminal:"关闭终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",aiBashGroup:"终端接管 bash",exampleName:"例如:启动开发服务器",exampleCommand:"例如:npm run dev",scmTab:"Git",scmTitle:"源代码管理",scmRefreshTip:"重新查询 Git 状态与差异",scmCurrentBranch:"当前分支",scmUpstreamGone:"上游已删除",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"分离 HEAD",scmSelectBranch:"选择分支…",scmRemoteBranches:"远程分支",scmStageTip:"暂存 {path}",scmUnstageTip:"取消暂存 {path}",scmSwitch:"切换",scmSwitchBranch:"切换分支",scmSwitchBranchTip:"在终端中执行 git checkout {branch}",scmPush:"推送",scmPushTip:"在终端中执行 git push",scmPull:"拉取",scmPullTip:"在终端中执行 git pull",scmCommit:"提交",scmCommitTip:'在终端中执行 git add -A && git commit -m "…"(提交全部更改,含未跟踪)',scmCommitPlaceholder:"输入提交信息…",scmChanges:"更改",scmHistory:"提交树",scmCommitDetail:"提交详情",scmSelectCommitHint:"点击左侧提交查看详情",scmNoHistory:"暂无提交记录",scmNoChanges:"工作区干净,没有更改",scmNotGitRepo:"当前目录不是 Git 仓库",scmLoading:"查询中…",scmConnecting:"等待连接…",scmDiff:"差异",scmSelectFileHint:"点击左侧文件查看差异",scmNoDiff:"(无差异)",scmStaged:"已暂存",scmUnstaged:"未暂存",scmStagedUnstaged:"已暂存 + 未暂存",scmUntracked:"未跟踪",scmUntrackedNote:"未跟踪文件:差异不显示,提交时会一并包含",scmQueryFailed:"Git 查询失败:{error}",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"只需填入 API 密钥",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",cloneProvider:"添加密钥",cloning:"添加中",cloneProviderTitle:"为该供应商添加第二把密钥(自动复制 baseUrl 与模型列表,可改名后保存)",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",addKey:"添加密钥",addKeyPlaceholder:"粘贴密钥值…",keyNamePh:"名称(可留空,如 备用)",noKeyYet:"尚无密钥,添加一把即可用",activateKey:"设为当前",removeKey:"移除",removeKeyConfirm:"确定移除该密钥?移除后需重新配置才能使用。",customProviders:"自定义服务商",customDesc:"用于 Ollama / vLLM / 兼容 OpenAI 的代理等,写入 pi 的 models.json,保存后热重载、立即生效。",noCustomProviders:"还没有自定义服务商",modelsCount:"{n} 个模型",addProvider:"新增服务商",providerId:"服务商 ID",providerIdHint:"(必填,如 ollama / my-proxy)",displayName:"显示名",displayNamePh:"我的代理",apiType:"API 类型",baseUrlHint:"(OpenAI 兼容端点)",apiKeyHint:"sk-…(可留空,用 auth.json 的密钥)",authHeader:"自动添加 Authorization 请求头",modelsTitle:"模型",modelIdReq:"模型 ID(必填)",text:"文本",textImage:"文本+图片",contextWindow:"上下文",maxOutput:"最大输出",removeModel:"移除模型",addModel:"添加模型",deleteProviderConfirm:"删除服务商 {id} 及其 {n} 个模型?",fetchModels:"自动获取模型列表",fetchModelsHint:"从 baseUrl 的 /models 接口自动拉取模型 ID(服务端请求,不受 CORS 限制)",fetchingModels:"获取中…",fetchModelsOk:"已获取 {n} 个模型",fetchModelsEmpty:"接口未返回任何模型",fetchModelsErr:"获取失败:{msg}",fetchModelsNeedBaseUrl:"请先填写 baseUrl 再获取",goalBarTitle:"目标",goalBarPlaceholder:"设定一个目标,agent 完成后自动审查…",goalBarSet:"开始",goalBarClear:"取消",goalBarLocked:"锁定:应用到后续所有回合",goalBarUnlocked:"仅本回合(改完自动清除)",goalBarReviewModel:"审查模型",goalBarUseMainModel:"使用主模型",goalBarMaxRounds:"最大轮数",goalBarMaxRoundsTip:"最大审查重改轮数;0 或不填 = 不限(持续改到通过)",goalBarUnlimitedShort:"不限",goalBarReviewing:"审查中…",goalBarRound:"第 {n} 轮",goalBarActive:"目标生效中",goalBarPassed:"已通过",goalBarFailed:"未通过",goalBarStatusPending:"等待生成…",goalWizardBtn:"AI 提炼",goalWizardTip:"让 AI 通过问卷调研细化需求,收敛为目标",goalWizardRunning:"目标调研中",goalWizardAnswer:"回答",goalWizardCard:"目标调研",settings:"设置",settingsTitle:"设置",settingsDesc:"修改立即生效:系统提示词、技能与插件开关会重建当前会话;审查提示词与审查技能只影响后续目标审查(回复进行中则主会话变更自动延迟)。",settingsSystemPrompt:"系统提示词",settingsPromptMode:"模式",promptModeAppend:"追加",promptModeReplace:"替换",promptAppendHint:"追加模式:自定义内容拼接到默认系统提示词末尾(推荐,保留默认行为约束)。",promptReplaceHint:"替换模式:完全用自定义内容替换系统提示词(项目上下文与技能段仍会自动附加)。切换后输入框会显示原本的默认提示词,可直接修改;不改动失焦则仍使用默认。",promptPlaceholder:"输入自定义系统提示词…(失焦后自动应用)",settingsViewPrompt:"查看当前完整提示词",settingsViewPromptHint:"当前会话实际生效的完整系统提示词(含自定义追加/替换内容、项目上下文、技能说明与工具引导),只读。",settingsViewPromptEmpty:"会话尚未就绪,暂无系统提示词。",settingsSkills:"技能",settingsReview:"目标审查",settingsReviewDesc:"为独立的目标审查会话配置额外提示词和技能;不会改变主会话设置。",settingsReviewSkills:"审查可用技能",reviewPromptPlaceholder:"输入审查自定义提示词…(失焦后自动应用)",reviewPromptHint:"这些内容会追加到审查任务中;审查仍会强制要求输出 pass/fail JSON。技能开关仅对审查生效。",settingsVisionBridge:"视觉桥",settingsVisionBridgeDesc:"当前模型不支持识图时,把图片交给已配置的视觉模型转写为文字证据,再让模型回答",visionBridgeEnabled:"启用视觉桥",visionBridgeModel:"转写模型",visionBridgeAuto:"自动选择(按顺序)",visionBridgeNoModels:"未找到已配置的视觉模型:在模型配置里添加任意支持图片的模型(如 qwen-vl、GLM-4V、Gemini)即可自动启用",visionBridgeOffHint:"已关闭:图片将原样发送,纯文本模型可能看不到图片内容",visionBridgeCurrent:"当前转写模型:{model}",visionBridgePromptMode:"转写提示词",settingsTerminalTools:"终端工具",terminalToolsEnabled:"启用持久终端工具",settingsTerminalToolsDesc:"让 AI 在交互式程序(REPL/vim)、长驻服务、需要持续观察输出或你要求在可见终端操作时,使用内置终端;普通命令仍走一次性 bash 工具",terminalToolsOffHint:"已关闭:AI 无法使用 terminal_* 工具,也不会收到相关使用引导",settingsMessageDisplay:"消息显示",thinkingWrap:"完整显示思考",thinkingWrapDesc:"开启:思考内容始终完整展开并自动换行(流式推理过程也实时可见);关闭:折叠成一行摘要,流式中一行实时显示最新文本",toolsWrap:"完整显示工具",toolsWrapDesc:"开启:工具调用始终完整展开显示参数和输出;关闭:默认折叠,点击展开",terminalBashTakeover:"终端接管 bash",terminalBashTakeoverDesc:"此开关决定 bash 是否覆盖为终端版:关 = 原生 SDK bash(纯进程、不开终端);开 = 跑进可见终端,且 persist 参数在本开关的基础上决定一次性(false,命令跑完进程退出、输出留档)还是持久(true,shell 状态跨调用保留、静默自动转后台并通知 AI)",terminalBashIdleMs:"静默转后台阈值(毫秒)",terminalBashIdleMsDesc:"持久终端模式下,命令连续无输出达到该时长即不再阻塞等待,转入后台继续运行并通知 AI;0 = 一直等到命令结束(默认 15000)",visionBridgePromptPlaceholder:"输入自定义转写提示词…(留空 = 使用内置默认提示词,失焦后自动应用)",visionBridgePromptAppendHint:"追加模式:自定义内容拼接到内置转写提示词末尾(推荐,保留默认的逐字转写约束)。",visionBridgePromptReplaceHint:"替换模式:完全用自定义内容替换内置转写提示词。切换后输入框会显示内置默认提示词,可直接修改;不改动失焦则仍使用默认。",uninstallExt:"卸载",uninstallConfirm:"确认卸载?",uninstallConfirmHint:"再次点击确认,将在终端执行 pi remove",uninstallHint:"通过可见终端执行 pi remove 卸载此包,完成后自动刷新列表",uninstallTitle:"卸载",pluginUpdate:"更新",pluginUpdateHint:"从安装来源重新拉取并覆盖安装(保留 config.json 配置),完成后自动重载插件列表",pluginUninstallHint:"在可见终端执行 pi-web-ui uninstall 卸载此插件(再次点击确认),完成后自动刷新列表",settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",dshPatches:"DSH 用户补丁",dshPatchesDesc:"启动时按文件名序加载的 Cordis patch(<dataDir>/dsh-patches/*.yml)。新增/修改后点「重扫」重启运行时生效;失败的文件会被跳过并打印到运行时 stderr。",dshPatchesRescan:"重扫",dshPatchesRescanHint:"重新扫描补丁目录并重启 DSH 运行时使新补丁生效",dshPatchesEmpty:"未放置补丁文件",dshPatchesPath:"补丁目录:",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},bi={cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",collapsePanel:"Collapse panel",expandPanel:"Expand panel",dragToResize:"Drag to resize · double-click to reset",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",githubRepo:"GitHub repository (xing-shuyin/pi-web-ui)",copy:"Copy",viewSwitch:"Switch view",chat:"Chat",terminal:"Terminal",selectModel:"Select model",availableModels:"Available models",allProviders:"All",providers:"Providers",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",engineBadge:"Engine",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",cacheHit:"Cache hit",cacheHitTip:"read {read} · write {write} · miss {miss} (of {input} input tokens)",tps:"t/s",rateTip:"Live generation rate (estimated)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",placeholderStreaming:"The agent is working… press Enter to steer, or click Queue to send after the reply finishes",placeholderIdle:"Message pi — Enter to send, / for commands",placeholderConnecting:"Connecting to server…",stopAgent:"Stop agent",stop:"Stop",bgTasks:"Background tasks",bgTasksTip:"Servers the AI started in the background (npm run dev & etc.) — stop them individually or all at once; they survive the conversation",bgTasksEmpty:"No background tasks",bgTasksDesc:"Processes the AI started that are still listening (detected by port)",bgTaskPort:"Port",bgTaskPid:"PID",bgTaskSince:"Started",bgTaskStop:"Stop",bgTaskStopAll:"Stop all",bgTaskRefresh:"Refresh",bgTaskJustNow:"just now",bgTaskMinutes:"{n} min ago",bgTaskHours:"{n} hr ago",bgTaskDays:"{n} days ago",stopBash:"Stop",stopBashTip:"Stop the running bash command (conversation continues)",supplement:"Queue",supplementTip:"Add to queue: sent only after the whole run finishes (no interruption)",queueSteerTag:"Steer",queueFollowTag:"Queued",queueRemoveTip:"Remove this queued message",sendTip:"Send (Enter)",slashCommands:"Commands",slashMenuHint:"↑↓ select · Enter/Tab complete",slashHelpTitle:"pi commands",slashHelpHint:"Type / anytime to open the command list",slashLoading:"Loading commands… (available once connected)",slashBuiltin:"Builtin",slashExtension:"Extension",slashPrompt:"Template",slashSkill:"Skill",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",historySessions:"History",openHistory:"History",openFiles:"Files",streaming:"Streaming…",noHistory:"No previous chats",current:"Current",messageCount:"{n} messages",tuiTip:"Chat in the pi terminal (TUI)",deleteProject:"Remove from recent projects",deleteProjectConfirm:"Confirm remove",deleteSession:"Delete this chat transcript permanently",deleteSessionConfirm:"Confirm delete",emptyChat:"Empty chat",editReask:"Edit & re-ask",editReaskTip:"Edit this question and re-ask from here (forks a new conversation; the original is kept)",reaskFromHere:"Re-ask from here",editPlaceholder:"Edit the question…",editHint:"⌘/Ctrl+Enter to submit · Esc to cancel",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-web-ui",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-web-ui",updateTerminalHint:"Clicking runs npm i -g pi-web-ui@latest in a visible terminal; restart the service afterwards to take effect (pi-web-ui server restart).",updatesAllTitle:"Component updates",updatesAllBadge:"{n} updates",updatesAllUpToDate:"All components up to date",kindWebUi:"Web UI",kindPiCore:"Core",kindPackage:"Package",updatesAllRefresh:"Re-check all",updateCheckFailed:"Check failed",updateBtn:"Update",updateAllBtn:"Update all",updatePkgTabTitle:"Update {name}",updateAllTabTitle:"Update all components",rootDir:"Root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",previewFile:"Preview",downloadFile:"Download file",downloadFailed:"Download failed: {error}",uploadToFolder:"Upload files to this folder",uploadToCurrentDir:"Upload files to current directory",protocolMismatch:"Page version differs from the server (the app was just updated). Refresh the page to restore full functionality.",selectLinesHint:"Click a line to select; drag or Shift+click for a range",enableWrap:"Enable line wrap",disableWrap:"Disable line wrap",selectedRange:"Selected {n} lines (lines {start}-{end})",fileLines:"{n} lines",selectAll:"Select all",clearSelection:"Clear",addToChat:"Add to chat",addedToChat:"Added",previewTruncated:"⚠ File too large — previewing the first 512KB",previewLinesTruncated:"… too many lines — showing the first {n}",binaryFile:"🔣 Binary file — first 4KB shown as hex",binaryHexTruncated:" (file larger — download for the full file)",previewNotSupported:"This file type can't be previewed (only images / videos / text)",emptyFile:"(empty file)",editFile:"Edit file",exitEditFile:"Exit editing",saveFile:"Save file",discardFileChanges:"Discard unsaved changes?",fileSaved:"Saved",fileEditTruncated:"The preview is incomplete, so this file can't be edited",showMarkdownSource:"Show Markdown source",showMarkdownPreview:"Show Markdown preview",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",zoomIn:"Increase font size",zoomOut:"Decrease font size",resetZoom:"Reset zoom",pluginRequest:"Plugin request",modelQuestion:"Model question",modelQuestionCustom:"Custom answer (optional)",modelQuestionSubmit:"Submit answer",questionTimeout:"⏳ {s}s left — auto-cancels on timeout",questionTimeoutExpired:"Question timed out, resuming conversation…",modelNoVision:"Current model {name} doesn't support images — switch to DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH uses runtime-built-in skills (dsh-skill); toggling is not supported in settings yet",dshExtensionsNote:"DSH has no pi extension system; capabilities are runtime-built-in (MCP/subagent/goal/plan/skill…)",dshReviewPromptNote:"DSH has no separate reviewer: this text is appended to the system prompt for goal rounds",dshVisionHiddenNote:"DSH supports real image input (DeepSeek V4 Flash Vision (exp) only) — no vision bridge needed",dshNoReviewModel:"DSH has no separate reviewer model — the model self-certifies goal completion; max rounds = auto-iteration count",noOptions:"(no options)",inputPlaceholder:"Enter content",soundHeader:"Sound notifications",enableSound:"Enable sound",preview:"Preview",volume:"Volume","sound.question":"Question popup","sound.question.desc":"When ask_user_question appears","sound.done":"Reply finished","sound.done.desc":"When the agent finishes a turn","sound.start":"Reply started","sound.start.desc":"When the agent starts a new turn","sound.error":"Error","sound.error.desc":"When an error notice appears",setupTitle:"pi agent config not detected",setupDesc:"pi-web-ui needs pi's config directory (~/.pi/agent) and at least one API key to run the agent. pi has built-in providers such as openai, anthropic, and deepseek — just pick one and enter a key, no terminal needed.",installFailed:"✖ pi agent installation failed:",retryInstall:"Retry install",skip:"Skip",installDone:"✅ pi agent CLI installed. Pick a provider and enter an API key to start chatting:",cliReadyHint:"✅ pi agent CLI already installed locally. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",directory:"Directory",waitingResponse:"Waiting for model response…",backToBottom:"Back to bottom",questionNavTitle:"Questions",searchPlaceholder:"Search in conversation…",searchNoResults:"No results",searchModels:"Filter models…",noModelMatches:"No matching models",modelUsedCount:"used {n}×",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search full conversation text (AI replies included), recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching…",gsTruncated:"Too many matches — showing a subset",gsCurrentProject:"current",gsOpenPreview:"Open file preview",gsNavigate:"select",gsOpen:"open",gsCloseHint:"close",bgTaskCommand:"Command",searchPrev:"Previous (Shift+Enter)",searchNext:"Next (Enter)",searchClose:"Close (Esc)",questionNavTip:"All questions in this conversation — hover to expand, click to jump","tpl.title":"Prompt templates","tpl.hint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.clickCard":"Click to fill the input","tpl.editTpl":"Edit / delete template","tpl.openPicker":"Prompt templates (reusable prompts, anytime)","tpl.pickerTitle":"Prompt templates","tpl.pickerHint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.add":"New template","tpl.addDesc":"Save a workflow you use often","tpl.reset":"Restore defaults","tpl.resetConfirm":"Restore defaults?","tpl.builtin":"Built-in","tpl.custom":"Custom","tpl.newTitle":"New prompt template","tpl.editTitle":"Edit prompt template","tpl.fieldIcon":"Icon","tpl.fieldTitle":"Title","tpl.fieldTitlePh":"Short title shown on the card","tpl.fieldDesc":"Description","tpl.fieldDescPh":"One-liner shown on the card","tpl.fieldPrompt":"Prompt","tpl.fieldPromptPh":"The full prompt sent to the agent","tpl.required":"Title and prompt are required","tpl.save":"Save","tpl.fill":"Fill input","tpl.fillTip":"Fill the input so you can tweak it before sending","tpl.sendNow":"Send now","tpl.sendTip":"Send immediately as a new conversation","tpl.delete":"Delete","tpl.deleteTip":"Delete this custom template","tpl.remove":"Remove from library","tpl.removeTip":"Remove this built-in template; restore later via “Restore defaults”","tpl.restore":"Restore default","tpl.restoreTip":"Discard your edits and restore the built-in default","tpl.sk.setup":"Repo setup","tpl.sk.setup.desc":"Give the repo a baseline that other workflows can use","tpl.sk.setup.prompt":`Scan this repository and build the baseline context other workflows rely on, then report concisely:
|
|
153
153
|
|
|
154
154
|
1. Project type, tech stack and directory layout
|
|
155
155
|
2. Concrete commands for build / test / run / format
|
|
@@ -299,23 +299,23 @@ 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}",aiBashGroup:"Terminal-backed bash",exampleName:"e.g. start dev server",exampleCommand:"e.g. npm run dev",scmTab:"Git",scmTitle:"Source Control",scmRefreshTip:"Re-query git status & diff",scmCurrentBranch:"Current branch",scmUpstreamGone:"Upstream deleted",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"Detached HEAD",scmSelectBranch:"Select branch…",scmRemoteBranches:"Remote branches",scmStageTip:"Stage {path}",scmUnstageTip:"Unstage {path}",scmSwitch:"Switch",scmSwitchBranch:"Switch branch",scmSwitchBranchTip:"Runs git checkout {branch} in the terminal",scmPush:"Push",scmPushTip:"Runs git push in the terminal",scmPull:"Pull",scmPullTip:"Runs git pull in the terminal",scmCommit:"Commit",scmCommitTip:'Runs git 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:"Add key",cloning:"Adding",cloneProviderTitle:"Add a second API key for this provider (baseUrl and model list are copied automatically)",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",addKey:"Add key",addKeyPlaceholder:"Paste the key value…",keyNamePh:"Name (optional, e.g. backup)",noKeyYet:"No key yet — add one to use this provider",activateKey:"Set active",removeKey:"Remove",removeKeyConfirm:"Remove this key? It must be re-configured to be used again.",customProviders:"Custom providers",customDesc:"For Ollama / vLLM / OpenAI-compatible proxies, etc. Written to pi's models.json — hot-reloaded immediately.",noCustomProviders:"No custom providers yet",modelsCount:"{n} models",addProvider:"Add provider",providerId:"Provider ID",providerIdHint:"(required, e.g. ollama / my-proxy)",displayName:"Display name",displayNamePh:"My proxy",apiType:"API type",baseUrlHint:"(OpenAI-compatible endpoint)",apiKeyHint:"sk-… (optional — uses the auth.json key)",authHeader:"Auto-add Authorization header",modelsTitle:"Models",modelIdReq:"Model ID (required)",text:"Text",textImage:"Text+image",contextWindow:"Context",maxOutput:"Max output",removeModel:"Remove model",addModel:"Add model",deleteProviderConfirm:"Delete provider {id} and its {n} models?",fetchModels:"Fetch model list",fetchModelsHint:"Pull model IDs from the baseUrl /models endpoint (server-side, no CORS)",fetchingModels:"Fetching…",fetchModelsOk:"Fetched {n} models",fetchModelsEmpty:"The endpoint returned no models",fetchModelsErr:"Fetch failed: {msg}",fetchModelsNeedBaseUrl:"Enter a baseUrl first",goalBarTitle:"Goal",goalBarPlaceholder:"Set a goal; the agent's output is auto-reviewed…",goalBarSet:"Start",goalBarClear:"Cancel",goalBarLocked:"Locked: applies to every later turn",goalBarUnlocked:"This turn only (cleared afterwards)",goalBarReviewModel:"Review model",goalBarUseMainModel:"Use the main model",goalBarMaxRounds:"Max rounds",goalBarMaxRoundsTip:"Max review-revision rounds; 0 or empty = unlimited (keep revising until it passes)",goalBarUnlimitedShort:"Unlimited",goalBarReviewing:"Reviewing…",goalBarRound:"Round {n}",goalBarActive:"Goal active",goalBarPassed:"Passed",goalBarFailed:"Failed",goalBarStatusPending:"Waiting to generate…",goalWizardBtn:"AI Scrape",goalWizardTip:"Let AI refine the requirement into a goal via a Q&A survey",goalWizardRunning:"Scoping the goal",goalWizardAnswer:"Answer",goalWizardCard:"Goal survey",settings:"Settings",settingsTitle:"Settings",settingsDesc:"Changes apply immediately: system prompt, skill and extension toggles rebuild the current session; review instructions and review skills affect later goal reviews (main-session changes are deferred while streaming).",settingsSystemPrompt:"System prompt",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:"This switch decides whether bash is overridden to a terminal version: OFF = native SDK bash (process spawn, no terminal); ON = runs in a visible terminal, where the persist parameter decides (on top of the switch) one-shot (false — process exits when the command finishes, output retained) vs persistent (true — shell state retained across calls, silent commands move to the background and notify the AI)",terminalBashIdleMs:"Silence-to-background threshold (ms)",terminalBashIdleMsDesc:"In persistent-terminal mode, when a command produces no output for this long, stop blocking and let it keep running in the background; the AI is notified when it finishes. 0 = always wait until completion (default 15000)",visionBridgePromptPlaceholder:"Type a custom transcription prompt… (empty = built-in default, applied on blur)",visionBridgePromptAppendHint:"Append mode: custom text is appended after the built-in transcription prompt (recommended — keeps the verbatim-transcription contract).",visionBridgePromptReplaceHint:"Replace mode: custom text replaces the built-in transcription prompt entirely. After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",uninstallExt:"Uninstall",uninstallConfirm:"Confirm?",uninstallConfirmHint:"Click again to confirm — runs pi remove in the terminal",uninstallHint:"Runs pi remove in a visible terminal, then refreshes the list automatically",uninstallTitle:"Uninstall",pluginUpdate:"Update",pluginUpdateHint:"Re-installs from the recorded source (--force, keeps config.json), then refreshes the plugin list automatically",pluginUninstallHint:"Runs pi-web-ui uninstall in a visible terminal (click again to confirm), then refreshes the list automatically",settingsExtensions:"Extensions",settingsUiPlugins:"UI plugins",noUiPlugins:"No UI plugins installed (<dataDir>/plugins/)",dshPatches:"DSH user patches",dshPatchesDesc:"Cordis patches loaded at runtime boot, in filename order (<dataDir>/dsh-patches/*.yml). New/edited files take effect after 'Rescan' restarts the runtime; broken files are skipped and logged to runtime stderr.",dshPatchesRescan:"Rescan",dshPatchesRescanHint:"Re-scan the patch directory and restart the DSH runtime so new patches take effect",dshPatchesEmpty:"No patch files yet",dshPatchesPath:"Patch directory: ",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",settingsPresets:"Presets",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…"},sn=r.createContext(null);function bi(){try{const t=localStorage.getItem(tn);if(t==="zh"||t==="en")return t}catch{}return"zh"}function ji({children:t}){const[s,n]=r.useState(bi),a=r.useCallback(i=>{n(i);try{localStorage.setItem(tn,i)}catch{}},[]),o=r.useCallback((i,c)=>{let d=ki[i];if(s==="zh"&&(d=yi[i]),c)for(const[u,f]of Object.entries(c))d=d.replaceAll(`{${u}}`,String(f));return d},[s]);r.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en"},[s]);const l=r.useMemo(()=>({locale:s,setLocale:a,t:o}),[s,a,o]);return e.jsx(sn.Provider,{value:l,children:t})}function Ut(){const t=r.useContext(sn);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function fe(){return Ut().t}const wi=[{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 gs({settings:t,onChange:s,onPreview:n}){const a=fe(),o=l=>s({...t,...l});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:a("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Us,{className:"sound-icon"}),e.jsx("span",{children:a("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:l=>o({enabled:l.target.checked})})]}),wi.map(({kind:l,labelKey:i,descKey:c})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:a(i)}),e.jsx("span",{className:"sound-desc",children:a(c)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:a("preview"),disabled:!t.enabled,onClick:d=>{d.preventDefault(),n(l)},children:a("preview")}),e.jsx("input",{type:"checkbox",checked:t[l],disabled:!t.enabled,onChange:d=>o({[l]:d.target.checked})})]})]},l)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:a("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:l=>o({volume:Number(l.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}function Ni({chat:t,send:s,terminal:n,view:a,plugins:o,onViewChange:l,onOpenPanel:i,onOpenSettings:c,onOpenBgTasks:d,onOpenGlobalSearch:u,sound:f,onSoundChange:h,onSoundPreview:x,themes:v,theme:T,onThemeChange:R}){var he;const{locale:O,setLocale:y,t:C}=Ut(),[z,G]=r.useState(!1),[I,F]=r.useState(!1),[E,K]=r.useState(!1),[j,H]=r.useState(!1),[J,se]=r.useState(!1),W=[{value:"zh",label:C("langZh")},{value:"en",label:C("langEn")}],V=t.ready?C("connected"):t.status==="closed"?C("reconnecting"):C("connecting"),q=t.ready?"ok":"busy",k=()=>{var Q,ne;if(!t.ready)return;const p=C("updateTabTitle"),U={name:p,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},B=t.terminals.find(re=>re.title===p);B?(n.restart(B.id),s({type:"run_command",terminalId:B.id,conversationId:B.conversationId,command:U,cols:80,rows:24})):n.create({id:Fe(),conversationId:t.activeConversationId||((Q=t.state)==null?void 0:Q.conversationId)||"",title:p,cwd:((ne=t.state)==null?void 0:ne.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:U}),H(!1),se(!1),l("terminal")},w=(p,U)=>{var ne,re;if(!t.ready||p.length===0)return;const B={name:U,command:vi(p),cwd:"${pwd}"},Q=t.terminals.find(ue=>ue.title===U);Q?(n.restart(Q.id),s({type:"run_command",terminalId:Q.id,conversationId:Q.conversationId,command:B,cols:80,rows:24})):n.create({id:Fe(),conversationId:t.activeConversationId||((ne=t.state)==null?void 0:ne.conversationId)||"",title:U,cwd:((re=t.state)==null?void 0:re.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:B}),H(!1),se(!1),l("terminal")},b=t.updatesAll??[],L=b.filter(p=>!p.upToDate&&!p.error).length,$=b.filter(p=>!p.upToDate&&!p.error&&p.kind!=="webui"),ie=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:C("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:C("checkingUpdate")}):b.length===0?e.jsx("div",{className:"dd-note",children:C("updatesAllUpToDate")}):e.jsx("ul",{className:"dd-all-list",children:b.map(p=>e.jsxs("li",{className:`dd-all-item${p.error?" err":p.upToDate?"":" warn"}`,children:[e.jsx("span",{className:"dd-all-name",title:p.name,children:p.name}),e.jsx("span",{className:"dd-all-kind",children:p.kind==="webui"?C("kindWebUi"):p.kind==="pi-core"?C("kindPiCore"):C("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:p.error?C("updateCheckFailed"):p.upToDate?`v${p.current}`:e.jsxs(e.Fragment,{children:["v",p.current," → v",p.latest]})}),p.kind!=="webui"&&!p.upToDate&&!p.error&&e.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>w([p],C("updatePkgTabTitle",{name:p.name})),children:C("updateBtn")})]},`${p.kind}:${p.name}`))}),e.jsxs("div",{className:"dd-actions",children:[$.length>0&&e.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>w($,C("updateAllTabTitle")),children:C("updateAllBtn")}),e.jsx("button",{type:"button",className:"dd-refresh",style:$.length>0?{flex:1}:void 0,onClick:()=>s({type:"check_updates_all",force:!0}),children:C("updatesAllRefresh")})]})]}),de=()=>{var p,U;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dd-update",children:[e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:C("currentVersion")}),e.jsxs("b",{children:["v",((p=t.update)==null?void 0:p.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:C("latestVersion")}),e.jsx("b",{children:t.update===null?C("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:C("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:C("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:C("updateAvailable",{version:t.update.latest})}),((U=t.update)==null?void 0:U.latestPublishedAt)&&Date.now()-new Date(t.update.latestPublishedAt).getTime()<30*6e4&&e.jsx("div",{className:"dd-note warn",children:C("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:C("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?C("checkingUpdate"):C("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:k,children:C("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:C("openHistory"),onClick:()=>i("left"),children:e.jsx(ii,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${q}`,title:V}),e.jsx("span",{className:"conn-label",children:V})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":C("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":a==="chat",className:a==="chat"?"active":"",onClick:()=>l("chat"),children:[e.jsx(Xe,{}),e.jsx("span",{children:C("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":a==="terminal",className:a==="terminal"?"active":"",onClick:()=>l("terminal"),children:[e.jsx(Je,{}),e.jsx("span",{children:C("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":a==="git",className:a==="git"?"active":"",onClick:()=>l("git"),children:[e.jsx(pt,{}),e.jsx("span",{children:C("scmTab")})]}),o.map(p=>{const U=p.error?`${p.name}: ${p.error}`:p.description?`${p.name} — ${p.description}`:p.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":a===`plugin:${p.id}`,className:`plugin-tab${a===`plugin:${p.id}`?" active":""}${p.error?" broken":""}`,title:U,onClick:()=>l(`plugin:${p.id}`),children:[p.icon?e.jsx("span",{"aria-hidden":!0,children:p.icon}):null,e.jsx("span",{children:p.name})]},p.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:C("searchGlobalTip"),onClick:u,children:[e.jsx(xt,{}),e.jsx("span",{className:"chip-sub",children:C("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":C("bgTasksTip"),onClick:d,children:[e.jsx(vt,{}),e.jsx("span",{className:"chip-sub",children:C("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:C("settingsTitle"),onClick:c,children:[e.jsx(ft,{}),e.jsx("span",{className:"chip-sub",children:C("settings")})]}),e.jsx(Ke,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Us,{}),e.jsx("span",{className:"chip-sub",children:C("sound")})]}),open:z,onOpenChange:G,children:e.jsx(gs,{settings:f,onChange:h,onPreview:x})}),e.jsxs(Ke,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(ui,{}),e.jsx("span",{className:"chip-sub",children:O==="zh"?C("langZh"):"EN"})]}),open:I,onOpenChange:F,children:[e.jsx("div",{className:"dd-header",children:C("language")}),W.map(p=>e.jsx(Te,{active:O===p.value,onClick:()=>{y(p.value),F(!1)},children:p.label},p.value))]}),e.jsxs(Ke,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Xn,{}),e.jsx("span",{className:"chip-sub",children:C("theme")})]}),open:E,onOpenChange:K,children:[e.jsx("div",{className:"dd-header",children:C("theme")}),e.jsx(Te,{active:T===null,onClick:()=>{R(null),K(!1)},children:C("themeDefault")}),v.map(p=>e.jsx(Te,{active:T===p.id,onClick:()=>{R(p.id),K(!1)},children:p.name},p.id))]}),e.jsxs(Ke,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Wt,{}),e.jsxs("span",{className:"chip-sub",children:["v",((he=t.update)==null?void 0:he.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:C("updateAvailable",{version:t.update.latest??""})}),L>0&&e.jsx("span",{className:"update-badge",children:C("updatesAllBadge",{n:L})})]}),open:j,onOpenChange:p=>{H(p),p&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:C("update")}),de(),ie()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:C("githubRepo"),children:e.jsx(hs,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":C("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(Ae,{}),e.jsx("span",{children:C("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Ke,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(si,{}),e.jsx("span",{className:"chip-sub",children:C("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:J,onOpenChange:p=>{se(p),p&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:C("sound")}),e.jsx("div",{className:"dd-header",children:C("settings")}),e.jsxs(Te,{onClick:()=>{se(!1),c()},children:[e.jsx(ft,{})," ",C("settingsTitle")]}),e.jsxs(Te,{onClick:()=>{se(!1),u()},children:[e.jsx(xt,{})," ",C("searchGlobal")]}),e.jsxs(Te,{onClick:()=>{se(!1),d()},children:[e.jsx(vt,{})," ",C("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(gs,{settings:f,onChange:h,onPreview:x}),e.jsx("div",{className:"dd-header",children:C("language")}),W.map(p=>e.jsx(Te,{active:O===p.value,onClick:()=>y(p.value),children:p.label},p.value)),e.jsx("div",{className:"dd-header",children:C("theme")}),e.jsx(Te,{active:T===null,onClick:()=>{R(null),se(!1)},children:C("themeDefault")}),v.map(p=>e.jsx(Te,{active:T===p.id,onClick:()=>{R(p.id),se(!1)},children:p.name},p.id)),e.jsx("div",{className:"dd-header",children:C("update")}),de(),ie(),e.jsxs("a",{className:"dd-refresh dd-more-link",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",children:[e.jsx(hs,{})," ",C("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:C("openFiles"),onClick:()=>i("right"),children:e.jsx(Ze,{})})]})]})}function fs(t){const s=new Date(t),n=new Date;return s.toDateString()===n.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function Ci(t,s){const n=new Map;for(const o of t){const l=n.get(o.cwd)??[];l.push(o),n.set(o.cwd,l)}const a=[...n.entries()].map(([o,l])=>({cwd:o,isCurrent:o===s,convs:l}));return a.sort((o,l)=>o.isCurrent?-1:l.isCurrent?1:o.cwd<l.cwd?-1:o.cwd>l.cwd?1:0),a}const Si=r.memo(function({ready:s,status:n,cwd:a,sessionFile:o,conversations:l,sessions:i,projects:c,activeConversationId:d,send:u,active:f,collapsible:h,onToggleCollapse:x}){const v=fe(),T=o,R=a,[O,y]=r.useState(null);r.useEffect(()=>{!f||!s||n!=="open"||a&&(u({type:"list_sessions"}),u({type:"list_projects"}))},[f,s,n,a,u]);const C=I=>{const F=I.name||I.firstMessage.trim();return F.length>0?F:v("emptyChat")},z=I=>I.split(/[\\/]/).pop()||I,G=(I,F,E,K)=>{const j=O===I;return e.jsx("button",{type:"button",className:`lp-del ${j?"confirm":""}`,title:j?E:F,onClick:H=>{H.stopPropagation(),j?(y(null),K()):y(I)},children:j?e.jsx(ot,{}):e.jsx(Ie,{})})};return e.jsxs("aside",{className:"panel panel-left",children:[h&&x&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:v("collapsePanel"),onClick:x,children:e.jsx(Xs,{})}),c.length>0&&e.jsxs("div",{className:"panel-projects",children:[e.jsx("div",{className:"panel-section-title",children:v("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:c.map(I=>{const F=R===I.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>y(E=>E===`proj:${I.path}`?null:E),children:[e.jsxs("button",{type:"button",className:`project-item ${F?"active":""}`,title:I.path,onClick:()=>{F||u({type:"set_cwd",path:I.path})},children:[e.jsx(Ze,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:z(I.path)}),e.jsx("span",{className:"project-path",children:I.path})]}),e.jsx("span",{className:"project-time",children:fs(I.lastUsed)})]}),G(`proj:${I.path}`,v("deleteProject"),v("deleteProjectConfirm"),()=>u({type:"remove_project",path:I.path}))]},I.path)})})]}),l.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:v("runningConversations")}),Ci(l,a).map(I=>e.jsxs("div",{className:"panel-conv-group",children:[!I.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:I.cwd,children:z(I.cwd)}),I.convs.map(F=>{const E=d===F.id;return e.jsxs("button",{type:"button",className:`session-item ${E?"active":""}`,title:`${F.title}${I.isCurrent?"":` — ${I.cwd}`}`,onClick:()=>{E||u({type:"switch_conversation",id:F.id})},children:[e.jsx(Xe,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:F.title}),e.jsx("span",{className:"session-sub",children:E?v("current"):v("messageCount",{n:F.messageCount})})]}),F.isStreaming&&e.jsx("span",{className:"conv-streaming",title:v("streaming")})]},F.id)})]},I.cwd)),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:v("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[i.length===0&&e.jsx("div",{className:"panel-empty",children:v("noHistory")}),i.map(I=>{const F=T===I.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>y(E=>E===`sess:${I.path}`?null:E),children:[e.jsxs("button",{type:"button",className:`session-item ${F?"active":""}`,title:I.path,onClick:()=>{F||u({type:"switch_session",path:I.path})},children:[e.jsx(Xe,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:C(I)}),e.jsxs("span",{className:"session-sub",children:[F?v("current"):v("messageCount",{n:I.messageCount}),I.source==="tui"&&e.jsx("span",{className:"session-src",title:v("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:fs(I.modified)})]}),G(`sess:${I.path}`,v("deleteSession"),v("deleteSessionConfirm"),()=>u({type:"delete_session",path:I.path}))]},I.path)})]})]})]})}),nn="pi-web-ui:token";function Ti(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem(nn,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function Ei(){try{return localStorage.getItem(nn)??""}catch{return""}}function bt(t){const s=Ei();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}let Ct=null;function Mi(t){if(t===void 0){const n=globalThis.document;if(n&&typeof n.baseURI=="string"&&n.baseURI)try{t=new URL(n.baseURI).pathname}catch{}if(t===void 0)return"/"}if(!t||t==="/")return"/";let s=t.replace(/index\.html$/i,"");return s.endsWith("/")||(s+="/"),s}function Ri(){return Ct===null&&(Ct=Mi()),Ct}function Pi(t,s){return s==="/"?t:s+t.replace(/^\/+/,"")}function et(t){return Pi(t,Ri())}function Ii(t,s){const n=s.assistantMessageEvent,a=t.stats.tokens,o=s.usage!==null?{...a,...s.usage}:a,l=o===a?t.stats:{...t.stats,tokens:o};if(n.type!=="text_delta"&&n.type!=="thinking_delta")return l===t.stats?t:{...t,stats:l};const i=n.delta??"";if(!i)return l===t.stats?t:{...t,stats:l};const c=t.streamingMessage??null,d=c&&c.id===s.messageId?c:{id:s.messageId,content:[]},u=[...d.content],f=n.type==="thinking_delta"?"thinking":"text",h=n.contentIndex??u.length-1;return h>=0&&h<u.length&&u[h].type===f?u[h]=f==="thinking"?{type:"thinking",thinking:(u[h].thinking??"")+i}:{type:"text",text:(u[h].text??"")+i}:u.push(f==="thinking"?{type:"thinking",thinking:i}:{type:"text",text:i}),{...t,stats:l,streamingMessage:{...d,id:s.messageId,content:u}}}const At="pi-web-ui:plugin-data";function Li(t,s){window.dispatchEvent(new CustomEvent(At,{detail:{pluginId:t,payload:s}}))}function Di(t){const s=n=>{const a=n.detail;t(a.pluginId,a.payload)};return window.addEventListener(At,s),()=>window.removeEventListener(At,s)}const Ye=new Map,$t=new Set,Ge=new Set;let xs=-1;function an(){return[...Ye.values()]}function Bi(){const t=an();for(const s of $t)s(t)}function _i(t){return $t.add(t),t(an()),()=>$t.delete(t)}async function Ai(t,s){s!==xs&&(xs=s,Ye.clear(),Ge.clear());const n=new Set(t.map(a=>a.id));for(const a of[...Ye.keys()])n.has(a)||Ye.delete(a);for(const a of[...Ge])n.has(a)||Ge.delete(a);await Promise.all(t.filter(a=>a.hasClient&&!a.error&&!Ye.has(a.id)&&!Ge.has(a.id)).map(async a=>{try{const l=(await import(et(`/plugins/${encodeURIComponent(a.id)}/client/entry.mjs?e=${s}`))).default;l&&typeof l.mount=="function"?Ye.set(a.id,{info:a,module:l}):(Ge.add(a.id),console.error(`[plugin:${a.id}] entry.mjs 缺少 default.mount`))}catch(o){Ge.add(a.id),console.error(`[plugin:${a.id}] 客户端加载失败:`,o)}})),Bi()}function $i(t,s){return{pluginId:t,send:n=>s({type:"plugin_message",pluginId:t,payload:n}),onData:n=>Di((a,o)=>{a===t&&n(o)})}}const Fi=10,St=2e5,Hi=2e5,Ki={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 Oi(){const t=new Map,s=new Map,n=(a,o)=>`${a}:${o}`;return{write(a,o,l){const i=n(a,o),c=t.get(i);if(c&&c.size>0){for(const f of c)try{f.write(l)}catch{}return}const d=s.get(i)??"",u=d.length+l.length>Hi?l:d+l;s.set(i,u)},register(a,o,l){const i=n(a,o);let c=t.get(i);c||(c=new Set,t.set(i,c)),c.add(l);const d=s.get(i);if(d){try{l.write(d)}catch{}s.delete(i)}return()=>{const u=t.get(i);u&&(u.delete(l),u.size===0&&t.delete(i)),s.delete(i)}},clear(){t.clear(),s.clear()}}}function vs(t,s){const n=new Set;for(const o of s.messages)o.role==="toolResult"&&o.toolCallId&&n.add(o.toolCallId),o.role==="bashExecution"&&n.add(`bash-${o.id}`);let a=!1;for(const o of t.keys())n.has(o)&&(t.delete(o),a=!0);return a?new Map(t):t}function ys(t,s){if(t.size===0)return t;const n=new Set;for(const o of s.messages)o.role==="toolResult"&&o.toolCallId&&n.add(o.toolCallId);let a=!1;for(const o of t.keys())n.has(o)&&(t.delete(o),a=!0);return a?new Map(t):t}function Wi(t,s){var n,a,o,l;switch(s.type){case"status":return{...t,status:s.status,ready:s.status==="open"?t.ready:!1,terminals:s.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:s.serverVersion,engine:s.engine,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==Fi};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:vs(t.liveOutputs,s.state),toolStatuses:ys(t.toolStatuses,s.state)};case"snapshot_delta":{const i=t.state,c=s.msg;if(!i||i.conversationId!==c.conversationId||i.rev!==c.baseRev)return t;const d={...i,...c.state,messages:c.appended.length>0?[...i.messages,...c.appended]:i.messages};return{...t,ready:!0,state:d,activeConversationId:d.conversationId,liveOutputs:vs(t.liveOutputs,d),toolStatuses:ys(t.toolStatuses,d)}}case"tool_delta":{const i=t.liveOutputs.get(s.toolCallId),c=((i==null?void 0:i.text)??"")+s.delta,d=c.length>St?`…[前 ${c.length-St} 字符已省略]…
|
|
303
|
-
`+c.slice(c.length-St):c,u=new Map(t.liveOutputs);return u.set(s.toolCallId,{toolName:s.toolName,text:d}),{...t,liveOutputs:u}}case"message_delta":{const i=t.state;return!i||i.conversationId!==s.msg.conversationId?t:{...t,state:Ii(i,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(i=>i.id!==s.id)};case"sessions":return{...t,sessions:s.sessions};case"conversations":return{...t,conversations:s.conversations,activeConversationId:s.activeId};case"projects":return{...t,projects:s.projects};case"files":return{...t,files:s.files};case"file_changed":return{...t,fileChanged:{path:s.path}};case"file_content":return{...t,fileContent:s.content};case"models":return{...t,models:s.models,modelsLoading:s.loading};case"models_config":return{...t,modelsConfig:s.providers};case"providers_status":return{...t,providers:s.providers};case"provider_keys":return{...t,providerKeys:s.keys};case"fetch_models_result":return{...t,fetchModelsResult:s.result};case"refresh_provider_result":return{...t,refreshProviderResult:s.result};case"clone_provider_result":return{...t,cloneProviderResult:s.result};case"install_result":return{...t,installResult:s.result};case"scm_data":return{...t,scmData:s.data};case"file_search_result":return{...t,fileSearch:s.result};case"session_search_result":return{...t,sessionSearch:s.result};case"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"update_status_all":return{...t,updatesAll:s.items};case"updates_check_started":return{...t,updatesAll:null};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"question":return{...t,question:s.question};case"commands":return{...t,commands:s.commands,commandsPath:s.path};case"slash_commands":return{...t,slashCommands:s.commands};case"goal_status":return{...t,goal:s.status};case"settings":return{...t,settings:s.settings};case"bg_servers":return{...t,bgServers:s.servers};case"plugins":return{...t,plugins:s.plugins,pluginsEpoch:s.epoch};case"dsh_patches":return{...t,dshPatches:{patchDir:s.patchDir,files:s.files}};case"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(i=>i.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(n=t.state)!=null&&n.conversationId)&&s.conversationId!==(t.activeConversationId||((a=t.state)==null?void 0:a.conversationId))?t:{...t,terminals:t.terminals.map(i=>i.id===s.terminalId?{...i,running:!1,exitCode:s.exitCode}:i)};case"terminal_restart":return{...t,terminals:t.terminals.map(i=>i.id===s.terminalId?{...i,running:!0,exitCode:null}:i)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(o=t.state)!=null&&o.conversationId)&&s.conversationId!==(t.activeConversationId||((l=t.state)==null?void 0:l.conversationId))?t:{...t,terminals:s.terminals.map(i=>{var c;return{...i,conversationId:s.conversationId??((c=t.state)==null?void 0:c.conversationId)??""}})};case"terminal_active":return{...t,terminalActiveId:s.id};default:return t}}const ks="pi-web-client-id";let Tt=null;function qt(){if(Tt)return Tt;let t=null;try{t=sessionStorage.getItem(ks),t||(t=Fe(),sessionStorage.setItem(ks,t))}catch{t=t??Fe()}return Tt=t,t}function Ui(){const t=location.protocol==="https:"?"wss:":"ws:";return bt(`${t}//${location.host}${et("/ws")}`)}function qi(){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:[],providerKeys:{},installResult:null,pathCompletions:[],update:null,updatesAll:null,widgets:[],statuses:[],dialog:null,question:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],terminalActiveId:null,goal:Ki,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,dshPatches:null,protocolMismatch:!1}),n=r.useRef(null),a=r.useRef(Oi()),o=r.useRef(0),l=r.useRef(null),i=r.useRef(!0),c=r.useRef(0),d=r.useRef(0),u=r.useRef(new Map),f=r.useRef(null),h=()=>{f.current||(f.current=setTimeout(()=>{f.current=null;const E=n.current;E&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:"get_state"}))},300))},x=(E,K)=>{var J;const j=u.current,H=j.get(E);if(H!==void 0&&K!==H+1){const se=F.current.chat,W=se.activeConversationId||((J=se.state)==null?void 0:J.conversationId);E===W&&h()}j.set(E,K)},v=r.useCallback((E,K)=>{const j=++d.current;s({type:"notice",notice:{id:j,level:E,text:K}})},[]),T=r.useCallback(E=>{const K=n.current;return K&&K.readyState===WebSocket.OPEN?(E.type==="check_updates_all"&&E.force===!0&&s({type:"updates_check_started"}),K.send(JSON.stringify(E)),!0):!1},[]),R=r.useCallback(()=>{if(!i.current)return;s({type:"status",status:"connecting"});const E=new WebSocket(Ui());n.current=E,E.onopen=()=>{n.current===E&&(s({type:"status",status:"open"}),o.current=0,c.current=Date.now(),E.send(JSON.stringify({type:"hello",clientId:qt()})))},E.onmessage=K=>{if(n.current!==E)return;c.current=Date.now();let j;try{j=JSON.parse(K.data)}catch{return}switch(j.type){case"ready":s({type:"ready",serverVersion:j.serverVersion,protocolVersion:j.protocolVersion,engine:j.engine}),E.send(JSON.stringify({type:"get_state"})),E.send(JSON.stringify({type:"list_files"})),E.send(JSON.stringify({type:"list_models"})),E.send(JSON.stringify({type:"list_commands"})),E.send(JSON.stringify({type:"get_commands"})),E.send(JSON.stringify({type:"check_update"})),E.send(JSON.stringify({type:"check_updates_all"}));break;case"snapshot":u.current=new Map,s({type:"snapshot",state:j.state});break;case"snapshot_delta":{const H=F.current.chat.state;(!H||H.conversationId!==j.conversationId||H.rev!==j.baseRev)&&h(),s({type:"snapshot_delta",msg:j});break}case"tool_delta":x(j.conversationId,j.seq),s({type:"tool_delta",toolCallId:j.toolCallId,toolName:j.toolName,delta:j.delta});break;case"tool_status":s({type:"tool_status",status:j});break;case"message_delta":{x(j.conversationId,j.seq),s({type:"message_delta",msg:j});break}case"notice":{const H=++d.current;s({type:"notice",notice:{id:H,level:j.level,text:j.text}});break}case"sessions":s({type:"sessions",sessions:j.sessions});break;case"conversations":s({type:"conversations",conversations:j.conversations,activeId:j.activeId});break;case"projects":s({type:"projects",projects:j.projects});break;case"files":s({type:"files",files:j});break;case"file_changed":s({type:"file_changed",path:j.path});break;case"file_content":s({type:"file_content",content:j});break;case"models":s({type:"models",models:j.models,loading:!1});break;case"models_config":s({type:"models_config",providers:j.providers});break;case"providers_status":s({type:"providers_status",providers:j.providers});break;case"provider_keys":s({type:"provider_keys",keys:j.keys});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:j.reqId,ok:j.ok,models:j.models,error:j.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:j.reqId,ok:j.ok,added:j.added,total:j.total,error:j.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:j.reqId,ok:j.ok,config:j.config,configs:j.configs,error:j.error}});break;case"scm_data":s({type:"scm_data",data:j});break;case"search_files_result":s({type:"file_search_result",result:{reqId:j.reqId,ok:j.ok,results:j.results,truncated:j.truncated}});break;case"session_search_results":s({type:"session_search_result",result:{reqId:j.reqId,ok:j.ok,results:j.results}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:j});break;case"path_completions":s({type:"path_completions",completions:j.completions});break;case"update_status":s({type:"update_status",status:j});break;case"update_status_all":s({type:"update_status_all",items:j.items});break;case"widgets":s({type:"widgets",widgets:j.widgets});break;case"statuses":s({type:"statuses",statuses:j.statuses});break;case"dialog":s({type:"dialog",dialog:{id:j.id,kind:j.kind,title:j.title,args:j.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"question_pending":s({type:"question",question:{id:j.id,questions:j.questions}});break;case"terminal_output":a.current.write(j.conversationId??F.current.chat.activeConversationId,j.terminalId,j.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:j.conversationId,terminalId:j.terminalId,exitCode:j.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:j.conversationId,terminals:j.terminals});break;case"commands":s({type:"commands",commands:j.commands,path:j.path});break;case"slash_commands":s({type:"slash_commands",commands:j.commands});break;case"goal_status":s({type:"goal_status",status:j.status});break;case"settings_state":s({type:"settings",settings:j.settings});break;case"bg_servers":s({type:"bg_servers",servers:j.servers});break;case"plugins":s({type:"plugins",plugins:j.plugins,epoch:j.epoch});break;case"dsh_patches":s({type:"dsh_patches",patchDir:j.patchDir,files:j.files});break;case"plugin_data":Li(j.pluginId,j.payload);break}},E.onclose=()=>{if(n.current===E&&(n.current=null),a.current.clear(),!i.current||n.current&&n.current!==E)return;s({type:"status",status:"closed"});const K=Math.min(1e3*2**o.current,1e4);o.current+=1,l.current=setTimeout(()=>{l.current=null,R()},K)},E.onerror=()=>{}},[]);r.useEffect(()=>{i.current=!0,R();const E=setInterval(()=>{if(!i.current)return;const K=n.current;K&&K.readyState===WebSocket.OPEN&&Date.now()-c.current>3e4&&K.close()},5e3);return()=>{var K;i.current=!1,clearInterval(E),l.current&&(clearTimeout(l.current),l.current=null),(K=n.current)==null||K.close(),n.current=null}},[R]);const O=r.useCallback(E=>s({type:"dismiss_notice",id:E}),[]),y=r.useCallback(E=>s({type:"terminal_add",meta:E}),[]),C=r.useCallback(E=>s({type:"terminal_remove",id:E}),[]),z=r.useCallback(E=>s({type:"terminal_restart",terminalId:E}),[]),G=r.useCallback(E=>s({type:"terminal_active",id:E}),[]),I=r.useCallback((E,K,j)=>a.current.register(E,K,j),[]),F=r.useRef({chat:t,send:T,pushNotice:v,dismissNotice:O,terminal:{create:y,close:C,register:I,restart:z,select:G}});return F.current={chat:t,send:T,pushNotice:v,dismissNotice:O,terminal:{create:y,close:C,register:I,restart:z,select:G}},F.current}const zi=200*1024*1024,Vi=/windows/i.test(navigator.userAgent),Gi=/[<>:"/\\|?*\u0000-\u001f]/g,Qi=/[. ]+$/,Yi=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Ji(t){const s=t.replace(Gi,"_").replace(Qi,"");return s?Yi.test(s)?`_${s}`:s:"_"}function bs(t,s=!0){const n=new URLSearchParams({clientId:qt(),path:t,...s?{download:"1"}:{}});return bt(et(`/api/file?${n}`))}async function Xi(t,s){const n=Vi?Ji(s):s;try{const a=await fetch(bs(t));if(!a.ok)return{ok:!1,cancelled:!1,error:await a.text().catch(()=>"")||(a.status===404?"文件不存在":`HTTP ${a.status}`)};if(Number(a.headers.get("content-length")??"0")>zi)return window.location.assign(bs(t)),{ok:!0};const l=await a.blob();return window.showSaveFilePicker&&window.isSecureContext?Zi(l,n):Ft(l,n)}catch(a){return{ok:!1,cancelled:!1,error:a instanceof Error?a.message:String(a)}}}async function Zi(t,s){let n;const a=window.showSaveFilePicker;if(!a)return Ft(t,s);try{n=await a({suggestedName:s})}catch(o){return o instanceof DOMException&&o.name==="AbortError"?{ok:!1,cancelled:!0}:Ft(t,s)}try{const o=await n.createWritable();return await o.write(t),await o.close(),{ok:!0}}catch(o){return{ok:!1,cancelled:!1,error:o instanceof Error?o.message:String(o)}}}function Ft(t,s){const n=URL.createObjectURL(t),a=document.createElement("a");return a.href=n,a.download=s,document.body.appendChild(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}const ea=r.memo(function({files:s,fileChanged:n,widgets:a,cwd:o,send:l,onAttach:i,onPreview:c,onNotice:d,collapsible:u,onToggleCollapse:f}){const h=fe(),[x,v]=r.useState(""),[T,R]=r.useState(null),[O,y]=r.useState(!1),[C,z]=r.useState(null),G=r.useRef(""),I=r.useRef(null),F=r.useCallback((p,U)=>{p.preventDefault(),G.current=U,z({x:Math.min(p.clientX,window.innerWidth-220),y:Math.min(p.clientY,window.innerHeight-90)})},[]),E=r.useCallback(()=>z(null),[]);r.useEffect(()=>{if(!C)return;const p=Q=>{var ne;(ne=Q.target)!=null&&ne.closest(".ctx-menu")||E()},U=Q=>{Q.key==="Escape"&&E()};window.addEventListener("mousedown",p,!0),window.addEventListener("keydown",U);const B=()=>E();return window.addEventListener("blur",B),()=>{window.removeEventListener("mousedown",p,!0),window.removeEventListener("keydown",U),window.removeEventListener("blur",B)}},[C,E]);const K=r.useCallback(()=>{var p;E(),I.current&&(I.current.value=""),(p=I.current)==null||p.click()},[E]),j=r.useCallback((p,U)=>{for(const B of U){const Q=new FileReader;Q.onload=()=>{const ne=Q.result,re=ne.slice(ne.indexOf(",")+1);re&&l({type:"upload_file",dirPath:p,name:B.name,data:re})},Q.readAsDataURL(B)}},[l]),H=r.useCallback(p=>{j(G.current,Array.from(p.target.files??[]))},[j]),J=r.useRef(null),se=p=>{var U;return Array.from(((U=p.dataTransfer)==null?void 0:U.types)??[]).includes("Files")},W=r.useCallback(()=>{var p,U;(p=J.current)==null||p.querySelectorAll(".file-item.drop-target").forEach(B=>B.classList.remove("drop-target")),(U=J.current)==null||U.classList.remove("drop-root")},[]),V=r.useCallback(p=>{var B,Q;if(W(),p==null)return;const U=(B=J.current)==null?void 0:B.querySelector(`.file-item[data-path="${CSS.escape(p)}"]`);U?U.classList.add("drop-target"):(Q=J.current)==null||Q.classList.add("drop-root")},[W]),q=p=>{const U=p instanceof Element?p.closest(".file-item"):null;return(U==null?void 0:U.dataset.type)==="dir"?U.dataset.path??x:x},k=r.useCallback(()=>{const p=document.querySelector(".app");p&&p.dispatchEvent(new DragEvent("dragleave",{bubbles:!0}))},[]),w=1e4,b=r.useRef(0),L=r.useRef(void 0),$=r.useCallback((p,U)=>{const B=++b.current;v(p),U!=null&&U.silent||y(!0),l({type:"list_files",path:p===""?void 0:p})||b.current===B&&y(!1)},[l]);r.useEffect(()=>{s&&s.path===x&&y(!1)},[s,x]),r.useEffect(()=>{if(o!==L.current){L.current=o,$("",{silent:!0});return}const p=setInterval(()=>{document.visibilityState!=="hidden"&&$(x,{silent:!0})},w);return()=>clearInterval(p)},[o,x,$]),r.useEffect(()=>{n&&n.path===x&&$(x,{silent:!0})},[n,x,$]);const ie=p=>$(p),de=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&$(s.parent)},he=x.split("/").filter(Boolean);return e.jsxs("aside",{className:"panel panel-right",children:[u&&f&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:h("collapsePanel"),onClick:f,children:e.jsx(Js,{})}),e.jsxs("div",{className:"panel-crumbs",children:[e.jsx("button",{type:"button",className:`crumb ${x===""?"active":""}`,onClick:()=>$(""),children:h("rootDir")}),he.map((p,U)=>{const B=he.slice(0,U+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(kt,{}),e.jsx("button",{type:"button",className:`crumb ${B===x?"active":""}`,onClick:()=>$(B),children:p})]},B)})]}),e.jsxs("div",{ref:J,className:"panel-body",onContextMenu:p=>F(p,x),onDragOver:p=>{se(p)&&(p.preventDefault(),p.stopPropagation(),p.dataTransfer.dropEffect="copy",k(),V(q(p.target)))},onDragLeave:p=>{p.relatedTarget&&p.currentTarget.contains(p.relatedTarget)||W()},onDrop:p=>{var B;if(W(),!se(p))return;p.preventDefault(),p.stopPropagation(),k();const U=Array.from(((B=p.dataTransfer)==null?void 0:B.files)??[]);if(U.length===0){d("warning",h("foldersNotSupported"));return}j(q(p.target),U)},onDragEnd:W,children:[e.jsx("input",{ref:I,type:"file",multiple:!0,hidden:!0,onChange:H}),O&&e.jsx("div",{className:"panel-empty",children:h("loading")}),!O&&s&&s.path===x&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:de,children:[e.jsx(Ze,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(p=>p.type==="dir"?e.jsxs("div",{className:"file-item dir","data-type":"dir","data-path":p.path,onContextMenu:U=>{U.stopPropagation(),F(U,p.path)},children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>ie(p.path),children:[e.jsx(Ze,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:p.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":h("linkFolderTip"),onClick:()=>i(p.path,p.name,"reference",!0),children:e.jsx(Dt,{})})]},p.path):e.jsxs("div",{className:"file-item file","data-type":"file","data-path":p.path,onContextMenu:U=>{U.stopPropagation(),F(U,x)},children:[e.jsxs("button",{type:"button",className:"file-name",title:`${p.path} — ${h("previewFile")}`,onClick:()=>c(p.path,p.name),children:[e.jsx(Vs,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:p.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":h("downloadFile"),onClick:()=>{Xi(p.path,p.name).then(U=>{U.ok||U.cancelled||d("error",h("downloadFailed",{error:U.error}))})},children:e.jsx(Wt,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":h("attachInlineTip"),onClick:()=>i(p.path,p.name,"inline"),children:e.jsx(Ae,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":h("referenceTip"),onClick:()=>i(p.path,p.name,"reference"),children:e.jsx(Dt,{})})]},p.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:h("filesTruncated")})]}),!O&&!s&&e.jsx("div",{className:"panel-empty",children:h("noFiles")})]}),a.filter(p=>p.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:a.filter(p=>p.lines.length>0).map(p=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:h("widgetExpand"),onClick:()=>R(p.key),children:[e.jsx("span",{children:p.key}),e.jsx(ri,{})]}),e.jsx("pre",{className:"widget-lines",children:p.lines.join(`
|
|
304
|
-
`)})]},p.key))}),
|
|
305
|
-
`)})]})}):null})(),C&&e.jsx("div",{className:"ctx-menu",style:{left:C.x,top:C.y},onContextMenu:p=>{p.preventDefault(),p.stopPropagation()},children:e.jsxs("button",{type:"button",className:"ctx-item",onClick:K,children:[e.jsx(
|
|
306
|
-
`).map(i=>i===""?[]:[i])}if(Array.isArray(a)){let l=[];for(const i of a){const c=s(i);if(l.length===0)l=c;else{const d=c[0]??[];l[l.length-1].push(...d),l.push(...c.slice(1))}}return l}if(a&&typeof a=="object"&&"props"in a){const l=a,i=(o=l.props)==null?void 0:o.children,c={...l.props??{},children:void 0},d=i==null?[]:s(i);return d.length===0?[[r.createElement(l.type,c)]]:d.map(u=>[r.createElement(l.type,c,...u)])}return[[a]]},n=s(t);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}const
|
|
307
|
-
`),n=[];let a=[],o=null;for(let l=0;l<s.length;l++){const i=s[l];if(o!==null){const d=js(i);d&&d[0]===o[0]&&d.length>=o.length&&(o=null),a.push(i);continue}const c=js(i);if(c&&!Et(i)){o=c,a.push(i);continue}if(Et(i)){let d=l;for(;d<s.length&&Et(s[d]);)d++;if(!(d<s.length&&
|
|
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}",aiBashGroup:"Terminal-backed bash",exampleName:"e.g. start dev server",exampleCommand:"e.g. npm run dev",scmTab:"Git",scmTitle:"Source Control",scmRefreshTip:"Re-query git status & diff",scmCurrentBranch:"Current branch",scmUpstreamGone:"Upstream deleted",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"Detached HEAD",scmSelectBranch:"Select branch…",scmRemoteBranches:"Remote branches",scmStageTip:"Stage {path}",scmUnstageTip:"Unstage {path}",scmSwitch:"Switch",scmSwitchBranch:"Switch branch",scmSwitchBranchTip:"Runs git checkout {branch} in the terminal",scmPush:"Push",scmPushTip:"Runs git push in the terminal",scmPull:"Pull",scmPullTip:"Runs git pull in the terminal",scmCommit:"Commit",scmCommitTip:'Runs git 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:"Add key",cloning:"Adding",cloneProviderTitle:"Add a second API key for this provider (baseUrl and model list are copied automatically)",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",addKey:"Add key",addKeyPlaceholder:"Paste the key value…",keyNamePh:"Name (optional, e.g. backup)",noKeyYet:"No key yet — add one to use this provider",activateKey:"Set active",removeKey:"Remove",removeKeyConfirm:"Remove this key? It must be re-configured to be used again.",customProviders:"Custom providers",customDesc:"For Ollama / vLLM / OpenAI-compatible proxies, etc. Written to pi's models.json — hot-reloaded immediately.",noCustomProviders:"No custom providers yet",modelsCount:"{n} models",addProvider:"Add provider",providerId:"Provider ID",providerIdHint:"(required, e.g. ollama / my-proxy)",displayName:"Display name",displayNamePh:"My proxy",apiType:"API type",baseUrlHint:"(OpenAI-compatible endpoint)",apiKeyHint:"sk-… (optional — uses the auth.json key)",authHeader:"Auto-add Authorization header",modelsTitle:"Models",modelIdReq:"Model ID (required)",text:"Text",textImage:"Text+image",contextWindow:"Context",maxOutput:"Max output",removeModel:"Remove model",addModel:"Add model",deleteProviderConfirm:"Delete provider {id} and its {n} models?",fetchModels:"Fetch model list",fetchModelsHint:"Pull model IDs from the baseUrl /models endpoint (server-side, no CORS)",fetchingModels:"Fetching…",fetchModelsOk:"Fetched {n} models",fetchModelsEmpty:"The endpoint returned no models",fetchModelsErr:"Fetch failed: {msg}",fetchModelsNeedBaseUrl:"Enter a baseUrl first",goalBarTitle:"Goal",goalBarPlaceholder:"Set a goal; the agent's output is auto-reviewed…",goalBarSet:"Start",goalBarClear:"Cancel",goalBarLocked:"Locked: applies to every later turn",goalBarUnlocked:"This turn only (cleared afterwards)",goalBarReviewModel:"Review model",goalBarUseMainModel:"Use the main model",goalBarMaxRounds:"Max rounds",goalBarMaxRoundsTip:"Max review-revision rounds; 0 or empty = unlimited (keep revising until it passes)",goalBarUnlimitedShort:"Unlimited",goalBarReviewing:"Reviewing…",goalBarRound:"Round {n}",goalBarActive:"Goal active",goalBarPassed:"Passed",goalBarFailed:"Failed",goalBarStatusPending:"Waiting to generate…",goalWizardBtn:"AI Scrape",goalWizardTip:"Let AI refine the requirement into a goal via a Q&A survey",goalWizardRunning:"Scoping the goal",goalWizardAnswer:"Answer",goalWizardCard:"Goal survey",settings:"Settings",settingsTitle:"Settings",settingsDesc:"Changes apply immediately: system prompt, skill and extension toggles rebuild the current session; review instructions and review skills affect later goal reviews (main-session changes are deferred while streaming).",settingsSystemPrompt:"System prompt",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:"This switch decides whether bash is overridden to a terminal version: OFF = native SDK bash (process spawn, no terminal); ON = runs in a visible terminal, where the persist parameter decides (on top of the switch) one-shot (false — process exits when the command finishes, output retained) vs persistent (true — shell state retained across calls, silent commands move to the background and notify the AI)",terminalBashIdleMs:"Silence-to-background threshold (ms)",terminalBashIdleMsDesc:"In persistent-terminal mode, when a command produces no output for this long, stop blocking and let it keep running in the background; the AI is notified when it finishes. 0 = always wait until completion (default 15000)",visionBridgePromptPlaceholder:"Type a custom transcription prompt… (empty = built-in default, applied on blur)",visionBridgePromptAppendHint:"Append mode: custom text is appended after the built-in transcription prompt (recommended — keeps the verbatim-transcription contract).",visionBridgePromptReplaceHint:"Replace mode: custom text replaces the built-in transcription prompt entirely. After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",uninstallExt:"Uninstall",uninstallConfirm:"Confirm?",uninstallConfirmHint:"Click again to confirm — runs pi remove in the terminal",uninstallHint:"Runs pi remove in a visible terminal, then refreshes the list automatically",uninstallTitle:"Uninstall",pluginUpdate:"Update",pluginUpdateHint:"Re-installs from the recorded source (--force, keeps config.json), then refreshes the plugin list automatically",pluginUninstallHint:"Runs pi-web-ui uninstall in a visible terminal (click again to confirm), then refreshes the list automatically",settingsExtensions:"Extensions",settingsUiPlugins:"UI plugins",noUiPlugins:"No UI plugins installed (<dataDir>/plugins/)",dshPatches:"DSH user patches",dshPatchesDesc:"Cordis patches loaded at runtime boot, in filename order (<dataDir>/dsh-patches/*.yml). New/edited files take effect after 'Rescan' restarts the runtime; broken files are skipped and logged to runtime stderr.",dshPatchesRescan:"Rescan",dshPatchesRescanHint:"Re-scan the patch directory and restart the DSH runtime so new patches take effect",dshPatchesEmpty:"No patch files yet",dshPatchesPath:"Patch directory: ",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",settingsPresets:"Presets",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…"},nn=r.createContext(null);function ji(){try{const t=localStorage.getItem(sn);if(t==="zh"||t==="en")return t}catch{}return"zh"}function wi({children:t}){const[s,n]=r.useState(ji),a=r.useCallback(i=>{n(i);try{localStorage.setItem(sn,i)}catch{}},[]),o=r.useCallback((i,c)=>{let d=bi[i];if(s==="zh"&&(d=ki[i]),c)for(const[u,f]of Object.entries(c))d=d.replaceAll(`{${u}}`,String(f));return d},[s]);r.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en"},[s]);const l=r.useMemo(()=>({locale:s,setLocale:a,t:o}),[s,a,o]);return e.jsx(nn.Provider,{value:l,children:t})}function Ut(){const t=r.useContext(nn);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function fe(){return Ut().t}const Ni=[{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 gs({settings:t,onChange:s,onPreview:n}){const a=fe(),o=l=>s({...t,...l});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:a("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(qs,{className:"sound-icon"}),e.jsx("span",{children:a("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:l=>o({enabled:l.target.checked})})]}),Ni.map(({kind:l,labelKey:i,descKey:c})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:a(i)}),e.jsx("span",{className:"sound-desc",children:a(c)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:a("preview"),disabled:!t.enabled,onClick:d=>{d.preventDefault(),n(l)},children:a("preview")}),e.jsx("input",{type:"checkbox",checked:t[l],disabled:!t.enabled,onChange:d=>o({[l]:d.target.checked})})]})]},l)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:a("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:l=>o({volume:Number(l.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}function Ci({chat:t,send:s,terminal:n,view:a,plugins:o,onViewChange:l,onOpenPanel:i,onOpenSettings:c,onOpenBgTasks:d,onOpenGlobalSearch:u,sound:f,onSoundChange:h,onSoundPreview:x,themes:v,theme:S,onThemeChange:R}){var me;const{locale:O,setLocale:y,t:C}=Ut(),[z,G]=r.useState(!1),[I,F]=r.useState(!1),[E,K]=r.useState(!1),[j,H]=r.useState(!1),[J,se]=r.useState(!1),W=[{value:"zh",label:C("langZh")},{value:"en",label:C("langEn")}],V=t.ready?C("connected"):t.status==="closed"?C("reconnecting"):C("connecting"),q=t.ready?"ok":"busy",k=()=>{var Q,ne;if(!t.ready)return;const p=C("updateTabTitle"),U={name:p,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},B=t.terminals.find(ae=>ae.title===p);B?(n.restart(B.id),s({type:"run_command",terminalId:B.id,conversationId:B.conversationId,command:U,cols:80,rows:24})):n.create({id:He(),conversationId:t.activeConversationId||((Q=t.state)==null?void 0:Q.conversationId)||"",title:p,cwd:((ne=t.state)==null?void 0:ne.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:U}),H(!1),se(!1),l("terminal")},w=(p,U)=>{var ne,ae;if(!t.ready||p.length===0)return;const B={name:U,command:yi(p),cwd:"${pwd}"},Q=t.terminals.find(ue=>ue.title===U);Q?(n.restart(Q.id),s({type:"run_command",terminalId:Q.id,conversationId:Q.conversationId,command:B,cols:80,rows:24})):n.create({id:He(),conversationId:t.activeConversationId||((ne=t.state)==null?void 0:ne.conversationId)||"",title:U,cwd:((ae=t.state)==null?void 0:ae.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:B}),H(!1),se(!1),l("terminal")},b=t.updatesAll??[],L=b.filter(p=>!p.upToDate&&!p.error).length,A=b.filter(p=>!p.upToDate&&!p.error&&p.kind!=="webui"),ie=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:C("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:C("checkingUpdate")}):b.length===0?e.jsx("div",{className:"dd-note",children:C("updatesAllUpToDate")}):e.jsx("ul",{className:"dd-all-list",children:b.map(p=>e.jsxs("li",{className:`dd-all-item${p.error?" err":p.upToDate?"":" warn"}`,children:[e.jsx("span",{className:"dd-all-name",title:p.name,children:p.name}),e.jsx("span",{className:"dd-all-kind",children:p.kind==="webui"?C("kindWebUi"):p.kind==="pi-core"?C("kindPiCore"):C("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:p.error?C("updateCheckFailed"):p.upToDate?`v${p.current}`:e.jsxs(e.Fragment,{children:["v",p.current," → v",p.latest]})}),p.kind!=="webui"&&!p.upToDate&&!p.error&&e.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>w([p],C("updatePkgTabTitle",{name:p.name})),children:C("updateBtn")})]},`${p.kind}:${p.name}`))}),e.jsxs("div",{className:"dd-actions",children:[A.length>0&&e.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>w(A,C("updateAllTabTitle")),children:C("updateAllBtn")}),e.jsx("button",{type:"button",className:"dd-refresh",style:A.length>0?{flex:1}:void 0,onClick:()=>s({type:"check_updates_all",force:!0}),children:C("updatesAllRefresh")})]})]}),de=()=>{var p,U;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dd-update",children:[e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:C("currentVersion")}),e.jsxs("b",{children:["v",((p=t.update)==null?void 0:p.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:C("latestVersion")}),e.jsx("b",{children:t.update===null?C("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:C("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:C("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:C("updateAvailable",{version:t.update.latest})}),((U=t.update)==null?void 0:U.latestPublishedAt)&&Date.now()-new Date(t.update.latestPublishedAt).getTime()<30*6e4&&e.jsx("div",{className:"dd-note warn",children:C("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:C("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?C("checkingUpdate"):C("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:k,children:C("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:C("openHistory"),onClick:()=>i("left"),children:e.jsx(ai,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${q}`,title:V}),e.jsx("span",{className:"conn-label",children:V})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":C("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":a==="chat",className:a==="chat"?"active":"",onClick:()=>l("chat"),children:[e.jsx(Xe,{}),e.jsx("span",{children:C("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":a==="terminal",className:a==="terminal"?"active":"",onClick:()=>l("terminal"),children:[e.jsx(Je,{}),e.jsx("span",{children:C("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":a==="git",className:a==="git"?"active":"",onClick:()=>l("git"),children:[e.jsx(pt,{}),e.jsx("span",{children:C("scmTab")})]}),o.map(p=>{const U=p.error?`${p.name}: ${p.error}`:p.description?`${p.name} — ${p.description}`:p.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":a===`plugin:${p.id}`,className:`plugin-tab${a===`plugin:${p.id}`?" active":""}${p.error?" broken":""}`,title:U,onClick:()=>l(`plugin:${p.id}`),children:[p.icon?e.jsx("span",{"aria-hidden":!0,children:p.icon}):null,e.jsx("span",{children:p.name})]},p.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:C("searchGlobalTip"),onClick:u,children:[e.jsx(xt,{}),e.jsx("span",{className:"chip-sub",children:C("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":C("bgTasksTip"),onClick:d,children:[e.jsx(vt,{}),e.jsx("span",{className:"chip-sub",children:C("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:C("settingsTitle"),onClick:c,children:[e.jsx(ft,{}),e.jsx("span",{className:"chip-sub",children:C("settings")})]}),e.jsx(We,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(qs,{}),e.jsx("span",{className:"chip-sub",children:C("sound")})]}),open:z,onOpenChange:G,children:e.jsx(gs,{settings:f,onChange:h,onPreview:x})}),e.jsxs(We,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(pi,{}),e.jsx("span",{className:"chip-sub",children:O==="zh"?C("langZh"):"EN"})]}),open:I,onOpenChange:F,children:[e.jsx("div",{className:"dd-header",children:C("language")}),W.map(p=>e.jsx(Ee,{active:O===p.value,onClick:()=>{y(p.value),F(!1)},children:p.label},p.value))]}),e.jsxs(We,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Zn,{}),e.jsx("span",{className:"chip-sub",children:C("theme")})]}),open:E,onOpenChange:K,children:[e.jsx("div",{className:"dd-header",children:C("theme")}),e.jsx(Ee,{active:S===null,onClick:()=>{R(null),K(!1)},children:C("themeDefault")}),v.map(p=>e.jsx(Ee,{active:S===p.id,onClick:()=>{R(p.id),K(!1)},children:p.name},p.id))]}),e.jsxs(We,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Wt,{}),e.jsxs("span",{className:"chip-sub",children:["v",((me=t.update)==null?void 0:me.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:C("updateAvailable",{version:t.update.latest??""})}),L>0&&e.jsx("span",{className:"update-badge",children:C("updatesAllBadge",{n:L})})]}),open:j,onOpenChange:p=>{H(p),p&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:C("update")}),de(),ie()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:C("githubRepo"),children:e.jsx(hs,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":C("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx($e,{}),e.jsx("span",{children:C("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(We,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(ni,{}),e.jsx("span",{className:"chip-sub",children:C("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:J,onOpenChange:p=>{se(p),p&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:C("sound")}),e.jsx("div",{className:"dd-header",children:C("settings")}),e.jsxs(Ee,{onClick:()=>{se(!1),c()},children:[e.jsx(ft,{})," ",C("settingsTitle")]}),e.jsxs(Ee,{onClick:()=>{se(!1),u()},children:[e.jsx(xt,{})," ",C("searchGlobal")]}),e.jsxs(Ee,{onClick:()=>{se(!1),d()},children:[e.jsx(vt,{})," ",C("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(gs,{settings:f,onChange:h,onPreview:x}),e.jsx("div",{className:"dd-header",children:C("language")}),W.map(p=>e.jsx(Ee,{active:O===p.value,onClick:()=>y(p.value),children:p.label},p.value)),e.jsx("div",{className:"dd-header",children:C("theme")}),e.jsx(Ee,{active:S===null,onClick:()=>{R(null),se(!1)},children:C("themeDefault")}),v.map(p=>e.jsx(Ee,{active:S===p.id,onClick:()=>{R(p.id),se(!1)},children:p.name},p.id)),e.jsx("div",{className:"dd-header",children:C("update")}),de(),ie(),e.jsxs("a",{className:"dd-refresh dd-more-link",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",children:[e.jsx(hs,{})," ",C("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:C("openFiles"),onClick:()=>i("right"),children:e.jsx(Ze,{})})]})]})}function fs(t){const s=new Date(t),n=new Date;return s.toDateString()===n.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function Si(t,s){const n=new Map;for(const o of t){const l=n.get(o.cwd)??[];l.push(o),n.set(o.cwd,l)}const a=[...n.entries()].map(([o,l])=>({cwd:o,isCurrent:o===s,convs:l}));return a.sort((o,l)=>o.isCurrent?-1:l.isCurrent?1:o.cwd<l.cwd?-1:o.cwd>l.cwd?1:0),a}const Ti=r.memo(function({ready:s,status:n,cwd:a,sessionFile:o,conversations:l,sessions:i,projects:c,activeConversationId:d,send:u,active:f,collapsible:h,onToggleCollapse:x}){const v=fe(),S=o,R=a,[O,y]=r.useState(null);r.useEffect(()=>{!f||!s||n!=="open"||a&&(u({type:"list_sessions"}),u({type:"list_projects"}))},[f,s,n,a,u]);const C=I=>{const F=I.name||I.firstMessage.trim();return F.length>0?F:v("emptyChat")},z=I=>I.split(/[\\/]/).pop()||I,G=(I,F,E,K)=>{const j=O===I;return e.jsx("button",{type:"button",className:`lp-del ${j?"confirm":""}`,title:j?E:F,onClick:H=>{H.stopPropagation(),j?(y(null),K()):y(I)},children:j?e.jsx(ot,{}):e.jsx(Le,{})})};return e.jsxs("aside",{className:"panel panel-left",children:[h&&x&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:v("collapsePanel"),onClick:x,children:e.jsx(Zs,{})}),c.length>0&&e.jsxs("div",{className:"panel-projects",children:[e.jsx("div",{className:"panel-section-title",children:v("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:c.map(I=>{const F=R===I.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>y(E=>E===`proj:${I.path}`?null:E),children:[e.jsxs("button",{type:"button",className:`project-item ${F?"active":""}`,title:I.path,onClick:()=>{F||u({type:"set_cwd",path:I.path})},children:[e.jsx(Ze,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:z(I.path)}),e.jsx("span",{className:"project-path",children:I.path})]}),e.jsx("span",{className:"project-time",children:fs(I.lastUsed)})]}),G(`proj:${I.path}`,v("deleteProject"),v("deleteProjectConfirm"),()=>u({type:"remove_project",path:I.path}))]},I.path)})})]}),l.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:v("runningConversations")}),Si(l,a).map(I=>e.jsxs("div",{className:"panel-conv-group",children:[!I.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:I.cwd,children:z(I.cwd)}),I.convs.map(F=>{const E=d===F.id;return e.jsxs("button",{type:"button",className:`session-item ${E?"active":""}`,title:`${F.title}${I.isCurrent?"":` — ${I.cwd}`}`,onClick:()=>{E||u({type:"switch_conversation",id:F.id})},children:[e.jsx(Xe,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:F.title}),e.jsx("span",{className:"session-sub",children:E?v("current"):v("messageCount",{n:F.messageCount})})]}),F.isStreaming&&e.jsx("span",{className:"conv-streaming",title:v("streaming")})]},F.id)})]},I.cwd)),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:v("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[i.length===0&&e.jsx("div",{className:"panel-empty",children:v("noHistory")}),i.map(I=>{const F=S===I.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>y(E=>E===`sess:${I.path}`?null:E),children:[e.jsxs("button",{type:"button",className:`session-item ${F?"active":""}`,title:I.path,onClick:()=>{F||u({type:"switch_session",path:I.path})},children:[e.jsx(Xe,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:C(I)}),e.jsxs("span",{className:"session-sub",children:[F?v("current"):v("messageCount",{n:I.messageCount}),I.source==="tui"&&e.jsx("span",{className:"session-src",title:v("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:fs(I.modified)})]}),G(`sess:${I.path}`,v("deleteSession"),v("deleteSessionConfirm"),()=>u({type:"delete_session",path:I.path}))]},I.path)})]})]})]})}),an="pi-web-ui:token";function Ei(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem(an,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function Mi(){try{return localStorage.getItem(an)??""}catch{return""}}function bt(t){const s=Mi();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}let Ct=null;function Ri(t){if(t===void 0){const n=globalThis.document;if(n&&typeof n.baseURI=="string"&&n.baseURI)try{t=new URL(n.baseURI).pathname}catch{}if(t===void 0)return"/"}if(!t||t==="/")return"/";let s=t.replace(/index\.html$/i,"");return s.endsWith("/")||(s+="/"),s}function Pi(){return Ct===null&&(Ct=Ri()),Ct}function Ii(t,s){return s==="/"?t:s+t.replace(/^\/+/,"")}function et(t){return Ii(t,Pi())}function Li(t,s){const n=s.assistantMessageEvent,a=t.stats.tokens,o=s.usage!==null?{...a,...s.usage}:a,l=o===a?t.stats:{...t.stats,tokens:o};if(n.type!=="text_delta"&&n.type!=="thinking_delta")return l===t.stats?t:{...t,stats:l};const i=n.delta??"";if(!i)return l===t.stats?t:{...t,stats:l};const c=t.streamingMessage??null,d=c&&c.id===s.messageId?c:{id:s.messageId,content:[]},u=[...d.content],f=n.type==="thinking_delta"?"thinking":"text",h=n.contentIndex??u.length-1;return h>=0&&h<u.length&&u[h].type===f?u[h]=f==="thinking"?{type:"thinking",thinking:(u[h].thinking??"")+i}:{type:"text",text:(u[h].text??"")+i}:u.push(f==="thinking"?{type:"thinking",thinking:i}:{type:"text",text:i}),{...t,stats:l,streamingMessage:{...d,id:s.messageId,content:u}}}const At="pi-web-ui:plugin-data";function Di(t,s){window.dispatchEvent(new CustomEvent(At,{detail:{pluginId:t,payload:s}}))}function Bi(t){const s=n=>{const a=n.detail;t(a.pluginId,a.payload)};return window.addEventListener(At,s),()=>window.removeEventListener(At,s)}const Ye=new Map,$t=new Set,Ge=new Set;let xs=-1;function rn(){return[...Ye.values()]}function _i(){const t=rn();for(const s of $t)s(t)}function Ai(t){return $t.add(t),t(rn()),()=>$t.delete(t)}async function $i(t,s){s!==xs&&(xs=s,Ye.clear(),Ge.clear());const n=new Set(t.map(a=>a.id));for(const a of[...Ye.keys()])n.has(a)||Ye.delete(a);for(const a of[...Ge])n.has(a)||Ge.delete(a);await Promise.all(t.filter(a=>a.hasClient&&!a.error&&!Ye.has(a.id)&&!Ge.has(a.id)).map(async a=>{try{const l=(await import(et(`/plugins/${encodeURIComponent(a.id)}/client/entry.mjs?e=${s}`))).default;l&&typeof l.mount=="function"?Ye.set(a.id,{info:a,module:l}):(Ge.add(a.id),console.error(`[plugin:${a.id}] entry.mjs 缺少 default.mount`))}catch(o){Ge.add(a.id),console.error(`[plugin:${a.id}] 客户端加载失败:`,o)}})),_i()}function Fi(t,s){return{pluginId:t,send:n=>s({type:"plugin_message",pluginId:t,payload:n}),onData:n=>Bi((a,o)=>{a===t&&n(o)})}}const Hi=10,St=2e5,Ki=2e5,Oi={conversationId:null,goal:null,reviewModel:null,maxRounds:3,locked:!0,reviewing:!1,round:0,status:"",verdict:"pending",wizard:{active:!1,draft:"",model:null,step:0,maxSteps:6,status:""}};function Wi(){const t=new Map,s=new Map,n=(a,o)=>`${a}:${o}`;return{write(a,o,l){const i=n(a,o),c=t.get(i);if(c&&c.size>0){for(const f of c)try{f.write(l)}catch{}return}const d=s.get(i)??"",u=d.length+l.length>Ki?l:d+l;s.set(i,u)},register(a,o,l){const i=n(a,o);let c=t.get(i);c||(c=new Set,t.set(i,c)),c.add(l);const d=s.get(i);if(d){try{l.write(d)}catch{}s.delete(i)}return()=>{const u=t.get(i);u&&(u.delete(l),u.size===0&&t.delete(i)),s.delete(i)}},clear(){t.clear(),s.clear()}}}function vs(t,s){const n=new Set;for(const o of s.messages)o.role==="toolResult"&&o.toolCallId&&n.add(o.toolCallId),o.role==="bashExecution"&&n.add(`bash-${o.id}`);let a=!1;for(const o of t.keys())n.has(o)&&(t.delete(o),a=!0);return a?new Map(t):t}function ys(t,s){if(t.size===0)return t;const n=new Set;for(const o of s.messages)o.role==="toolResult"&&o.toolCallId&&n.add(o.toolCallId);let a=!1;for(const o of t.keys())n.has(o)&&(t.delete(o),a=!0);return a?new Map(t):t}function Ui(t,s){var n,a,o,l;switch(s.type){case"status":return{...t,status:s.status,ready:s.status==="open"?t.ready:!1,terminals:s.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:s.serverVersion,engine:s.engine,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==Hi};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:vs(t.liveOutputs,s.state),toolStatuses:ys(t.toolStatuses,s.state)};case"snapshot_delta":{const i=t.state,c=s.msg;if(!i||i.conversationId!==c.conversationId||i.rev!==c.baseRev)return t;const d={...i,...c.state,messages:c.appended.length>0?[...i.messages,...c.appended]:i.messages};return{...t,ready:!0,state:d,activeConversationId:d.conversationId,liveOutputs:vs(t.liveOutputs,d),toolStatuses:ys(t.toolStatuses,d)}}case"tool_delta":{const i=t.liveOutputs.get(s.toolCallId),c=((i==null?void 0:i.text)??"")+s.delta,d=c.length>St?`…[前 ${c.length-St} 字符已省略]…
|
|
303
|
+
`+c.slice(c.length-St):c,u=new Map(t.liveOutputs);return u.set(s.toolCallId,{toolName:s.toolName,text:d}),{...t,liveOutputs:u}}case"message_delta":{const i=t.state;return!i||i.conversationId!==s.msg.conversationId?t:{...t,state:Li(i,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(i=>i.id!==s.id)};case"sessions":return{...t,sessions:s.sessions};case"conversations":return{...t,conversations:s.conversations,activeConversationId:s.activeId};case"projects":return{...t,projects:s.projects};case"files":return{...t,files:s.files};case"file_changed":return{...t,fileChanged:{path:s.path}};case"file_content":return{...t,fileContent:s.content};case"models":return{...t,models:s.models,modelsLoading:s.loading};case"models_config":return{...t,modelsConfig:s.providers};case"providers_status":return{...t,providers:s.providers};case"provider_keys":return{...t,providerKeys:s.keys};case"fetch_models_result":return{...t,fetchModelsResult:s.result};case"refresh_provider_result":return{...t,refreshProviderResult:s.result};case"clone_provider_result":return{...t,cloneProviderResult:s.result};case"install_result":return{...t,installResult:s.result};case"scm_data":return{...t,scmData:s.data};case"file_search_result":return{...t,fileSearch:s.result};case"session_search_result":return{...t,sessionSearch:s.result};case"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"update_status_all":return{...t,updatesAll:s.items};case"updates_check_started":return{...t,updatesAll:null};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"question":return{...t,question:s.question};case"commands":return{...t,commands:s.commands,commandsPath:s.path};case"slash_commands":return{...t,slashCommands:s.commands};case"goal_status":return{...t,goal:s.status};case"settings":return{...t,settings:s.settings};case"bg_servers":return{...t,bgServers:s.servers};case"plugins":return{...t,plugins:s.plugins,pluginsEpoch:s.epoch};case"dsh_patches":return{...t,dshPatches:{patchDir:s.patchDir,files:s.files}};case"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(i=>i.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(n=t.state)!=null&&n.conversationId)&&s.conversationId!==(t.activeConversationId||((a=t.state)==null?void 0:a.conversationId))?t:{...t,terminals:t.terminals.map(i=>i.id===s.terminalId?{...i,running:!1,exitCode:s.exitCode}:i)};case"terminal_restart":return{...t,terminals:t.terminals.map(i=>i.id===s.terminalId?{...i,running:!0,exitCode:null}:i)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(o=t.state)!=null&&o.conversationId)&&s.conversationId!==(t.activeConversationId||((l=t.state)==null?void 0:l.conversationId))?t:{...t,terminals:s.terminals.map(i=>{var c;return{...i,conversationId:s.conversationId??((c=t.state)==null?void 0:c.conversationId)??""}})};case"terminal_active":return{...t,terminalActiveId:s.id};default:return t}}const ks="pi-web-client-id";let Tt=null;function qt(){if(Tt)return Tt;let t=null;try{t=sessionStorage.getItem(ks),t||(t=He(),sessionStorage.setItem(ks,t))}catch{t=t??He()}return Tt=t,t}function qi(){const t=location.protocol==="https:"?"wss:":"ws:";return bt(`${t}//${location.host}${et("/ws")}`)}function zi(){const[t,s]=r.useReducer(Ui,{status:"connecting",ready:!1,state:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:[],conversations:[],activeConversationId:"",projects:[],files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},installResult:null,pathCompletions:[],update:null,updatesAll:null,widgets:[],statuses:[],dialog:null,question:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],terminalActiveId:null,goal:Oi,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,dshPatches:null,protocolMismatch:!1}),n=r.useRef(null),a=r.useRef(Wi()),o=r.useRef(0),l=r.useRef(null),i=r.useRef(!0),c=r.useRef(0),d=r.useRef(0),u=r.useRef(new Map),f=r.useRef(null),h=()=>{f.current||(f.current=setTimeout(()=>{f.current=null;const E=n.current;E&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:"get_state"}))},300))},x=(E,K)=>{var J;const j=u.current,H=j.get(E);if(H!==void 0&&K!==H+1){const se=F.current.chat,W=se.activeConversationId||((J=se.state)==null?void 0:J.conversationId);E===W&&h()}j.set(E,K)},v=r.useCallback((E,K)=>{const j=++d.current;s({type:"notice",notice:{id:j,level:E,text:K}})},[]),S=r.useCallback(E=>{const K=n.current;return K&&K.readyState===WebSocket.OPEN?(E.type==="check_updates_all"&&E.force===!0&&s({type:"updates_check_started"}),K.send(JSON.stringify(E)),!0):!1},[]),R=r.useCallback(()=>{if(!i.current)return;s({type:"status",status:"connecting"});const E=new WebSocket(qi());n.current=E,E.onopen=()=>{n.current===E&&(s({type:"status",status:"open"}),o.current=0,c.current=Date.now(),E.send(JSON.stringify({type:"hello",clientId:qt()})))},E.onmessage=K=>{if(n.current!==E)return;c.current=Date.now();let j;try{j=JSON.parse(K.data)}catch{return}switch(j.type){case"ready":s({type:"ready",serverVersion:j.serverVersion,protocolVersion:j.protocolVersion,engine:j.engine}),E.send(JSON.stringify({type:"get_state"})),E.send(JSON.stringify({type:"list_files"})),E.send(JSON.stringify({type:"list_models"})),E.send(JSON.stringify({type:"list_commands"})),E.send(JSON.stringify({type:"get_commands"})),E.send(JSON.stringify({type:"check_update"})),E.send(JSON.stringify({type:"check_updates_all"}));break;case"snapshot":u.current=new Map,s({type:"snapshot",state:j.state});break;case"snapshot_delta":{const H=F.current.chat.state;(!H||H.conversationId!==j.conversationId||H.rev!==j.baseRev)&&h(),s({type:"snapshot_delta",msg:j});break}case"tool_delta":x(j.conversationId,j.seq),s({type:"tool_delta",toolCallId:j.toolCallId,toolName:j.toolName,delta:j.delta});break;case"tool_status":s({type:"tool_status",status:j});break;case"message_delta":{x(j.conversationId,j.seq),s({type:"message_delta",msg:j});break}case"notice":{const H=++d.current;s({type:"notice",notice:{id:H,level:j.level,text:j.text}});break}case"sessions":s({type:"sessions",sessions:j.sessions});break;case"conversations":s({type:"conversations",conversations:j.conversations,activeId:j.activeId});break;case"projects":s({type:"projects",projects:j.projects});break;case"files":s({type:"files",files:j});break;case"file_changed":s({type:"file_changed",path:j.path});break;case"file_content":s({type:"file_content",content:j});break;case"models":s({type:"models",models:j.models,loading:!1});break;case"models_config":s({type:"models_config",providers:j.providers});break;case"providers_status":s({type:"providers_status",providers:j.providers});break;case"provider_keys":s({type:"provider_keys",keys:j.keys});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:j.reqId,ok:j.ok,models:j.models,error:j.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:j.reqId,ok:j.ok,added:j.added,total:j.total,error:j.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:j.reqId,ok:j.ok,config:j.config,configs:j.configs,error:j.error}});break;case"scm_data":s({type:"scm_data",data:j});break;case"search_files_result":s({type:"file_search_result",result:{reqId:j.reqId,ok:j.ok,results:j.results,truncated:j.truncated}});break;case"session_search_results":s({type:"session_search_result",result:{reqId:j.reqId,ok:j.ok,results:j.results}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:j});break;case"path_completions":s({type:"path_completions",completions:j.completions});break;case"update_status":s({type:"update_status",status:j});break;case"update_status_all":s({type:"update_status_all",items:j.items});break;case"widgets":s({type:"widgets",widgets:j.widgets});break;case"statuses":s({type:"statuses",statuses:j.statuses});break;case"dialog":s({type:"dialog",dialog:{id:j.id,kind:j.kind,title:j.title,args:j.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"question_pending":s({type:"question",question:{id:j.id,questions:j.questions}});break;case"terminal_output":a.current.write(j.conversationId??F.current.chat.activeConversationId,j.terminalId,j.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:j.conversationId,terminalId:j.terminalId,exitCode:j.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:j.conversationId,terminals:j.terminals});break;case"commands":s({type:"commands",commands:j.commands,path:j.path});break;case"slash_commands":s({type:"slash_commands",commands:j.commands});break;case"goal_status":s({type:"goal_status",status:j.status});break;case"settings_state":s({type:"settings",settings:j.settings});break;case"bg_servers":s({type:"bg_servers",servers:j.servers});break;case"plugins":s({type:"plugins",plugins:j.plugins,epoch:j.epoch});break;case"dsh_patches":s({type:"dsh_patches",patchDir:j.patchDir,files:j.files});break;case"plugin_data":Di(j.pluginId,j.payload);break}},E.onclose=()=>{if(n.current===E&&(n.current=null),a.current.clear(),!i.current||n.current&&n.current!==E)return;s({type:"status",status:"closed"});const K=Math.min(1e3*2**o.current,1e4);o.current+=1,l.current=setTimeout(()=>{l.current=null,R()},K)},E.onerror=()=>{}},[]);r.useEffect(()=>{i.current=!0,R();const E=setInterval(()=>{if(!i.current)return;const K=n.current;K&&K.readyState===WebSocket.OPEN&&Date.now()-c.current>3e4&&K.close()},5e3);return()=>{var K;i.current=!1,clearInterval(E),l.current&&(clearTimeout(l.current),l.current=null),(K=n.current)==null||K.close(),n.current=null}},[R]);const O=r.useCallback(E=>s({type:"dismiss_notice",id:E}),[]),y=r.useCallback(E=>s({type:"terminal_add",meta:E}),[]),C=r.useCallback(E=>s({type:"terminal_remove",id:E}),[]),z=r.useCallback(E=>s({type:"terminal_restart",terminalId:E}),[]),G=r.useCallback(E=>s({type:"terminal_active",id:E}),[]),I=r.useCallback((E,K,j)=>a.current.register(E,K,j),[]),F=r.useRef({chat:t,send:S,pushNotice:v,dismissNotice:O,terminal:{create:y,close:C,register:I,restart:z,select:G}});return F.current={chat:t,send:S,pushNotice:v,dismissNotice:O,terminal:{create:y,close:C,register:I,restart:z,select:G}},F.current}const Vi=200*1024*1024,Gi=/windows/i.test(navigator.userAgent),Qi=/[<>:"/\\|?*\u0000-\u001f]/g,Yi=/[. ]+$/,Ji=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Xi(t){const s=t.replace(Qi,"_").replace(Yi,"");return s?Ji.test(s)?`_${s}`:s:"_"}function bs(t,s=!0){const n=new URLSearchParams({clientId:qt(),path:t,...s?{download:"1"}:{}});return bt(et(`/api/file?${n}`))}async function Zi(t,s){const n=Gi?Xi(s):s;try{const a=await fetch(bs(t));if(!a.ok)return{ok:!1,cancelled:!1,error:await a.text().catch(()=>"")||(a.status===404?"文件不存在":`HTTP ${a.status}`)};if(Number(a.headers.get("content-length")??"0")>Vi)return window.location.assign(bs(t)),{ok:!0};const l=await a.blob();return window.showSaveFilePicker&&window.isSecureContext?ea(l,n):Ft(l,n)}catch(a){return{ok:!1,cancelled:!1,error:a instanceof Error?a.message:String(a)}}}async function ea(t,s){let n;const a=window.showSaveFilePicker;if(!a)return Ft(t,s);try{n=await a({suggestedName:s})}catch(o){return o instanceof DOMException&&o.name==="AbortError"?{ok:!1,cancelled:!0}:Ft(t,s)}try{const o=await n.createWritable();return await o.write(t),await o.close(),{ok:!0}}catch(o){return{ok:!1,cancelled:!1,error:o instanceof Error?o.message:String(o)}}}function Ft(t,s){const n=URL.createObjectURL(t),a=document.createElement("a");return a.href=n,a.download=s,document.body.appendChild(a),a.click(),a.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}const ta=r.memo(function({files:s,fileChanged:n,widgets:a,cwd:o,send:l,onAttach:i,onPreview:c,onNotice:d,collapsible:u,onToggleCollapse:f}){const h=fe(),[x,v]=r.useState(""),[S,R]=r.useState(null),[O,y]=r.useState(!1),[C,z]=r.useState(null),G=r.useRef(""),I=r.useRef(null),F=r.useCallback((p,U)=>{p.preventDefault(),G.current=U,z({x:Math.min(p.clientX,window.innerWidth-220),y:Math.min(p.clientY,window.innerHeight-90)})},[]),E=r.useCallback(()=>z(null),[]);r.useEffect(()=>{if(!C)return;const p=Q=>{var ne;(ne=Q.target)!=null&&ne.closest(".ctx-menu")||E()},U=Q=>{Q.key==="Escape"&&E()};window.addEventListener("mousedown",p,!0),window.addEventListener("keydown",U);const B=()=>E();return window.addEventListener("blur",B),()=>{window.removeEventListener("mousedown",p,!0),window.removeEventListener("keydown",U),window.removeEventListener("blur",B)}},[C,E]);const K=r.useCallback(()=>{var p;E(),I.current&&(I.current.value=""),(p=I.current)==null||p.click()},[E]),j=r.useCallback((p,U)=>{for(const B of U){const Q=new FileReader;Q.onload=()=>{const ne=Q.result,ae=ne.slice(ne.indexOf(",")+1);ae&&l({type:"upload_file",dirPath:p,name:B.name,data:ae})},Q.readAsDataURL(B)}},[l]),H=r.useCallback(p=>{j(G.current,Array.from(p.target.files??[]))},[j]),J=r.useRef(null),se=p=>{var U;return Array.from(((U=p.dataTransfer)==null?void 0:U.types)??[]).includes("Files")},W=r.useCallback(()=>{var p,U;(p=J.current)==null||p.querySelectorAll(".file-item.drop-target").forEach(B=>B.classList.remove("drop-target")),(U=J.current)==null||U.classList.remove("drop-root")},[]),V=r.useCallback(p=>{var B,Q;if(W(),p==null)return;const U=(B=J.current)==null?void 0:B.querySelector(`.file-item[data-path="${CSS.escape(p)}"]`);U?U.classList.add("drop-target"):(Q=J.current)==null||Q.classList.add("drop-root")},[W]),q=p=>{const U=p instanceof Element?p.closest(".file-item"):null;return(U==null?void 0:U.dataset.type)==="dir"?U.dataset.path??x:x},k=r.useCallback(()=>{const p=document.querySelector(".app");p&&p.dispatchEvent(new DragEvent("dragleave",{bubbles:!0}))},[]),w=1e4,b=r.useRef(0),L=r.useRef(void 0),A=r.useCallback((p,U)=>{const B=++b.current;v(p),U!=null&&U.silent||y(!0),l({type:"list_files",path:p===""?void 0:p})||b.current===B&&y(!1)},[l]);r.useEffect(()=>{s&&s.path===x&&y(!1)},[s,x]),r.useEffect(()=>{if(o!==L.current){L.current=o,A("",{silent:!0});return}const p=setInterval(()=>{document.visibilityState!=="hidden"&&A(x,{silent:!0})},w);return()=>clearInterval(p)},[o,x,A]),r.useEffect(()=>{n&&n.path===x&&A(x,{silent:!0})},[n,x,A]);const ie=p=>A(p),de=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&A(s.parent)},me=x.split("/").filter(Boolean);return e.jsxs("aside",{className:"panel panel-right",children:[u&&f&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:h("collapsePanel"),onClick:f,children:e.jsx(Xs,{})}),e.jsxs("div",{className:"panel-crumbs",children:[e.jsx("button",{type:"button",className:`crumb ${x===""?"active":""}`,onClick:()=>A(""),children:h("rootDir")}),me.map((p,U)=>{const B=me.slice(0,U+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(kt,{}),e.jsx("button",{type:"button",className:`crumb ${B===x?"active":""}`,onClick:()=>A(B),children:p})]},B)})]}),e.jsxs("div",{ref:J,className:"panel-body",onContextMenu:p=>F(p,x),onDragOver:p=>{se(p)&&(p.preventDefault(),p.stopPropagation(),p.dataTransfer.dropEffect="copy",k(),V(q(p.target)))},onDragLeave:p=>{p.relatedTarget&&p.currentTarget.contains(p.relatedTarget)||W()},onDrop:p=>{var B;if(W(),!se(p))return;p.preventDefault(),p.stopPropagation(),k();const U=Array.from(((B=p.dataTransfer)==null?void 0:B.files)??[]);if(U.length===0){d("warning",h("foldersNotSupported"));return}j(q(p.target),U)},onDragEnd:W,children:[e.jsx("input",{ref:I,type:"file",multiple:!0,hidden:!0,onChange:H}),O&&e.jsx("div",{className:"panel-empty",children:h("loading")}),!O&&s&&s.path===x&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:de,children:[e.jsx(Ze,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(p=>p.type==="dir"?e.jsxs("div",{className:"file-item dir","data-type":"dir","data-path":p.path,onContextMenu:U=>{U.stopPropagation(),F(U,p.path)},children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>ie(p.path),children:[e.jsx(Ze,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:p.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":h("linkFolderTip"),onClick:()=>i(p.path,p.name,"reference",!0),children:e.jsx(Dt,{})})]},p.path):e.jsxs("div",{className:"file-item file","data-type":"file","data-path":p.path,onContextMenu:U=>{U.stopPropagation(),F(U,x)},children:[e.jsxs("button",{type:"button",className:"file-name",title:`${p.path} — ${h("previewFile")}`,onClick:()=>c(p.path,p.name),children:[e.jsx(Gs,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:p.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":h("downloadFile"),onClick:()=>{Zi(p.path,p.name).then(U=>{U.ok||U.cancelled||d("error",h("downloadFailed",{error:U.error}))})},children:e.jsx(Wt,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":h("attachInlineTip"),onClick:()=>i(p.path,p.name,"inline"),children:e.jsx($e,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":h("referenceTip"),onClick:()=>i(p.path,p.name,"reference"),children:e.jsx(Dt,{})})]},p.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:h("filesTruncated")})]}),!O&&!s&&e.jsx("div",{className:"panel-empty",children:h("noFiles")})]}),a.filter(p=>p.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:a.filter(p=>p.lines.length>0).map(p=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:h("widgetExpand"),onClick:()=>R(p.key),children:[e.jsx("span",{children:p.key}),e.jsx(li,{})]}),e.jsx("pre",{className:"widget-lines",children:p.lines.join(`
|
|
304
|
+
`)})]},p.key))}),S&&(()=>{const p=a.find(U=>U.key===S);return p?e.jsx("div",{className:"modal-backdrop",onClick:()=>R(null),children:e.jsxs("div",{className:"widget-expand",onClick:U=>U.stopPropagation(),children:[e.jsxs("div",{className:"widget-expand-head",children:[e.jsx("span",{className:"widget-expand-title",children:p.key}),e.jsx("button",{type:"button",className:"btn",title:h("close"),onClick:()=>R(null),children:e.jsx(Te,{})})]}),e.jsx("pre",{className:"widget-expand-lines",children:p.lines.join(`
|
|
305
|
+
`)})]})}):null})(),C&&e.jsx("div",{className:"ctx-menu",style:{left:C.x,top:C.y},onContextMenu:p=>{p.preventDefault(),p.stopPropagation()},children:e.jsxs("button",{type:"button",className:"ctx-item",onClick:K,children:[e.jsx(Jn,{}),G.current===x?h("uploadToCurrentDir"):h("uploadToFolder")]})})]})});var sa=Os();const ln=r.memo(function({text:s}){const n=fe(),[a,o]=r.useState(!1);return s?e.jsx("button",{type:"button",className:"copy-btn",title:n("copy"),onClick:()=>{navigator.clipboard.writeText(s).then(()=>{o(!0),setTimeout(()=>o(!1),1200)})},children:a?e.jsx(ot,{}):e.jsx(Js,{})}):null});function na(t){const s=a=>{var o;if(typeof a=="string"||typeof a=="number"){const l=String(a);return l===""?[[]]:l.split(`
|
|
306
|
+
`).map(i=>i===""?[]:[i])}if(Array.isArray(a)){let l=[];for(const i of a){const c=s(i);if(l.length===0)l=c;else{const d=c[0]??[];l[l.length-1].push(...d),l.push(...c.slice(1))}}return l}if(a&&typeof a=="object"&&"props"in a){const l=a,i=(o=l.props)==null?void 0:o.children,c={...l.props??{},children:void 0},d=i==null?[]:s(i);return d.length===0?[[r.createElement(l.type,c)]]:d.map(u=>[r.createElement(l.type,c,...u)])}return[[a]]},n=s(t);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}const on=[_n],cn=[[Bn,{detect:!0,ignoreMissing:!0}]];function dn({text:t}){return e.jsx(Ks,{remarkPlugins:on,rehypePlugins:cn,components:{pre:ia},children:t})}const jt=r.memo(function({text:s}){return e.jsx("div",{className:"md",children:e.jsx(dn,{text:s})})});function ia({children:t,...s}){var i;const n=t&&typeof t=="object"&&"props"in t?(i=t.props)==null?void 0:i.children:t,a=na(n),o=a.length>1,l=o?`${String(a.length).length+1}ch`:void 0;return e.jsxs("div",{className:"codeblock",children:[e.jsx(ln,{text:Ht(t)}),e.jsx("pre",{...s,children:a.map((c,d)=>e.jsxs("div",{className:"code-line",children:[o&&e.jsx("span",{className:"code-num",style:l?{width:l}:void 0,children:d+1}),e.jsx("code",{className:"code-line-body hljs",children:c})]},d))})]})}function Ht(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(Ht).join("");if(t&&typeof t=="object"&&"props"in t){const s=t.props;return Ht(s==null?void 0:s.children)}return""}const aa=/^\s{0,3}(`{3,}|~{3,})/,ra=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function Et(t){return t.trim()===""}function js(t){const s=aa.exec(t);return s?s[1]:null}function la(t){const s=t.split(`
|
|
307
|
+
`),n=[];let a=[],o=null;for(let l=0;l<s.length;l++){const i=s[l];if(o!==null){const d=js(i);d&&d[0]===o[0]&&d.length>=o.length&&(o=null),a.push(i);continue}const c=js(i);if(c&&!Et(i)){o=c,a.push(i);continue}if(Et(i)){let d=l;for(;d<s.length&&Et(s[d]);)d++;if(!(d<s.length&&ra.test(s[d]))&&a.length>0){n.push(a.join(`
|
|
308
308
|
`)),a=[];continue}a.push(i);continue}a.push(i)}return{frozen:n,active:a.join(`
|
|
309
|
-
`),inFence:o!==null}}const
|
|
310
|
-
`)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${d?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>i(!c),children:[d?e.jsx(
|
|
309
|
+
`),inFence:o!==null}}const oa=r.memo(function({text:s}){return e.jsx(Ks,{remarkPlugins:on,rehypePlugins:cn,children:s})}),ws=200;function ca({text:t,inFence:s}){const[n,a]=r.useState(t),o=r.useRef(0),l=r.useRef(null);return r.useEffect(()=>{if(s)return;const i=Date.now()-o.current,c=()=>{o.current=Date.now(),a(t)};if(i>=ws){c();return}return l.current=setTimeout(c,ws-i),()=>{l.current&&clearTimeout(l.current)}},[t,s]),s?e.jsx("div",{className:"codeblock",children:e.jsx("pre",{children:e.jsx("code",{children:t})})}):e.jsx(dn,{text:n})}const da=r.memo(function({text:s}){const{frozen:n,active:a,inFence:o}=r.useMemo(()=>la(s),[s]);return e.jsxs("div",{className:"md",children:[n.map((l,i)=>e.jsx(oa,{text:l},i)),a.length>0&&e.jsx(ca,{text:a,inFence:o},n.length)]})});function ua({thinking:t,streaming:s,wrap:n=!0,forceOpen:a=!1}){const o=fe(),[l,i]=r.useState(null),c=l??n,d=c||a,u=s?t.trimEnd().slice(-80):t.split(`
|
|
310
|
+
`)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${d?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>i(!c),children:[d?e.jsx(qe,{}):e.jsx(kt,{}),e.jsx(rt,{className:"thinking-icon"}),e.jsx("span",{className:"thinking-label",children:s&&d?e.jsxs("span",{className:"thinking-live-label",children:[o("thinkingNow"),e.jsx("span",{className:"dots"})]}):d?o("thinking"):o("thinkingPreview",{preview:u})})]}),d&&e.jsx("div",{className:"thinking-body",children:t})]})}const pa={bash:"$",read:"📄",write:"✍️",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function ma(t){return pa[t]??"🛠"}const ha=r.memo(function({block:s,view:n,onKillBash:a,wrap:o=!0,forceOpen:l=!1}){var E,K,j,H;const i=fe(),[c,d]=r.useState(o),u=c||l,[f,h]=r.useState(!1),x=!n.result&&n.streaming&&!n.status,v=s.name==="bash"&&x,S=n.result!==void 0,R=!n.result&&!!n.status,O=((E=n.result)==null?void 0:E.isError)??((K=n.status)==null?void 0:K.isError)??!1,y=n.result?n.result.content.map(J=>J.type==="text"?J.text:"").join(""):n.liveOutput??"",C=O?"err":S?"ok":x||R?"run":"idle";let z=i(O?"error":S?"done":x?"running":R?"toolDoneWaitingModel":"toolQueued");const G=R&&((j=n.status)==null?void 0:j.durationMs)!==void 0?fa(n.status.durationMs):"";R&&G&&(z=`${z} · ${G}`);const I=R&&((H=n.status)==null?void 0:H.exitCode)!==void 0?`exit ${n.status.exitCode}`:"",F=()=>{s.argumentsText&&(navigator.clipboard.writeText(s.argumentsText),h(!0),setTimeout(()=>h(!1),1200))};return e.jsxs("div",{className:`toolcall ${C}`,children:[e.jsxs("div",{className:"toolcall-head",children:[e.jsx("span",{className:"toolcall-icon",children:ma(s.name)}),e.jsx("span",{className:"toolcall-name",children:s.name}),e.jsxs("span",{className:"toolcall-status",children:[z,I&&e.jsx("em",{className:"toolcall-exit",children:I})]}),e.jsx("span",{className:"toolcall-spacer"}),v&&a&&e.jsxs("button",{type:"button",className:"toolcall-kill",title:i("stopBashTip"),onClick:a,children:[e.jsx(gt,{}),e.jsx("span",{children:i("stopBash")})]}),e.jsx("button",{type:"button",className:"toolcall-copy",title:i("copyArgs"),onClick:F,children:f?e.jsx(gi,{}):e.jsx(Js,{})}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>d(J=>l?!0:!J),children:u?e.jsx(qe,{}):e.jsx(kt,{})})]}),u&&e.jsxs("div",{className:"toolcall-body",children:[s.argumentsText&&e.jsx("div",{className:"toolcall-args",children:s.name==="bash"&&s.argumentsText.startsWith("{")?e.jsx(ga,{args:s.argumentsText}):e.jsx("pre",{children:s.argumentsText})}),y.length>0&&e.jsxs("div",{className:"toolcall-output",children:[e.jsxs("div",{className:"toolcall-output-label",children:[i(O?"errorOutput":"output"),(x||R)&&e.jsx("span",{className:"cursor"})]}),e.jsx("pre",{children:y})]}),x&&y.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",i("waitingOutput")]}),R&&y.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",i("waitingModel")]})]})]})});function ga({args:t}){let s=null;try{s=JSON.parse(t)}catch{return e.jsx("pre",{children:t})}return typeof s.command!="string"?e.jsx("pre",{children:t}):e.jsxs("div",{className:"termline",children:[e.jsx(Je,{className:"termline-icon"}),e.jsx("code",{children:s.command}),typeof s.timeout=="number"&&e.jsxs("span",{className:"termline-timeout",children:["⏱ ",s.timeout,"s"]})]})}function fa(t){if(t===void 0)return"";const s=t/1e3;if(s<60)return`${s.toFixed(1)}s`;const n=Math.floor(s/60),a=Math.round(s%60);return`${n}m ${String(a).padStart(2,"0")}s`}const xa=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function zt(t){var n;const s=t.match(xa);return s?{name:s[1],location:s[2],content:s[3],userMessage:((n=s[4])==null?void 0:n.trim())||void 0}:null}const va=1568,ya=2*1024*1024;function Fe(t){return t.startsWith("image/")&&t!=="image/svg+xml"&&t!=="image/svg"}async function un(t){if(!t.type.startsWith("image/"))return null;let s;try{s=await createImageBitmap(t,{imageOrientation:"from-image"})}catch{return null}try{const n=Math.min(1,va/Math.max(s.width,s.height)),a=Math.max(1,Math.round(s.width*n)),o=Math.max(1,Math.round(s.height*n)),l=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 i=null;for(const[c,d]of l){const u=document.createElement("canvas");u.width=a,u.height=o;const f=u.getContext("2d");if(!f)continue;c!=="image/png"&&(f.fillStyle="#ffffff",f.fillRect(0,0,a,o)),f.drawImage(s,0,0,a,o);const h=u.toDataURL(c,d),x=h.match(/^data:([^;]+);base64,/),v=x?x[1]:c,S=h.replace(/^data:[^;]*;base64,/,""),R=Math.floor(S.length*3/4);if(i={data:S,mimeType:v,name:t.name,size:R},R<=ya)return i}return i}finally{s.close()}}const ka=20*1024*1024;function lt(t){return t.type==="text"&&typeof t.text=="string"?t:null}function pn(t){return t.type==="thinking"&&typeof t.thinking=="string"?t:null}function mn(t){return t.type==="toolCall"&&typeof t.id=="string"&&typeof t.name=="string"?t:null}function hn(t){return t.type==="image"&&typeof t.dataUrl=="string"?t:null}function gn(t){return t.type==="bash"&&typeof t.command=="string"?t:null}function ba(t){return t.imageData?"image":t.uploadPath?"upload":t.fileData?"file":"path"}function ja(t,s){if(t.imageData)return s("attachImage",{name:t.name??"image"});if(t.uploadPath)return s("attachFile",{name:t.name??t.uploadPath});if(t.fileData)return s("attachFile",{name:t.name??"file"});const n=t.path.split("/").pop()??t.path;return t.mode==="lines"&&t.lines?s("attachLines",{path:n,start:t.lines.start,end:t.lines.end}):t.mode==="reference"?s("refOnly",{path:n}):s("attachContent",{path:n})}const Ns=r.memo(function({message:s,toolResults:n,liveOutputs:a,toolStatuses:o,streaming:l,isLast:i,onEdit:c,onKillBash:d,onCollapse:u,questionAttachments:f,qnIndex:h,qnActive:x,onJump:v,thinkingWrap:S,toolsWrap:R,searchActive:O}){const y=fe(),[C,z]=r.useState(!1),[G,I]=r.useState(""),[F,E]=r.useState([]),[K,j]=r.useState(!1),[H,J]=r.useState(null),se=B=>{J(B),window.setTimeout(()=>J(Q=>Q===B?null:Q),4e3)};if(s.role==="toolResult")return null;const W=s.role==="custom"&&s.customType==="file",V=s.content.map(B=>{var Q;return((Q=lt(B))==null?void 0:Q.text)??""}).filter(Boolean).join(`
|
|
311
311
|
`),q=s.role==="user"?zt(V):null,k=q?q.userMessage??`skill:${q.name}`:V.split(`
|
|
312
|
-
`).join(" ").trim(),w=l&&i&&s.content.length===0,b=s.role==="user"&&!l&&!w&&!!c,L=async B=>{const Q=[];for(const ne of B){if(
|
|
313
|
-
`)),E(f??[]),z(!0)},
|
|
314
|
-
`).length+1)),onChange:B=>I(B.target.value),onPaste:B=>{var ne;const Q=[];for(const
|
|
315
|
-
`),x=
|
|
316
|
-
`).length;return e.jsxs("div",{className:`attachcard ${u?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>o(R=>s?!0:!R),children:[e.jsx("span",{className:"attachcard-icon",children:d?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:c}),i.path&&e.jsx("span",{className:"attachcard-path",children:i.path}),e.jsx("span",{className:`attachcard-mode ${i.mode==="lines"?"lines":u?"ref":f?"bridged":"inline"}`,children:u?d?n("folderRefShort"):`${n("refOnlyShort")} · ${Cs(i.size)}`:f?n("bridgedVision"):v?n("image"):i.mode==="lines"?n("inlineLinesRange",{start:i.startLine??1,end:i.endLine??i.lines??1}):n("inlineLines",{n:i.lines??
|
|
317
|
-
`)}function
|
|
318
|
-
`)}function $a(t,s){let n=0,a=t.indexOf(s);for(;a!==-1;)n++,a=t.indexOf(s,a+s.length);return n}function Fa(t,s,n,a){const o=new Map,l=n.toLowerCase();if(!l)return o;for(const i of t){if(!s.has(i.id))continue;const c=$a(Aa(i,a).toLowerCase(),l);c>0&&o.set(i.id,c)}return o}function Ha(t,s){var l;const n=[],a=s.toLowerCase();if(!a)return n;const o=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(i){const c=i.parentElement;return!c||c.closest(".search-bar")||c.closest(".msg-collapsed")?NodeFilter.FILTER_REJECT:(i.textContent??"").toLowerCase().includes(a)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let i=o.nextNode();i;i=o.nextNode()){const c=(i.textContent??"").toLowerCase();if(!((l=i.parentElement)!=null&&l.closest("[data-msg-id]")))continue;let d=c.indexOf(a);for(;d!==-1;){const u=document.createRange();u.setStart(i,d),u.setEnd(i,d+a.length),n.push(u),d=c.indexOf(a,d+a.length)}}return n}function Ka(t,s,n,a,o){var d;const l=Fa(n,a,s,o),i=new Map;for(const u of Ha(t,s)){const f=(d=u.startContainer.parentElement)==null?void 0:d.closest("[data-msg-id]");if(!(f!=null&&f.dataset.msgId))continue;const h=i.get(f.dataset.msgId);h?h.push(u):i.set(f.dataset.msgId,[u])}const c=[];for(const u of n){const f=i.get(u.id);if(f)for(let x=0;x<f.length;x++)c.push({kind:"dom",range:f[x],msgId:u.id,k:x});const h=l.get(u.id);if(h)for(let x=0;x<h;x++)c.push({kind:"folded",msgId:u.id,k:x})}return c}function Mt(t,s){return t.findIndex(n=>n.msgId===s.msgId&&n.k===s.k)}function Re(t,s){const n=CSS;if(!n.highlights)return;if(s.length===0){n.highlights.delete(t);return}const a=window.Highlight;a&&n.highlights.set(t,new a(...s))}function Oa(t,s){const n=[];let a=t;for(;a&&a!==s;){const o=getComputedStyle(a);/(auto|scroll|hidden)/.test(o.overflowY+o.overflowX)&&(a.scrollHeight>a.clientHeight||a.scrollWidth>a.clientWidth)&&n.push(a),a=a.parentElement}return n}function Wa(t,s){const n=s.startContainer.parentElement;for(const c of Oa(n,t)){const d=s.getBoundingClientRect(),u=c.getBoundingClientRect();if(d.height<=0||d.width<=0)return;d.top>=u.top+4&&d.bottom<=u.bottom-4||(c.scrollTop+=d.top-u.top-(c.clientHeight-d.height)/2),d.left>=u.left+4&&d.right<=u.right-4||(c.scrollLeft+=d.left-u.left-(c.clientWidth-d.width)/2)}const a=s.getBoundingClientRect(),o=t.getBoundingClientRect();if(a.height<=0||a.width<=0)return;const l=a.top>=o.top+6&&a.bottom<=o.bottom-6,i=a.left>=o.left+6&&a.right<=o.right-6;l&&i||(l||(t.scrollTop+=a.top-o.top-(o.height-a.height)/2),i||(t.scrollLeft+=a.left-o.left-(o.width-a.width)/2))}function Ua({containerRef:t,messages:s,collapsedIds:n,toolResults:a,onExpand:o,onProgrammaticScroll:l,open:i,onClose:c}){const d=fe(),u=r.useRef(null),[f,h]=r.useState(""),[x,v]=r.useState(null),[T,R]=r.useState(0),[O,y]=r.useState(0),C=r.useDeferredValue(f),z=i?C.trim():"",G=r.useRef(null);G.current=x;const I=r.useRef([]),F=r.useRef({key:null}),E=r.useRef("");r.useEffect(()=>{i&&(v(null),requestAnimationFrame(()=>{var H;return(H=u.current)==null?void 0:H.select()}))},[i]),r.useEffect(()=>{if(!i)return;const H=J=>{J.key==="Escape"&&(J.preventDefault(),J.stopPropagation(),c())};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[i,c]),r.useEffect(()=>(i||(Re("msg-search",[]),Re("msg-search-active",[])),()=>{Re("msg-search",[]),Re("msg-search-active",[])}),[i]),r.useLayoutEffect(()=>{const H=()=>{R(0),v(null),y(0),I.current=[],Re("msg-search",[]),Re("msg-search-active",[]),F.current={key:null},E.current=""};if(!i||!z){H();return}const J=t.current;if(!J)return;let se=!1,W=0;return W=requestAnimationFrame(()=>{var de,he;if(se)return;const V=Ka(J,z,s,n,a);I.current=V;const q=V.length;if(R(q),q===0){v(null),y(0),Re("msg-search",[]),Re("msg-search-active",[]),F.current={key:null},E.current=z;return}const k=G.current;let w;if(k){if(w=Mt(V,k),w===-1){const p=[];for(let U=0;U<V.length;U++)V[U].msgId===k.msgId&&p.push(U);if(p.length>0){const U=Math.min(k.k,p.length-1);w=p[U]}else w=0}}else w=0;w<0&&(w=0),w>=q&&(w=q-1),(!k||k.msgId!==V[w].msgId||k.k!==V[w].k)&&v({msgId:V[w].msgId,k:V[w].k}),y(w);const b=V[w],L=F.current,$=((de=L.key)==null?void 0:de.msgId)!==b.msgId||((he=L.key)==null?void 0:he.k)!==b.k||L.kind==="folded"&&b.kind==="dom"||z!==E.current;F.current={key:{msgId:b.msgId,k:b.k},kind:b.kind},E.current=z;const ie=V.filter(p=>p.kind==="dom").map(p=>p.range);if(Re("msg-search",ie),b.kind==="folded"){Re("msg-search-active",[]),$&&o(b.msgId);return}Re("msg-search-active",[b.range]),$&&(l==null||l(),Wa(J,b.range))}),()=>{se=!0,cancelAnimationFrame(W)}},[i,z,s,t,x,n,a,o,l]);const K=r.useCallback(H=>{const J=I.current,se=J.length;if(se===0)return;const W=G.current,V=W?Mt(J,W):0,q=J[(V+H+se)%se];v(q.kind==="dom"||q.kind==="folded"?{msgId:q.msgId,k:q.k}:null)},[]);if(!i)return null;const j=x?(()=>{const H=Mt(I.current,x);return H===-1?0:H})():0;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:u,className:"search-input",type:"text",value:f,placeholder:d("searchPlaceholder"),onChange:H=>{h(H.target.value)},onKeyDown:H=>{H.key==="Enter"&&(H.preventDefault(),K(H.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${T===0?"empty":""}`,children:T===0?d("searchNoResults"):`${Math.min(j+1,T)}/${T}`}),e.jsx("button",{type:"button",className:"search-btn",title:d("searchPrev"),disabled:T===0,onClick:()=>K(-1),children:e.jsx(yt,{})}),e.jsx("button",{type:"button",className:"search-btn",title:d("searchNext"),disabled:T===0,onClick:()=>K(1),children:e.jsx(ze,{})}),e.jsx("button",{type:"button",className:"search-btn",title:d("searchClose"),onClick:c,children:e.jsx(Se,{})})]})}function qa(t){const{dSt:s,dSh:n,escaped:a,graceActive:o,stuck:l}=t;return o?{flipEscape:!1,reassert:!1}:s>=-4||s<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:l&&!a}:{flipEscape:!0,reassert:!1}}const xn=[{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"}],vn="pi-web-ui:prompt-templates";function za(){try{const t=localStorage.getItem(vn);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(n=>!!n&&typeof n=="object"&&typeof n.id=="string"):[]}catch{return[]}}function Es(t){return xn.some(s=>s.id===t)}function dt(t){return typeof t.title=="string"}const yn=r.createContext(null);function kn(){const t=r.useContext(yn);if(!t)throw new Error("useTemplates must be used within TemplateProvider");return t}function Va({send:t,children:s}){const n=fe(),[a,o]=r.useState(za),[l,i]=r.useState(!1),[c,d]=r.useState(null),[u,f]=r.useState(!1),[h,x]=r.useState(!1),[v,T]=r.useState(!1);r.useEffect(()=>{try{localStorage.setItem(vn,JSON.stringify(a))}catch{}},[a]);const R=r.useMemo(()=>{const W=new Map,V=new Set;for(const w of a)w.hidden?V.add(w.id):(dt(w)&&!Es(w.id)||dt(w))&&W.set(w.id,w);const q=xn.filter(w=>!V.has(w.id)).map(w=>{const b=W.get(w.id);return{id:w.id,icon:(b==null?void 0:b.icon)??w.icon,title:(b==null?void 0:b.title)??n(w.titleKey),desc:(b==null?void 0:b.desc)??n(w.descKey),prompt:(b==null?void 0:b.prompt)??n(w.promptKey),builtin:!0}}),k=a.filter(w=>dt(w)&&!Es(w.id)).map(w=>({id:w.id,icon:w.icon??"📌",title:w.title??"",desc:w.desc??"",prompt:w.prompt??""}));return[...q,...k]},[a,n]),O=r.useCallback(()=>i(!0),[]),y=r.useCallback(W=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:W}))},[]),C=r.useCallback((W,V=!1)=>{T(V),W?(f(!1),d({...W})):(f(!0),d({id:Fe(),icon:"📌",title:"",desc:"",prompt:""}))},[]),z=r.useCallback(()=>{i(!1),d(null),T(!1)},[]),G=r.useCallback(()=>{h?(o([]),x(!1)):(x(!0),setTimeout(()=>x(!1),5e3))},[h]),I=r.useCallback(W=>{i(!1),y(W.prompt)},[y]),F=r.useCallback(W=>{i(!1),C(W,!0)},[C]),E=r.useCallback(()=>{i(!1),C(void 0,!0)},[C]),K=r.useCallback(W=>{o(V=>{const q=V.findIndex(k=>k.id===W.id);if(q>=0){const k=[...V];return k[q]=W,k}return[...V,W]}),d(null),v&&(i(!0),T(!1))},[v]),j=r.useCallback(W=>{o(V=>W.builtin?[...V.filter(k=>k.id!==W.id),{id:W.id,hidden:!0}]:V.filter(q=>q.id!==W.id)),d(null),v&&(i(!0),T(!1))},[v]),H=r.useCallback(W=>{o(V=>V.filter(q=>q.id!==W.id||q.hidden)),d(null),v&&(i(!0),T(!1))},[v]),J=r.useMemo(()=>({templates:R,fill:y,openPicker:O,openEdit:C,resetConfirm:h,toggleReset:G}),[R,y,O,C,h,G]),se=c?a.some(W=>W.id===c.id&&!W.hidden&&dt(W)):!1;return e.jsxs(yn.Provider,{value:J,children:[s,l&&e.jsx(Qa,{templates:R,resetConfirm:h,onFill:I,onEditTpl:F,onNew:E,onResetToggle:G,onClose:z}),c&&e.jsx(Ya,{editing:c,isNew:u,hasOverride:se,onDraft:d,onSave:K,onRestore:()=>H(c),onRemove:()=>j(c),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:c.prompt})),z()},onSend:()=>{const W=c.prompt.trim();W&&t({type:"prompt",text:W,queue:!1})&&z()},onClose:z})]})}function Ga(){const t=fe(),{templates:s,fill:n,openEdit:a,toggleReset:o,resetConfirm:l}=kn();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(i=>e.jsx(bn,{tpl:i,title:t("tpl.clickCard"),onFill:()=>n(i.prompt),onEdit:()=>a(i),editTitle:t("tpl.editTpl")},i.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>a(),title:t("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(Ae,{})}),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:o,children:[e.jsx(zs,{}),t(l?"tpl.resetConfirm":"tpl.reset")]})})]})}function bn({tpl:t,title:s,onFill:n,onEdit:a,editTitle:o}){const l=fe();return e.jsxs("button",{type:"button",className:"empty-template",title:s,onClick:n,children:[e.jsx("span",{className:"empty-template-icon",children:t.icon}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t.title}),e.jsx("span",{className:"empty-template-desc",children:t.desc})]}),e.jsx("span",{className:"template-card-ops",role:"button",title:o??l("tpl.editTpl"),onClick:i=>{i.stopPropagation(),a()},children:e.jsx(Qs,{})})]})}function Qa({templates:t,resetConfirm:s,onFill:n,onEditTpl:a,onNew:o,onResetToggle:l,onClose:i}){const c=fe();return r.useEffect(()=>{const d=u=>{u.key==="Escape"&&i()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[i]),e.jsx("div",{className:"modal-backdrop",onClick:i,children:e.jsxs("div",{className:"modal template-picker",onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"template-picker-head",children:[e.jsx("span",{className:"template-picker-title",children:c("tpl.pickerTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:c("close"),onClick:i,children:e.jsx(Se,{})})]}),e.jsx("div",{className:"template-picker-hint",children:c("tpl.pickerHint")}),e.jsxs("div",{className:"template-picker-grid",children:[t.map(d=>e.jsx(bn,{tpl:d,title:c("tpl.clickCard"),onFill:()=>n(d),onEdit:()=>a(d),editTitle:c("tpl.editTpl")},d.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:o,title:c("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(Ae,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:c("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:c("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"template-picker-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:l,children:[e.jsx(zs,{}),c(s?"tpl.resetConfirm":"tpl.reset")]})})]})})}function Ya({editing:t,isNew:s,hasOverride:n,onDraft:a,onSave:o,onRestore:l,onRemove:i,onFill:c,onSend:d,onClose:u}){const f=fe(),h=r.useRef(null);r.useEffect(()=>{const T=R=>{R.key==="Escape"&&u()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[u]),r.useEffect(()=>{const T=h.current;if(!T)return;T.style.height="auto";const R=T.scrollHeight>300;T.style.height=`${Math.min(T.scrollHeight,300)}px`,T.style.overflowY=R?"auto":"hidden"},[t.prompt]);const x=()=>{const T=t.title.trim(),R=t.prompt.trim();if(!T||!R){a({...t,error:f("tpl.required")});return}o({id:t.id,icon:t.icon.trim()||"📌",title:T,desc:t.desc.trim(),prompt:R})},v=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:u,children:e.jsxs("div",{className:"modal template-modal",onClick:T=>T.stopPropagation(),children:[e.jsxs("div",{className:"template-modal-head",children:[e.jsx("span",{className:"template-modal-icon",children:t.icon}),e.jsx("span",{className:"template-modal-badge",children:f(v?"tpl.builtin":"tpl.custom")}),e.jsx("span",{className:"template-modal-title",children:f(s?"tpl.newTitle":"tpl.editTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:f("close"),onClick:u,children:e.jsx(Se,{})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldIcon")}),e.jsx("input",{className:"template-field-input icon",value:t.icon,maxLength:4,onChange:T=>a({...t,icon:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldTitle")}),e.jsx("input",{className:"template-field-input",value:t.title,placeholder:f("tpl.fieldTitlePh"),onChange:T=>a({...t,title:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldDesc")}),e.jsx("input",{className:"template-field-input",value:t.desc,placeholder:f("tpl.fieldDescPh"),onChange:T=>a({...t,desc:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldPrompt")}),e.jsx("textarea",{ref:h,className:"template-field-prompt",value:t.prompt,placeholder:f("tpl.fieldPromptPh"),onChange:T=>a({...t,prompt:T.target.value})})]}),t.error&&e.jsx("div",{className:"template-error",children:t.error}),e.jsxs("div",{className:"template-modal-actions",children:[e.jsxs("div",{className:"template-modal-actions-left",children:[!s&&v&&n&&e.jsx("button",{type:"button",className:"btn template-btn ghost",title:f("tpl.restoreTip"),onClick:l,children:f("tpl.restore")}),!s&&v&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:f("tpl.removeTip"),onClick:i,children:[e.jsx(Ie,{})," ",f("tpl.remove")]}),!s&&!v&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:f("tpl.deleteTip"),onClick:i,children:[e.jsx(Ie,{})," ",f("tpl.delete")]})]}),e.jsxs("div",{className:"template-modal-actions-right",children:[e.jsx("button",{type:"button",className:"btn template-btn",onClick:x,children:f("tpl.save")}),e.jsx("button",{type:"button",className:"btn template-btn fill",onClick:c,title:f("tpl.fillTip"),children:f("tpl.fill")}),e.jsxs("button",{type:"button",className:"btn template-btn send",onClick:d,title:f("tpl.sendTip"),children:[e.jsx(qs,{})," ",f("tpl.sendNow")]})]})]})]})})}const Ms=new Map,Ja=15,Rs=30,Rt=250,Ps=1200,Xa=1600;function Is(t){return t.content.some(s=>s.type==="toolCall")}function Za({state:t,liveOutputs:s,toolStatuses:n,onEdit:a,onKillBash:o,onRemoveQueued:l,thinkingWrap:i,toolsWrap:c,jumpTarget:d,onJumpDone:u}){const f=fe(),h=r.useRef(null),[x,v]=r.useState(!0),T=r.useRef(!0),R=r.useRef(0),O=r.useRef(0),y=r.useRef(!1),C=r.useRef(0),[z,G]=r.useState(()=>new Set),[I,F]=r.useState(!1),E=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,K=r.useMemo(()=>{const S=new Map;for(const _ of t.messages)_.role==="toolResult"&&_.toolCallId&&S.set(_.toolCallId,_);return S},[t.messages]),j=r.useMemo(()=>Sa(t.messages),[t.messages]),H=E.length>0?E[E.length-1].id:null,J=t.messages.length>Rs?Math.max(0,t.messages.length-Ja):0,se=r.useMemo(()=>{const S=new Set;for(let _=0;_<J;_++){const ae=t.messages[_];ae.role!=="toolResult"&&(z.has(ae.id)||S.add(ae.id))}return S},[t.messages,J,z]),[W,V]=r.useState(()=>new Set),[q,k]=r.useState(()=>new Set),w=r.useRef(new Map),b=r.useRef(new Map),L=r.useRef(new Map),$=r.useRef(0),ie=r.useMemo(()=>{const S=new Map;for(const _ of t.messages)S.set(_.id,Da(_));return S},[t.messages]),de=r.useRef(ie);de.current=ie;const he=r.useRef(W);he.current=W;const p=t.messages.length>Rs&&!I,U=r.useRef(p);U.current=p;const B=Ia(t.messages,w.current,Xa),Q=r.useRef(B);Q.current=B;const ne=r.useCallback(()=>{const S=h.current;if(!S)return;if(!U.current){V(ye=>ye.size?new Set:ye);return}const _=S.getBoundingClientRect(),ae={top:_.top-Ps,bottom:_.bottom+Ps},le=[];for(const[ye,Ce]of L.current){const Be=Ce.getBoundingClientRect();le.push({id:ye,top:Be.top,bottom:Be.bottom}),he.current.has(ye)||N(ye,Be.bottom-Be.top,de.current.get(ye))}const ve=Ra(le,ae,Q.current,he.current);for(const ye of ve.hide){const Ce=L.current.get(ye);Ce&&N(ye,Ce.offsetHeight,de.current.get(ye))}V(ye=>Pa(ye,ve))},[]),re=r.useCallback(()=>{$.current||($.current=requestAnimationFrame(()=>{$.current=0,ne()}))},[ne]);r.useLayoutEffect(()=>{ne()},[ne]);const ue=r.useRef(I);r.useLayoutEffect(()=>{ue.current&&!I&&ne(),ue.current=I},[I,ne]);const N=r.useCallback((S,_,ae)=>{ae!==void 0&&(b.current.set(S,{h:_,len:ae}),w.current.set(S,_))},[]),Y=r.useCallback((S,_)=>{N(S,_,de.current.get(S))},[N]),m=r.useCallback(S=>{S&&L.current.set(S.dataset.lazyId??"",S)},[]);r.useEffect(()=>{const S=new Set(t.messages.map(_=>_.id));for(const[_,ae]of L.current)S.has(_)||(L.current.delete(_),w.current.delete(_),b.current.delete(_));V(_=>{let ae=!1;const le=new Set;for(const ve of _)S.has(ve)?le.add(ve):ae=!0;return ae?le:_})},[t.messages,z]),r.useEffect(()=>()=>cancelAnimationFrame($.current),[]);const P=r.useMemo(()=>{const S=[];for(const _ of t.messages){if(_.role!=="user")continue;const ae=_.content.map(ye=>{var Ce;return((Ce=lt(ye))==null?void 0:Ce.text)??""}).filter(Boolean).join(" "),le=zt(ae),ve=le?le.userMessage??`skill:${le.name}`:ae.trim();ve&&S.push({id:_.id,text:ve})}return S},[t.messages]),g=r.useMemo(()=>{const S=new Map;return P.forEach((_,ae)=>S.set(_.id,ae)),S},[P]),[D,Z]=r.useState(-1),ee=r.useRef(-1),me=r.useRef(P);r.useEffect(()=>{me.current=P},[P]);const ke=r.useCallback(()=>{const S=h.current,_=me.current;if(!S||_.length===0)return;const ae=S.getBoundingClientRect().top,le=140;let ve=-1;for(let ye=0;ye<_.length;ye++){const Ce=S.querySelector(`[data-msg-id="${_[ye].id}"]`);if(Ce)if(Ce.getBoundingClientRect().top<=ae+le)ve=ye;else break}ve!==ee.current&&(ee.current=ve,Z(ve))},[]);r.useEffect(()=>{ke()},[P,ke]);const pe=r.useCallback(S=>{G(_=>_.has(S)?_:new Set(_).add(S))},[]);r.useEffect(()=>{const S=_=>{if(!(_.ctrlKey||_.metaKey)||_.key.toLowerCase()!=="f")return;const ae=_.target;ae&&(ae.tagName==="INPUT"||ae.tagName==="TEXTAREA"||ae.isContentEditable)||(_.preventDefault(),F(!0))};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[]);const Le=r.useCallback(S=>{G(_=>{if(!_.has(S))return _;const ae=new Set(_);return ae.delete(S),ae})},[]),Pe=r.useCallback(S=>{const _=t.messages.findIndex(le=>le.id===S);ta.flushSync(()=>{_>=0&&_<J&&!z.has(S)&&pe(S),k(le=>le.has(S)?le:new Set(le).add(S))});const ae=me.current.findIndex(le=>le.id===S);ee.current=ae,Z(ae),requestAnimationFrame(()=>{var ve,ye,Ce;const le=(ve=h.current)==null?void 0:ve.querySelector(`[data-msg-id="${S}"]`);le&&((ye=h.current)==null||ye.querySelectorAll(".msg-flash").forEach(Be=>Be.classList.remove("msg-flash")),le.scrollIntoView({block:"start"}),le.classList.remove("msg-flash"),le.offsetWidth,le.classList.add("msg-flash"),le!==((Ce=h.current)==null?void 0:Ce.lastElementChild)&&(y.current=!0))})},[t.messages,J,z,pe]),Oe=r.useMemo(()=>{var S;return d?((S=t.messages.find(_=>_.role===d.role&&_.timestamp===d.timestamp))==null?void 0:S.id)??null:null},[t.messages,d]);r.useEffect(()=>{if(d){if(Oe){Pe(Oe),u==null||u();return}t.sessionFile===d.path&&t.messages.length>0&&(u==null||u())}},[Oe,Pe,u,d,t.sessionFile,t.messages.length]);const Ee=r.useCallback(()=>{const S=h.current;if(!S)return;const _=S.scrollTop-R.current,ae=S.scrollHeight-O.current;R.current=S.scrollTop,O.current=S.scrollHeight;const le=S.scrollHeight-S.scrollTop-S.clientHeight<80,ve=Date.now()<C.current,ye=qa({dSt:_,dSh:ae,escaped:y.current,graceActive:ve,stuck:T.current});ye.reassert&&(C.current=Date.now()+Rt,S.scrollTop=S.scrollHeight),ye.flipEscape&&(y.current=!0),le&&_>=0&&(y.current=!1),ve||(_<0?T.current=le&&!y.current:le&&(T.current=!0)),v(T.current),ke(),re()},[ke,re]),We=r.useRef(!1);r.useEffect(()=>{const S=We.current;if(We.current=!!t.isStreaming,S&&!t.isStreaming&&!y.current){const _=()=>{const le=h.current;le&&!y.current&&(le.scrollTop=le.scrollHeight,T.current=!0,v(!0))};requestAnimationFrame(()=>requestAnimationFrame(_));const ae=setTimeout(_,180);return()=>clearTimeout(ae)}},[t.isStreaming]),r.useEffect(()=>{const S=h.current;S&&T.current&&(S.scrollTop=S.scrollHeight)},[E,t.isStreaming,s]);const Ue=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");r.useEffect(()=>{const S=h.current;S&&T.current&&(S.scrollTop=S.scrollHeight)},[Ue]),r.useEffect(()=>{const S=h.current;if(!S||typeof ResizeObserver>"u")return;const _=new ResizeObserver(()=>{T.current&&!y.current&&(S.scrollTop=S.scrollHeight,v(!0))});return _.observe(S),()=>_.disconnect()},[]),r.useEffect(()=>{const S=h.current;if(!S||typeof MutationObserver>"u")return;let _=!1;const ae=new MutationObserver(()=>{_||(_=!0,requestAnimationFrame(()=>{_=!1;const le=h.current;le&&T.current&&!y.current&&(le.scrollTop=le.scrollHeight,v(!0))}))});return ae.observe(S,{childList:!0,subtree:!0,characterData:!0}),()=>ae.disconnect()},[]);const Ve=r.useCallback(()=>{if(!h.current)return;T.current=!0,y.current=!1,v(!0),C.current=Date.now()+Rt;const _=()=>{const ae=h.current;!ae||!T.current||y.current||(C.current=Date.now()+Rt,ae.scrollTop=ae.scrollHeight)};_(),requestAnimationFrame(()=>requestAnimationFrame(_)),setTimeout(_,120),setTimeout(_,300),setTimeout(_,600)},[]),De=r.useRef(null);r.useEffect(()=>{const S=De.current,_=h.current;if(!S||!_)return;const ae=le=>{le.preventDefault();const ve=S.querySelector(".qn-list");if(ve&&ve.contains(le.target)&&ve.scrollHeight>ve.clientHeight){ve.scrollTop+=le.deltaY;return}_.scrollTop+=le.deltaY};return S.addEventListener("wheel",ae,{passive:!1}),()=>S.removeEventListener("wheel",ae)},[]);const[M,ge]=r.useState(0);r.useEffect(()=>{const S=()=>{var _;ge(((_=h.current)==null?void 0:_.clientHeight)??0),re()};return S(),window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[re]);const ce=P.length,je=r.useMemo(()=>ce===0?27:Math.max(4,Math.min(27,Math.floor(((M||600)-16)/ce)-3)),[ce,M]),xe=je<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:`messages${I||x?"":" anchor-live"}`,ref:h,onScroll:Ee,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(Ga,{})}),t.messages.map((S,_)=>{const ae=_<J,le=ae&&z.has(S.id);if(ae&&!le)return S.role==="toolResult"?null:e.jsx(Ta,{message:S,onExpand:pe},S.id);const ve=S.role==="user"?g.get(S.id):void 0,ye=!p||B.has(S.id)||q.has(S.id)||!W.has(S.id);return e.jsx(Ma,{id:S.id,show:ye,height:Ba(S.id,ie.get(S.id)??-1,b.current,fn(S.role,S.customType)),containerRef:h,onMeasured:Y,lazyRef:m,children:e.jsx(Ns,{message:S,qnIndex:ve,qnActive:ve!==void 0?ve===D:void 0,onJump:Pe,toolResults:K,liveOutputs:Is(S)?s:Ms,toolStatuses:n,streaming:t.isStreaming,onKillBash:o,toolsWrap:c,thinkingWrap:i,isLast:S.id===H,onEdit:a,questionAttachments:j.get(S.id),onCollapse:le?Le:void 0,searchActive:I},S.id)},S.id)}),t.streamingMessage&&e.jsx(Ns,{message:t.streamingMessage,toolResults:K,liveOutputs:Is(t.streamingMessage)?s:Ms,toolStatuses:n,streaming:!0,isLast:!0,onEdit:a,onKillBash:o,toolsWrap:c,thinkingWrap:i,searchActive:I},t.streamingMessage.id),t.isStreaming&&E.length===0&&e.jsx("div",{className:"streaming-wait",children:f("waitingResponse")}),t.queue.steering.map((S,_)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:f("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:S}),l&&e.jsx("button",{type:"button",className:"queued-remove",title:f("queueRemoveTip"),onClick:()=>l("steer",S),children:"✕"})]})},`q-steer-${_}`)),t.queue.followUp.map((S,_)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:f("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:S}),l&&e.jsx("button",{type:"button",className:"queued-remove",title:f("queueRemoveTip"),onClick:()=>l("followUp",S),children:"✕"})]})},`q-fu-${_}`))]}),!x&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Ve,children:[e.jsx(en,{})," ",f("backToBottom")]}),e.jsx(Ua,{containerRef:h,messages:E,collapsedIds:se,toolResults:K,onExpand:pe,onProgrammaticScroll:()=>{y.current=!0,T.current=!1,v(!1)},open:I,onClose:()=>F(!1)}),P.length>0&&e.jsxs("div",{className:`qn-rail ${xe?"many":""}`,ref:De,"aria-label":f("questionNavTitle"),style:{"--rail-gap":`${je}px`},children:[P.map((S,_)=>e.jsx("button",{type:"button",className:`qn-bar ${_===D?"active":""}`,"aria-label":`${_+1}. ${S.text}`,onClick:()=>Pe(S.id),children:e.jsxs("span",{className:"qn-bar-text",children:[_+1,". ",S.text]})},S.id)),xe&&e.jsx("div",{className:"qn-list",children:P.map((S,_)=>e.jsxs("button",{type:"button",className:`qn-list-item ${_===D?"active":""}`,"aria-label":`${_+1}. ${S.text}`,onClick:()=>Pe(S.id),children:[e.jsx("span",{className:"qn-list-idx",children:_+1}),e.jsx("span",{className:"qn-list-text",children:S.text})]},S.id))})]})]})}const jn="pi-web-model-usage";function er(t){if(!t||typeof t!="object")return{};const s={};for(const[n,a]of Object.entries(t)){const o=typeof a=="number"?Math.floor(a):0;Number.isFinite(o)&&o>0&&(s[n]=o)}return s}function tr(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function sr(t,s){const n=s;return t.map((a,o)=>({m:a,i:o,count:n[a.id]??0})).sort((a,o)=>o.count-a.count||a.i-o.i).map(a=>a.m)}function wn(){try{const t=localStorage.getItem(jn);return t?er(JSON.parse(t)):{}}catch{return{}}}function nr(t){try{localStorage.setItem(jn,JSON.stringify(t))}catch{}}function ir(t){const s=tr(wn(),t);return nr(s),s}const ar=["off","minimal","low","medium","high","xhigh","max"],rr=r.memo(function({state:s,models:n,modelsLoading:a,send:o,onManageModels:l,providerKeys:i,compact:c=!1}){const d=fe(),u=s==null?void 0:s.model,f=u?`${u.provider}/${u.id}`:null,[h,x]=r.useState(!1),[v,T]=r.useState(!1),[R,O]=r.useState(""),[y,C]=r.useState(null),[z,G]=r.useState({}),I=r.useRef(null),F=r.useRef(null),[E,K]=r.useState(null);r.useEffect(()=>{if(!h){K(null);return}if(n.length===0)return;const b=requestAnimationFrame(()=>{const L=F.current;L&&K(L.offsetWidth)});return()=>cancelAnimationFrame(b)},[h,n.length]),r.useEffect(()=>{h&&G(wn())},[h]),r.useEffect(()=>{h||(O(""),C(null))},[h]);const j=r.useMemo(()=>{const b=new Map;for(const $ of n)b.set($.provider,(b.get($.provider)??0)+1);const L=[];for(const[$,ie]of[...b.entries()].sort((de,he)=>de[0].localeCompare(he[0]))){const de=i[$];if(de&&de.length>1)for(const he of de)L.push({provider:$,keyName:he.name,count:ie});else L.push({provider:$,keyName:null,count:ie})}return L},[n,i]),H=r.useMemo(()=>sr(n,z),[n,z]),J=r.useMemo(()=>{let b=H;y&&(b=b.filter($=>$.provider===y.provider));const L=R.trim().toLowerCase();return L?b.filter($=>$.name.toLowerCase().includes(L)||$.provider.toLowerCase().includes(L)||$.id.toLowerCase().includes(L)):b},[H,R,y]),se=r.useMemo(()=>{const b=[];for(const L of J){const $=i[L.provider];if(!$||$.length<=1){b.push({model:L,key:null});continue}let ie=$.find(de=>de.active)??$[0];if((y==null?void 0:y.provider)===L.provider&&y.keyName){const de=$.find(he=>he.name===y.keyName);de&&(ie=de)}b.push({model:L,key:ie})}return b},[J,i,y]),[W,V]=r.useState(!1),q=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,k=ar.map(b=>({value:b,label:d(`thinking.${b}`),supported:q?q.has(b):!0})),w=b=>{var L;return((L=k.find($=>$.value===b))==null?void 0:L.label)??b};return r.useEffect(()=>{h&&n.length===0&&!W&&!a&&(V(!0),o({type:"list_models"}))},[h,n.length,W,a,o]),r.useEffect(()=>{n.length>0&&V(!1)},[n.length]),r.useEffect(()=>{var L;if(!h)return;const b=(L=I.current)==null?void 0:L.querySelector(".dd-item.active");b==null||b.scrollIntoView({block:"nearest"})},[h,f,n.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Ke,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(rt,{}),e.jsx("span",{className:"chip-model",children:u?u.name:d("selectModel")}),!c&&(u==null?void 0:u.vision)&&e.jsx("span",{className:"chip-vision",title:d("vision"),children:"🖼"}),!c&&u&&e.jsx("span",{className:"chip-sub",children:u.provider})]}),open:h,onOpenChange:x,menuClassName:"dd-menu-model",menuRef:F,menuStyle:E!=null?{width:E}:void 0,direction:"up",children:[e.jsx("div",{className:"dd-header",children:d("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(xt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:d("searchModels"),value:R,onChange:b=>O(b.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[j.length>1&&e.jsxs("div",{className:"dd-provider-col",children:[e.jsx("div",{className:"dd-provider-head",children:d("providers")}),e.jsx("button",{type:"button",className:`dd-provider-item ${y===null?"active":""}`,onClick:()=>C(null),children:e.jsx("span",{children:d("allProviders")})}),j.map(b=>{const L=(y==null?void 0:y.provider)===b.provider&&(y==null?void 0:y.keyName)===b.keyName;return e.jsxs("button",{type:"button",className:`dd-provider-item ${L?"active":""}`,onClick:()=>C(L?null:{provider:b.provider,keyName:b.keyName}),title:b.keyName?`${b.provider} · ${b.keyName}`:`${b.provider} · ${b.count}`,children:[e.jsxs("span",{className:"dd-provider-txt",children:[e.jsx("span",{className:"dd-provider-name",children:b.provider}),b.keyName&&e.jsx("span",{className:"dd-provider-key",children:b.keyName})]}),e.jsx("span",{className:"dd-provider-count",children:b.count})]},b.keyName?`${b.provider}::${b.keyName}`:b.provider)})]}),e.jsxs("div",{className:"dd-model-scroll",ref:I,children:[(W||a)&&e.jsx("div",{className:"dd-loading",children:d("loading")}),n.length===0&&!W&&!a&&e.jsx("div",{className:"dd-loading",children:d("noModels")}),J.length===0&&n.length>0&&e.jsx("div",{className:"dd-loading",children:d("noModelMatches")}),se.map(b=>{const L=b.model,$=f===L.id&&(!b.key||b.key.active);return e.jsx(Te,{active:$,onClick:()=>{b.key&&!b.key.active&&o({type:"activate_provider_key",provider:L.provider,keyName:b.key.name}),f!==L.id&&o({type:"set_model",modelId:L.id}),x(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:L.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:L.provider}),b.key&&e.jsxs("span",{className:`dd-model-key ${b.key.active?"active":""}`,children:[b.key.active?"●":"○"," ",b.key.name]}),(z[L.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:d("modelUsedCount",{n:z[L.id]})}),(L.reasoning||L.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[L.reasoning&&e.jsx("span",{className:"dd-model-badge",children:d("reasoning")}),L.vision&&e.jsx("span",{className:"dd-model-badge",children:d("vision")})]})]})]})},b.key?`${L.id}::${b.key.name}`:L.id)})]})]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>o({type:"list_models"}),children:d("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{x(!1),l()},children:d("manageModels")})]})]}),e.jsxs(Ke,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(ut,{}),e.jsx("span",{className:"chip-sub",children:d("thinkingChip",{level:s?w(s.thinkingLevel):"—"})})]}),open:v,onOpenChange:T,direction:"up",children:[e.jsx("div",{className:"dd-header",children:d("thinkingLevel")}),k.map(b=>e.jsx(Te,{active:(s==null?void 0:s.thinkingLevel)===b.value,disabled:!b.supported,title:b.supported?void 0:d("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==b.value&&o({type:"set_thinking",level:b.value}),T(!1)},children:b.label},b.value))]})]})}),lr=r.memo(function({ready:s,streaming:n,messages:a,slashCommands:o,modelState:l,models:i,modelsLoading:c,send:d,attachments:u,onRemoveAttachment:f,onAddImageFiles:h,onAddLocalFiles:x,onNotice:v,onSent:T,onManageModels:R,providerKeys:O}){const y=fe(),{locale:C}=Ut(),{openPicker:z}=kn(),G=m=>C==="en"&&m.descriptionEn?m.descriptionEn:m.description??"",I=m=>C==="en"&&m.argumentHintEn?m.argumentHintEn:m.argumentHint??"",[F,E]=r.useState(""),[K,j]=r.useState(!1),[H,J]=r.useState(null),[se,W]=r.useState(0),[V,q]=r.useState(!1),[k,w]=r.useState(void 0),b=r.useRef(null),L=r.useRef(null),$=r.useRef(null),ie={builtin:y("slashBuiltin"),extension:y("slashExtension"),prompt:y("slashPrompt"),skill:y("slashSkill"),plugin:y("slashPlugin")},de=m=>{const P=m.match(/^\/([^\s]*)$/);if(P&&s){const g=P[1].toLowerCase(),D=o.filter(Z=>Z.name.toLowerCase().startsWith(g));J(D.length>0?D:null),W(0)}else J(null)};r.useEffect(()=>{var P;const m=(P=$.current)==null?void 0:P.querySelector(".slash-item.active");m==null||m.scrollIntoView({block:"nearest"})},[se,H]);const he=m=>{var ee;const P=H??[],g=m??P[se%Math.max(P.length,1)];if(!g){J(null);return}const D=F.match(/^\/([^\s]*)([\s\S]*)$/),Z=D?D[2]:"";E(`/${g.name} ${Z}`),J(null),(ee=b.current)==null||ee.focus()},p=async()=>{const P=[...a].reverse().find(D=>D.role==="assistant"&&D.content.some(Z=>Z.type==="text"&&Z.text)),g=P==null?void 0:P.content.filter(D=>D.type==="text").map(D=>D.text).join(`
|
|
319
|
-
`);if(!g){v("warning",y("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(g),v("info",y("slashCopied"))}catch{v("error",y("slashCopyFailed"))}},U=m=>{if(!m||m.length===0){v("warning",y("foldersNotSupported"));return}const P=Array.from(m).filter(Z=>$e(Z.type)),g=Array.from(m).filter(Z=>!$e(Z.type)),D=Q();P.length>0&&D?v("warning",D):P.length>0&&h(P),g.length>0&&x(g)},B=m=>{var Z;const P=(Z=m.clipboardData)==null?void 0:Z.items;if(!P)return;const g=[];for(const ee of P)if(ee.kind==="file"&&$e(ee.type)){const me=ee.getAsFile();me&&g.push(me)}if(g.length===0)return;m.preventDefault();const D=Q();if(D){v("warning",D);return}h(g)},Q=()=>{const m=l==null?void 0:l.model;if(!(m!=null&&m.id))return null;const P=i.find(g=>g.id===m.id);return P&&P.vision===!1?y("modelNoVision",{name:P.name}):null},ne=s,re=r.useRef(F);r.useEffect(()=>{re.current=F},[F]),r.useEffect(()=>{de(re.current)},[o]),r.useEffect(()=>{const m=P=>{var D;const g=P.detail;E(g),(D=b.current)==null||D.focus()};return window.addEventListener("pi-web:fill",m),()=>window.removeEventListener("pi-web:fill",m)},[]),r.useEffect(()=>{if(!V)return;const m=P=>{P.key==="Escape"&&q(!1)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[V]),r.useEffect(()=>{const m=b.current;if(!m)return;m.style.height="auto";const P=m.scrollHeight>220;m.style.height=`${Math.min(m.scrollHeight,220)}px`,m.style.overflowY=P?"auto":"hidden"},[F]);const ue=(m=!1)=>{var D,Z,ee,me,ke;const P=F.trim(),g=u.some(pe=>pe.imageData||pe.fileData);if(!(!ne||!P&&!g)){if(P==="/help"){const pe=(Z=(D=b.current)==null?void 0:D.closest(".inputbox"))==null?void 0:Z.getBoundingClientRect();w(pe==null?void 0:pe.width),q(!0),E(""),(ee=b.current)==null||ee.focus();return}if(P==="/copy"){E(""),(me=b.current)==null||me.focus(),p();return}if(d({type:"prompt",text:P,queue:m,attachments:u.map(pe=>pe.imageData?{path:"",imageData:pe.imageData,mimeType:pe.mimeType,name:pe.name}:pe.fileData?{path:"",fileData:pe.fileData,mimeType:pe.mimeType,name:pe.name,size:pe.size}:{path:pe.path,mode:pe.mode,...pe.lines?{lines:pe.lines}:{}})})){E(""),T();const pe=l==null?void 0:l.model;pe&&ir(`${pe.provider}/${pe.id}`),(ke=b.current)==null||ke.focus()}}},N=m=>{if(!m.nativeEvent.isComposing){if(H&&H.length>0)switch(m.key){case"ArrowDown":m.preventDefault(),W(P=>(P+1)%H.length);return;case"ArrowUp":m.preventDefault(),W(P=>(P-1+H.length)%H.length);return;case"Tab":case"Enter":m.preventDefault(),he();return;case"Escape":m.preventDefault(),J(null);return}m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),ue())}},Y=()=>e.jsx("div",{className:"inputbox-actions",children:n?e.jsxs(e.Fragment,{children:[F.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:y("supplementTip"),onClick:()=>ue(!0),children:[e.jsx(qs,{})," ",y("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:y("stopAgent"),onClick:()=>d({type:"abort"}),children:e.jsx(gt,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:y("sendTip"),disabled:!ne||!F.trim()&&!u.some(m=>m.imageData||m.fileData),onClick:()=>ue(),children:e.jsx(Zs,{})})});return e.jsxs("div",{className:`inputbar${K?" drop-active":""}`,onDragOver:m=>{m.preventDefault(),m.stopPropagation(),j(!0)},onDragLeave:m=>{m.currentTarget.contains(m.relatedTarget)||j(!1)},onDrop:m=>{var P;m.preventDefault(),m.stopPropagation(),j(!1),U(((P=m.dataTransfer)==null?void 0:P.files)??null)},children:[K&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",y("dropHereToAttach")]})}),u.length>0&&e.jsxs("div",{className:"attach-row",children:[u.map(m=>e.jsxs("span",{className:`attach-chip ${m.imageData?"image":m.fileData?"file":m.mode}`,title:m.imageData?y("attachImage",{name:m.name}):m.fileData?y("attachFile",{name:m.name}):m.isDir?y("folderRef",{path:m.path}):m.mode==="reference"?y("refOnly",{path:m.path}):m.mode==="lines"&&m.lines?y("attachLines",{path:m.path,start:m.lines.start,end:m.lines.end}):y("attachContent",{path:m.path}),children:[m.imageData?"🖼":m.fileData?"📄":m.isDir?"📁":m.mode==="reference"?"🔗":"📎"," ",m.name,m.mode==="lines"&&m.lines&&e.jsxs("span",{className:"attach-range",children:["L",m.lines.start,"-",m.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:y("removeAttachment"),onClick:()=>f(m.key??m.path),children:"×"})]},m.key??`${m.path}|${m.mode}|${m.lines?`${m.lines.start}-${m.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:y("attachHint")})]}),H&&H.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:$,"aria-label":y("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:y("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>J(null),children:"Esc"})]}),H.map((m,P)=>e.jsxs("button",{type:"button",className:`slash-item${P===se?" active":""}`,onMouseEnter:()=>W(P),onClick:()=>he(m),children:[e.jsxs("span",{className:"slash-name",children:["/",m.name]}),e.jsx("span",{className:`slash-source ${m.source}`,children:ie[m.source]}),e.jsxs("span",{className:"slash-desc",children:[G(m),m.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(m)})]})]},m.name))]}),V&&e.jsx("div",{className:"modal-backdrop",onClick:()=>q(!1),children:e.jsxs("div",{className:"slash-help",style:k?{width:k}:void 0,onClick:m=>m.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",y("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>q(!1),children:y("close")})]}),e.jsx("div",{className:"slash-help-body",children:o.length===0?e.jsx("div",{className:"slash-help-empty",children:y("slashLoading")}):o.map(m=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",m.name]}),e.jsx("span",{className:`slash-source ${m.source}`,children:ie[m.source]}),e.jsxs("span",{className:"slash-help-desc",children:[G(m),m.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(m)})]})]},m.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:L,type:"file",multiple:!0,hidden:!0,onChange:m=>{U(m.target.files),m.target.value=""}}),e.jsx("textarea",{ref:b,value:F,rows:1,placeholder:y(ne?n?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!ne,onChange:m=>{E(m.target.value),de(m.target.value)},onKeyDown:N,onPaste:B}),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:y("uploadFile"),disabled:!ne,onClick:()=>{var m;return(m=L.current)==null?void 0:m.click()},children:e.jsx(ti,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:y("tpl.openPicker"),onClick:z,children:e.jsx(di,{})}),e.jsx(rr,{state:l,models:i,modelsLoading:c,send:d,onManageModels:R,providerKeys:O,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:Y()})]})]})]})}),or=r.memo(function({goal:s,models:n,modelsLoading:a,activeConversationId:o,engine:l,send:i}){var W,V,q,k,w,b;const c=fe(),d=l==="dsh",u=!s.conversationId||s.conversationId===o,f=s.goal!==null&&u,[h,x]=r.useState(""),[v,T]=r.useState(s.reviewModel??""),[R,O]=r.useState(s.maxRounds),[y,C]=r.useState(s.locked),[z,G]=r.useState(!1),[I,F]=r.useState(!1),[E,K]=r.useState(!0);r.useEffect(()=>{T(s.reviewModel??""),O(s.maxRounds||0),C(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),r.useEffect(()=>{z&&n.length===0&&!I&&!a&&(F(!0),i({type:"list_models"}))},[z,n.length,I,a,i]),r.useEffect(()=>{n.length>0&&F(!1)},[n.length]);const j=()=>{var L;return v?((L=n.find($=>$.id===v))==null?void 0:L.name)??v:c("goalBarUseMainModel")},H=()=>{const L=h.trim();L&&(i({type:"set_goal",goal:L,...v?{reviewModel:v}:{},maxRounds:R,locked:y}),x(""),K(!1))},J=()=>{const L=h.trim();L&&(i({type:"start_goal_wizard",text:L,...v?{wizardModel:v}:{},maxRounds:R,locked:y}),x(""),K(!1))},se=(((W=s.wizard)==null?void 0:W.active)??!1)&&u;return se?e.jsx("div",{className:`goalbar goalbar-active ${se?"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:((V=s.wizard)==null?void 0:V.draft)??"",children:[c("goalWizardRunning"),": ",(q=s.wizard)==null?void 0:q.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[c("goalBarRound",{n:(((k=s.wizard)==null?void 0:k.step)??0)+1})," ","/ ",((w=s.wizard)==null?void 0:w.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((b=s.wizard)==null?void 0:b.status)||c("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:c("goalBarClear"),onClick:()=>{i({type:"clear_goal"}),K(!0)},children:e.jsx(Se,{})})]})}):f?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:[c("goalBarReviewing")," ",c("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?c("goalBarPassed"):s.verdict==="fail"?c("goalBarFailed"):`${c("goalBarRound",{n:s.round||1})} · ${s.locked?c("goalBarLocked"):c("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:s.status}),e.jsx("button",{type:"button",className:"goalbar-x",title:c("goalBarClear"),disabled:s.reviewing,onClick:()=>{i({type:"clear_goal"}),K(!0)},children:e.jsx(Se,{})})]})}):E?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:c("goalBarPlaceholder"),onClick:()=>K(!1),children:[e.jsx(ps,{})," ",e.jsx("span",{children:c("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx(ps,{})}),e.jsx("input",{className:"goalbar-input",value:h,placeholder:c("goalBarPlaceholder"),onChange:L=>x(L.target.value),onKeyDown:L=>{L.key==="Enter"&&H()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!h.trim(),onClick:H,children:c("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!h.trim(),title:c("goalWizardTip"),onClick:J,children:["🔍 ",c("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:c(y?"goalBarLocked":"goalBarUnlocked"),onClick:()=>C(L=>(i({type:"set_goal_prefs",locked:!L}),!L)),children:y?e.jsx(li,{}):e.jsx(Jn,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:c("goalBarClear"),onClick:()=>K(!0),children:e.jsx(yt,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[d?e.jsx("p",{className:"goalbar-dsh-note",children:c("dshNoReviewModel")}):e.jsxs(Ke,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[c("goalBarReviewModel"),": ",e.jsx("b",{children:j()})]}),open:z,onOpenChange:G,direction:"up",children:[e.jsx("div",{className:"dd-header",children:c("goalBarReviewModel")}),(I||a)&&e.jsx("div",{className:"dd-loading",children:c("loading")}),n.length===0&&!I&&!a&&e.jsx("div",{className:"dd-loading",children:c("noModels")}),e.jsx(Te,{active:v==="",onClick:()=>{T(""),G(!1),i({type:"set_goal_prefs",reviewModel:""})},children:c("goalBarUseMainModel")}),n.map(L=>e.jsx(Te,{active:v===L.id,onClick:()=>{T(L.id),G(!1),i({type:"set_goal_prefs",reviewModel:L.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:L.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:L.provider})})]})},L.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>i({type:"list_models"}),children:c("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:c("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:c("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:R,placeholder:c("goalBarUnlimitedShort"),onChange:L=>{const $=parseInt(L.target.value,10);if(Number.isNaN($)||$<0){O(0);return}O($)},onBlur:()=>i({type:"set_goal_prefs",maxRounds:R}),onKeyDown:L=>{L.key==="Enter"&&(i({type:"set_goal_prefs",maxRounds:R}),L.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:c(y?"goalBarLocked":"goalBarUnlocked")})]})]})});function cr(t){const s=Math.max(0,t.input??0),n=Math.max(0,t.cacheRead??0),a=Math.max(0,t.cacheWrite??0),o=s+n+a;return{totalInput:o,miss:s,read:n,write:a,hitRate:o>0?Math.min(n/o,1):0,writeRate:o>0?Math.min(a/o,1):0}}const Nn=2e3;function dr(t,s,n=Nn){return t.filter(a=>s-a.t<=n)}function ur(t,s=Nn){if(t.length<2)return 0;const n=t[t.length-1],a=t.find(l=>l.t>=n.t-s)??t[0],o=(n.t-a.t)/1e3;return o<=0?0:Math.max(0,(n.out-a.out)/o)}function Ls(t){if(!t)return 0;let s=0;for(let a=0;a<t.length;a++){const o=t.charCodeAt(a);(o>=12352&&o<=12543||o>=13312&&o<=19903||o>=19968&&o<=40959||o>=63744&&o<=64255||o>=65280&&o<=65519||o===12288)&&s++}const n=t.length-s;return Math.round(s+n/4)}function pr(t){let s=0;for(const n of t)n.type==="text"&&typeof n.text=="string"&&n.text?s+=Ls(n.text):n.type==="thinking"&&typeof n.thinking=="string"&&n.thinking&&(s+=Ls(n.thinking));return s}function mr({chat:t,send:s}){const n=fe(),a=t.state,[o,l]=r.useState(!1),[i,c]=r.useState(""),[d,u]=r.useState(0),f=r.useRef(null),h=t.pathCompletions;r.useEffect(()=>{if(!o)return;const k=setTimeout(()=>{s({type:"complete_path",path:i})},150);return()=>clearTimeout(k)},[i,o,s]),r.useEffect(()=>u(0),[h]),r.useEffect(()=>{const k=document.querySelector(`.status-completions .pc-item[data-idx="${d}"]`);k==null||k.scrollIntoView({block:"nearest"})},[d]);const x=r.useRef([]),v=(a==null?void 0:a.isStreaming)??!1,T=a!=null&&a.streamingMessage?pr(a.streamingMessage.content):0;if(r.useEffect(()=>{if(!v){x.current=[];return}const k=Date.now(),w=x.current,b=w[w.length-1];b&&k-b.t<250||(x.current=dr([...w,{t:k,out:T}],k))},[v,T]),!a)return null;const R=a.stats,O=cr(R.tokens),y=O.hitRate*100,C=O.totalInput===0?"":O.hitRate>=.7?"ok":O.hitRate>=.4?"mid":"warn",z=O.totalInput>0?`${y.toFixed(1)}%`:"—",G=v?ur(x.current):0,I=t.ready?"ok":"busy",F=t.ready?n("connected"):n("connecting"),E=R.contextUsage,K=E.tokens!==null&&E.percent!==null?`${Qe(E.tokens)} / ${Qe(E.contextWindow)}`:"—",j=E.percent??null,H=j===null?"":j>=80?"warn":j>=50?"mid":"ok",J=a.queue.steering.length+a.queue.followUp.length,se=()=>{c(a.cwd),l(!0)},W=(k,w)=>{var L;const b=k.includes("\\")?"\\":"/";c(w?`${k}${b}`:k),u(0),(L=f.current)==null||L.focus()},V=k=>{const w=k.trim();w&&w!==a.cwd&&s({type:"set_cwd",path:w}),l(!1)},q=k=>{if(k.key==="ArrowDown")k.preventDefault(),u(w=>Math.min(w+1,h.length-1));else if(k.key==="ArrowUp")k.preventDefault(),u(w=>Math.max(w-1,0));else if(k.key==="Tab"&&h.length>0){k.preventDefault();const w=h[Math.min(d,h.length-1)];W(w.path,w.type==="dir")}else if(k.key==="Enter"&&!k.nativeEvent.isComposing){const w=i.trim();if(w.endsWith("/")||w.endsWith("\\"))V(w);else if(h.some(b=>b.path===w))V(w);else if(h.length>0&&h[d]){k.preventDefault();const b=h[d];W(b.path,b.type==="dir")}else V(w)}else k.key==="Escape"&&(h.length>0?(k.stopPropagation(),s({type:"complete_path",path:""})):l(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${I}`,title:F}),e.jsx("span",{className:"status-item",children:F}),e.jsx("span",{className:"status-sep",children:"·"}),t.engine&&t.engine!=="pi"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`status-item engine-badge engine-${t.engine}`,title:`${n("engineBadge")}: ${t.engine}`,children:t.engine==="dsh"?"DSH":t.engine}),e.jsx("span",{className:"status-sep",children:"·"})]}),e.jsxs("span",{className:"status-item status-ctx",title:n("contextUsage"),children:[n("context"),e.jsx("span",{className:`ctx-bar ${H}`,children:j!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(j,100)}%`}})}),K]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("cumulativeCost"),children:["$",hr(R.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-cache",title:n("cacheHitTip",{read:Qe(O.read),write:Qe(O.write),miss:Qe(O.miss),input:Qe(O.totalInput)}),children:[n("cacheHit"),e.jsx("b",{className:`cache-pct ${C}`,children:z})]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("sessionMessages"),children:[n("messages")," ",R.totalMessages]}),t.statuses.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsx("span",{className:"status-item ext-status",title:n("pluginStatus"),children:t.statuses.map(k=>k.text).join(" · ")})]}),a.isStreaming&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item working",children:[e.jsx("span",{className:"working-spin"}),n("working"),J>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",J," ",n("queued")]})]}),e.jsx("span",{className:"status-item status-rate",title:n("rateTip"),children:G>0?`${Math.round(G)}${n("tps")}`:"…"})]}),o?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:f,className:"status-cwd-input",value:i,autoFocus:!0,placeholder:n("enterPath"),onChange:k=>c(k.target.value),onKeyDown:q,onBlur:()=>l(!1)}),h.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:k=>k.preventDefault(),children:h.map((k,w)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":w,className:`pc-item ${w===d?"sel":""}`,onMouseEnter:()=>u(w),onClick:()=>W(k.path,k.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:k.type==="dir"?e.jsx(Ze,{}):e.jsx(Vs,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:k.name}),e.jsx("span",{className:"pc-path",children:k.path})]})]})},k.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:n("cwdTip",{path:a.cwd}),onClick:se,children:["📁 ",a.cwd]})]})}function Qe(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function hr(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function gr({dialog:t,send:s}){const n=fe(),[a,o]=r.useState(""),[l,i]=r.useState(0),c=f=>{s({type:"dialog_response",id:t.id,value:f})};r.useEffect(()=>{o(""),i(0);const f=h=>{h.key==="Escape"&&c(null)};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t.id]);const d=Array.isArray(t.args[0])?t.args[0]:[],u=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("pluginRequest")}),t.title&&t.title!==n("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>c(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[d.map((f,h)=>e.jsx("button",{type:"button",className:`dialog-option ${h===l?"sel":""}`,onMouseEnter:()=>i(h),onClick:()=>c(f),children:f},h)),d.length===0&&e.jsx("div",{className:"dialog-hint",children:n("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:u}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>c(!1),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>c(!0),children:n("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:a,placeholder:u||n("inputPlaceholder"),autoFocus:!0,onChange:f=>o(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.nativeEvent.isComposing&&c(a)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>c(null),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>c(a),children:n("ok")})]})]})]})}function fr({question:t,send:s}){const n=fe(),[a,o]=r.useState({}),[l,i]=r.useState({}),[c,d]=r.useState(()=>t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1);r.useEffect(()=>{o({}),i({}),d(t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1)},[t.id,t.deadline]),r.useEffect(()=>{if(!t.deadline)return;const x=setInterval(()=>{d(v=>{const T=Math.max(0,Math.ceil((t.deadline-Date.now())/1e3));return T<=0&&v>0&&s({type:"question_answer",id:t.id,answers:[],cancelled:!0}),T})},1e3);return()=>clearInterval(x)},[t.id,t.deadline]);const u=x=>{if(x){s({type:"question_answer",id:t.id,answers:[],cancelled:!0});return}const v=t.questions.map(T=>{const R=a[T.id]??[],O=(l[T.id]??"").trim();return{id:T.id,selected:R,...O?{custom:O}:{}}});s({type:"question_answer",id:t.id,answers:v})};r.useEffect(()=>{const x=v=>{v.key==="Escape"&&u(!0)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t.id]);const f=(x,v,T)=>{o(R=>{const O=R[x]??[];return T?{...R,[x]:O.includes(v)?O.filter(y=>y!==v):[...O,v]}:{...R,[x]:[v]}})},h=t.questions.every(x=>{var v;return(((v=a[x.id])==null?void 0:v.length)??0)>0||(l[x.id]??"").trim()!==""});return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":"select",children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("modelQuestion")}),c>=0&&e.jsx("span",{className:"question-timer",children:c>0?n("questionTimeout",{s:c}):n("questionTimeoutExpired")}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>u(!0),children:"✕"})]}),t.questions.map((x,v)=>{var T;return e.jsxs("div",{className:"set-section",children:[e.jsx("div",{className:"set-section-title",children:x.header??`${n("modelQuestion")} ${v+1}`}),e.jsx("p",{className:"set-row-desc",children:x.question}),x.detail&&e.jsx("p",{className:"set-hint",children:x.detail}),(((T=x.options)==null?void 0:T.length)??0)>0&&e.jsx("div",{className:"set-list",children:x.options.map(R=>{const O=(a[x.id]??[]).includes(R.label);return e.jsxs("button",{type:"button",className:`set-row question-option${O?" active":""}`,onClick:()=>f(x.id,R.label,!!x.multiSelect),children:[e.jsxs("span",{className:"set-row-name",children:[x.multiSelect?O?"☑ ":"☐ ":O?"● ":"○ ",R.label]}),R.description&&e.jsx("span",{className:"set-row-desc",children:R.description})]},R.label)})}),e.jsx("input",{className:"set-prompt-input question-custom",placeholder:n("modelQuestionCustom"),value:l[x.id]??"",onChange:R=>i(O=>({...O,[x.id]:R.target.value}))})]},x.id)}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"dialog-submit",disabled:!h,onClick:()=>u(!1),children:n("modelQuestionSubmit")}),e.jsx("button",{type:"button",className:"dialog-dismiss-inline",onClick:()=>u(!0),children:n("cancel")})]})]})}function xr(t){if(t.x==="?"&&t.y==="?")return"untracked";const s=t.x!==" "&&t.x!=="?",n=t.y!==" "&&t.y!=="?";return s&&n?"both":s?"staged":"unstaged"}function vr({chat:t,send:s,terminal:n,active:a,onSwitchToTerminal:o}){var Ve,De;const l=fe(),[i,c]=r.useState(null),[d,u]=r.useState([]),[f,h]=r.useState(""),[x,v]=r.useState(new Map),[T,R]=r.useState("changes"),[O,y]=r.useState([]),[C,z]=r.useState(null),[G,I]=r.useState(""),[F,E]=r.useState(!1),[K,j]=r.useState(null),[H,J]=r.useState(null),[se,W]=r.useState(!1),[V,q]=r.useState(!1),[k,w]=r.useState(!1),[b,L]=r.useState(null),[$,ie]=r.useState(!1),[de,he]=r.useState(""),p=r.useRef(0),U=r.useRef(-1),B=r.useRef(-1),Q=r.useRef(-1),ne=r.useRef(-1),re=r.useRef(void 0),ue=r.useRef(null),N=r.useRef([]),Y=r.useCallback(M=>{if(M.reqId===U.current){if(U.current=-1,q(!1),L(null),!M.ok){L(M.error??"查询失败");return}if(M.notRepo){ie(!0),c(null),u([]),v(new Map),y([]),z(null),I(""),J(null);return}ie(!1);const ge={branch:M.branch??"",detached:!!M.detached,upstream:M.upstream??null,ahead:M.ahead??0,behind:M.behind??0,upstreamGone:!!M.upstreamGone,files:(M.files??[]).map(xe=>({...xe}))},ce=(M.branches??[]).map(xe=>({...xe})),je=new Map;for(const[xe,S]of Object.entries(M.stats??{}))je.set(xe,{add:S[0],del:S[1]});c(ge),u(ce),v(je),h(xe=>{var S;return ge.detached?xe||"":ge.branch&&ce.some(_=>_.name===ge.branch)?ge.branch:xe&&ce.some(_=>_.name===xe)?xe:((S=ce[0])==null?void 0:S.name)??""}),J(xe=>xe&&!ge.files.some(S=>S.path===xe.file.path)?null:xe)}else if(M.reqId===B.current){if(B.current=-1,W(!1),!M.ok){L(M.error??"查询失败");return}const ge=ue.current;if(!ge)return;J({file:ge,staged:M.stagedText??"",worktree:M.worktreeText??"",untracked:!1})}else if(M.reqId===ne.current){if(ne.current=-1,w(!1),!M.ok){L(M.error??"查询失败");return}y((M.history??[]).map(ge=>({...ge})))}else if(M.reqId===Q.current){if(Q.current=-1,E(!1),!M.ok){L(M.error??"查询失败");return}I(M.text??"")}},[]);r.useEffect(()=>{const M=t.scmData;M&&M.type==="scm_data"&&Y(M)},[t.scmData,Y]);const m=r.useCallback((M,ge)=>{if(!t.ready||t.status!=="open")return!1;const ce=++p.current;return s({...M,reqId:ce})?(ge.current=ce,!0):(p.current-=1,!1)},[t.ready,t.status,s]),P=r.useCallback((M=!1,ge=!1)=>{var ce;!t.ready||t.status!=="open"||(ce=t.state)!=null&&ce.cwd&&(re.current!==void 0&&re.current!==t.state.cwd&&(c(null),u([]),v(new Map),y([]),w(!1),ne.current=-1,z(null),I(""),J(null),j(null)),re.current=t.state.cwd,L(null),m({type:"scm_status"},U)&&(ge||q(!0)))},[t.ready,(Ve=t.state)==null?void 0:Ve.cwd,t.status,m]),g=r.useCallback(M=>{if(j(M),z(null),ue.current=M,M.x==="?"&&M.y==="?"){J({file:M,staged:"",worktree:"",untracked:!0});return}W(!0),L(null),m({type:"scm_filediff",path:M.path},B)||W(!1)},[m]),D=r.useCallback(M=>{z(M),j(null),J(null),I(""),E(!0),L(null),m({type:"scm_commit",hash:M.hash},Q)||E(!1)},[m]),Z=r.useCallback((M,ge)=>{var S,_;if(!t.ready)return;const ce={name:M,command:ge,cwd:"${pwd}"};let je;const xe=t.terminals.find(ae=>ae.title===M);xe?(n.restart(xe.id),s({type:"run_command",terminalId:xe.id,conversationId:xe.conversationId,command:ce,cols:80,rows:24}),je=xe.id):(je=Fe(),n.create({id:je,conversationId:t.activeConversationId||((S=t.state)==null?void 0:S.conversationId)||"",title:M,cwd:((_=t.state)==null?void 0:_.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:ce})),n.select(je),o()},[t.ready,(De=t.state)==null?void 0:De.cwd,t.terminals,o,s,n]),ee=r.useCallback(()=>{const M=de.trim();if(!M||$)return;const ge=M.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");Z("git commit",`git add -A && git commit -m "${ge}"`),he("")},[de,$,Z]),me=M=>`'${M.replace(/'/g,"'\\''")}`,ke=r.useCallback(M=>{$||Z("git add",`git add -- ${me(M.path)}`)},[$,Z]),pe=r.useCallback(M=>{$||Z("git reset",`git reset HEAD -- ${me(M.path)}`)},[$,Z]),Le=r.useCallback(()=>{if(!f||$)return;const M=d.find(ge=>ge.name===f);if(M!=null&&M.remote&&typeof M.remote=="string"){const ge=f.slice(M.remote.length+1);Z("git checkout",`git checkout -b ${ge} ${f} || git checkout ${f}`)}else Z("git checkout",`git checkout ${f}`)},[f,d,$,Z]),Pe=r.useCallback(()=>Z("git push","git push"),[Z]),Oe=r.useCallback(()=>Z("git pull","git pull"),[Z]),Ee=r.useCallback(()=>{m({type:"scm_history"},ne)||(ne.current=-1)},[m]);r.useEffect(()=>{a&&P()},[a,P]),r.useEffect(()=>{T==="history"&&i&&Ee()},[T,i,Ee]),r.useEffect(()=>{t.scmDirty>0&&a&&P(!1,!0)},[t.scmDirty]),r.useEffect(()=>{if(!a||!t.ready||t.status!=="open")return;const M=setInterval(()=>{document.visibilityState!=="hidden"&&P(!1,!0)},3e4);return()=>clearInterval(M)},[a,t.ready,t.status,P]),r.useEffect(()=>{const M=N.current;if(N.current=t.terminals,!a)return;t.terminals.some(ce=>{var xe;return ce.running!==!1?!1:((xe=M.find(S=>S.id===ce.id))==null?void 0:xe.running)===!0&&/^git /.test(ce.title)})&&t.ready&&t.status==="open"&&(P(!1,!0),T==="history"&&i&&Ee())},[t.terminals,a,t.ready,t.status,P,T,i,Ee]);const We={staged:l("scmStaged"),unstaged:l("scmUnstaged"),untracked:l("scmUntracked"),both:l("scmStagedUnstaged")},Ue=M=>{const ge=M.split(`
|
|
320
|
-
`);return e.jsx("pre",{className:"scm-diff-pre",children:ge.map((ce,je)=>{let xe="";return ce.startsWith("diff --git")||ce.startsWith("index ")||ce.startsWith("new file")||ce.startsWith("deleted file")||ce.startsWith("old mode")||ce.startsWith("new mode")||ce.startsWith("similarity index")||ce.startsWith("rename ")||ce.startsWith("copy ")||ce.startsWith("Binary files")||ce.startsWith("---")||ce.startsWith("+++")?xe="hdr":ce.startsWith("@@")?xe="hunk":ce.startsWith("+")?xe="add":ce.startsWith("-")&&(xe="del"),e.jsx("div",{className:`scm-diff-line ${xe}`,children:ce||" "},je)})})};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(pt,{}),l("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":T==="changes",className:T==="changes"?"active":"",onClick:()=>{R("changes"),L(null)},children:l("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":T==="history",className:T==="history"?"active":"",onClick:()=>{R("history"),L(null)},children:l("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:l("scmRefreshTip"),disabled:V,onClick:()=>P(!0),children:e.jsx(at,{className:V?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:l("scmCurrentBranch"),children:[e.jsx(pt,{}),i?i.detached?l("scmDetached"):i.branch:"…",(i==null?void 0:i.upstream)&&e.jsx("span",{className:"scm-upstream",children:i.upstreamGone?l("scmUpstreamGone"):i.ahead>0||i.behind>0?l("scmAheadBehind",{ahead:i.ahead,behind:i.behind}):i.upstream})]}),e.jsxs("select",{className:"scm-select",value:f,disabled:$||d.length===0,title:l("scmSwitchBranch"),onChange:M=>h(M.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:l("scmSelectBranch")}),d.filter(M=>!M.remote).map(M=>e.jsx("option",{value:M.name,children:M.current?`* ${M.name}`:M.name},M.name)),d.some(M=>M.remote)&&e.jsx("optgroup",{label:l("scmRemoteBranches"),children:d.filter(M=>M.remote).map(M=>e.jsx("option",{value:M.name,children:M.name},M.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!f||f===(i==null?void 0:i.branch)||$,title:l("scmSwitchBranchTip",{branch:f}),onClick:Le,children:[e.jsx(pt,{}),l("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!i||i.detached||$,title:l("scmPushTip"),onClick:Pe,children:[e.jsx(Zs,{}),l("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!i||i.detached||$,title:l("scmPullTip"),onClick:Oe,children:[e.jsx(en,{}),l("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:de,placeholder:l("scmCommitPlaceholder"),disabled:$,onChange:M=>he(M.target.value),onKeyDown:M=>{M.key==="Enter"&&!M.nativeEvent.isComposing&&ee()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!de.trim()||$,title:l("scmCommitTip"),onClick:ee,children:[e.jsx(ot,{}),l("scmCommit")]})]})]}),e.jsxs("div",{className:"scm-body",children:[T==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:l("scmHistory")}),O.length>0&&e.jsx("span",{className:"scm-files-count",children:O.length})]}),e.jsx("div",{className:"scm-history-list",children:$?e.jsx("div",{className:"scm-empty",children:l("scmNotGitRepo")}):!i||k?e.jsx("div",{className:"scm-empty",children:t.status==="open"?l("scmLoading"):l("scmConnecting")}):O.length===0?e.jsx("div",{className:"scm-empty",children:l("scmNoHistory")}):O.map(M=>e.jsxs("button",{type:"button",className:`scm-commit ${(C==null?void 0:C.hash)===M.hash?"active":""}`,onClick:()=>D(M),title:M.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:M.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:M.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[M.shortHash," · ",M.author," · ",M.date]}),M.decorations&&e.jsx("span",{className:"scm-commit-refs",children:M.decorations})]})]},M.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:l("scmChanges")}),i&&i.files.length>0&&e.jsx("span",{className:"scm-files-count",children:i.files.length})]}),e.jsx("div",{className:"scm-files-list",children:$?e.jsx("div",{className:"scm-empty",children:l("scmNotGitRepo")}):i?i.files.length===0?e.jsx("div",{className:"scm-empty",children:l("scmNoChanges")}):i.files.map(M=>{const ge=xr(M),ce=x.get(M.path);return e.jsxs("div",{className:`scm-file ${(K==null?void 0:K.path)===M.path?"active":""}`,title:We[ge],onClick:()=>g(M),children:[e.jsx("span",{className:`scm-file-xy ${ge==="untracked"?"q":"x"}`,children:M.x!==" "?M.x:" "}),e.jsx("span",{className:`scm-file-xy ${ge==="untracked"?"q":"y"}`,children:M.y!==" "?M.y:" "}),e.jsx("span",{className:"scm-file-path",children:M.path}),ce&&(ce.add>0||ce.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[ce.add>0&&e.jsxs("span",{className:"add",children:["+",ce.add]}),ce.del>0&&e.jsxs("span",{className:"del",children:["-",ce.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(M.y!==" "||ge==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:l("scmStageTip",{path:M.path}),onClick:je=>{je.stopPropagation(),ke(M)},children:"+"}),ge==="staged"||ge==="both"?e.jsx("button",{type:"button",className:"scm-act",title:l("scmUnstageTip",{path:M.path}),onClick:je=>{je.stopPropagation(),pe(M)},children:"−"}):null]})]},M.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?l("scmLoading"):l("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:T==="history"?C?`${C.shortHash} ${C.subject}`:l("scmCommitDetail"):K?K.path:l("scmDiff")}),(T==="history"?F:se)&&e.jsx("span",{className:"scm-diff-loading",children:l("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:T==="history"?e.jsxs(e.Fragment,{children:[b&&e.jsx("div",{className:"scm-error",children:b}),!C&&!b&&e.jsx("div",{className:"scm-empty",children:l("scmSelectCommitHint")}),C&&F&&!b&&e.jsx("div",{className:"scm-empty",children:l("scmLoading")}),C&&!F&&!b&&G?Ue(G):null]}):e.jsxs(e.Fragment,{children:[b&&e.jsx("div",{className:"scm-error",children:b}),!K&&!b&&e.jsx("div",{className:"scm-empty",children:l("scmSelectFileHint")}),K&&!H&&!b&&e.jsx("div",{className:"scm-empty",children:l("scmLoading")}),K&&H&&H.untracked&&e.jsx("div",{className:"scm-empty",children:l("scmUntrackedNote")}),K&&H&&!H.untracked&&e.jsxs(e.Fragment,{children:[H.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:l("scmStaged")}),Ue(H.staged)]}),H.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:l("scmUnstaged")}),Ue(H.worktree)]}),!H.staged&&!H.worktree&&e.jsx("div",{className:"scm-empty",children:l("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(Je,{}),e.jsx("span",{children:l("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:o,children:l("scmViewTerminal")})]})]})}function yr({entry:t,send:s}){const n=r.useRef(null);return r.useEffect(()=>{const a=n.current;if(!a)return;let o;try{o=t.module.mount(a,$i(t.info.id,l=>s(l)))}catch(l){console.error(`[plugin:${t.info.id}] mount failed:`,l),a.textContent=`插件 ${t.info.name} 挂载失败`}return()=>{if(typeof o=="function")try{o()}catch(l){console.error(`[plugin:${t.info.id}] cleanup failed:`,l)}a.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:n})}function kr({send:t,piConfigured:s,piAgentInstalled:n,providers:a,installResult:o,onClose:l}){const i=fe(),[c,d]=r.useState(!1),[u,f]=r.useState(""),[h,x]=r.useState(""),[v,T]=r.useState(!1);r.useEffect(()=>{t({type:"list_providers"})},[t]),r.useEffect(()=>{s&&l()},[s,l]),r.useEffect(()=>{o&&d(!1)},[o]),r.useEffect(()=>{var G;!u&&a.length>0&&f(((G=a.find(I=>!I.configured))==null?void 0:G.id)??a[0].id)},[a,u]);const R=()=>{c||(d(!0),t({type:"install_pi_agent"}))},O=()=>{!h.trim()||v||(T(!0),t({type:"set_provider_api_key",provider:u.trim(),apiKey:h.trim()}),setTimeout(()=>T(!1),3e3))},y=()=>{t({type:"get_state"}),t({type:"list_providers"})},C=a.find(G=>G.id===u),z=o!==null&&!o.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:l,children:e.jsx(Se,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(rt,{className:"modal-head-icon"}),e.jsx("h2",{children:i("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:i("setupDesc")}),z?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:i("installFailed")}),e.jsx("pre",{className:"setup-detail",children:o.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:c,onClick:R,children:i("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:l,children:i("skip")})]})]}):n||o!=null&&o.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:o!=null&&o.ok?i("installDone"):i("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:i("provider")}),e.jsxs("select",{value:u,onChange:G=>f(G.target.value),children:[a.length===0&&e.jsx("option",{value:"",children:i("loading")}),a.map(G=>e.jsxs("option",{value:G.id,children:[G.name,"(",G.id,")",G.configured?` · ${i("configured")}`:""]},G.id))]}),(C==null?void 0:C.configured)&&e.jsx("div",{className:"field-hint",children:i("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:i("apiKey")}),e.jsx("input",{type:"password",value:h,onChange:G=>x(G.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!h.trim()||v||!u,onClick:O,children:i(v?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:y,children:[e.jsx(at,{})," ",i("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:c,onClick:R,children:i(c?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:l,children:i("skip")})]})]})})}const br=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],Vt=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),jr=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[Vt()]});function Pt(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:[Vt()]).map(s=>{var n;return{id:s.id,name:s.name??"",reasoning:s.reasoning??!1,input:(n=s.input)!=null&&n.includes("image")?"text-image":"text",contextWindow:s.contextWindow?String(s.contextWindow):"",maxTokens:s.maxTokens?String(s.maxTokens):""}})}}function wr({send:t,providers:s,providerStatus:n,providerKeys:a,fetchModelsResult:o,refreshProviderResult:l,cloneProviderResult:i,onClose:c}){const d=fe(),[u,f]=r.useState(null),[h,x]=r.useState({}),[v,T]=r.useState({}),[R,O]=r.useState(null),[y,C]=r.useState(!1),[z,G]=r.useState(0),[I,F]=r.useState(null),E=r.useRef(0),[K,j]=r.useState({});r.useRef(0);const H=r.useRef(0),[J,se]=r.useState(null),[W,V]=r.useState(null);r.useRef(0);const q=r.useRef(0),[k,w]=r.useState(null),[b,L]=r.useState(""),[$,ie]=r.useState(null);r.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"}),t({type:"list_provider_keys"})},[t]);const de=()=>{if(!u)return;const N=u.baseUrl.trim();if(!N){F({ok:!1,text:d("fetchModelsNeedBaseUrl")});return}if(y)return;C(!0),F(null);const Y=z+1;G(Y),t({type:"fetch_models",reqId:Y,baseUrl:N,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};r.useEffect(()=>{var N;if(!(!o||o.reqId===E.current))if(E.current=o.reqId,C(!1),o.ok&&((N=o.models)!=null&&N.length)){const Y=o.models;f(m=>{if(!m)return m;const P=m.models.map(ee=>{var pe;if(!ee.id.trim())return ee;const me=Y.find(Le=>Le.id===ee.id.trim());if(!me)return ee;const ke={...ee};return!ke.name&&me.name&&(ke.name=me.name),!ke.contextWindow&&me.contextWindow&&(ke.contextWindow=String(me.contextWindow)),!ke.maxTokens&&me.maxTokens&&(ke.maxTokens=String(me.maxTokens)),ke.input==="text"&&((pe=me.input)!=null&&pe.includes("image"))&&(ke.input="text-image"),!ke.reasoning&&me.reasoning&&(ke.reasoning=!0),ke}),g=new Set(P.map(ee=>ee.id.trim()).filter(Boolean)),D=Y.filter(ee=>!g.has(ee.id)).map(ee=>{var me;return{id:ee.id,name:ee.name??"",reasoning:ee.reasoning??!1,input:(me=ee.input)!=null&&me.includes("image")?"text-image":"text",contextWindow:ee.contextWindow?String(ee.contextWindow):"",maxTokens:ee.maxTokens?String(ee.maxTokens):""}}),Z=[...P,...D];return Z.some(ee=>ee.id.trim())?{...m,models:Z.filter(ee=>ee.id.trim())}:m}),F({ok:!0,text:d("fetchModelsOk",{n:Y.length})})}else F({ok:!1,text:o.error||d("fetchModelsEmpty")})},[o]);const he=N=>{const Y=(h[N.id]??"").trim();!Y||R||(O(N.id),t({type:"add_provider_key",provider:N.id,apiKey:Y,name:(v[N.id]??"").trim()||void 0}),setTimeout(()=>{O(null),x(m=>({...m,[N.id]:""})),T(m=>({...m,[N.id]:""})),t({type:"list_providers"}),t({type:"list_provider_keys"})},1500))},p=(N,Y)=>{t({type:"activate_provider_key",provider:N,keyName:Y}),t({type:"list_provider_keys"})},U=(N,Y)=>{window.confirm(d("removeKeyConfirm"))&&(t({type:"remove_provider_key",provider:N,keyName:Y}),t({type:"list_provider_keys"}))},B=()=>{if(!$)return;const N=$.providerId.trim();if(!N||!$.apiKey.trim())return;const Y=$.models.filter(P=>P.id.trim()).map(P=>({id:P.id.trim(),name:P.name.trim()||void 0,reasoning:P.reasoning||void 0,input:P.input==="text-image"?["text","image"]:void 0,contextWindow:P.contextWindow?Number(P.contextWindow):void 0,maxTokens:P.maxTokens?Number(P.maxTokens):void 0})),m={providerId:N,name:$.name.trim()||void 0,api:$.api.trim()||void 0,baseUrl:$.baseUrl.trim()||void 0,apiKey:$.apiKey.trim()||void 0,authHeader:$.authHeader||void 0,models:Y};t({type:"save_model_config",providerId:N,config:m}),ie(null),c()},Q=()=>{if(!u)return;const N=u.providerId.trim(),Y=u.models.filter(P=>P.id.trim()).map(P=>({id:P.id.trim(),name:P.name.trim()||void 0,reasoning:P.reasoning||void 0,input:P.input==="text-image"?["text","image"]:void 0,contextWindow:P.contextWindow?Number(P.contextWindow):void 0,maxTokens:P.maxTokens?Number(P.maxTokens):void 0})),m={providerId:N,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:Y};t({type:"save_model_config",providerId:N,config:m}),c()};r.useEffect(()=>{!l||l.reqId===H.current||(H.current=l.reqId,j({}))},[l]),r.useEffect(()=>{if(!(!i||i.reqId===q.current)){if(q.current=i.reqId,se(null),i.ok){const N=i.configs;if(N&&N.length>1){w(N.map(Y=>Pt({...Y,apiKey:""}))),L(""),V(null);return}if(i.config){ie(Pt({...i.config,apiKey:""})),V(null);return}}i.error&&V({ok:!1,text:i.error})}},[i]);const ne=N=>{window.confirm(d("clearKeyConfirm",{id:N}))&&t({type:"clear_provider_api_key",provider:N})},re=N=>{window.confirm(d("deleteProviderConfirm",{id:N.providerId,n:N.models.length}))&&t({type:"delete_model_config",providerId:N.providerId})},ue=(N,Y)=>{u&&f({...u,models:u.models.map((m,P)=>P===N?{...m,...Y}:m)})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal model-modal",onClick:N=>N.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":d("close"),onClick:c,children:e.jsx(Se,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:$?"添加密钥":k?`批量创建供应商 (${k.length}个接口)`:d(u?"editProvider":"manageModelsTitle")})}),$?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsxs("p",{className:"modal-desc",style:{marginBottom:12},children:["为 ",e.jsx("strong",{children:$.api})," · ",$.baseUrl||"(无 baseUrl)"," · ",$.models.length," 个模型添加第二把密钥,只需指定新供应商名字和密钥即可。"]}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["供应商名字 ",e.jsx("em",{children:"(新 ID,如 opencode-2)"})]}),e.jsx("input",{type:"text",value:$.providerId,onChange:N=>ie({...$,providerId:N.target.value}),placeholder:"opencode-2"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"API 密钥"}),e.jsx("input",{type:"password",value:$.apiKey,onChange:N=>ie({...$,apiKey:N.target.value}),placeholder:"sk-… 第二把 key"})]})]}),e.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:8},children:[$.models.slice(0,5).map(N=>N.id).join(", "),$.models.length>5?` … +${$.models.length-5}`:""]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>ie(null),children:d("cancel")}),e.jsx("button",{type:"button",className:"btn",onClick:()=>{const N=$;ie(null),f(N)},children:"高级编辑"}),e.jsx("button",{type:"button",className:"btn primary",disabled:!$.providerId.trim()||!$.apiKey.trim(),onClick:B,children:d("save")})]})]}):k?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsxs("p",{className:"modal-desc",style:{marginBottom:12},children:["该供应商含多种接口(",k.map(N=>N.api).join("、"),"),已按接口拆分为 ",k.length," 个自定义供应商,分别保存后才能让所有模型(如 muse-spark)都可用。统一填入第二把 API 密钥后一键保存。"]}),e.jsxs("label",{className:"field",style:{marginBottom:16},children:[e.jsxs("span",{className:"field-label",children:["统一 API 密钥(将应用到全部 ",k.length," 个供应商)"]}),e.jsx("input",{type:"password",value:b,onChange:N=>L(N.target.value),placeholder:"sk-… 第二把 key"})]}),e.jsx("div",{className:"provider-list",style:{marginBottom:16},children:k.map((N,Y)=>e.jsxs("div",{className:"provider-row",style:{flexDirection:"column",alignItems:"stretch",gap:6},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[e.jsx("strong",{children:N.providerId}),e.jsx("span",{style:{opacity:.7},children:N.api})]}),e.jsxs("div",{className:"provider-sub",style:{fontSize:12,opacity:.7},children:[N.baseUrl||"(无 baseUrl)"," · ",N.models.length," 个模型:",N.models.slice(0,3).map(m=>m.id).join(", "),N.models.length>3?` … +${N.models.length-3}`:""]}),e.jsx("input",{type:"text",value:N.providerId,onChange:m=>w(P=>P.map((g,D)=>D===Y?{...g,providerId:m.target.value}:g)),placeholder:"供应商 ID",style:{fontSize:12}}),e.jsx("input",{type:"text",value:N.baseUrl,onChange:m=>w(P=>P.map((g,D)=>D===Y?{...g,baseUrl:m.target.value}:g)),placeholder:"baseUrl 链接,如 https://api.opencode.ai/zen/v1 或 http://127.0.0.1:4096",style:{fontSize:12}})]},Y))})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>w(null),children:d("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!b.trim(),onClick:()=>{for(const N of k){const Y=N.providerId.trim();if(!Y)continue;const m=N.models.filter(g=>g.id.trim()).map(g=>({id:g.id.trim(),name:g.name.trim()||void 0,reasoning:g.reasoning||void 0,input:g.input==="text-image"?["text","image"]:void 0,contextWindow:g.contextWindow?Number(g.contextWindow):void 0,maxTokens:g.maxTokens?Number(g.maxTokens):void 0})),P={providerId:Y,name:N.name.trim()||void 0,api:N.api.trim()||void 0,baseUrl:N.baseUrl.trim()||void 0,apiKey:b.trim()||void 0,authHeader:N.authHeader||void 0,models:m};t({type:"save_model_config",providerId:Y,config:P})}w(null),c()},children:["一键保存全部 (",k.length,")"]})]})]}):u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[d("providerId")," ",e.jsx("em",{children:d("providerIdHint")})]}),e.jsx("input",{type:"text",value:u.providerId,disabled:s.some(N=>N.providerId===u.providerId),onChange:N=>f({...u,providerId:N.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:d("displayName")}),e.jsx("input",{type:"text",value:u.name,onChange:N=>f({...u,name:N.target.value}),placeholder:d("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:d("apiType")}),e.jsx("select",{value:u.api,onChange:N=>f({...u,api:N.target.value}),children:br.map(N=>e.jsx("option",{value:N,children:N},N))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:d("baseUrlHint")})]}),e.jsx("input",{type:"text",value:u.baseUrl,onChange:N=>f({...u,baseUrl:N.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:d("apiKey")}),e.jsx("input",{type:"password",value:u.apiKey,onChange:N=>f({...u,apiKey:N.target.value}),placeholder:d("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:N=>f({...u,authHeader:N.target.checked})}),e.jsx("span",{children:d("authHeader")})]})]}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:d("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[I&&e.jsx("span",{className:`fetch-msg ${I.ok?"ok":"err"}`,title:I.text,children:I.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:y||!u.baseUrl.trim(),title:d("fetchModelsHint"),onClick:de,children:[e.jsx(Wt,{})," ",d(y?"fetchingModels":"fetchModels")]})]})]}),u.models.map((N,Y)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:N.id,onChange:m=>ue(Y,{id:m.target.value}),placeholder:d("modelIdReq")}),e.jsx("input",{type:"text",value:N.name,onChange:m=>ue(Y,{name:m.target.value}),placeholder:d("displayName")}),e.jsxs("select",{value:N.input,onChange:m=>ue(Y,{input:m.target.value}),children:[e.jsx("option",{value:"text",children:d("text")}),e.jsx("option",{value:"text-image",children:d("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:N.reasoning,onChange:m=>ue(Y,{reasoning:m.target.checked})}),e.jsx("span",{children:d("reasoning")})]}),e.jsx("input",{type:"number",value:N.contextWindow,onChange:m=>ue(Y,{contextWindow:m.target.value}),placeholder:d("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:N.maxTokens,onChange:m=>ue(Y,{maxTokens:m.target.value}),placeholder:d("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:d("removeModel"),onClick:()=>f({...u,models:u.models.filter((m,P)=>P!==Y)}),children:e.jsx(Ie,{})})]},Y)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>f({...u,models:[...u.models,Vt()]}),children:[e.jsx(Ae,{})," ",d("addModel")]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>f(null),children:d("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(N=>N.id.trim()),onClick:Q,children:d("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-fixed-hint",children:e.jsxs("div",{className:"form-section-title",children:[d("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:d("hintKeyOnly")})]})}),e.jsxs("div",{className:"model-modal-body",children:[e.jsxs("div",{className:"provider-list",children:[n.length===0&&e.jsx("div",{className:"dd-loading",children:d("loading")}),n.map(N=>{const Y=a[N.id]??[];return e.jsxs("div",{className:"provider-row provider-key-row",children:[e.jsxs("div",{className:"provider-key-head",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:N.name}),e.jsxs("span",{className:"provider-sub",children:[N.id,N.configured&&e.jsx("span",{className:"auth-badge",children:d("configuredBadge")}),N.source&&!N.configured&&e.jsx("span",{className:"auth-badge dim",children:N.source})]})]}),N.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:d("clearKeyTitle"),onClick:()=>ne(N.id),children:[e.jsx(Ie,{})," ",d("clearKey")]})]}),e.jsxs("div",{className:"provider-keys",children:[Y.length===0&&e.jsx("div",{className:"provider-key-empty",children:d("noKeyYet")}),Y.map(m=>e.jsxs("div",{className:`provider-key-item ${m.active?"active":""}`,children:[e.jsx("span",{className:"provider-key-dot",children:m.active?"●":"○"}),e.jsx("span",{className:"provider-key-label",children:m.name}),!m.active&&e.jsx("button",{type:"button",className:"iconbtn",title:d("activateKey"),onClick:()=>p(N.id,m.name),children:e.jsx(ot,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:d("removeKey"),onClick:()=>U(N.id,m.name),children:e.jsx(Ie,{})})]},m.name)),e.jsxs("div",{className:"provider-add-key",children:[e.jsx("input",{type:"text",className:"key-input key-input-name",placeholder:d("keyNamePh"),value:v[N.id]??"",onChange:m=>T(P=>({...P,[N.id]:m.target.value}))}),e.jsx("input",{type:"password",className:"key-input key-input-value",placeholder:d("addKeyPlaceholder"),value:h[N.id]??"",onChange:m=>x(P=>({...P,[N.id]:m.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(h[N.id]??"").trim()||R===N.id,onClick:()=>he(N),children:[e.jsx(Ae,{})," ",R===N.id?d("savingKey"):d("addKey")]})]})]})]},N.id)})]}),e.jsx("div",{className:"form-section-title",children:d("customProviders")}),e.jsx("p",{className:"modal-desc",children:d("customDesc")}),s.length===0&&e.jsx("div",{className:"dd-loading",children:d("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:s.map(N=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:N.providerId}),e.jsxs("span",{className:"provider-sub",children:[N.api??"—",N.baseUrl?` · ${N.baseUrl}`:"",N.models.length>0&&` · ${d("modelsCount",{n:N.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:d("edit"),onClick:()=>f(Pt(N)),children:e.jsx(Qs,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:d("delete"),onClick:()=>re(N),children:e.jsx(Ie,{})})]})]},N.providerId))})]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>f(jr()),children:[e.jsx(Ae,{})," ",d("addProvider")]})})]})]})})}function Nr({plugin:t,send:s}){const n=fe(),a=t.settingsSchema??[],[o,l]=r.useState(()=>({...t.settingsValues??{}})),[i,c]=r.useState(!1);if(a.length===0)return null;const d=(x,v)=>l(T=>({...T,[x]:v})),u=a.some(x=>{var v;return o[x.key]!==((v=t.settingsValues)==null?void 0:v[x.key])}),f=()=>{c(!0),s({type:"plugin_settings",pluginId:t.id,values:o}),setTimeout(()=>c(!1),800)},h=()=>l({...t.settingsValues??{}});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:a.map(x=>e.jsxs("label",{className:"plugin-settings-field",title:x.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:x.label}),x.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!o[x.key],onChange:v=>d(x.key,v.target.checked)}):x.type==="select"?e.jsx("select",{value:String(o[x.key]??""),onChange:v=>d(x.key,v.target.value),children:(x.options??[]).map(v=>e.jsx("option",{value:v,children:v},v))}):e.jsx("input",{type:x.type==="password"?"password":x.type==="number"?"number":"text",value:String(o[x.key]??""),min:x.min,max:x.max,onChange:v=>d(x.key,x.type==="number"?Number(v.target.value):v.target.value)})]},x.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!u||i,onClick:f,children:n(i?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:h,children:n("pluginSettingsReset")})]})]})}function Cr(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function it({text:t}){const s=r.useRef(null),[n,a]=r.useState(!1),o=()=>{var i;const l=(i=s.current)==null?void 0:i.getBoundingClientRect();l&&a(window.innerWidth-l.right<340)};return e.jsxs("span",{ref:s,className:`set-tip${n?" flip":""}`,tabIndex:0,"aria-label":t,onMouseEnter:o,onFocus:o,children:["?",e.jsx("span",{className:"set-tip-bubble",role:"tooltip",children:t})]})}function _e({title:t,subtitle:s,tip:n,enabled:a,onToggle:o,action:l}){const i=fe();return e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[t,n&&e.jsx(it,{text:n})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),l,e.jsx("button",{type:"button",className:`set-switch ${a?"on":""}`,role:"switch","aria-checked":a,title:i(a?"settingsEnabled":"settingsDisabled"),onClick:o,children:e.jsx("span",{className:"set-switch-knob"})})]})}function Sr({chat:t,send:s,terminal:n,onSwitchToTerminal:a,onClose:o}){var Y,m,P;const l=fe(),i=t.settings,c=t.engine==="dsh",[d,u]=r.useState("prompt"),f=r.useRef(null);r.useEffect(()=>{var g;(g=f.current)==null||g.scrollTo({top:0})},[d]),r.useEffect(()=>{d==="plugins"&&t.engine==="dsh"&&s({type:"dsh_patches_list"})},[d,t.engine,s]);const[h,x]=r.useState(""),[v,T]=r.useState("append"),R=r.useRef(!1),[O,y]=r.useState(""),[C,z]=r.useState("append"),G=r.useRef(!1),[I,F]=r.useState(""),E=r.useRef(!1),[K,j]=r.useState(""),[H,J]=r.useState(!1),[se,W]=r.useState(null),[V,q]=r.useState(null);r.useEffect(()=>{i&&(T(i.promptMode),!R.current&&(x(v==="append"||i.customSystemPrompt?i.customSystemPrompt:i.defaultSystemPrompt||""),z(i.visionBridgePromptMode),!G.current&&(y(C==="append"||i.visionBridgePrompt?i.visionBridgePrompt:i.visionBridgeDefaultPrompt||""),E.current||F(i.reviewPrompt))))},[i,v,C]);const[k,w]=r.useState(String((i==null?void 0:i.terminalBashIdleMs)??15e3));if(r.useEffect(()=>{w(String((i==null?void 0:i.terminalBashIdleMs)??15e3))},[i==null?void 0:i.terminalBashIdleMs]),!i)return null;const b=[{id:"prompt",icon:e.jsx(Gs,{}),label:l("settingsSystemPrompt")},{id:"terminal",icon:e.jsx(Je,{}),label:l("settingsTerminalTools")},{id:"display",icon:e.jsx(Xe,{}),label:l("settingsMessageDisplay")},{id:"skills",icon:e.jsx(rt,{}),label:l("settingsSkills"),count:i.skills.length},{id:"extensions",icon:e.jsx(ms,{}),label:l("settingsExtensions"),count:i.extensions.length},{id:"plugins",icon:e.jsx(Nt,{}),label:l("settingsUiPlugins"),count:t.plugins.length},{id:"review",icon:e.jsx(ut,{}),label:l("settingsReview"),count:i.reviewSkills.length},...c?[]:[{id:"vision",icon:e.jsx(Bt,{}),label:l("settingsVisionBridge")}],{id:"presets",icon:e.jsx(Zn,{}),label:l("settingsPresets"),count:i.presets.length}],L=new Set(i.disabledSkills),$=new Set(i.disabledExtensions),ie=g=>s({type:"set_settings",...g}),de=g=>{const D=new Set(L);D.has(g.name)?D.delete(g.name):D.add(g.name),ie({disabledSkills:[...D]})},he=new Set(i.disabledPlugins??[]),p=g=>{const D=new Set(he);D.has(g.id)?D.delete(g.id):D.add(g.id),ie({disabledPlugins:[...D]})},U=g=>{const D=new Set($);D.has(g.id)?D.delete(g.id):D.add(g.id),ie({disabledExtensions:[...D]})},B=(g,D)=>{var ke,pe;const Z={name:g,command:D,cwd:"${pwd}"};let ee;const me=t.terminals.find(Le=>Le.title===g);me?(n.restart(me.id),s({type:"run_command",terminalId:me.id,conversationId:me.conversationId,command:Z,cols:80,rows:24}),ee=me.id):(ee=Fe(),n.create({id:ee,conversationId:t.activeConversationId||((ke=t.state)==null?void 0:ke.conversationId)||"",title:g,cwd:((pe=t.state)==null?void 0:pe.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Z})),n.select(ee),a(),o()},Q=g=>{W(null),B(`${l("uninstallTitle")} ${g}`,`pi remove npm:${g}`)},ne=g=>{q(null),B(`${l("uninstallTitle")} ${g}`,`pi-web-ui uninstall ${g}`)},re=(g,D)=>{B(`${l("pluginUpdate")} ${g}`,`pi-web-ui install ${D} --name ${g} --force`)},ue=g=>{const D=new Set(i.reviewSkills.filter(Z=>!Z.enabled).map(Z=>Z.name));D.has(g.name)?D.delete(g.name):D.add(g.name),ie({reviewDisabledSkills:[...D]})},N=()=>{const g=v==="replace"&&i.defaultSystemPrompt&&h===i.defaultSystemPrompt?"":h;ie({promptMode:v,customSystemPrompt:g})};return e.jsx("div",{className:"modal-backdrop",onClick:o,children:e.jsxs("div",{className:"modal settings-modal",onClick:g=>g.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":l("close"),onClick:o,children:e.jsx(Se,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(ft,{className:"modal-head-icon"}),e.jsx("h2",{children:l("settingsTitle")}),e.jsx(it,{text:l("settingsDesc")})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-rail","aria-label":l("settingsTitle"),children:b.map(g=>e.jsxs("button",{type:"button",className:`settings-tab${d===g.id?" active":""}`,"aria-current":d===g.id?"true":void 0,title:g.label,onClick:()=>u(g.id),children:[e.jsx("span",{className:"settings-tab-icon",children:g.icon}),e.jsx("span",{className:"settings-tab-label",children:g.label}),g.count!==void 0&&e.jsx("span",{className:"set-count",children:g.count})]},g.id))}),e.jsxs("div",{className:"modal-body",ref:f,children:[d==="prompt"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ut,{className:"set-section-icon"}),l("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:l("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:v,onChange:g=>{const D=g.target.value;T(D),ie({promptMode:D})},children:[e.jsx("option",{value:"append",children:l("promptModeAppend")}),e.jsx("option",{value:"replace",children:l("promptModeReplace")})]}),e.jsx(it,{text:l(v==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:l("promptPlaceholder"),value:h,onFocus:()=>R.current=!0,onBlur:()=>{R.current=!1,N()},onChange:g=>x(g.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":H,onClick:()=>J(g=>!g),children:[l("settingsViewPrompt")," ",H?"▴":"▾"]}),H&&e.jsxs("div",{className:"set-prompt-view",children:[e.jsxs("div",{className:"set-prompt-view-head",children:[e.jsx("span",{children:l("settingsViewPromptHint")}),e.jsx(rn,{text:i.effectiveSystemPrompt})]}),i.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:i.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:l("settingsViewPromptEmpty")})]})]}),d==="terminal"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Je,{className:"set-section-icon"}),l("settingsTerminalTools")]}),e.jsx(_e,{title:l("terminalToolsEnabled"),tip:l("settingsTerminalToolsDesc"),enabled:i.terminalToolsEnabled,onToggle:()=>ie({terminalToolsEnabled:!i.terminalToolsEnabled})}),!i.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:l("terminalToolsOffHint")}),e.jsx(_e,{title:l("terminalBashTakeover"),tip:l("terminalBashTakeoverDesc"),enabled:i.terminalBash,onToggle:()=>ie({terminalBash:!i.terminalBash})}),i.terminalBash&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:l("terminalBashIdleMs")}),e.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:k,onChange:g=>w(g.target.value),onBlur:()=>{const g=Math.max(0,Math.floor(Number(k)||0));w(String(g)),g!==i.terminalBashIdleMs&&ie({terminalBashIdleMs:g})}})]})]}),d==="display"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Xe,{className:"set-section-icon"}),l("settingsMessageDisplay")]}),e.jsx(_e,{title:l("thinkingWrap"),tip:l("thinkingWrapDesc"),enabled:i.thinkingWrap??!0,onToggle:()=>ie({thinkingWrap:!(i.thinkingWrap??!0)})}),e.jsx(_e,{title:l("toolsWrap"),tip:l("toolsWrapDesc"),enabled:i.toolsWrap??!0,onToggle:()=>ie({toolsWrap:!(i.toolsWrap??!0)})})]}),d==="skills"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(rt,{className:"set-section-icon"}),l("settingsSkills"),e.jsx("span",{className:"set-count",children:i.skills.length})]}),i.skills.length===0?e.jsx("p",{className:"set-empty",children:l(c?"dshSkillsNote":"noSkills")}):e.jsx("div",{className:"set-list",children:i.skills.map(g=>e.jsx(_e,{title:g.name,subtitle:g.description,enabled:g.enabled,onToggle:()=>de(g)},g.name))})]}),d==="extensions"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ms,{className:"set-section-icon"}),l("settingsExtensions"),e.jsx("span",{className:"set-count",children:i.extensions.length})]}),i.extensions.length===0?e.jsx("p",{className:"set-empty",children:l(c?"dshExtensionsNote":"noExtensions")}):e.jsx("div",{className:"set-list",children:i.extensions.map(g=>{const D=g.id.startsWith("npm:")?g.id.slice(4):null;return e.jsx(_e,{title:g.name,subtitle:g.path,enabled:g.enabled,onToggle:()=>U(g),action:D?se===g.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:l("uninstallConfirmHint"),onClick:()=>Q(D),children:l("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:l("uninstallHint"),onClick:()=>W(g.id),children:[e.jsx(Ie,{}),l("uninstallExt")]}):void 0},g.id)})})]}),d==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Nt,{className:"set-section-icon"}),l("settingsUiPlugins"),e.jsx("span",{className:"set-count",children:t.plugins.length})]}),t.plugins.length===0?e.jsx("p",{className:"set-empty",children:l("noUiPlugins")}):e.jsx("div",{className:"set-list",children:t.plugins.map(g=>{var D;return e.jsxs(e.Fragment,{children:[e.jsx(_e,{title:`${g.icon?`${g.icon} `:""}${g.name}`,subtitle:(g.error?`${g.id} · ${g.error}`:g.source?`${g.id} · ${g.source}`:`${g.id} · ${l("uiPluginNoSource")}`)+((D=g.permissions)!=null&&D.length?` · ${l("uiPluginPerms")}: ${g.permissions.join(", ")}`:""),enabled:!he.has(g.id)&&!g.error,onToggle:()=>!g.error&&p(g),action:e.jsxs("div",{className:"set-row-actions",children:[g.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:l("pluginUpdateHint"),onClick:()=>re(g.id,g.source),children:[e.jsx(at,{}),l("pluginUpdate")]}),V===g.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:l("pluginUninstallHint"),onClick:()=>ne(g.id),children:l("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:l("pluginUninstallHint"),onClick:()=>q(g.id),children:[e.jsx(Ie,{}),l("uninstallExt")]})]})},g.id),g.settingsSchema&&g.settingsSchema.length>0&&e.jsx(Nr,{plugin:g,send:s})]})})})]}),d==="plugins"&&t.engine==="dsh"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Nt,{className:"set-section-icon"}),l("dshPatches"),e.jsx(it,{text:l("dshPatchesDesc")}),e.jsx("span",{className:"set-count",children:((Y=t.dshPatches)==null?void 0:Y.files.length)??0}),e.jsxs("button",{type:"button",className:"set-uninstall",title:l("dshPatchesRescanHint"),onClick:()=>s({type:"dsh_patches_rescan"}),children:[e.jsx(at,{}),l("dshPatchesRescan")]})]}),(((m=t.dshPatches)==null?void 0:m.files.length)??0)===0?e.jsx("p",{className:"set-empty",children:l("dshPatchesEmpty")}):e.jsx("div",{className:"set-list",children:t.dshPatches.files.map(g=>e.jsx("div",{className:"set-row",children:e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:g.name}),e.jsxs("div",{className:"set-row-desc",children:[Cr(g.size)," · ",new Date(g.mtimeMs).toLocaleString()]})]})},g.name))}),e.jsxs("p",{className:"set-hint",children:[l("dshPatchesPath")," ",((P=t.dshPatches)==null?void 0:P.patchDir)??""]})]}),d==="review"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ut,{className:"set-section-icon"}),l("settingsReview"),e.jsx(it,{text:l("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:i.reviewSkills.length})]}),c&&e.jsx("p",{className:"set-hint",children:l("dshReviewPromptNote")}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:l("reviewPromptPlaceholder"),value:I,onFocus:()=>E.current=!0,onBlur:()=>{E.current=!1,ie({reviewPrompt:I})},onChange:g=>F(g.target.value)}),e.jsx("div",{className:"set-field-label",children:l("settingsReviewSkills")}),i.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:l("noSkills")}):e.jsx("div",{className:"set-list",children:i.reviewSkills.map(g=>e.jsx(_e,{title:g.name,subtitle:g.description,enabled:g.enabled,onToggle:()=>ue(g)},`review-${g.name}`))})]}),d==="vision"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Bt,{className:"set-section-icon"}),l("settingsVisionBridge")]}),e.jsx(_e,{title:l("visionBridgeEnabled"),tip:l("settingsVisionBridgeDesc"),enabled:i.visionBridgeEnabled,onToggle:()=>ie({visionBridgeEnabled:!i.visionBridgeEnabled})}),!i.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:l("visionBridgeOffHint")}),i.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:l("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:i.visionBridgeModel??"",onChange:g=>ie({visionBridgeModel:g.target.value||null}),children:[e.jsx("option",{value:"",children:l("visionBridgeAuto")}),i.visionModels.map(g=>e.jsx("option",{value:`${g.provider}/${g.id}`,children:g.label},`${g.provider}/${g.id}`))]})]}),i.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:l("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:C,onChange:g=>{const D=g.target.value;z(D),ie({visionBridgePromptMode:D})},children:[e.jsx("option",{value:"append",children:l("promptModeAppend")}),e.jsx("option",{value:"replace",children:l("promptModeReplace")})]})]}),i.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:l("visionBridgePromptPlaceholder"),value:O,onFocus:()=>G.current=!0,onBlur:()=>{G.current=!1;const g=C==="replace"&&i.visionBridgeDefaultPrompt&&O===i.visionBridgeDefaultPrompt?"":O;ie({visionBridgePromptMode:C,visionBridgePrompt:g})},onChange:g=>y(g.target.value)}),i.visionBridgeEnabled&&(i.visionModels.length===0?e.jsx("p",{className:"set-hint",children:l("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:l("visionBridgeCurrent",{model:i.visionBridgeModel??l("visionBridgeAuto")})}))]}),d==="presets"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ft,{className:"set-section-icon"}),l("settingsPresets"),e.jsx("span",{className:"set-count",children:i.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:l("presetNamePlaceholder"),value:K,onChange:g=>j(g.target.value),onKeyDown:g=>{g.key==="Enter"&&K.trim()&&(s({type:"save_preset",name:K.trim()}),j(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!K.trim(),onClick:()=>{s({type:"save_preset",name:K.trim()}),j("")},children:[e.jsx(Ae,{})," ",l("saveAsPreset")]})]}),i.presets.length===0?e.jsx("p",{className:"set-empty",children:l("noPresets")}):e.jsx("div",{className:"set-list",children:i.presets.map(g=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:g.name}),e.jsxs("div",{className:"set-row-desc",children:[g.promptMode==="replace"?l("promptModeReplace"):l("promptModeAppend"),g.disabledSkills.length>0&&` · ${l("settingsSkills")} ${g.disabledSkills.length}`,g.disabledExtensions.length>0&&` · ${l("settingsExtensions")} ${g.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:g.name}),children:l("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:l("deletePreset"),onClick:()=>s({type:"delete_preset",name:g.name}),children:e.jsx(Ie,{})})]})]},g.name))})]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:o,children:l("close")})})]})})}function Tr(t,s){const n=Math.max(0,Date.now()-t),a=Math.floor(n/6e4);if(a<1)return s("bgTaskJustNow");if(a<60)return s("bgTaskMinutes",{n:a});const o=Math.floor(a/60);return o<24?s("bgTaskHours",{n:o}):s("bgTaskDays",{n:Math.floor(o/24)})}function Er({servers:t,send:s,onClose:n}){const a=fe(),[o,l]=r.useState(new Set),i=c=>l(d=>{const u=new Set(d);return u.has(c)?u.delete(c):u.add(c),u});return r.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"bg-task-modal",onClick:c=>c.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(vt,{})," ",a("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:a("close"),onClick:n,children:e.jsx(Se,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(vt,{}),e.jsx("span",{children:a("bgTasksEmpty")}),e.jsx("small",{children:a("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(c=>{const d=!!c.taskId,u=c.taskId??String(c.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:d?c.plugin:a("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[d?e.jsxs("span",{className:"bg-task-port",title:c.taskId,children:["🧩 ",c.plugin]}):e.jsxs("span",{className:"bg-task-port",children:[":",c.port]}),c.name&&e.jsx("span",{className:"bg-task-name",children:c.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[!d&&e.jsxs("span",{children:[a("bgTaskPid")," ",c.pid]}),e.jsxs("span",{children:[a("bgTaskSince")," ",Tr(c.since,a)]}),d&&c.status&&e.jsx("span",{className:"bg-task-status",children:c.status})]}),c.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${o.has(u)?"open":""}`,title:`${a("bgTaskCommand")}: ${c.command}`,onClick:()=>i(u),children:[e.jsx(Je,{}),e.jsx("code",{children:c.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:a("bgTaskStop"),onClick:()=>s(d?{type:"kill_background_server",taskId:c.taskId}:{type:"kill_background_server",port:c.port}),children:[e.jsx(gt,{}),e.jsx("span",{children:a("bgTaskStop")})]})]},u)})}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:a("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(at,{}),e.jsx("span",{children:a("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:a("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(gt,{}),e.jsx("span",{children:a("bgTaskStopAll")})]})]})]})})}function Mr(t,s){return t.toLowerCase().includes(s)}function Rr({open:t,send:s,projects:n,cwd:a,fileSearch:o,sessionSearch:l,onClose:i,onSwitchSession:c,onSwitchProject:d,onPreviewFile:u}){const f=fe(),h=r.useRef(null),[x,v]=r.useState(""),T=r.useDeferredValue(x),[R,O]=r.useState(0),y=r.useRef(1),C=r.useRef(0),z=r.useRef(null);r.useEffect(()=>{if(!t)return;s({type:"list_sessions"}),s({type:"list_projects"});const k=x.trim();if(k){const w=++y.current;C.current=w,I(!0),s({type:"search_files",reqId:w,query:k}),s({type:"search_sessions",reqId:w,query:k})}requestAnimationFrame(()=>{var w;return(w=h.current)==null?void 0:w.select()})},[t]);const[G,I]=r.useState(!1);r.useEffect(()=>{z.current&&clearTimeout(z.current);const k=T.trim();if(!k){I(!1);return}return z.current=setTimeout(()=>{const w=++y.current;C.current=w,I(!0),s({type:"search_files",reqId:w,query:k}),s({type:"search_sessions",reqId:w,query:k})},300),()=>{z.current&&clearTimeout(z.current)}},[T]);const F=T.trim().toLowerCase(),E=r.useMemo(()=>!F||!l||l.reqId!==C.current||!l.ok?[]:l.results,[l,F]),K=r.useMemo(()=>F?n.filter(k=>Mr(k.path,F)).slice(0,10):[],[n,F]),j=r.useMemo(()=>!F||!o||o.reqId!==C.current||!o.ok?[]:o.results,[o,F]);r.useEffect(()=>{o&&o.reqId===C.current&&l&&l.reqId===C.current&&C.current!==0&&I(!1)},[o,l]);const H=!!o&&o.ok&&o.truncated,J=r.useMemo(()=>[...E.map(k=>({kind:"session",path:k.path,anchors:k.anchors})),...K.map(k=>({kind:"project",path:k.path})),...j.filter(k=>k.type==="file").map(k=>({kind:"file",path:k.path,name:k.name}))],[E,K,j]);r.useEffect(()=>{O(0)},[T]);const se=r.useCallback(k=>{if(k)if(k.kind==="session")c(k.path,k.anchors),i();else if(k.kind==="project"){d(k.path),s({type:"list_sessions"}),s({type:"list_projects"});const w=T.trim();if(w){const b=++y.current;C.current=b,I(!0),s({type:"search_files",reqId:b,query:w}),s({type:"search_sessions",reqId:b,query:w})}}else u(k.path,k.name)},[c,d,u,s,T]);r.useEffect(()=>{if(!t)return;const k=w=>{w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),i()):w.key==="ArrowDown"?(w.preventDefault(),O(b=>Math.min(b+1,J.length-1))):w.key==="ArrowUp"?(w.preventDefault(),O(b=>Math.max(b-1,0))):w.key==="Enter"&&(w.preventDefault(),se(J[R]))};return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[J,R,se,i,t]);const W=E.length+K.length+j.length,V=(k,w,b)=>e.jsxs("div",{className:"gs-section-head",children:[b,e.jsx("span",{children:k}),e.jsx("em",{children:w})]});let q=-1;return t?e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:i,children:e.jsxs("div",{className:"gs-modal",onClick:k=>k.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(xt,{}),e.jsx("input",{ref:h,type:"text",value:x,placeholder:f("gsPlaceholder"),onChange:k=>v(k.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:f("close"),onClick:i,children:e.jsx(Se,{})})]}),e.jsxs("div",{className:"gs-results",children:[!F&&e.jsx("div",{className:"gs-empty",children:f("gsHint")}),F&&W===0&&!H&&e.jsx("div",{className:"gs-empty",children:f(G?"gsSearching":"gsNoResults")}),E.length>0&&e.jsxs("div",{className:"gs-section",children:[V(f("gsSessions"),E.length,e.jsx(Xe,{})),E.map(k=>{q++;const w=q;return e.jsxs("button",{type:"button",className:w===R?"gs-item active":"gs-item",onMouseEnter:()=>O(w),onClick:()=>se({kind:"session",path:k.path,anchors:k.anchors}),children:[e.jsxs("span",{className:"gs-item-title",children:[k.name||k.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:k.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:k.firstMessage})]},k.path)})]}),K.length>0&&e.jsxs("div",{className:"gs-section",children:[V(f("gsProjects"),K.length,e.jsx(Ze,{})),K.map(k=>{q++;const w=q,b=a&&k.path===a;return e.jsxs("button",{type:"button",className:w===R?"gs-item active":"gs-item",onMouseEnter:()=>O(w),onClick:()=>se({kind:"project",path:k.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[k.path.split(/[\\/]/).pop(),b&&e.jsx("em",{className:"gs-item-meta",children:f("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:k.path})]},k.path)})]}),(j.length>0||F&&H)&&e.jsxs("div",{className:"gs-section",children:[V(f("gsFiles"),j.length,e.jsx(Gs,{})),j.map(k=>{q++;const w=q;return e.jsxs("button",{type:"button",className:w===R?"gs-item active":"gs-item",disabled:k.type==="dir",title:k.type==="dir"?void 0:f("gsOpenPreview"),onMouseEnter:()=>O(w),onClick:()=>{k.type==="file"&&se({kind:"file",path:k.path,name:k.name})},children:[e.jsx("span",{className:"gs-item-title",children:k.name}),e.jsx("span",{className:"gs-item-sub",children:k.path})]},`${k.type}:${k.path}`)}),H&&e.jsx("div",{className:"gs-truncated",children:f("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",f("gsNavigate")]}),e.jsxs("span",{children:["Enter ",f("gsOpen")]}),e.jsxs("span",{children:["Esc ",f("gsCloseHint")]})]})]})}):null}const It=5e3;function Pr({file:t,content:s,send:n,onAddLines:a,onAttach:o,onClose:l}){const i=fe(),[c,d]=r.useState(null),[u,f]=r.useState(!1),[h,x]=r.useState(null),[v,T]=r.useState(!1),[R,O]=r.useState(!1),[y,C]=r.useState(!1),[z,G]=r.useState(""),[I,F]=r.useState(!0),E=r.useRef(!1),[K,j]=r.useState(!0),[H,J]=r.useState(!1),[se,W]=r.useState(100),V=r.useRef(0),q=r.useRef(!1),k=r.useRef(null);r.useEffect(()=>{f(!0),d(null),x(null),C(!1),G(""),F(!0),E.current=!1,n({type:"read_file",path:t.path})},[t.path,n]),r.useEffect(()=>{s&&s.path===t.path&&(d(s),y||G(s.text),f(!1))},[s,y,t.path]),r.useEffect(()=>{const D=Z=>{if(Z.key==="Escape"){Q();return}if((Z.ctrlKey||Z.metaKey)&&Z.key.toLowerCase()==="s"&&y){Z.preventDefault(),B();return}const ee=Z.target,me=ee&&(ee.tagName==="INPUT"||ee.tagName==="TEXTAREA"||ee.isContentEditable);(Z.ctrlKey||Z.metaKey)&&Z.key.toLowerCase()==="a"&&!me&&(Z.preventDefault(),ie())};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[l,c,y,z]),r.useEffect(()=>{const D=()=>{q.current=!1,T(!1)};return window.addEventListener("mouseup",D),()=>window.removeEventListener("mouseup",D)},[]);const w=r.useMemo(()=>{if(!c)return[];const D=c.text.split(`
|
|
321
|
-
`);return D.length>0&&D[D.length-1]===""&&D.pop(),D.slice(0,It)},[c]),b=(c==null?void 0:c.lines)??0,L=b>It,$=(D,Z)=>{if(Z){const ee=V.current>0?V.current:D;x({start:Math.min(ee,D),end:Math.max(ee,D)})}else V.current=D,x({start:D,end:D})},ie=()=>{w.length!==0&&(V.current=1,x({start:1,end:w.length}))},de=()=>{h&&(a(t.path,t.name,h.start,h.end),O(!0),k.current&&clearTimeout(k.current),k.current=setTimeout(()=>O(!1),1400))},he=c!==null&&c.kind==="text"&&!c.binary&&!c.truncated,p=()=>{G((c==null?void 0:c.text)??""),C(!1),E.current&&F(!0)},U=()=>{if(y){if(z!==((c==null?void 0:c.text)??"")&&!window.confirm(i("discardFileChanges")))return;p();return}!he||!c||(E.current=Lt(t.name)&&I,Lt(t.name)&&F(!1),x(null),G(c.text),C(!0))},B=()=>{!y||!c||!he||n({type:"write_file",path:t.path,text:z})&&(C(!1),E.current&&F(!0),x(null))},Q=()=>{y&&z!==((c==null?void 0:c.text)??"")&&!window.confirm(i("discardFileChanges"))||l()},ne=D=>{W(Math.min(200,Math.max(50,D)))},re=h?h.end-h.start+1:0,ue=(c==null?void 0:c.binary)??!1,N=(c==null?void 0:c.truncated)??!1,Y=(c==null?void 0:c.kind)??"text",m=Lt(t.name),P=m&&I&&!y&&Y==="text"&&!ue,g=D=>bt(et(`/api/file?clientId=${encodeURIComponent(qt())}&path=${encodeURIComponent(D)}`));return e.jsx("div",{className:`fp-overlay ${H?"fullscreen":""}`,onMouseDown:D=>{D.target===D.currentTarget&&Q()},children:e.jsxs("div",{className:`fp ${H?"fullscreen":""}`,style:{"--fp-zoom":se/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:[c&&Y==="text"&&!ue&&i("fileLines",{n:b}),c&&` · ${Ir(c.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[m&&Y==="text"&&!ue&&c&&e.jsx("button",{type:"button",className:`fp-attach markdown ${I?"on":""}`,"data-tip":i(I?"showMarkdownSource":"showMarkdownPreview"),disabled:y,onClick:()=>F(D=>!D),children:I?e.jsx(Bt,{}):e.jsx(mi,{})}),Y==="text"&&!ue&&c&&e.jsx("button",{type:"button",className:`fp-attach edit ${y?"on":""}`,"data-tip":i(N?"fileEditTruncated":y?"exitEditFile":"editFile"),disabled:!he&&!y,onClick:U,children:e.jsx(_t,{})}),Y==="text"&&!ue&&!P&&e.jsx("button",{type:"button",className:`fp-attach wrap ${K?"on":""}`,"data-tip":i(K?"disableWrap":"enableWrap"),onClick:()=>j(D=>!D),children:e.jsx(pi,{})}),Y==="text"&&c&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":i("zoomOut"),disabled:se<=50,onClick:()=>ne(se-10),children:e.jsx(Gn,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:i("resetZoom"),onClick:()=>W(100),children:[se,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":i("zoomIn"),disabled:se>=200,onClick:()=>ne(se+10),children:e.jsx(Qn,{})})]}),Y!=="video"&&Y!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":i("attachInlineTip"),onClick:()=>o(t.path,t.name,"inline"),children:e.jsx(Ae,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":i("referenceTip"),onClick:()=>o(t.path,t.name,"reference"),children:e.jsx(Dt,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${H?"on":""}`,"data-tip":i(H?"exitFullscreen":"fullscreen"),onClick:()=>J(D=>!D),children:H?e.jsx(ni,{}):e.jsx(ai,{})}),e.jsx("button",{type:"button",className:"fp-close",title:i("close"),onClick:Q,children:e.jsx(Se,{})})]})]}),N&&Y==="text"&&!ue&&e.jsx("div",{className:"fp-notice",children:i("previewTruncated")}),u&&!c&&e.jsx("div",{className:"fp-empty",children:i("loading")}),!u&&Y==="none"&&!ue&&e.jsx("div",{className:"fp-empty",children:i("previewNotSupported")}),!u&&Y==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:g(t.path),alt:t.name})}),!u&&Y==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:g(t.path),controls:!0,preload:"metadata"})}),!u&&P&&c&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(jt,{text:c.text})})}),!u&&ue&&Y!=="image"&&Y!=="video"&&c&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[i("binaryFile"),c.truncated&&i("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:c.text})]}),!u&&y&&Y==="text"&&!ue&&c&&e.jsx("textarea",{className:`fp-editor ${K?"":"no-wrap"}`,value:z,onChange:D=>G(D.target.value),wrap:K?"soft":"off",spellCheck:!1,autoFocus:!0}),!u&&!P&&!y&&Y==="text"&&!ue&&c&&w.length===0&&e.jsx("div",{className:"fp-empty",children:i("emptyFile")}),!u&&!P&&!y&&Y==="text"&&!ue&&w.length>0&&e.jsxs("div",{className:`fp-code ${v?"dragging":""} ${K?"":"no-wrap"}`,onMouseDown:D=>{D.button===0&&D.preventDefault()},children:[w.map((D,Z)=>{const ee=Z+1,me=h!==null&&ee>=h.start&&ee<=h.end;return e.jsxs("div",{className:`fp-line ${me?"sel":""}`,onMouseDown:ke=>{ke.button===0&&($(ee,ke.shiftKey),q.current=!0,T(!0))},onMouseEnter:()=>{q.current&&$(ee,!0)},children:[e.jsx("span",{className:"fp-num",children:ee}),e.jsx("span",{className:"fp-code-text",children:D})]},ee)}),L&&e.jsx("div",{className:"fp-lines-note",children:i("previewLinesTruncated",{n:It})})]}),e.jsx("div",{className:"fp-foot",children:y?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:i("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:U,children:i("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:z===((c==null?void 0:c.text)??""),onClick:B,children:[e.jsx(ei,{})," ",i("saveFile")]})]})]}):!P&&Y==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:h?i("selectedRange",{n:re,start:h.start,end:h.end}):i("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:w.length===0,onClick:ie,children:i("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!h,onClick:()=>x(null),children:i("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!h||ue,onClick:de,children:[R?e.jsx(ot,{}):null,i(R?"addedToChat":"addToChat")]})]})]})})]})})}function Lt(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function Ir(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",tt={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function Sn(){try{const t=localStorage.getItem(Cn);if(!t)return{...tt};const s=JSON.parse(t),n={...tt,...s};for(const a of["enabled","question","done","start","error"])typeof n[a]!="boolean"&&(n[a]=tt[a]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=tt.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...tt}}}function Lr(t){try{localStorage.setItem(Cn,JSON.stringify(t))}catch{}}let st=null;function Dr(){try{if(!st){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;st=new t}return st.state==="suspended"&&st.resume(),st}catch{return null}}const Br=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],_r=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],Ar=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],$r=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],Fr={question:Br,done:_r,start:Ar,error:$r};function Hr(t,s,n){const a=t.createOscillator(),o=t.createGain();a.type=s.type,a.frequency.value=s.freq;const l=t.currentTime+s.start,i=Math.max(1e-4,s.peak*n);o.gain.setValueAtTime(1e-4,l),o.gain.exponentialRampToValueAtTime(i,l+.012),o.gain.exponentialRampToValueAtTime(1e-4,l+s.dur),a.connect(o),o.connect(t.destination),a.start(l),a.stop(l+s.dur+.05)}function nt(t,s=Sn()){if(!s.enabled||!s[t])return;const n=Dr();if(!n)return;const a=Math.max(0,Math.min(1,s.volume/100));for(const o of Fr[t])Hr(n,o,a)}const Kt="pi-web-ui:theme",Tn="dark",Ds="theme-stylesheet",Bs="pi-web-ui:theme-change";function En(){try{const t=localStorage.getItem(Kt);if(t&&t!==Tn)return t}catch{}return null}function Kr(t){try{t?localStorage.setItem(Kt,t):localStorage.removeItem(Kt)}catch{}}function Mn(t){let s=document.getElementById(Ds);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(Bs));return}s||(s=document.createElement("link"),s.id=Ds,s.rel="stylesheet",document.head.appendChild(s)),s.href=et(`/themes/${encodeURIComponent(t)}.css`),s.onload=()=>window.dispatchEvent(new CustomEvent(Bs))}async function Or(){try{const t=await fetch(bt(et("/api/themes")));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function Wr(){const[t,s]=r.useState([]),[n,a]=r.useState(()=>En());return r.useEffect(()=>{let l=!1;return Or().then(i=>{l||s(i)}),()=>{l=!0}},[]),r.useEffect(()=>{Mn(n),Kr(n)},[n]),{themes:t,theme:n,switchTheme:l=>a(l===Tn?null:l)}}function Jr(){const t=getComputedStyle(document.documentElement),s=(n,a)=>t.getPropertyValue(n).trim()||a;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 Ur=r.lazy(()=>Hn(()=>import("./TerminalPanel-BkCWDsIG.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function qr({notice:t,onDismiss:s}){const n=fe(),[a,o]=r.useState(!1);r.useEffect(()=>{if(a)return;const i=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(i)},[a,t.id,t.level,s]);const l=t.level==="error"?xi:t.level==="warning"?fi:oi;return e.jsxs("div",{className:`notice notice-${t.level}${a?" paused":""}`,role:"status",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[e.jsx(l,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:t.text}),e.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>s(t.id),children:e.jsx(Se,{})})]})}const zr=[],Rn=180,Pn=520,In=240,Ln=t=>`pi-web-ui:${t}-panel-width`;function _s(t){const s=Number(localStorage.getItem(Ln(t)));return Number.isFinite(s)&&s>=Rn&&s<=Pn?s:In}const Ot=t=>`pi-web-ui:${t}-panel-collapsed`;function As(t){return localStorage.getItem(Ot(t))==="1"}function $s({side:t,width:s,onResize:n}){const a=fe(),o=r.useCallback(l=>{l.preventDefault();const i=l.clientX,c=s;let d=c;const u=h=>{const x=t==="left"?h.clientX-i:i-h.clientX;d=Math.min(Pn,Math.max(Rn,Math.round(c+x))),n(d)},f=()=>{window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",f),document.body.classList.remove("panel-resizing"),localStorage.setItem(Ln(t),String(d))};window.addEventListener("pointermove",u),window.addEventListener("pointerup",f),document.body.classList.add("panel-resizing")},[t,s,n]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:a("dragToResize"),onPointerDown:o,onDoubleClick:()=>n(In)})}function Fs({side:t,onClick:s}){const n=fe();return e.jsx("button",{type:"button",className:`panel-rail panel-rail-${t}`,title:n("expandPanel"),onClick:s,children:t==="left"?e.jsx(Js,{}):e.jsx(Xs,{})})}function Vr(){var Be,Gt,Qt,Yt,Jt,Xt,Zt,es,ts,ss,ns,is,as,rs;const t=fe(),{chat:s,send:n,dismissNotice:a,pushNotice:o,terminal:l}=qi(),[i,c]=r.useState([]),[d,u]=r.useState(null),[f,h]=r.useState(!1),[x,v]=r.useState("chat"),T=r.useMemo(()=>s.plugins.filter(A=>{var X,oe;return!((oe=(X=s.settings)==null?void 0:X.disabledPlugins)!=null&&oe.includes(A.id))}),[s.plugins,(Be=s.settings)==null?void 0:Be.disabledPlugins]),[R,O]=r.useState([]);r.useEffect(()=>_i(O),[]),r.useEffect(()=>{Ai(T,s.pluginsEpoch)},[T,s.pluginsEpoch]);const[y,C]=r.useState(()=>_s("left")),[z,G]=r.useState(()=>_s("right")),I=r.useCallback(A=>C(A),[]),F=r.useCallback(A=>G(A),[]),[E,K]=r.useState(()=>As("left")),[j,H]=r.useState(()=>As("right")),J=r.useCallback(()=>{K(A=>(localStorage.setItem(Ot("left"),A?"0":"1"),!A))},[]),se=r.useCallback(()=>{H(A=>(localStorage.setItem(Ot("right"),A?"0":"1"),!A))},[]),[W,V]=r.useState(null),[q,k]=r.useState(()=>window.matchMedia("(max-width: 768px)").matches);r.useEffect(()=>{const A=window.matchMedia("(max-width: 768px)"),X=oe=>k(oe.matches);return A.addEventListener("change",X),()=>A.removeEventListener("change",X)},[]);const[w,b]=r.useState(!1),[L,$]=r.useState(!1),[ie,de]=r.useState(!1),[he,p]=r.useState(!1),[U,B]=r.useState(!1),[Q,ne]=r.useState(null);r.useEffect(()=>{if(!Q)return;const A=setTimeout(()=>ne(null),15e3);return()=>clearTimeout(A)},[Q]),r.useEffect(()=>{const A=X=>{var He,ls;const oe=X.detail,be=(oe==null?void 0:oe.title)||"插件命令",we=oe==null?void 0:oe.command;if(!we||!s.ready)return;const Me={name:be,command:we,cwd:"${pwd}"},Ne=s.terminals.find(wt=>wt.title===be);if(Ne)l.restart(Ne.id),n({type:"run_command",terminalId:Ne.id,conversationId:Ne.conversationId,command:Me,cols:80,rows:24});else{const wt=Fe();l.create({id:wt,conversationId:s.activeConversationId||((He=s.state)==null?void 0:He.conversationId)||"",title:be,cwd:((ls=s.state)==null?void 0:ls.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Me})}v("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",A),()=>window.removeEventListener("pi-web-ui:plugin-run-command",A)},[s,l,n]),r.useEffect(()=>{const A=X=>{!(X.ctrlKey||X.metaKey)||X.key.toLowerCase()!=="k"||(X.preventDefault(),B(oe=>!oe))};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[]);const[re,ue]=r.useState(Sn),{themes:N,theme:Y,switchTheme:m}=Wr(),P=r.useRef(null),g=r.useRef(null),D=r.useRef(0),Z=r.useRef(!1),ee=r.useRef(s.terminals);r.useEffect(()=>{Lr(re)},[re]),r.useEffect(()=>{var X;const A=ee.current;ee.current=s.terminals;for(const oe of s.terminals){const be=((X=oe.command)==null?void 0:X.command)??"",we=A.find(Me=>Me.id===oe.id);!(we!=null&&we.running)||oe.running||(be.startsWith("pi remove ")?n({type:"extensions_reload"}):be.startsWith("pi-web-ui install ")||be.startsWith("pi-web-ui uninstall ")?n({type:"plugins_reload"}):be.startsWith("npm i -g ")&&(n({type:"extensions_reload"}),n({type:"plugins_reload"}),n({type:"check_updates_all",force:!0})))}},[s.terminals,n]),r.useEffect(()=>{var oe;const A=((oe=s.state)==null?void 0:oe.isStreaming)??!1,X=P.current;P.current=A,X!==null&&(!X&&A?nt("start",re):X&&!A&&nt("done",re))},[(Gt=s.state)==null?void 0:Gt.isStreaming,re]),r.useEffect(()=>{var X;const A=((X=s.dialog)==null?void 0:X.id)??null;A!==null&&A!==g.current&&nt("question",re),g.current=A},[s.dialog,re]),r.useEffect(()=>{const A=[...s.notices].reverse().find(X=>X.level==="error");A&&A.id!==D.current&&(D.current=A.id,nt("error",re))},[s.notices,re]);const me=(A,X,oe,be=!1,we)=>{const Me=`${A}|${oe}|${we?`${we.start}-${we.end}`:""}`;c(Ne=>Ne.some(He=>`${He.path}|${He.mode}|${He.lines?`${He.lines.start}-${He.lines.end}`:""}`===Me)?Ne:[...Ne,{path:A,name:X,mode:oe,isDir:be,...we?{lines:we}:{}}])},ke=A=>c(X=>X.filter(oe=>oe.key?oe.key!==A:oe.path!==A)),pe=r.useCallback(A=>(!A.type.startsWith("list_")&&!A.type.startsWith("get_")&&V(null),n(A)),[n]),Le=r.useRef(0),Pe=r.useRef(0),Oe=A=>{var be;const X=Date.now();(be=s.state)!=null&&be.model&&!s.state.model.vision&&X-Pe.current>1e4&&(Pe.current=X,o("warning",t("imageNotSupported")));const oe=`paste-${++Le.current}`;c(we=>[...we,{path:"",key:oe,name:A.name,mode:"inline",imageData:A.data,mimeType:A.mimeType}])},Ee=async A=>{for(const X of A){const oe=await dn(X);if(!oe){o("error",t("imageLoadFailed",{name:X.name}));continue}Oe(oe)}},We=20*1024*1024,Ue=r.useRef(0),Ve=async A=>{if(A.size>We){o("warning",t("fileTooLarge",{name:A.name,size:We/1024/1024}));return}let X;try{X=(await new Promise((we,Me)=>{const Ne=new FileReader;Ne.onload=()=>we(Ne.result),Ne.onerror=()=>Me(Ne.error??new Error("read failed")),Ne.readAsDataURL(A)})).replace(/^data:[^;]*;base64,/,"")}catch{o("error",t("fileLoadFailed",{name:A.name}));return}const oe=`upload-${++Ue.current}`;c(be=>[...be,{path:"",key:oe,name:A.name,mode:"inline",fileData:X,size:A.size,mimeType:A.type||void 0}])},De=async A=>{for(const X of A)$e(X.type)?await Ee([X]):await Ve(X)},M=r.useCallback((A,X,oe)=>{n({type:"edit_message",messageId:A,text:X,attachments:oe})},[n]),ge=r.useCallback((A,X)=>{n({type:"queue_remove",kind:A,text:X})},[n]),ce=r.useCallback(()=>$(!0),[]),je=r.useCallback(()=>c([]),[]),xe=r.useCallback(ke,[]),S=r.useCallback(Ee,[Ee]),_=r.useCallback(De,[De]),ae=(Qt=s.state)==null?void 0:Qt.model,le=(Yt=s.state)==null?void 0:Yt.thinkingLevel,ve=(Jt=s.state)==null?void 0:Jt.availableThinkingLevels,ye=r.useMemo(()=>ae?{model:ae,thinkingLevel:le??"off",availableThinkingLevels:ve??[]}:null,[ae,le,ve]),Ce=r.useCallback(()=>{var A,X;return!s.ready||s.terminals.length!==0?!1:(l.create({id:Fe(),conversationId:s.activeConversationId||((A=s.state)==null?void 0:A.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((X=s.state)==null?void 0:X.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,(Xt=s.state)==null?void 0:Xt.cwd,s.terminals.length,t,l]);return r.useEffect(()=>{if(Z.current){if(x!=="terminal"||s.terminals.length!==0){Z.current=!1;return}Ce()&&(Z.current=!1)}},[s.terminals.length,Ce,x]),e.jsxs("div",{className:"app",onDragOver:A=>{var X;Array.from(((X=A.dataTransfer)==null?void 0:X.types)??[]).includes("Files")&&(A.preventDefault(),h(!0))},onDragLeave:A=>{A.currentTarget.contains(A.relatedTarget)||h(!1)},onDrop:A=>{var we,Me;if(h(!1),!Array.from(((we=A.dataTransfer)==null?void 0:we.types)??[]).includes("Files"))return;A.preventDefault();const X=Array.from(((Me=A.dataTransfer)==null?void 0:Me.files)??[]);if(X.length===0){o("warning",t("foldersNotSupported"));return}const oe=X.filter(Ne=>$e(Ne.type)),be=X.filter(Ne=>!$e(Ne.type));oe.length>0&&Ee(oe),be.length>0&&De(be)},children:[f&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(Ni,{chat:s,send:n,terminal:l,view:x,plugins:T,onViewChange:A=>{Z.current=A==="terminal"&&s.terminals.length===0,Z.current&&Ce()&&(Z.current=!1),v(A),V(null)},onOpenPanel:V,onOpenSettings:()=>de(!0),onOpenBgTasks:()=>p(!0),onOpenGlobalSearch:()=>B(!0),sound:re,onSoundChange:ue,onSoundPreview:A=>nt(A,re),themes:N,theme:Y,onThemeChange:m}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(A=>e.jsx(qr,{notice:A,onDismiss:a},A.id))}),e.jsx(Va,{send:n,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${y}px`,"--right-w":`${z}px`},children:[W&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>V(null)}),e.jsxs("div",{className:`view-pane ${x==="chat"?"":"hidden"}`,children:[!q&&E&&e.jsx(Fs,{side:"left",onClick:J}),e.jsx("div",{className:`panel-drawer drawer-left ${W==="left"?"open":""}${q?"":E?" hidden":""}`,children:e.jsx(Si,{collapsible:!q,onToggleCollapse:J,send:pe,active:!q||W==="left",ready:s.ready,status:s.status,cwd:((Zt=s.state)==null?void 0:Zt.cwd)??"",sessionFile:((es=s.state)==null?void 0:es.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!q&&e.jsx($s,{side:"left",width:y,onResize:I}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(Za,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:M,onKillBash:()=>n({type:"abort_bash"}),onRemoveQueued:ge,thinkingWrap:((ts=s.settings)==null?void 0:ts.thinkingWrap)??!0,toolsWrap:((ss=s.settings)==null?void 0:ss.toolsWrap)??!0,jumpTarget:Q,onJumpDone:()=>ne(null)},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(or,{send:n,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId,engine:s.engine}),s.dialog&&e.jsx(gr,{dialog:s.dialog,send:n}),s.question&&e.jsx(fr,{question:s.question,send:n}),e.jsx(lr,{send:n,ready:s.ready,streaming:((ns=s.state)==null?void 0:ns.isStreaming)??!1,messages:((is=s.state)==null?void 0:is.messages)??zr,slashCommands:s.slashCommands,modelState:ye,models:s.models,modelsLoading:s.modelsLoading,providerKeys:s.providerKeys,attachments:i,onRemoveAttachment:xe,onAddImageFiles:S,onAddLocalFiles:_,onNotice:o,onManageModels:ce,onSent:je})]}),!q&&e.jsx($s,{side:"right",width:z,onResize:F}),e.jsx("div",{className:`panel-drawer drawer-right ${W==="right"?"open":""}${q?"":j?" hidden":""}`,children:e.jsx(ea,{collapsible:!q,onToggleCollapse:se,send:pe,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((as=s.state)==null?void 0:as.cwd)??"",onAttach:(A,X,oe,be)=>{V(null),me(A,X,oe,be)},onPreview:(A,X)=>{V(null),u({path:A,name:X})},onNotice:(A,X)=>o(A,X)})}),!q&&j&&e.jsx(Fs,{side:"right",onClick:se})]}),e.jsx("div",{className:`view-pane ${x==="terminal"?"":"hidden"}`,children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(Ur,{chat:s,send:n,terminal:l})})}),e.jsx("div",{className:`view-pane ${x==="git"?"":"hidden"}`,children:e.jsx(vr,{chat:s,send:n,terminal:l,active:x==="git",onSwitchToTerminal:()=>v("terminal")})}),R.map(A=>{const X=`plugin:${A.info.id}`;return e.jsx("div",{className:`view-pane ${x===X?"":"hidden"}`,children:e.jsx(yr,{entry:A,send:n})},A.info.id)})]})}),e.jsx(mr,{chat:s,send:n}),d&&e.jsx(Pr,{file:d,content:s.fileContent,send:n,onAddLines:(A,X,oe,be)=>me(A,X,"lines",!1,{start:oe,end:be}),onAttach:(A,X,oe)=>me(A,X,oe),onClose:()=>u(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!w&&!L&&e.jsx(kr,{send:n,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>b(!0)}),L&&e.jsx(wr,{send:n,providers:s.modelsConfig,providerStatus:s.providers,providerKeys:s.providerKeys,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>$(!1)}),ie&&e.jsx(Sr,{chat:s,send:n,terminal:l,onSwitchToTerminal:()=>v("terminal"),onClose:()=>de(!1)}),he&&e.jsx(Er,{servers:s.bgServers,send:n,onClose:()=>p(!1)}),e.jsx(Rr,{open:U,send:n,projects:s.projects,cwd:((rs=s.state)==null?void 0:rs.cwd)??"",fileSearch:s.fileSearch,sessionSearch:s.sessionSearch,onClose:()=>B(!1),onSwitchSession:(A,X)=>{n({type:"switch_session",path:A});const oe=X&&X[0];ne(oe?{path:A,role:oe.role,timestamp:oe.timestamp}:null)},onSwitchProject:A=>{n({type:"set_cwd",path:A})},onPreviewFile:(A,X)=>{u({path:A,name:X})}})]})}Ti();Mn(En());An.createRoot(document.getElementById("root")).render(e.jsx(r.StrictMode,{children:e.jsx(ji,{children:e.jsx(Vr,{})})}));export{at as F,Bs as T,Ae as a,Jr as b,Yr as c,Qs as d,Ie as e,ii as f,Je as g,Se as h,Fe as r,fe as u};
|
|
312
|
+
`).join(" ").trim(),w=l&&i&&s.content.length===0,b=s.role==="user"&&!l&&!w&&!!c,L=async B=>{const Q=[];for(const ne of B){if(!Fe(ne.type))continue;const ae=await un(ne);ae&&Q.push({path:"",imageData:ae.data,mimeType:ae.mimeType,name:ae.name})}Q.length>0&&E(ne=>[...ne,...Q])},A=async B=>{if(B.size>ka){se(y("fileTooLarge",{name:B.name,size:20}));return}let Q;try{Q=(await new Promise((ae,ue)=>{const N=new FileReader;N.onload=()=>ae(N.result),N.onerror=()=>ue(N.error??new Error("read failed")),N.readAsDataURL(B)})).replace(/^data:[^;]*;base64,/,"")}catch{se(y("fileLoadFailed",{name:B.name}));return}E(ne=>[...ne,{path:"",fileData:Q,name:B.name,size:B.size,mimeType:B.type||void 0}])},ie=async B=>{const Q=[];for(const ne of B)Fe(ne.type)?Q.push(ne):A(ne);Q.length>0&&await L(Q)},de=()=>{I(q?`/skill:${q.name}${q.userMessage?` ${q.userMessage}`:""}`:s.content.map(B=>{var Q;return((Q=lt(B))==null?void 0:Q.text)??""}).filter(Boolean).join(`
|
|
313
|
+
`)),E(f??[]),z(!0)},me=()=>{const B=G.trim();B&&(c==null||c(s.id,B,F.length>0?F:void 0),z(!1))},p=s.role==="custom"&&(s.customType==="goal-review"||s.customType==="goal-wizard"),U=s.role==="custom"&&s.customType==="goal-wizard";return e.jsxs("div",{className:`msg msg-${s.role}${p?" 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"?U?y("goalWizardCard"):p?y("goalBarTitle"):s.customType==="file"?y("attachment"):`${y("plugin")} · ${s.customType??y("unknown")}`:fn(s.role,y)}),s.model&&e.jsx("span",{className:"msg-model",children:s.model}),s.timestamp&&e.jsx("span",{className:"msg-time",children:Sa(s.timestamp)}),u&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:y("collapseMsg"),onClick:()=>u(s.id),children:[e.jsx(yt,{})," ",y("collapseMsg")]}),h!==void 0&&v&&e.jsxs("button",{type:"button",className:`qn-tag ${x?"active":""}`,title:`${h+1}. ${k}`,"aria-label":`${h+1}. ${k}`,onClick:()=>v(s.id),children:[e.jsx("span",{className:"qn-tag-bar"}),e.jsx("span",{className:"qn-tag-idx",children:h+1})]})]}),e.jsx("div",{className:"msg-body",children:C?e.jsxs("div",{className:`msg-editor${K?" drag-over":""}`,onDragOver:B=>{B.preventDefault(),B.stopPropagation(),j(!0)},onDragLeave:B=>{B.currentTarget.contains(B.relatedTarget)||j(!1)},onDrop:B=>{var Q;B.preventDefault(),B.stopPropagation(),j(!1),ie(Array.from(((Q=B.dataTransfer)==null?void 0:Q.files)??[]))},children:[F.length>0&&e.jsx("div",{className:"msg-editor-images",children:F.map((B,Q)=>{var ae;const ne=ba(B);return e.jsxs("span",{className:`msg-editor-img ${ne==="image"?"":"file-chip"}`,title:ja(B,y),children:[ne==="image"?e.jsx("img",{src:`data:${B.mimeType??"image/png"};base64,${B.imageData}`,alt:B.name}):e.jsxs("span",{className:"msg-editor-file",children:[e.jsx("span",{className:"msg-editor-file-icon",children:ne==="path"?B.mode==="reference"?"🔗":"📎":"📄"}),e.jsx("span",{className:"msg-editor-file-name",children:B.name??((ae=B.path)==null?void 0:ae.split("/").pop())})]}),e.jsx("button",{type:"button",className:"msg-editor-img-remove",title:y("removeAttachment"),onClick:()=>E(ue=>ue.filter((N,Y)=>Y!==Q)),children:e.jsx(Te,{})})]},`${B.name??B.path??"att"}-${Q}`)})}),H&&e.jsx("div",{className:"msg-editor-notice",children:H}),e.jsx("textarea",{className:"msg-editor-input",value:G,autoFocus:!0,placeholder:y("editPlaceholder"),rows:Math.max(2,Math.min(10,G.split(`
|
|
314
|
+
`).length+1)),onChange:B=>I(B.target.value),onPaste:B=>{var ne;const Q=[];for(const ae of((ne=B.clipboardData)==null?void 0:ne.items)??[])if(ae.kind==="file"&&Fe(ae.type)){const ue=ae.getAsFile();ue&&Q.push(ue)}Q.length!==0&&(B.preventDefault(),L(Q))},onKeyDown:B=>{B.key==="Enter"&&(B.metaKey||B.ctrlKey)?(B.preventDefault(),me()):B.key==="Escape"&&z(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(di,{})," ",y("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>z(!1),children:y("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!G.trim(),title:y("reaskFromHere"),onClick:me,children:[e.jsx(_t,{})," ",y("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),W?e.jsx(wa,{message:s,forceOpen:O}):q?e.jsxs(e.Fragment,{children:[e.jsx(Ca,{block:q,forceOpen:O}),q.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(jt,{text:q.userMessage})}),s.content.map((B,Q)=>B.type==="text"?null:e.jsx(Ss,{block:B,toolResults:n,liveOutputs:a,toolStatuses:o,streaming:l,isLast:i,onKillBash:d,toolsWrap:R,thinkingWrap:S,searchActive:O},`${s.id}-${Q}`))]}):s.content.map((B,Q)=>e.jsx(Ss,{block:B,toolResults:n,liveOutputs:a,toolStatuses:o,streaming:l,isLast:i,onKillBash:d,toolsWrap:R,thinkingWrap:S,searchActive:O},`${s.id}-${Q}`)),w&&e.jsxs("div",{className:"thinking-wait",children:[y("thinkingWait"),e.jsx("span",{className:"dot"})]}),l&&i&&!w&&e.jsx("span",{className:"stream-cursor"})]})}),b&&!C&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:y("editReaskTip"),onClick:de,children:[e.jsx(_t,{})," ",y("editReask")]})})]})});function wa({message:t,forceOpen:s=!1}){const n=fe(),[a,o]=r.useState(!1),l=a||s,i=t.details??{},c=i.name??i.path??n("attachment"),d=i.type==="folder",u=i.mode==="reference",f=i.mode==="bridged",h=t.content.filter(R=>R.type==="text").map(R=>R.text).join(`
|
|
315
|
+
`),x=Na(h),v=t.content.find(R=>R.type==="image"),S=x.split(`
|
|
316
|
+
`).length;return e.jsxs("div",{className:`attachcard ${u?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>o(R=>s?!0:!R),children:[e.jsx("span",{className:"attachcard-icon",children:d?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:c}),i.path&&e.jsx("span",{className:"attachcard-path",children:i.path}),e.jsx("span",{className:`attachcard-mode ${i.mode==="lines"?"lines":u?"ref":f?"bridged":"inline"}`,children:u?d?n("folderRefShort"):`${n("refOnlyShort")} · ${Cs(i.size)}`:f?n("bridgedVision"):v?n("image"):i.mode==="lines"?n("inlineLinesRange",{start:i.startLine??1,end:i.endLine??i.lines??1}):n("inlineLines",{n:i.lines??S})}),!u&&(l?e.jsx(qe,{}):e.jsx(kt,{}))]}),!u&&l&&(f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:n("bridgedVisionDetail")}),(v==null?void 0:v.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:v.dataUrl,alt:c})}),x&&e.jsx("pre",{className:"attachcard-content",children:x})]}):v!=null&&v.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:v.dataUrl,alt:c})}):e.jsx("pre",{className:"attachcard-content",children:x})),u&&e.jsx("div",{className:"attachcard-refnote",children:d?n("folderNotExpanded"):n("fileNotExpanded",{size:Cs(i.size)})})]})}function Cs(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function Na(t){const s=t.match(/^\s*<file path="[^"]*"(?:\s+lines="[^"]*")?>\s*```\s*\n?([\s\S]*?)\n?```\s*<\/file>\s*$/);if(s)return s[1].trim();const n=t.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return n?n[1].trim():t.trim()}function Ca({block:t,forceOpen:s=!1}){const n=fe(),[a,o]=r.useState(!1),l=a||s;return e.jsxs("div",{className:`skillcard${a?" expanded":""}`,children:[e.jsxs("button",{type:"button",className:"skillcard-head",onClick:()=>o(i=>s?!0:!i),title:t.location,children:[e.jsx("span",{className:"skillcard-icon",children:e.jsx(fi,{})}),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:[l?e.jsx(yt,{}):e.jsx(qe,{}),n(l?"collapseMsg":"expandMsg")]})]}),l&&e.jsx("div",{className:"skillcard-body",children:e.jsx(jt,{text:t.content})})]})}function Ss({block:t,toolResults:s,liveOutputs:n,toolStatuses:a,streaming:o,isLast:l,onKillBash:i,thinkingWrap:c,toolsWrap:d,searchActive:u}){const f=fe(),h=lt(t);if(h){const O=o&&l;return e.jsxs("div",{className:"msg-text",children:[O?e.jsx(da,{text:h.text}):e.jsx(jt,{text:h.text}),h.truncated&&e.jsx("div",{className:"trunc-note",children:f("truncated")})]})}const x=pn(t);if(x)return e.jsx(ua,{thinking:x.thinking,streaming:o&&l,wrap:c,forceOpen:u});const v=mn(t);if(v){const O=s.get(v.id),y=n.get(v.id),C={result:O,liveOutput:y==null?void 0:y.text,streaming:o,status:a.get(v.id)};return e.jsx(ha,{block:v,view:C,onKillBash:i,wrap:d,forceOpen:u})}const S=hn(t);if(S&&S.dataUrl)return e.jsx("div",{className:"msg-image",children:e.jsx("img",{src:S.dataUrl,alt:"attachment"})});const R=gn(t);return R?e.jsxs("div",{className:"bashblock",children:[e.jsxs("div",{className:"bashblock-command",children:[e.jsx("span",{className:"bashblock-prompt",children:"$"}),e.jsx("code",{children:R.command}),R.exitCode!==void 0&&e.jsx("span",{className:`bashblock-exit ${R.exitCode===0?"ok":"err"}`,children:f("exitCode",{code:R.exitCode})}),R.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:f("cancelled")})]}),R.output&&e.jsx("pre",{className:"bashblock-output",children:R.output}),R.truncated&&e.jsx("div",{className:"trunc-note",children:f("outputTruncated")})]}):null}function fn(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 Sa(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),a=String(s.getMinutes()).padStart(2,"0");return`${n}:${a}`}function Ts(t,s,n){let a=!1;for(const o of s){const l=o;if(l.type!=="image"||typeof l.dataUrl!="string"||!l.dataUrl.startsWith("data:"))continue;const i=l.dataUrl.match(/^data:([^;]*);base64,(.+)$/);i&&(a=!0,t.push({path:"",imageData:i[2],mimeType:i[1]||"image/png",name:n??`image.${(i[1]||"image/png").split("/")[1]??"png"}`}))}return a}function Ta(t){const s=new Map;for(let n=0;n<t.length;n++){const a=t[n];if(a.role!=="user"||!a.id)continue;const o=[];Ts(o,a.content);for(let l=n+1;l<t.length&&t[l].role==="custom"&&t[l].customType==="file";l++){const i=t[l].details??{};if(!Ts(o,t[l].content,i.name)){if(i.upload&&i.path){o.push({path:"",uploadPath:i.path,name:i.name??i.path,size:i.size});continue}if(i.path&&i.mode){const c=i.mode==="inline"||i.mode==="lines"?i.mode:"reference",d={path:i.path,mode:c};i.mode==="lines"&&typeof i.startLine=="number"&&typeof i.endLine=="number"&&(d.lines={start:i.startLine,end:i.endLine}),o.push(d)}}}o.length>0&&s.set(a.id,o)}return s}const Ea=r.memo(function({message:s,onExpand:n}){const a=fe();let o="";for(const h of s.content){const x=lt(h);if(x&&x.text.trim()){const v=zt(x.text);v?o=`skill:${v.name}`+(v.userMessage?` · ${v.userMessage.replace(/\s+/g," ").trim()}`:""):o=x.text.replace(/\s+/g," ").trim();break}}if(!o&&s.role==="custom"&&s.customType==="file"){const h=s.details??{};o=h.name??h.path??""}o.length>90&&(o=`${o.slice(0,90)}…`);let i=0,c=0,d=0,u=0;for(const h of s.content)pn(h)?i++:mn(h)?c++:gn(h)?d++:hn(h)&&u++;const f=[];return i&&f.push(`${a("thinking")} ${i}`),c&&f.push(`${a("toolCalls")} ${c}`),d&&f.push(`${a("bashRuns")} ${d}`),u&&f.push(`${a("images")} ${u}`),e.jsxs("button",{type:"button",className:"msg-collapsed","data-msg-id":s.id,title:`${a("expandMsg")} · ${o||f.join(" · ")||s.role}`,onClick:()=>n(s.id),children:[e.jsx("span",{className:`msg-collapsed-role role-${s.role}`,children:s.role==="custom"&&s.customType==="file"?a("attachment"):fn(s.role,a)}),e.jsxs("span",{className:"msg-collapsed-body",children:[o&&e.jsx("span",{className:"msg-collapsed-preview",children:o}),f.length>0&&e.jsx("span",{className:"msg-collapsed-chips",children:f.map((h,x)=>e.jsx("span",{className:"msg-collapsed-chip",children:h},x))})]}),s.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:Ma(s.timestamp)}):null,e.jsxs("span",{className:"msg-collapsed-action",children:[e.jsx(qe,{})," ",a("expandMsg")]})]})});function Ma(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),a=String(s.getMinutes()).padStart(2,"0");return`${n}:${a}`}const Ra=r.memo(function({id:s,show:n,height:a,containerRef:o,onMeasured:l,lazyRef:i,children:c}){const d=r.useRef(null),u=r.useRef(null);return r.useLayoutEffect(()=>{const f=u.current;if(u.current=n,!n||f!==!1)return;const h=d.current,x=o.current;if(!h||!x)return;const v=h.offsetHeight;l==null||l(s,v);const S=v-a;if(S!==0){const R=h.parentElement;R&&R.getBoundingClientRect().bottom<=x.getBoundingClientRect().top&&(x.scrollTop+=S)}},[n]),n?e.jsx("div",{ref:i,"data-lazy-id":s,children:e.jsx("div",{ref:d,children:c})}):e.jsx("div",{ref:i,className:"msg-lazy-ph","data-msg-id":s,"data-lazy-id":s,style:{height:a},"aria-hidden":"true"})});function Pa(t,s,n,a){const o=[],l=[];let i=0;for(const c of t){if(n.has(c.id))continue;c.top<s.bottom&&c.bottom>s.top?a.has(c.id)&&o.push(c.id):a.has(c.id)||(l.push(c.id),c.bottom<=s.top&&(i+=c.bottom-c.top))}return{show:o,hide:l,shrinkAbove:i}}function Ia(t,s){if(s.show.length===0&&s.hide.length===0)return t;const n=new Set(t);for(const a of s.show)n.delete(a);for(const a of s.hide)n.add(a);return n}function La(t,s,n){const a=new Set;let o=0;for(let l=t.length-1;l>=0&&!(l<t.length-1&&o>=n);l--){const i=t[l];a.add(i.id),o+=s.get(i.id)??xn(i.role,i.customType)}return a}function xn(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 Da=["text","thinking","argumentsText","output","command"];function Ba(t){let s=0;for(const n of t.content){n.type==="image"&&(s+=1);for(const a of Da){const o=n[a];typeof o=="string"&&(s+=o.length)}}return s}function _a(t,s,n,a){const o=n.get(t);return o&&o.len===s?o.h:a}function Aa(t){const s=[];for(const n of t.content)n.type==="text"&&typeof n.text=="string"&&s.push(n.text);return s.join(`
|
|
317
|
+
`)}function $a(t,s){const n=[];for(const a of t.content)if(a.type==="text"&&typeof a.text=="string")n.push(a.text);else if(a.type==="thinking"&&typeof a.thinking=="string")n.push(a.thinking);else if(a.type==="toolCall"){if(typeof a.name=="string"&&n.push(a.name),typeof a.argumentsText=="string"&&n.push(a.argumentsText),typeof a.id=="string"){const o=s.get(a.id);if(o){const l=Aa(o);l&&n.push(l)}}}else a.type==="bash"&&(typeof a.command=="string"&&n.push(a.command),typeof a.output=="string"&&n.push(a.output));return n.join(`
|
|
318
|
+
`)}function Fa(t,s){let n=0,a=t.indexOf(s);for(;a!==-1;)n++,a=t.indexOf(s,a+s.length);return n}function Ha(t,s,n,a){const o=new Map,l=n.toLowerCase();if(!l)return o;for(const i of t){if(!s.has(i.id))continue;const c=Fa($a(i,a).toLowerCase(),l);c>0&&o.set(i.id,c)}return o}function Ka(t,s){var l;const n=[],a=s.toLowerCase();if(!a)return n;const o=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(i){const c=i.parentElement;return!c||c.closest(".search-bar")||c.closest(".msg-collapsed")?NodeFilter.FILTER_REJECT:(i.textContent??"").toLowerCase().includes(a)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let i=o.nextNode();i;i=o.nextNode()){const c=(i.textContent??"").toLowerCase();if(!((l=i.parentElement)!=null&&l.closest("[data-msg-id]")))continue;let d=c.indexOf(a);for(;d!==-1;){const u=document.createRange();u.setStart(i,d),u.setEnd(i,d+a.length),n.push(u),d=c.indexOf(a,d+a.length)}}return n}function Oa(t,s,n,a,o){var d;const l=Ha(n,a,s,o),i=new Map;for(const u of Ka(t,s)){const f=(d=u.startContainer.parentElement)==null?void 0:d.closest("[data-msg-id]");if(!(f!=null&&f.dataset.msgId))continue;const h=i.get(f.dataset.msgId);h?h.push(u):i.set(f.dataset.msgId,[u])}const c=[];for(const u of n){const f=i.get(u.id);if(f)for(let x=0;x<f.length;x++)c.push({kind:"dom",range:f[x],msgId:u.id,k:x});const h=l.get(u.id);if(h)for(let x=0;x<h;x++)c.push({kind:"folded",msgId:u.id,k:x})}return c}function Mt(t,s){return t.findIndex(n=>n.msgId===s.msgId&&n.k===s.k)}function Re(t,s){const n=CSS;if(!n.highlights)return;if(s.length===0){n.highlights.delete(t);return}const a=window.Highlight;a&&n.highlights.set(t,new a(...s))}function Wa(t,s){const n=[];let a=t;for(;a&&a!==s;){const o=getComputedStyle(a);/(auto|scroll|hidden)/.test(o.overflowY+o.overflowX)&&(a.scrollHeight>a.clientHeight||a.scrollWidth>a.clientWidth)&&n.push(a),a=a.parentElement}return n}function Ua(t,s){const n=s.startContainer.parentElement;for(const c of Wa(n,t)){const d=s.getBoundingClientRect(),u=c.getBoundingClientRect();if(d.height<=0||d.width<=0)return;d.top>=u.top+4&&d.bottom<=u.bottom-4||(c.scrollTop+=d.top-u.top-(c.clientHeight-d.height)/2),d.left>=u.left+4&&d.right<=u.right-4||(c.scrollLeft+=d.left-u.left-(c.clientWidth-d.width)/2)}const a=s.getBoundingClientRect(),o=t.getBoundingClientRect();if(a.height<=0||a.width<=0)return;const l=a.top>=o.top+6&&a.bottom<=o.bottom-6,i=a.left>=o.left+6&&a.right<=o.right-6;l&&i||(l||(t.scrollTop+=a.top-o.top-(o.height-a.height)/2),i||(t.scrollLeft+=a.left-o.left-(o.width-a.width)/2))}function qa({containerRef:t,messages:s,collapsedIds:n,toolResults:a,onExpand:o,onProgrammaticScroll:l,open:i,onClose:c}){const d=fe(),u=r.useRef(null),[f,h]=r.useState(""),[x,v]=r.useState(null),[S,R]=r.useState(0),[O,y]=r.useState(0),C=r.useDeferredValue(f),z=i?C.trim():"",G=r.useRef(null);G.current=x;const I=r.useRef([]),F=r.useRef({key:null}),E=r.useRef("");r.useEffect(()=>{i&&(v(null),requestAnimationFrame(()=>{var H;return(H=u.current)==null?void 0:H.select()}))},[i]),r.useEffect(()=>{if(!i)return;const H=J=>{J.key==="Escape"&&(J.preventDefault(),J.stopPropagation(),c())};return window.addEventListener("keydown",H,!0),()=>window.removeEventListener("keydown",H,!0)},[i,c]),r.useEffect(()=>(i||(Re("msg-search",[]),Re("msg-search-active",[])),()=>{Re("msg-search",[]),Re("msg-search-active",[])}),[i]),r.useLayoutEffect(()=>{const H=()=>{R(0),v(null),y(0),I.current=[],Re("msg-search",[]),Re("msg-search-active",[]),F.current={key:null},E.current=""};if(!i||!z){H();return}const J=t.current;if(!J)return;let se=!1,W=0;return W=requestAnimationFrame(()=>{var de,me;if(se)return;const V=Oa(J,z,s,n,a);I.current=V;const q=V.length;if(R(q),q===0){v(null),y(0),Re("msg-search",[]),Re("msg-search-active",[]),F.current={key:null},E.current=z;return}const k=G.current;let w;if(k){if(w=Mt(V,k),w===-1){const p=[];for(let U=0;U<V.length;U++)V[U].msgId===k.msgId&&p.push(U);if(p.length>0){const U=Math.min(k.k,p.length-1);w=p[U]}else w=0}}else w=0;w<0&&(w=0),w>=q&&(w=q-1),(!k||k.msgId!==V[w].msgId||k.k!==V[w].k)&&v({msgId:V[w].msgId,k:V[w].k}),y(w);const b=V[w],L=F.current,A=((de=L.key)==null?void 0:de.msgId)!==b.msgId||((me=L.key)==null?void 0:me.k)!==b.k||L.kind==="folded"&&b.kind==="dom"||z!==E.current;F.current={key:{msgId:b.msgId,k:b.k},kind:b.kind},E.current=z;const ie=V.filter(p=>p.kind==="dom").map(p=>p.range);if(Re("msg-search",ie),b.kind==="folded"){Re("msg-search-active",[]),A&&o(b.msgId);return}Re("msg-search-active",[b.range]),A&&(l==null||l(),Ua(J,b.range))}),()=>{se=!0,cancelAnimationFrame(W)}},[i,z,s,t,x,n,a,o,l]);const K=r.useCallback(H=>{const J=I.current,se=J.length;if(se===0)return;const W=G.current,V=W?Mt(J,W):0,q=J[(V+H+se)%se];v(q.kind==="dom"||q.kind==="folded"?{msgId:q.msgId,k:q.k}:null)},[]);if(!i)return null;const j=x?(()=>{const H=Mt(I.current,x);return H===-1?0:H})():0;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:u,className:"search-input",type:"text",value:f,placeholder:d("searchPlaceholder"),onChange:H=>{h(H.target.value)},onKeyDown:H=>{H.key==="Enter"&&(H.preventDefault(),K(H.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${S===0?"empty":""}`,children:S===0?d("searchNoResults"):`${Math.min(j+1,S)}/${S}`}),e.jsx("button",{type:"button",className:"search-btn",title:d("searchPrev"),disabled:S===0,onClick:()=>K(-1),children:e.jsx(yt,{})}),e.jsx("button",{type:"button",className:"search-btn",title:d("searchNext"),disabled:S===0,onClick:()=>K(1),children:e.jsx(qe,{})}),e.jsx("button",{type:"button",className:"search-btn",title:d("searchClose"),onClick:c,children:e.jsx(Te,{})})]})}function za(t){const{dSt:s,dSh:n,escaped:a,graceActive:o,stuck:l}=t;return o?{flipEscape:!1,reassert:!1}:s>=-4||s<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:l&&!a}:{flipEscape:!0,reassert:!1}}const vn=[{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"}],yn="pi-web-ui:prompt-templates";function Va(){try{const t=localStorage.getItem(yn);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(n=>!!n&&typeof n=="object"&&typeof n.id=="string"):[]}catch{return[]}}function Es(t){return vn.some(s=>s.id===t)}function dt(t){return typeof t.title=="string"}const kn=r.createContext(null);function bn(){const t=r.useContext(kn);if(!t)throw new Error("useTemplates must be used within TemplateProvider");return t}function Ga({send:t,children:s}){const n=fe(),[a,o]=r.useState(Va),[l,i]=r.useState(!1),[c,d]=r.useState(null),[u,f]=r.useState(!1),[h,x]=r.useState(!1),[v,S]=r.useState(!1);r.useEffect(()=>{try{localStorage.setItem(yn,JSON.stringify(a))}catch{}},[a]);const R=r.useMemo(()=>{const W=new Map,V=new Set;for(const w of a)w.hidden?V.add(w.id):(dt(w)&&!Es(w.id)||dt(w))&&W.set(w.id,w);const q=vn.filter(w=>!V.has(w.id)).map(w=>{const b=W.get(w.id);return{id:w.id,icon:(b==null?void 0:b.icon)??w.icon,title:(b==null?void 0:b.title)??n(w.titleKey),desc:(b==null?void 0:b.desc)??n(w.descKey),prompt:(b==null?void 0:b.prompt)??n(w.promptKey),builtin:!0}}),k=a.filter(w=>dt(w)&&!Es(w.id)).map(w=>({id:w.id,icon:w.icon??"📌",title:w.title??"",desc:w.desc??"",prompt:w.prompt??""}));return[...q,...k]},[a,n]),O=r.useCallback(()=>i(!0),[]),y=r.useCallback(W=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:W}))},[]),C=r.useCallback((W,V=!1)=>{S(V),W?(f(!1),d({...W})):(f(!0),d({id:He(),icon:"📌",title:"",desc:"",prompt:""}))},[]),z=r.useCallback(()=>{i(!1),d(null),S(!1)},[]),G=r.useCallback(()=>{h?(o([]),x(!1)):(x(!0),setTimeout(()=>x(!1),5e3))},[h]),I=r.useCallback(W=>{i(!1),y(W.prompt)},[y]),F=r.useCallback(W=>{i(!1),C(W,!0)},[C]),E=r.useCallback(()=>{i(!1),C(void 0,!0)},[C]),K=r.useCallback(W=>{o(V=>{const q=V.findIndex(k=>k.id===W.id);if(q>=0){const k=[...V];return k[q]=W,k}return[...V,W]}),d(null),v&&(i(!0),S(!1))},[v]),j=r.useCallback(W=>{o(V=>W.builtin?[...V.filter(k=>k.id!==W.id),{id:W.id,hidden:!0}]:V.filter(q=>q.id!==W.id)),d(null),v&&(i(!0),S(!1))},[v]),H=r.useCallback(W=>{o(V=>V.filter(q=>q.id!==W.id||q.hidden)),d(null),v&&(i(!0),S(!1))},[v]),J=r.useMemo(()=>({templates:R,fill:y,openPicker:O,openEdit:C,resetConfirm:h,toggleReset:G}),[R,y,O,C,h,G]),se=c?a.some(W=>W.id===c.id&&!W.hidden&&dt(W)):!1;return e.jsxs(kn.Provider,{value:J,children:[s,l&&e.jsx(Ya,{templates:R,resetConfirm:h,onFill:I,onEditTpl:F,onNew:E,onResetToggle:G,onClose:z}),c&&e.jsx(Ja,{editing:c,isNew:u,hasOverride:se,onDraft:d,onSave:K,onRestore:()=>H(c),onRemove:()=>j(c),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:c.prompt})),z()},onSend:()=>{const W=c.prompt.trim();W&&t({type:"prompt",text:W,queue:!1})&&z()},onClose:z})]})}function Qa(){const t=fe(),{templates:s,fill:n,openEdit:a,toggleReset:o,resetConfirm:l}=bn();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(i=>e.jsx(jn,{tpl:i,title:t("tpl.clickCard"),onFill:()=>n(i.prompt),onEdit:()=>a(i),editTitle:t("tpl.editTpl")},i.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>a(),title:t("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx($e,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:t("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"empty-templates-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:o,children:[e.jsx(Vs,{}),t(l?"tpl.resetConfirm":"tpl.reset")]})})]})}function jn({tpl:t,title:s,onFill:n,onEdit:a,editTitle:o}){const l=fe();return e.jsxs("button",{type:"button",className:"empty-template",title:s,onClick:n,children:[e.jsx("span",{className:"empty-template-icon",children:t.icon}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t.title}),e.jsx("span",{className:"empty-template-desc",children:t.desc})]}),e.jsx("span",{className:"template-card-ops",role:"button",title:o??l("tpl.editTpl"),onClick:i=>{i.stopPropagation(),a()},children:e.jsx(Ys,{})})]})}function Ya({templates:t,resetConfirm:s,onFill:n,onEditTpl:a,onNew:o,onResetToggle:l,onClose:i}){const c=fe();return r.useEffect(()=>{const d=u=>{u.key==="Escape"&&i()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[i]),e.jsx("div",{className:"modal-backdrop",onClick:i,children:e.jsxs("div",{className:"modal template-picker",onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"template-picker-head",children:[e.jsx("span",{className:"template-picker-title",children:c("tpl.pickerTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:c("close"),onClick:i,children:e.jsx(Te,{})})]}),e.jsx("div",{className:"template-picker-hint",children:c("tpl.pickerHint")}),e.jsxs("div",{className:"template-picker-grid",children:[t.map(d=>e.jsx(jn,{tpl:d,title:c("tpl.clickCard"),onFill:()=>n(d),onEdit:()=>a(d),editTitle:c("tpl.editTpl")},d.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:o,title:c("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx($e,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:c("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:c("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"template-picker-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:l,children:[e.jsx(Vs,{}),c(s?"tpl.resetConfirm":"tpl.reset")]})})]})})}function Ja({editing:t,isNew:s,hasOverride:n,onDraft:a,onSave:o,onRestore:l,onRemove:i,onFill:c,onSend:d,onClose:u}){const f=fe(),h=r.useRef(null);r.useEffect(()=>{const S=R=>{R.key==="Escape"&&u()};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[u]),r.useEffect(()=>{const S=h.current;if(!S)return;S.style.height="auto";const R=S.scrollHeight>300;S.style.height=`${Math.min(S.scrollHeight,300)}px`,S.style.overflowY=R?"auto":"hidden"},[t.prompt]);const x=()=>{const S=t.title.trim(),R=t.prompt.trim();if(!S||!R){a({...t,error:f("tpl.required")});return}o({id:t.id,icon:t.icon.trim()||"📌",title:S,desc:t.desc.trim(),prompt:R})},v=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:u,children:e.jsxs("div",{className:"modal template-modal",onClick:S=>S.stopPropagation(),children:[e.jsxs("div",{className:"template-modal-head",children:[e.jsx("span",{className:"template-modal-icon",children:t.icon}),e.jsx("span",{className:"template-modal-badge",children:f(v?"tpl.builtin":"tpl.custom")}),e.jsx("span",{className:"template-modal-title",children:f(s?"tpl.newTitle":"tpl.editTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:f("close"),onClick:u,children:e.jsx(Te,{})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldIcon")}),e.jsx("input",{className:"template-field-input icon",value:t.icon,maxLength:4,onChange:S=>a({...t,icon:S.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldTitle")}),e.jsx("input",{className:"template-field-input",value:t.title,placeholder:f("tpl.fieldTitlePh"),onChange:S=>a({...t,title:S.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldDesc")}),e.jsx("input",{className:"template-field-input",value:t.desc,placeholder:f("tpl.fieldDescPh"),onChange:S=>a({...t,desc:S.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:f("tpl.fieldPrompt")}),e.jsx("textarea",{ref:h,className:"template-field-prompt",value:t.prompt,placeholder:f("tpl.fieldPromptPh"),onChange:S=>a({...t,prompt:S.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&&v&&n&&e.jsx("button",{type:"button",className:"btn template-btn ghost",title:f("tpl.restoreTip"),onClick:l,children:f("tpl.restore")}),!s&&v&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:f("tpl.removeTip"),onClick:i,children:[e.jsx(Le,{})," ",f("tpl.remove")]}),!s&&!v&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:f("tpl.deleteTip"),onClick:i,children:[e.jsx(Le,{})," ",f("tpl.delete")]})]}),e.jsxs("div",{className:"template-modal-actions-right",children:[e.jsx("button",{type:"button",className:"btn template-btn",onClick:x,children:f("tpl.save")}),e.jsx("button",{type:"button",className:"btn template-btn fill",onClick:c,title:f("tpl.fillTip"),children:f("tpl.fill")}),e.jsxs("button",{type:"button",className:"btn template-btn send",onClick:d,title:f("tpl.sendTip"),children:[e.jsx(zs,{})," ",f("tpl.sendNow")]})]})]})]})})}const Ms=new Map,Xa=15,Rs=30,Rt=250,Ps=1200,Za=1600;function Is(t){return t.content.some(s=>s.type==="toolCall")}function er({state:t,liveOutputs:s,toolStatuses:n,onEdit:a,onKillBash:o,onRemoveQueued:l,thinkingWrap:i,toolsWrap:c,jumpTarget:d,onJumpDone:u}){const f=fe(),h=r.useRef(null),[x,v]=r.useState(!0),S=r.useRef(!0),R=r.useRef(0),O=r.useRef(0),y=r.useRef(!1),C=r.useRef(0),[z,G]=r.useState(()=>new Set),[I,F]=r.useState(!1),E=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,K=r.useMemo(()=>{const T=new Map;for(const $ of t.messages)$.role==="toolResult"&&$.toolCallId&&T.set($.toolCallId,$);return T},[t.messages]),j=r.useMemo(()=>Ta(t.messages),[t.messages]),H=E.length>0?E[E.length-1].id:null,J=t.messages.length>Rs?Math.max(0,t.messages.length-Xa):0,se=r.useMemo(()=>{const T=new Set;for(let $=0;$<J;$++){const re=t.messages[$];re.role!=="toolResult"&&(z.has(re.id)||T.add(re.id))}return T},[t.messages,J,z]),[W,V]=r.useState(()=>new Set),[q,k]=r.useState(()=>new Set),w=r.useRef(new Map),b=r.useRef(new Map),L=r.useRef(new Map),A=r.useRef(0),ie=r.useMemo(()=>{const T=new Map;for(const $ of t.messages)T.set($.id,Ba($));return T},[t.messages]),de=r.useRef(ie);de.current=ie;const me=r.useRef(W);me.current=W;const p=t.messages.length>Rs&&!I,U=r.useRef(p);U.current=p;const B=La(t.messages,w.current,Za),Q=r.useRef(B);Q.current=B;const ne=r.useCallback(()=>{const T=h.current;if(!T)return;if(!U.current){V(ye=>ye.size?new Set:ye);return}const $=T.getBoundingClientRect(),re={top:$.top-Ps,bottom:$.bottom+Ps},le=[];for(const[ye,Se]of L.current){const _e=Se.getBoundingClientRect();le.push({id:ye,top:_e.top,bottom:_e.bottom}),me.current.has(ye)||N(ye,_e.bottom-_e.top,de.current.get(ye))}const ve=Pa(le,re,Q.current,me.current);for(const ye of ve.hide){const Se=L.current.get(ye);Se&&N(ye,Se.offsetHeight,de.current.get(ye))}V(ye=>Ia(ye,ve))},[]),ae=r.useCallback(()=>{A.current||(A.current=requestAnimationFrame(()=>{A.current=0,ne()}))},[ne]);r.useLayoutEffect(()=>{ne()},[ne]);const ue=r.useRef(I);r.useLayoutEffect(()=>{ue.current&&!I&&ne(),ue.current=I},[I,ne]);const N=r.useCallback((T,$,re)=>{re!==void 0&&(b.current.set(T,{h:$,len:re}),w.current.set(T,$))},[]),Y=r.useCallback((T,$)=>{N(T,$,de.current.get(T))},[N]),m=r.useCallback(T=>{T&&L.current.set(T.dataset.lazyId??"",T)},[]);r.useEffect(()=>{const T=new Set(t.messages.map($=>$.id));for(const[$,re]of L.current)T.has($)||(L.current.delete($),w.current.delete($),b.current.delete($));V($=>{let re=!1;const le=new Set;for(const ve of $)T.has(ve)?le.add(ve):re=!0;return re?le:$})},[t.messages,z]),r.useEffect(()=>()=>cancelAnimationFrame(A.current),[]);const P=r.useMemo(()=>{const T=[];for(const $ of t.messages){if($.role!=="user")continue;const re=$.content.map(ye=>{var Se;return((Se=lt(ye))==null?void 0:Se.text)??""}).filter(Boolean).join(" "),le=zt(re),ve=le?le.userMessage??`skill:${le.name}`:re.trim();ve&&T.push({id:$.id,text:ve})}return T},[t.messages]),g=r.useMemo(()=>{const T=new Map;return P.forEach(($,re)=>T.set($.id,re)),T},[P]),[D,Z]=r.useState(-1),ee=r.useRef(-1),he=r.useRef(P);r.useEffect(()=>{he.current=P},[P]);const ke=r.useCallback(()=>{const T=h.current,$=he.current;if(!T||$.length===0)return;const re=T.getBoundingClientRect().top,le=140;let ve=-1;for(let ye=0;ye<$.length;ye++){const Se=T.querySelector(`[data-msg-id="${$[ye].id}"]`);if(Se)if(Se.getBoundingClientRect().top<=re+le)ve=ye;else break}ve!==ee.current&&(ee.current=ve,Z(ve))},[]);r.useEffect(()=>{ke()},[P,ke]);const pe=r.useCallback(T=>{G($=>$.has(T)?$:new Set($).add(T))},[]);r.useEffect(()=>{const T=$=>{if(!($.ctrlKey||$.metaKey)||$.key.toLowerCase()!=="f")return;const re=$.target;re&&(re.tagName==="INPUT"||re.tagName==="TEXTAREA"||re.isContentEditable)||($.preventDefault(),F(!0))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[]);const De=r.useCallback(T=>{G($=>{if(!$.has(T))return $;const re=new Set($);return re.delete(T),re})},[]),Pe=r.useCallback(T=>{const $=t.messages.findIndex(le=>le.id===T);sa.flushSync(()=>{$>=0&&$<J&&!z.has(T)&&pe(T),k(le=>le.has(T)?le:new Set(le).add(T))});const re=he.current.findIndex(le=>le.id===T);ee.current=re,Z(re),requestAnimationFrame(()=>{var ve,ye,Se;const le=(ve=h.current)==null?void 0:ve.querySelector(`[data-msg-id="${T}"]`);le&&((ye=h.current)==null||ye.querySelectorAll(".msg-flash").forEach(_e=>_e.classList.remove("msg-flash")),le.scrollIntoView({block:"start"}),le.classList.remove("msg-flash"),le.offsetWidth,le.classList.add("msg-flash"),le!==((Se=h.current)==null?void 0:Se.lastElementChild)&&(y.current=!0))})},[t.messages,J,z,pe]),Ie=r.useMemo(()=>{var T;return d?((T=t.messages.find($=>$.role===d.role&&$.timestamp===d.timestamp))==null?void 0:T.id)??null:null},[t.messages,d]);r.useEffect(()=>{if(d){if(Ie){Pe(Ie),u==null||u();return}t.sessionFile===d.path&&t.messages.length>0&&(u==null||u())}},[Ie,Pe,u,d,t.sessionFile,t.messages.length]);const Ke=r.useCallback(()=>{const T=h.current;if(!T)return;const $=T.scrollTop-R.current,re=T.scrollHeight-O.current;R.current=T.scrollTop,O.current=T.scrollHeight;const le=T.scrollHeight-T.scrollTop-T.clientHeight<80,ve=Date.now()<C.current,ye=za({dSt:$,dSh:re,escaped:y.current,graceActive:ve,stuck:S.current});ye.reassert&&(C.current=Date.now()+Rt,T.scrollTop=T.scrollHeight),ye.flipEscape&&(y.current=!0),le&&$>=0&&(y.current=!1),ve||($<0?S.current=le&&!y.current:le&&(S.current=!0)),v(S.current),ke(),ae()},[ke,ae]),Be=r.useRef(!1);r.useEffect(()=>{const T=Be.current;if(Be.current=!!t.isStreaming,T&&!t.isStreaming&&!y.current){const $=()=>{const le=h.current;le&&!y.current&&(le.scrollTop=le.scrollHeight,S.current=!0,v(!0))};requestAnimationFrame(()=>requestAnimationFrame($));const re=setTimeout($,180);return()=>clearTimeout(re)}},[t.isStreaming]),r.useEffect(()=>{const T=h.current;T&&S.current&&(T.scrollTop=T.scrollHeight)},[E,t.isStreaming,s]);const ze=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");r.useEffect(()=>{const T=h.current;T&&S.current&&(T.scrollTop=T.scrollHeight)},[ze]),r.useEffect(()=>{const T=h.current;if(!T||typeof ResizeObserver>"u")return;const $=new ResizeObserver(()=>{S.current&&!y.current&&(T.scrollTop=T.scrollHeight,v(!0))});return $.observe(T),()=>$.disconnect()},[]),r.useEffect(()=>{const T=h.current;if(!T||typeof MutationObserver>"u")return;let $=!1;const re=new MutationObserver(()=>{$||($=!0,requestAnimationFrame(()=>{$=!1;const le=h.current;le&&S.current&&!y.current&&(le.scrollTop=le.scrollHeight,v(!0))}))});return re.observe(T,{childList:!0,subtree:!0,characterData:!0}),()=>re.disconnect()},[]);const Ve=r.useCallback(()=>{if(!h.current)return;S.current=!0,y.current=!1,v(!0),C.current=Date.now()+Rt;const $=()=>{const re=h.current;!re||!S.current||y.current||(C.current=Date.now()+Rt,re.scrollTop=re.scrollHeight)};$(),requestAnimationFrame(()=>requestAnimationFrame($)),setTimeout($,120),setTimeout($,300),setTimeout($,600)},[]),M=r.useRef(null);r.useEffect(()=>{const T=M.current,$=h.current;if(!T||!$)return;const re=le=>{le.preventDefault();const ve=T.querySelector(".qn-list");if(ve&&ve.contains(le.target)&&ve.scrollHeight>ve.clientHeight){ve.scrollTop+=le.deltaY;return}$.scrollTop+=le.deltaY};return T.addEventListener("wheel",re,{passive:!1}),()=>T.removeEventListener("wheel",re)},[]);const[ge,ce]=r.useState(0);r.useEffect(()=>{const T=()=>{var $;ce((($=h.current)==null?void 0:$.clientHeight)??0),ae()};return T(),window.addEventListener("resize",T),()=>window.removeEventListener("resize",T)},[ae]);const je=P.length,xe=r.useMemo(()=>je===0?27:Math.max(4,Math.min(27,Math.floor(((ge||600)-16)/je)-3)),[je,ge]),Ce=xe<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:`messages${I||x?"":" anchor-live"}`,ref:h,onScroll:Ke,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(Qa,{})}),t.messages.map((T,$)=>{const re=$<J,le=re&&z.has(T.id);if(re&&!le)return T.role==="toolResult"?null:e.jsx(Ea,{message:T,onExpand:pe},T.id);const ve=T.role==="user"?g.get(T.id):void 0,ye=!p||B.has(T.id)||q.has(T.id)||!W.has(T.id);return e.jsx(Ra,{id:T.id,show:ye,height:_a(T.id,ie.get(T.id)??-1,b.current,xn(T.role,T.customType)),containerRef:h,onMeasured:Y,lazyRef:m,children:e.jsx(Ns,{message:T,qnIndex:ve,qnActive:ve!==void 0?ve===D:void 0,onJump:Pe,toolResults:K,liveOutputs:Is(T)?s:Ms,toolStatuses:n,streaming:t.isStreaming,onKillBash:o,toolsWrap:c,thinkingWrap:i,isLast:T.id===H,onEdit:a,questionAttachments:j.get(T.id),onCollapse:le?De:void 0,searchActive:I},T.id)},T.id)}),t.streamingMessage&&e.jsx(Ns,{message:t.streamingMessage,toolResults:K,liveOutputs:Is(t.streamingMessage)?s:Ms,toolStatuses:n,streaming:!0,isLast:!0,onEdit:a,onKillBash:o,toolsWrap:c,thinkingWrap:i,searchActive:I},t.streamingMessage.id),t.isStreaming&&E.length===0&&e.jsx("div",{className:"streaming-wait",children:f("waitingResponse")}),t.queue.steering.map((T,$)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:f("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:T}),l&&e.jsx("button",{type:"button",className:"queued-remove",title:f("queueRemoveTip"),onClick:()=>l("steer",T),children:"✕"})]})},`q-steer-${$}`)),t.queue.followUp.map((T,$)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:f("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:T}),l&&e.jsx("button",{type:"button",className:"queued-remove",title:f("queueRemoveTip"),onClick:()=>l("followUp",T),children:"✕"})]})},`q-fu-${$}`))]}),!x&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Ve,children:[e.jsx(tn,{})," ",f("backToBottom")]}),e.jsx(qa,{containerRef:h,messages:E,collapsedIds:se,toolResults:K,onExpand:pe,onProgrammaticScroll:()=>{y.current=!0,S.current=!1,v(!1)},open:I,onClose:()=>F(!1)}),P.length>0&&e.jsxs("div",{className:`qn-rail ${Ce?"many":""}`,ref:M,"aria-label":f("questionNavTitle"),style:{"--rail-gap":`${xe}px`},children:[P.map((T,$)=>e.jsx("button",{type:"button",className:`qn-bar ${$===D?"active":""}`,"aria-label":`${$+1}. ${T.text}`,onClick:()=>Pe(T.id),children:e.jsxs("span",{className:"qn-bar-text",children:[$+1,". ",T.text]})},T.id)),Ce&&e.jsx("div",{className:"qn-list",children:P.map((T,$)=>e.jsxs("button",{type:"button",className:`qn-list-item ${$===D?"active":""}`,"aria-label":`${$+1}. ${T.text}`,onClick:()=>Pe(T.id),children:[e.jsx("span",{className:"qn-list-idx",children:$+1}),e.jsx("span",{className:"qn-list-text",children:T.text})]},T.id))})]})]})}const wn="pi-web-model-usage";function tr(t){if(!t||typeof t!="object")return{};const s={};for(const[n,a]of Object.entries(t)){const o=typeof a=="number"?Math.floor(a):0;Number.isFinite(o)&&o>0&&(s[n]=o)}return s}function sr(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function nr(t,s){const n=s;return t.map((a,o)=>({m:a,i:o,count:n[a.id]??0})).sort((a,o)=>o.count-a.count||a.i-o.i).map(a=>a.m)}function Nn(){try{const t=localStorage.getItem(wn);return t?tr(JSON.parse(t)):{}}catch{return{}}}function ir(t){try{localStorage.setItem(wn,JSON.stringify(t))}catch{}}function ar(t){const s=sr(Nn(),t);return ir(s),s}const rr=["off","minimal","low","medium","high","xhigh","max"],lr=r.memo(function({state:s,models:n,modelsLoading:a,send:o,onManageModels:l,providerKeys:i,compact:c=!1}){const d=fe(),u=s==null?void 0:s.model,f=u?`${u.provider}/${u.id}`:null,[h,x]=r.useState(!1),[v,S]=r.useState(!1),[R,O]=r.useState(""),[y,C]=r.useState(null),[z,G]=r.useState({}),I=r.useRef(null),F=r.useRef(null),[E,K]=r.useState(null);r.useEffect(()=>{if(!h){K(null);return}if(n.length===0)return;const b=requestAnimationFrame(()=>{const L=F.current;L&&K(L.offsetWidth)});return()=>cancelAnimationFrame(b)},[h,n.length]),r.useEffect(()=>{h&&G(Nn())},[h]),r.useEffect(()=>{h||(O(""),C(null))},[h]);const j=r.useMemo(()=>{const b=new Map;for(const A of n)b.set(A.provider,(b.get(A.provider)??0)+1);const L=[];for(const[A,ie]of[...b.entries()].sort((de,me)=>de[0].localeCompare(me[0]))){const de=i[A];if(de&&de.length>1)for(const me of de)L.push({provider:A,keyName:me.name,count:ie});else L.push({provider:A,keyName:null,count:ie})}return L},[n,i]),H=r.useMemo(()=>nr(n,z),[n,z]),J=r.useMemo(()=>{let b=H;y&&(b=b.filter(A=>A.provider===y.provider));const L=R.trim().toLowerCase();return L?b.filter(A=>A.name.toLowerCase().includes(L)||A.provider.toLowerCase().includes(L)||A.id.toLowerCase().includes(L)):b},[H,R,y]),se=r.useMemo(()=>{const b=[];for(const L of J){const A=i[L.provider];if(!A||A.length<=1){b.push({model:L,key:null});continue}let ie=A.find(de=>de.active)??A[0];if((y==null?void 0:y.provider)===L.provider&&y.keyName){const de=A.find(me=>me.name===y.keyName);de&&(ie=de)}b.push({model:L,key:ie})}return b},[J,i,y]),[W,V]=r.useState(!1),q=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,k=rr.map(b=>({value:b,label:d(`thinking.${b}`),supported:q?q.has(b):!0})),w=b=>{var L;return((L=k.find(A=>A.value===b))==null?void 0:L.label)??b};return r.useEffect(()=>{h&&n.length===0&&!W&&!a&&(V(!0),o({type:"list_models"}))},[h,n.length,W,a,o]),r.useEffect(()=>{n.length>0&&V(!1)},[n.length]),r.useEffect(()=>{var L;if(!h)return;const b=(L=I.current)==null?void 0:L.querySelector(".dd-item.active");b==null||b.scrollIntoView({block:"nearest"})},[h,f,n.length]),e.jsxs(e.Fragment,{children:[e.jsxs(We,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(rt,{}),e.jsx("span",{className:"chip-model",children:u?u.name:d("selectModel")}),!c&&(u==null?void 0:u.vision)&&e.jsx("span",{className:"chip-vision",title:d("vision"),children:"🖼"}),!c&&u&&e.jsx("span",{className:"chip-sub",children:u.provider})]}),open:h,onOpenChange:x,menuClassName:"dd-menu-model",menuRef:F,menuStyle:E!=null?{width:E}:void 0,direction:"up",children:[e.jsx("div",{className:"dd-header",children:d("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(xt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:d("searchModels"),value:R,onChange:b=>O(b.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[j.length>1&&e.jsxs("div",{className:"dd-provider-col",children:[e.jsx("div",{className:"dd-provider-head",children:d("providers")}),e.jsx("button",{type:"button",className:`dd-provider-item ${y===null?"active":""}`,onClick:()=>C(null),children:e.jsx("span",{children:d("allProviders")})}),j.map(b=>{const L=(y==null?void 0:y.provider)===b.provider&&(y==null?void 0:y.keyName)===b.keyName;return e.jsxs("button",{type:"button",className:`dd-provider-item ${L?"active":""}`,onClick:()=>C(L?null:{provider:b.provider,keyName:b.keyName}),title:b.keyName?`${b.provider} · ${b.keyName}`:`${b.provider} · ${b.count}`,children:[e.jsxs("span",{className:"dd-provider-txt",children:[e.jsx("span",{className:"dd-provider-name",children:b.provider}),b.keyName&&e.jsx("span",{className:"dd-provider-key",children:b.keyName})]}),e.jsx("span",{className:"dd-provider-count",children:b.count})]},b.keyName?`${b.provider}::${b.keyName}`:b.provider)})]}),e.jsxs("div",{className:"dd-model-scroll",ref:I,children:[(W||a)&&e.jsx("div",{className:"dd-loading",children:d("loading")}),n.length===0&&!W&&!a&&e.jsx("div",{className:"dd-loading",children:d("noModels")}),J.length===0&&n.length>0&&e.jsx("div",{className:"dd-loading",children:d("noModelMatches")}),se.map(b=>{const L=b.model,A=f===L.id&&(!b.key||b.key.active);return e.jsx(Ee,{active:A,onClick:()=>{b.key&&!b.key.active&&o({type:"activate_provider_key",provider:L.provider,keyName:b.key.name}),f!==L.id&&o({type:"set_model",modelId:L.id}),x(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:L.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:L.provider}),b.key&&e.jsxs("span",{className:`dd-model-key ${b.key.active?"active":""}`,children:[b.key.active?"●":"○"," ",b.key.name]}),(z[L.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:d("modelUsedCount",{n:z[L.id]})}),(L.reasoning||L.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[L.reasoning&&e.jsx("span",{className:"dd-model-badge",children:d("reasoning")}),L.vision&&e.jsx("span",{className:"dd-model-badge",children:d("vision")})]})]})]})},b.key?`${L.id}::${b.key.name}`:L.id)})]})]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>o({type:"list_models"}),children:d("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{x(!1),l()},children:d("manageModels")})]})]}),e.jsxs(We,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(ut,{}),e.jsx("span",{className:"chip-sub",children:d("thinkingChip",{level:s?w(s.thinkingLevel):"—"})})]}),open:v,onOpenChange:S,direction:"up",children:[e.jsx("div",{className:"dd-header",children:d("thinkingLevel")}),k.map(b=>e.jsx(Ee,{active:(s==null?void 0:s.thinkingLevel)===b.value,disabled:!b.supported,title:b.supported?void 0:d("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==b.value&&o({type:"set_thinking",level:b.value}),S(!1)},children:b.label},b.value))]})]})}),or=r.memo(function({ready:s,streaming:n,messages:a,slashCommands:o,modelState:l,models:i,modelsLoading:c,send:d,attachments:u,onRemoveAttachment:f,onAddImageFiles:h,onAddLocalFiles:x,onNotice:v,onSent:S,onManageModels:R,providerKeys:O}){const y=fe(),{locale:C}=Ut(),{openPicker:z}=bn(),G=m=>C==="en"&&m.descriptionEn?m.descriptionEn:m.description??"",I=m=>C==="en"&&m.argumentHintEn?m.argumentHintEn:m.argumentHint??"",[F,E]=r.useState(""),[K,j]=r.useState(!1),[H,J]=r.useState(null),[se,W]=r.useState(0),[V,q]=r.useState(!1),[k,w]=r.useState(void 0),b=r.useRef(null),L=r.useRef(null),A=r.useRef(null),ie={builtin:y("slashBuiltin"),extension:y("slashExtension"),prompt:y("slashPrompt"),skill:y("slashSkill"),plugin:y("slashPlugin")},de=m=>{const P=m.match(/^\/([^\s]*)$/);if(P&&s){const g=P[1].toLowerCase(),D=o.filter(Z=>Z.name.toLowerCase().startsWith(g));J(D.length>0?D:null),W(0)}else J(null)};r.useEffect(()=>{var P;const m=(P=A.current)==null?void 0:P.querySelector(".slash-item.active");m==null||m.scrollIntoView({block:"nearest"})},[se,H]);const me=m=>{var ee;const P=H??[],g=m??P[se%Math.max(P.length,1)];if(!g){J(null);return}const D=F.match(/^\/([^\s]*)([\s\S]*)$/),Z=D?D[2]:"";E(`/${g.name} ${Z}`),J(null),(ee=b.current)==null||ee.focus()},p=async()=>{const P=[...a].reverse().find(D=>D.role==="assistant"&&D.content.some(Z=>Z.type==="text"&&Z.text)),g=P==null?void 0:P.content.filter(D=>D.type==="text").map(D=>D.text).join(`
|
|
319
|
+
`);if(!g){v("warning",y("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(g),v("info",y("slashCopied"))}catch{v("error",y("slashCopyFailed"))}},U=m=>{if(!m||m.length===0){v("warning",y("foldersNotSupported"));return}const P=Array.from(m).filter(Z=>Fe(Z.type)),g=Array.from(m).filter(Z=>!Fe(Z.type)),D=Q();P.length>0&&D?v("warning",D):P.length>0&&h(P),g.length>0&&x(g)},B=m=>{var Z;const P=(Z=m.clipboardData)==null?void 0:Z.items;if(!P)return;const g=[];for(const ee of P)if(ee.kind==="file"&&Fe(ee.type)){const he=ee.getAsFile();he&&g.push(he)}if(g.length===0)return;m.preventDefault();const D=Q();if(D){v("warning",D);return}h(g)},Q=()=>{const m=l==null?void 0:l.model;if(!(m!=null&&m.id))return null;const P=i.find(g=>g.id===m.id);return P&&P.vision===!1?y("modelNoVision",{name:P.name}):null},ne=s,ae=r.useRef(F);r.useEffect(()=>{ae.current=F},[F]),r.useEffect(()=>{de(ae.current)},[o]),r.useEffect(()=>{const m=P=>{var D;const g=P.detail;E(g),(D=b.current)==null||D.focus()};return window.addEventListener("pi-web:fill",m),()=>window.removeEventListener("pi-web:fill",m)},[]),r.useEffect(()=>{if(!V)return;const m=P=>{P.key==="Escape"&&q(!1)};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[V]),r.useEffect(()=>{const m=b.current;if(!m)return;m.style.height="auto";const P=m.scrollHeight>220;m.style.height=`${Math.min(m.scrollHeight,220)}px`,m.style.overflowY=P?"auto":"hidden"},[F]);const ue=(m=!1)=>{var D,Z,ee,he,ke;const P=F.trim(),g=u.some(pe=>pe.imageData||pe.fileData);if(!(!ne||!P&&!g)){if(P==="/help"){const pe=(Z=(D=b.current)==null?void 0:D.closest(".inputbox"))==null?void 0:Z.getBoundingClientRect();w(pe==null?void 0:pe.width),q(!0),E(""),(ee=b.current)==null||ee.focus();return}if(P==="/copy"){E(""),(he=b.current)==null||he.focus(),p();return}if(d({type:"prompt",text:P,queue:m,attachments:u.map(pe=>pe.imageData?{path:"",imageData:pe.imageData,mimeType:pe.mimeType,name:pe.name}:pe.fileData?{path:"",fileData:pe.fileData,mimeType:pe.mimeType,name:pe.name,size:pe.size}:{path:pe.path,mode:pe.mode,...pe.lines?{lines:pe.lines}:{}})})){E(""),S();const pe=l==null?void 0:l.model;pe&&ar(`${pe.provider}/${pe.id}`),(ke=b.current)==null||ke.focus()}}},N=m=>{if(!m.nativeEvent.isComposing){if(H&&H.length>0)switch(m.key){case"ArrowDown":m.preventDefault(),W(P=>(P+1)%H.length);return;case"ArrowUp":m.preventDefault(),W(P=>(P-1+H.length)%H.length);return;case"Tab":case"Enter":m.preventDefault(),me();return;case"Escape":m.preventDefault(),J(null);return}m.key==="Enter"&&!m.shiftKey&&(m.preventDefault(),ue())}},Y=()=>e.jsx("div",{className:"inputbox-actions",children:n?e.jsxs(e.Fragment,{children:[F.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:y("supplementTip"),onClick:()=>ue(!0),children:[e.jsx(zs,{})," ",y("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:y("stopAgent"),onClick:()=>d({type:"abort"}),children:e.jsx(gt,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:y("sendTip"),disabled:!ne||!F.trim()&&!u.some(m=>m.imageData||m.fileData),onClick:()=>ue(),children:e.jsx(en,{})})});return e.jsxs("div",{className:`inputbar${K?" drop-active":""}`,onDragOver:m=>{m.preventDefault(),m.stopPropagation(),j(!0)},onDragLeave:m=>{m.currentTarget.contains(m.relatedTarget)||j(!1)},onDrop:m=>{var P;m.preventDefault(),m.stopPropagation(),j(!1),U(((P=m.dataTransfer)==null?void 0:P.files)??null)},children:[K&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",y("dropHereToAttach")]})}),u.length>0&&e.jsxs("div",{className:"attach-row",children:[u.map(m=>e.jsxs("span",{className:`attach-chip ${m.imageData?"image":m.fileData?"file":m.mode}`,title:m.imageData?y("attachImage",{name:m.name}):m.fileData?y("attachFile",{name:m.name}):m.isDir?y("folderRef",{path:m.path}):m.mode==="reference"?y("refOnly",{path:m.path}):m.mode==="lines"&&m.lines?y("attachLines",{path:m.path,start:m.lines.start,end:m.lines.end}):y("attachContent",{path:m.path}),children:[m.imageData?"🖼":m.fileData?"📄":m.isDir?"📁":m.mode==="reference"?"🔗":"📎"," ",m.name,m.mode==="lines"&&m.lines&&e.jsxs("span",{className:"attach-range",children:["L",m.lines.start,"-",m.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:y("removeAttachment"),onClick:()=>f(m.key??m.path),children:"×"})]},m.key??`${m.path}|${m.mode}|${m.lines?`${m.lines.start}-${m.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:y("attachHint")})]}),H&&H.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:A,"aria-label":y("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:y("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>J(null),children:"Esc"})]}),H.map((m,P)=>e.jsxs("button",{type:"button",className:`slash-item${P===se?" active":""}`,onMouseEnter:()=>W(P),onClick:()=>me(m),children:[e.jsxs("span",{className:"slash-name",children:["/",m.name]}),e.jsx("span",{className:`slash-source ${m.source}`,children:ie[m.source]}),e.jsxs("span",{className:"slash-desc",children:[G(m),m.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(m)})]})]},m.name))]}),V&&e.jsx("div",{className:"modal-backdrop",onClick:()=>q(!1),children:e.jsxs("div",{className:"slash-help",style:k?{width:k}:void 0,onClick:m=>m.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",y("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>q(!1),children:y("close")})]}),e.jsx("div",{className:"slash-help-body",children:o.length===0?e.jsx("div",{className:"slash-help-empty",children:y("slashLoading")}):o.map(m=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",m.name]}),e.jsx("span",{className:`slash-source ${m.source}`,children:ie[m.source]}),e.jsxs("span",{className:"slash-help-desc",children:[G(m),m.argumentHint&&e.jsx("span",{className:"slash-hint",children:I(m)})]})]},m.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:L,type:"file",multiple:!0,hidden:!0,onChange:m=>{U(m.target.files),m.target.value=""}}),e.jsx("textarea",{ref:b,value:F,rows:1,placeholder:y(ne?n?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!ne,onChange:m=>{E(m.target.value),de(m.target.value)},onKeyDown:N,onPaste:B}),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:y("uploadFile"),disabled:!ne,onClick:()=>{var m;return(m=L.current)==null?void 0:m.click()},children:e.jsx(si,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:y("tpl.openPicker"),onClick:z,children:e.jsx(ui,{})}),e.jsx(lr,{state:l,models:i,modelsLoading:c,send:d,onManageModels:R,providerKeys:O,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:Y()})]})]})]})}),cr=r.memo(function({goal:s,models:n,modelsLoading:a,activeConversationId:o,engine:l,send:i}){var W,V,q,k,w,b;const c=fe(),d=l==="dsh",u=!s.conversationId||s.conversationId===o,f=s.goal!==null&&u,[h,x]=r.useState(""),[v,S]=r.useState(s.reviewModel??""),[R,O]=r.useState(s.maxRounds),[y,C]=r.useState(s.locked),[z,G]=r.useState(!1),[I,F]=r.useState(!1),[E,K]=r.useState(!0);r.useEffect(()=>{S(s.reviewModel??""),O(s.maxRounds||0),C(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),r.useEffect(()=>{z&&n.length===0&&!I&&!a&&(F(!0),i({type:"list_models"}))},[z,n.length,I,a,i]),r.useEffect(()=>{n.length>0&&F(!1)},[n.length]);const j=()=>{var L;return v?((L=n.find(A=>A.id===v))==null?void 0:L.name)??v:c("goalBarUseMainModel")},H=()=>{const L=h.trim();L&&(i({type:"set_goal",goal:L,...v?{reviewModel:v}:{},maxRounds:R,locked:y}),x(""),K(!1))},J=()=>{const L=h.trim();L&&(i({type:"start_goal_wizard",text:L,...v?{wizardModel:v}:{},maxRounds:R,locked:y}),x(""),K(!1))},se=(((W=s.wizard)==null?void 0:W.active)??!1)&&u;return se?e.jsx("div",{className:`goalbar goalbar-active ${se?"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:((V=s.wizard)==null?void 0:V.draft)??"",children:[c("goalWizardRunning"),": ",(q=s.wizard)==null?void 0:q.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[c("goalBarRound",{n:(((k=s.wizard)==null?void 0:k.step)??0)+1})," ","/ ",((w=s.wizard)==null?void 0:w.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((b=s.wizard)==null?void 0:b.status)||c("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:c("goalBarClear"),onClick:()=>{i({type:"clear_goal"}),K(!0)},children:e.jsx(Te,{})})]})}):f?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:[c("goalBarReviewing")," ",c("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?c("goalBarPassed"):s.verdict==="fail"?c("goalBarFailed"):`${c("goalBarRound",{n:s.round||1})} · ${s.locked?c("goalBarLocked"):c("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:s.status}),e.jsx("button",{type:"button",className:"goalbar-x",title:c("goalBarClear"),disabled:s.reviewing,onClick:()=>{i({type:"clear_goal"}),K(!0)},children:e.jsx(Te,{})})]})}):E?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:c("goalBarPlaceholder"),onClick:()=>K(!1),children:[e.jsx(ps,{})," ",e.jsx("span",{children:c("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx(ps,{})}),e.jsx("input",{className:"goalbar-input",value:h,placeholder:c("goalBarPlaceholder"),onChange:L=>x(L.target.value),onKeyDown:L=>{L.key==="Enter"&&H()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!h.trim(),onClick:H,children:c("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!h.trim(),title:c("goalWizardTip"),onClick:J,children:["🔍 ",c("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:c(y?"goalBarLocked":"goalBarUnlocked"),onClick:()=>C(L=>(i({type:"set_goal_prefs",locked:!L}),!L)),children:y?e.jsx(oi,{}):e.jsx(Xn,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:c("goalBarClear"),onClick:()=>K(!0),children:e.jsx(yt,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[d?e.jsx("p",{className:"goalbar-dsh-note",children:c("dshNoReviewModel")}):e.jsxs(We,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[c("goalBarReviewModel"),": ",e.jsx("b",{children:j()})]}),open:z,onOpenChange:G,direction:"up",children:[e.jsx("div",{className:"dd-header",children:c("goalBarReviewModel")}),(I||a)&&e.jsx("div",{className:"dd-loading",children:c("loading")}),n.length===0&&!I&&!a&&e.jsx("div",{className:"dd-loading",children:c("noModels")}),e.jsx(Ee,{active:v==="",onClick:()=>{S(""),G(!1),i({type:"set_goal_prefs",reviewModel:""})},children:c("goalBarUseMainModel")}),n.map(L=>e.jsx(Ee,{active:v===L.id,onClick:()=>{S(L.id),G(!1),i({type:"set_goal_prefs",reviewModel:L.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:L.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:L.provider})})]})},L.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>i({type:"list_models"}),children:c("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:c("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:c("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:R,placeholder:c("goalBarUnlimitedShort"),onChange:L=>{const A=parseInt(L.target.value,10);if(Number.isNaN(A)||A<0){O(0);return}O(A)},onBlur:()=>i({type:"set_goal_prefs",maxRounds:R}),onKeyDown:L=>{L.key==="Enter"&&(i({type:"set_goal_prefs",maxRounds:R}),L.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:c(y?"goalBarLocked":"goalBarUnlocked")})]})]})});function dr(t){const s=Math.max(0,t.input??0),n=Math.max(0,t.cacheRead??0),a=Math.max(0,t.cacheWrite??0),o=s+n+a;return{totalInput:o,miss:s,read:n,write:a,hitRate:o>0?Math.min(n/o,1):0,writeRate:o>0?Math.min(a/o,1):0}}const Cn=2e3;function ur(t,s,n=Cn){return t.filter(a=>s-a.t<=n)}function pr(t,s=Cn){if(t.length<2)return 0;const n=t[t.length-1],a=t.find(l=>l.t>=n.t-s)??t[0],o=(n.t-a.t)/1e3;return o<=0?0:Math.max(0,(n.out-a.out)/o)}function Ls(t){if(!t)return 0;let s=0;for(let a=0;a<t.length;a++){const o=t.charCodeAt(a);(o>=12352&&o<=12543||o>=13312&&o<=19903||o>=19968&&o<=40959||o>=63744&&o<=64255||o>=65280&&o<=65519||o===12288)&&s++}const n=t.length-s;return Math.round(s+n/4)}function mr(t){let s=0;for(const n of t)n.type==="text"&&typeof n.text=="string"&&n.text?s+=Ls(n.text):n.type==="thinking"&&typeof n.thinking=="string"&&n.thinking&&(s+=Ls(n.thinking));return s}function hr({chat:t,send:s}){const n=fe(),a=t.state,[o,l]=r.useState(!1),[i,c]=r.useState(""),[d,u]=r.useState(0),f=r.useRef(null),h=t.pathCompletions;r.useEffect(()=>{if(!o)return;const k=setTimeout(()=>{s({type:"complete_path",path:i})},150);return()=>clearTimeout(k)},[i,o,s]),r.useEffect(()=>u(0),[h]),r.useEffect(()=>{const k=document.querySelector(`.status-completions .pc-item[data-idx="${d}"]`);k==null||k.scrollIntoView({block:"nearest"})},[d]);const x=r.useRef([]),v=(a==null?void 0:a.isStreaming)??!1,S=a!=null&&a.streamingMessage?mr(a.streamingMessage.content):0;if(r.useEffect(()=>{if(!v){x.current=[];return}const k=Date.now(),w=x.current,b=w[w.length-1];b&&k-b.t<250||(x.current=ur([...w,{t:k,out:S}],k))},[v,S]),!a)return null;const R=a.stats,O=dr(R.tokens),y=O.hitRate*100,C=O.totalInput===0?"":O.hitRate>=.7?"ok":O.hitRate>=.4?"mid":"warn",z=O.totalInput>0?`${y.toFixed(1)}%`:"—",G=v?pr(x.current):0,I=t.ready?"ok":"busy",F=t.ready?n("connected"):n("connecting"),E=R.contextUsage,K=E.tokens!==null&&E.percent!==null?`${Qe(E.tokens)} / ${Qe(E.contextWindow)}`:"—",j=E.percent??null,H=j===null?"":j>=80?"warn":j>=50?"mid":"ok",J=a.queue.steering.length+a.queue.followUp.length,se=()=>{c(a.cwd),l(!0)},W=(k,w)=>{var L;const b=k.includes("\\")?"\\":"/";c(w?`${k}${b}`:k),u(0),(L=f.current)==null||L.focus()},V=k=>{const w=k.trim();w&&w!==a.cwd&&s({type:"set_cwd",path:w}),l(!1)},q=k=>{if(k.key==="ArrowDown")k.preventDefault(),u(w=>Math.min(w+1,h.length-1));else if(k.key==="ArrowUp")k.preventDefault(),u(w=>Math.max(w-1,0));else if(k.key==="Tab"&&h.length>0){k.preventDefault();const w=h[Math.min(d,h.length-1)];W(w.path,w.type==="dir")}else if(k.key==="Enter"&&!k.nativeEvent.isComposing){const w=i.trim();if(w.endsWith("/")||w.endsWith("\\"))V(w);else if(h.some(b=>b.path===w))V(w);else if(h.length>0&&h[d]){k.preventDefault();const b=h[d];W(b.path,b.type==="dir")}else V(w)}else k.key==="Escape"&&(h.length>0?(k.stopPropagation(),s({type:"complete_path",path:""})):l(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${I}`,title:F}),e.jsx("span",{className:"status-item",children:F}),e.jsx("span",{className:"status-sep",children:"·"}),t.engine&&t.engine!=="pi"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`status-item engine-badge engine-${t.engine}`,title:`${n("engineBadge")}: ${t.engine}`,children:t.engine==="dsh"?"DSH":t.engine}),e.jsx("span",{className:"status-sep",children:"·"})]}),e.jsxs("span",{className:"status-item status-ctx",title:n("contextUsage"),children:[n("context"),e.jsx("span",{className:`ctx-bar ${H}`,children:j!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(j,100)}%`}})}),K]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("cumulativeCost"),children:["$",gr(R.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-cache",title:n("cacheHitTip",{read:Qe(O.read),write:Qe(O.write),miss:Qe(O.miss),input:Qe(O.totalInput)}),children:[n("cacheHit"),e.jsx("b",{className:`cache-pct ${C}`,children:z})]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("sessionMessages"),children:[n("messages")," ",R.totalMessages]}),t.statuses.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsx("span",{className:"status-item ext-status",title:n("pluginStatus"),children:t.statuses.map(k=>k.text).join(" · ")})]}),a.isStreaming&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item working",children:[e.jsx("span",{className:"working-spin"}),n("working"),J>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",J," ",n("queued")]})]}),e.jsx("span",{className:"status-item status-rate",title:n("rateTip"),children:G>0?`${Math.round(G)}${n("tps")}`:"…"})]}),o?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:f,className:"status-cwd-input",value:i,autoFocus:!0,placeholder:n("enterPath"),onChange:k=>c(k.target.value),onKeyDown:q,onBlur:()=>l(!1)}),h.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:k=>k.preventDefault(),children:h.map((k,w)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":w,className:`pc-item ${w===d?"sel":""}`,onMouseEnter:()=>u(w),onClick:()=>W(k.path,k.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:k.type==="dir"?e.jsx(Ze,{}):e.jsx(Gs,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:k.name}),e.jsx("span",{className:"pc-path",children:k.path})]})]})},k.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:n("cwdTip",{path:a.cwd}),onClick:se,children:["📁 ",a.cwd]})]})}function Qe(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function gr(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function fr({dialog:t,send:s}){const n=fe(),[a,o]=r.useState(""),[l,i]=r.useState(0),c=f=>{s({type:"dialog_response",id:t.id,value:f})};r.useEffect(()=>{o(""),i(0);const f=h=>{h.key==="Escape"&&c(null)};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[t.id]);const d=Array.isArray(t.args[0])?t.args[0]:[],u=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("pluginRequest")}),t.title&&t.title!==n("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>c(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[d.map((f,h)=>e.jsx("button",{type:"button",className:`dialog-option ${h===l?"sel":""}`,onMouseEnter:()=>i(h),onClick:()=>c(f),children:f},h)),d.length===0&&e.jsx("div",{className:"dialog-hint",children:n("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:u}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>c(!1),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>c(!0),children:n("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:a,placeholder:u||n("inputPlaceholder"),autoFocus:!0,onChange:f=>o(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.nativeEvent.isComposing&&c(a)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>c(null),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>c(a),children:n("ok")})]})]})]})}function xr({question:t,send:s}){const n=fe(),[a,o]=r.useState({}),[l,i]=r.useState({}),[c,d]=r.useState(()=>t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1);r.useEffect(()=>{o({}),i({}),d(t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1)},[t.id,t.deadline]),r.useEffect(()=>{if(!t.deadline)return;const x=setInterval(()=>{d(v=>{const S=Math.max(0,Math.ceil((t.deadline-Date.now())/1e3));return S<=0&&v>0&&s({type:"question_answer",id:t.id,answers:[],cancelled:!0}),S})},1e3);return()=>clearInterval(x)},[t.id,t.deadline]);const u=x=>{if(x){s({type:"question_answer",id:t.id,answers:[],cancelled:!0});return}const v=t.questions.map(S=>{const R=a[S.id]??[],O=(l[S.id]??"").trim();return{id:S.id,selected:R,...O?{custom:O}:{}}});s({type:"question_answer",id:t.id,answers:v})};r.useEffect(()=>{const x=v=>{v.key==="Escape"&&u(!0)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t.id]);const f=(x,v,S)=>{o(R=>{const O=R[x]??[];return S?{...R,[x]:O.includes(v)?O.filter(y=>y!==v):[...O,v]}:{...R,[x]:[v]}})},h=t.questions.every(x=>{var v;return(((v=a[x.id])==null?void 0:v.length)??0)>0||(l[x.id]??"").trim()!==""});return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":"select",children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("modelQuestion")}),c>=0&&e.jsx("span",{className:"question-timer",children:c>0?n("questionTimeout",{s:c}):n("questionTimeoutExpired")}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>u(!0),children:"✕"})]}),t.questions.map((x,v)=>{var S;return e.jsxs("div",{className:"set-section",children:[e.jsx("div",{className:"set-section-title",children:x.header??`${n("modelQuestion")} ${v+1}`}),e.jsx("p",{className:"set-row-desc",children:x.question}),x.detail&&e.jsx("p",{className:"set-hint",children:x.detail}),(((S=x.options)==null?void 0:S.length)??0)>0&&e.jsx("div",{className:"set-list",children:x.options.map(R=>{const O=(a[x.id]??[]).includes(R.label);return e.jsxs("button",{type:"button",className:`set-row question-option${O?" active":""}`,onClick:()=>f(x.id,R.label,!!x.multiSelect),children:[e.jsxs("span",{className:"set-row-name",children:[x.multiSelect?O?"☑ ":"☐ ":O?"● ":"○ ",R.label]}),R.description&&e.jsx("span",{className:"set-row-desc",children:R.description})]},R.label)})}),e.jsx("input",{className:"set-prompt-input question-custom",placeholder:n("modelQuestionCustom"),value:l[x.id]??"",onChange:R=>i(O=>({...O,[x.id]:R.target.value}))})]},x.id)}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"dialog-submit",disabled:!h,onClick:()=>u(!1),children:n("modelQuestionSubmit")}),e.jsx("button",{type:"button",className:"dialog-dismiss-inline",onClick:()=>u(!0),children:n("cancel")})]})]})}const Ds=t=>`'${t.replace(/'/g,"'\\''")}'`;function vr(t){if(t.x==="?"&&t.y==="?")return"untracked";const s=t.x!==" "&&t.x!=="?",n=t.y!==" "&&t.y!=="?";return s&&n?"both":s?"staged":"unstaged"}function yr({chat:t,send:s,terminal:n,active:a,onSwitchToTerminal:o}){var ze,Ve;const l=fe(),[i,c]=r.useState(null),[d,u]=r.useState([]),[f,h]=r.useState(""),[x,v]=r.useState(new Map),[S,R]=r.useState("changes"),[O,y]=r.useState([]),[C,z]=r.useState(null),[G,I]=r.useState(""),[F,E]=r.useState(!1),[K,j]=r.useState(null),[H,J]=r.useState(null),[se,W]=r.useState(!1),[V,q]=r.useState(!1),[k,w]=r.useState(!1),[b,L]=r.useState(null),[A,ie]=r.useState(!1),[de,me]=r.useState(""),p=r.useRef(0),U=r.useRef(-1),B=r.useRef(-1),Q=r.useRef(-1),ne=r.useRef(-1),ae=r.useRef(void 0),ue=r.useRef(null),N=r.useRef([]),Y=r.useCallback(M=>{if(M.reqId===U.current){if(U.current=-1,q(!1),L(null),!M.ok){L(M.error??"查询失败");return}if(M.notRepo){ie(!0),c(null),u([]),v(new Map),y([]),z(null),I(""),J(null);return}ie(!1);const ge={branch:M.branch??"",detached:!!M.detached,upstream:M.upstream??null,ahead:M.ahead??0,behind:M.behind??0,upstreamGone:!!M.upstreamGone,files:(M.files??[]).map(xe=>({...xe}))},ce=(M.branches??[]).map(xe=>({...xe})),je=new Map;for(const[xe,Ce]of Object.entries(M.stats??{}))je.set(xe,{add:Ce[0],del:Ce[1]});c(ge),u(ce),v(je),h(xe=>{var Ce;return ge.detached?xe||"":ge.branch&&ce.some(T=>T.name===ge.branch)?ge.branch:xe&&ce.some(T=>T.name===xe)?xe:((Ce=ce[0])==null?void 0:Ce.name)??""}),J(xe=>xe&&!ge.files.some(Ce=>Ce.path===xe.file.path)?null:xe)}else if(M.reqId===B.current){if(B.current=-1,W(!1),!M.ok){L(M.error??"查询失败");return}const ge=ue.current;if(!ge)return;J({file:ge,staged:M.stagedText??"",worktree:M.worktreeText??"",untracked:!1})}else if(M.reqId===ne.current){if(ne.current=-1,w(!1),!M.ok){L(M.error??"查询失败");return}y((M.history??[]).map(ge=>({...ge})))}else if(M.reqId===Q.current){if(Q.current=-1,E(!1),!M.ok){L(M.error??"查询失败");return}I(M.text??"")}},[]);r.useEffect(()=>{const M=t.scmData;M&&M.type==="scm_data"&&Y(M)},[t.scmData,Y]);const m=r.useCallback((M,ge)=>{if(!t.ready||t.status!=="open")return!1;const ce=++p.current;return s({...M,reqId:ce})?(ge.current=ce,!0):(p.current-=1,!1)},[t.ready,t.status,s]),P=r.useCallback((M=!1,ge=!1)=>{var ce;!t.ready||t.status!=="open"||(ce=t.state)!=null&&ce.cwd&&(ae.current!==void 0&&ae.current!==t.state.cwd&&(c(null),u([]),v(new Map),y([]),w(!1),ne.current=-1,z(null),I(""),J(null),j(null)),ae.current=t.state.cwd,L(null),m({type:"scm_status"},U)&&(ge||q(!0)))},[t.ready,(ze=t.state)==null?void 0:ze.cwd,t.status,m]),g=r.useCallback(M=>{if(j(M),z(null),ue.current=M,M.x==="?"&&M.y==="?"){J({file:M,staged:"",worktree:"",untracked:!0});return}W(!0),L(null),m({type:"scm_filediff",path:M.path},B)||W(!1)},[m]),D=r.useCallback(M=>{z(M),j(null),J(null),I(""),E(!0),L(null),m({type:"scm_commit",hash:M.hash},Q)||E(!1)},[m]),Z=r.useCallback((M,ge)=>{var Ce,T;if(!t.ready)return;const ce={name:M,command:ge,cwd:"${pwd}"};let je;const xe=t.terminals.find($=>$.title===M);xe?(n.restart(xe.id),s({type:"run_command",terminalId:xe.id,conversationId:xe.conversationId,command:ce,cols:80,rows:24}),je=xe.id):(je=He(),n.create({id:je,conversationId:t.activeConversationId||((Ce=t.state)==null?void 0:Ce.conversationId)||"",title:M,cwd:((T=t.state)==null?void 0:T.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:ce})),n.select(je),o()},[t.ready,(Ve=t.state)==null?void 0:Ve.cwd,t.terminals,o,s,n]),ee=r.useCallback(()=>{const M=de.trim();if(!M||A)return;const ge=M.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");Z("git commit",`git add -A && git commit -m "${ge}"`),me("")},[de,A,Z]),he=r.useCallback(M=>{A||Z("git add",`git add -- ${Ds(M.path)}`)},[A,Z]),ke=r.useCallback(M=>{A||Z("git reset",`git reset HEAD -- ${Ds(M.path)}`)},[A,Z]),pe=r.useCallback(()=>{if(!f||A)return;const M=d.find(ge=>ge.name===f);if(M!=null&&M.remote&&typeof M.remote=="string"){const ge=f.slice(M.remote.length+1);Z("git checkout",`git checkout -b ${ge} ${f} || git checkout ${f}`)}else Z("git checkout",`git checkout ${f}`)},[f,d,A,Z]),De=r.useCallback(()=>Z("git push","git push"),[Z]),Pe=r.useCallback(()=>Z("git pull","git pull"),[Z]),Ie=r.useCallback(()=>{m({type:"scm_history"},ne)||(ne.current=-1)},[m]);r.useEffect(()=>{a&&P()},[a,P]),r.useEffect(()=>{S==="history"&&i&&Ie()},[S,i,Ie]),r.useEffect(()=>{t.scmDirty>0&&a&&P(!1,!0)},[t.scmDirty]),r.useEffect(()=>{if(!a||!t.ready||t.status!=="open")return;const M=setInterval(()=>{document.visibilityState!=="hidden"&&P(!1,!0)},3e4);return()=>clearInterval(M)},[a,t.ready,t.status,P]),r.useEffect(()=>{const M=N.current;if(N.current=t.terminals,!a)return;t.terminals.some(ce=>{var xe;return ce.running!==!1?!1:((xe=M.find(Ce=>Ce.id===ce.id))==null?void 0:xe.running)===!0&&/^git /.test(ce.title)})&&t.ready&&t.status==="open"&&(P(!1,!0),S==="history"&&i&&Ie())},[t.terminals,a,t.ready,t.status,P,S,i,Ie]);const Ke={staged:l("scmStaged"),unstaged:l("scmUnstaged"),untracked:l("scmUntracked"),both:l("scmStagedUnstaged")},Be=M=>{const ge=M.split(`
|
|
320
|
+
`);return e.jsx("pre",{className:"scm-diff-pre",children:ge.map((ce,je)=>{let xe="";return ce.startsWith("diff --git")||ce.startsWith("index ")||ce.startsWith("new file")||ce.startsWith("deleted file")||ce.startsWith("old mode")||ce.startsWith("new mode")||ce.startsWith("similarity index")||ce.startsWith("rename ")||ce.startsWith("copy ")||ce.startsWith("Binary files")||ce.startsWith("---")||ce.startsWith("+++")?xe="hdr":ce.startsWith("@@")?xe="hunk":ce.startsWith("+")?xe="add":ce.startsWith("-")&&(xe="del"),e.jsx("div",{className:`scm-diff-line ${xe}`,children:ce||" "},je)})})};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(pt,{}),l("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":S==="changes",className:S==="changes"?"active":"",onClick:()=>{R("changes"),L(null)},children:l("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":S==="history",className:S==="history"?"active":"",onClick:()=>{R("history"),L(null)},children:l("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:l("scmRefreshTip"),disabled:V,onClick:()=>P(!0),children:e.jsx(at,{className:V?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:l("scmCurrentBranch"),children:[e.jsx(pt,{}),i?i.detached?l("scmDetached"):i.branch:"…",(i==null?void 0:i.upstream)&&e.jsx("span",{className:"scm-upstream",children:i.upstreamGone?l("scmUpstreamGone"):i.ahead>0||i.behind>0?l("scmAheadBehind",{ahead:i.ahead,behind:i.behind}):i.upstream})]}),e.jsxs("select",{className:"scm-select",value:f,disabled:A||d.length===0,title:l("scmSwitchBranch"),onChange:M=>h(M.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:l("scmSelectBranch")}),d.filter(M=>!M.remote).map(M=>e.jsx("option",{value:M.name,children:M.current?`* ${M.name}`:M.name},M.name)),d.some(M=>M.remote)&&e.jsx("optgroup",{label:l("scmRemoteBranches"),children:d.filter(M=>M.remote).map(M=>e.jsx("option",{value:M.name,children:M.name},M.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!f||f===(i==null?void 0:i.branch)||A,title:l("scmSwitchBranchTip",{branch:f}),onClick:pe,children:[e.jsx(pt,{}),l("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!i||i.detached||A,title:l("scmPushTip"),onClick:De,children:[e.jsx(en,{}),l("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!i||i.detached||A,title:l("scmPullTip"),onClick:Pe,children:[e.jsx(tn,{}),l("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:de,placeholder:l("scmCommitPlaceholder"),disabled:A,onChange:M=>me(M.target.value),onKeyDown:M=>{M.key==="Enter"&&!M.nativeEvent.isComposing&&ee()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!de.trim()||A,title:l("scmCommitTip"),onClick:ee,children:[e.jsx(ot,{}),l("scmCommit")]})]})]}),e.jsxs("div",{className:"scm-body",children:[S==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:l("scmHistory")}),O.length>0&&e.jsx("span",{className:"scm-files-count",children:O.length})]}),e.jsx("div",{className:"scm-history-list",children:A?e.jsx("div",{className:"scm-empty",children:l("scmNotGitRepo")}):!i||k?e.jsx("div",{className:"scm-empty",children:t.status==="open"?l("scmLoading"):l("scmConnecting")}):O.length===0?e.jsx("div",{className:"scm-empty",children:l("scmNoHistory")}):O.map(M=>e.jsxs("button",{type:"button",className:`scm-commit ${(C==null?void 0:C.hash)===M.hash?"active":""}`,onClick:()=>D(M),title:M.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:M.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:M.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[M.shortHash," · ",M.author," · ",M.date]}),M.decorations&&e.jsx("span",{className:"scm-commit-refs",children:M.decorations})]})]},M.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:l("scmChanges")}),i&&i.files.length>0&&e.jsx("span",{className:"scm-files-count",children:i.files.length})]}),e.jsx("div",{className:"scm-files-list",children:A?e.jsx("div",{className:"scm-empty",children:l("scmNotGitRepo")}):i?i.files.length===0?e.jsx("div",{className:"scm-empty",children:l("scmNoChanges")}):i.files.map(M=>{const ge=vr(M),ce=x.get(M.path);return e.jsxs("div",{className:`scm-file ${(K==null?void 0:K.path)===M.path?"active":""}`,title:Ke[ge],onClick:()=>g(M),children:[e.jsx("span",{className:`scm-file-xy ${ge==="untracked"?"q":"x"}`,children:M.x!==" "?M.x:" "}),e.jsx("span",{className:`scm-file-xy ${ge==="untracked"?"q":"y"}`,children:M.y!==" "?M.y:" "}),e.jsx("span",{className:"scm-file-path",children:M.path}),ce&&(ce.add>0||ce.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[ce.add>0&&e.jsxs("span",{className:"add",children:["+",ce.add]}),ce.del>0&&e.jsxs("span",{className:"del",children:["-",ce.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(M.y!==" "||ge==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:l("scmStageTip",{path:M.path}),onClick:je=>{je.stopPropagation(),he(M)},children:"+"}),ge==="staged"||ge==="both"?e.jsx("button",{type:"button",className:"scm-act",title:l("scmUnstageTip",{path:M.path}),onClick:je=>{je.stopPropagation(),ke(M)},children:"−"}):null]})]},M.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?l("scmLoading"):l("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:S==="history"?C?`${C.shortHash} ${C.subject}`:l("scmCommitDetail"):K?K.path:l("scmDiff")}),(S==="history"?F:se)&&e.jsx("span",{className:"scm-diff-loading",children:l("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:S==="history"?e.jsxs(e.Fragment,{children:[b&&e.jsx("div",{className:"scm-error",children:b}),!C&&!b&&e.jsx("div",{className:"scm-empty",children:l("scmSelectCommitHint")}),C&&F&&!b&&e.jsx("div",{className:"scm-empty",children:l("scmLoading")}),C&&!F&&!b&&G?Be(G):null]}):e.jsxs(e.Fragment,{children:[b&&e.jsx("div",{className:"scm-error",children:b}),!K&&!b&&e.jsx("div",{className:"scm-empty",children:l("scmSelectFileHint")}),K&&!H&&!b&&e.jsx("div",{className:"scm-empty",children:l("scmLoading")}),K&&H&&H.untracked&&e.jsx("div",{className:"scm-empty",children:l("scmUntrackedNote")}),K&&H&&!H.untracked&&e.jsxs(e.Fragment,{children:[H.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:l("scmStaged")}),Be(H.staged)]}),H.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:l("scmUnstaged")}),Be(H.worktree)]}),!H.staged&&!H.worktree&&e.jsx("div",{className:"scm-empty",children:l("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(Je,{}),e.jsx("span",{children:l("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:o,children:l("scmViewTerminal")})]})]})}function kr({entry:t,send:s}){const n=r.useRef(null);return r.useEffect(()=>{const a=n.current;if(!a)return;let o;try{o=t.module.mount(a,Fi(t.info.id,l=>s(l)))}catch(l){console.error(`[plugin:${t.info.id}] mount failed:`,l),a.textContent=`插件 ${t.info.name} 挂载失败`}return()=>{if(typeof o=="function")try{o()}catch(l){console.error(`[plugin:${t.info.id}] cleanup failed:`,l)}a.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:n})}function br({send:t,piConfigured:s,piAgentInstalled:n,providers:a,installResult:o,onClose:l}){const i=fe(),[c,d]=r.useState(!1),[u,f]=r.useState(""),[h,x]=r.useState(""),[v,S]=r.useState(!1);r.useEffect(()=>{t({type:"list_providers"})},[t]),r.useEffect(()=>{s&&l()},[s,l]),r.useEffect(()=>{o&&d(!1)},[o]),r.useEffect(()=>{var G;!u&&a.length>0&&f(((G=a.find(I=>!I.configured))==null?void 0:G.id)??a[0].id)},[a,u]);const R=()=>{c||(d(!0),t({type:"install_pi_agent"}))},O=()=>{!h.trim()||v||(S(!0),t({type:"set_provider_api_key",provider:u.trim(),apiKey:h.trim()}),setTimeout(()=>S(!1),3e3))},y=()=>{t({type:"get_state"}),t({type:"list_providers"})},C=a.find(G=>G.id===u),z=o!==null&&!o.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:l,children:e.jsx(Te,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(rt,{className:"modal-head-icon"}),e.jsx("h2",{children:i("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:i("setupDesc")}),z?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:i("installFailed")}),e.jsx("pre",{className:"setup-detail",children:o.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:c,onClick:R,children:i("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:l,children:i("skip")})]})]}):n||o!=null&&o.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:o!=null&&o.ok?i("installDone"):i("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:i("provider")}),e.jsxs("select",{value:u,onChange:G=>f(G.target.value),children:[a.length===0&&e.jsx("option",{value:"",children:i("loading")}),a.map(G=>e.jsxs("option",{value:G.id,children:[G.name,"(",G.id,")",G.configured?` · ${i("configured")}`:""]},G.id))]}),(C==null?void 0:C.configured)&&e.jsx("div",{className:"field-hint",children:i("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:i("apiKey")}),e.jsx("input",{type:"password",value:h,onChange:G=>x(G.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!h.trim()||v||!u,onClick:O,children:i(v?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:y,children:[e.jsx(at,{})," ",i("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:c,onClick:R,children:i(c?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:l,children:i("skip")})]})]})})}const jr=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],Vt=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),wr=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[Vt()]});function Pt(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:[Vt()]).map(s=>{var n;return{id:s.id,name:s.name??"",reasoning:s.reasoning??!1,input:(n=s.input)!=null&&n.includes("image")?"text-image":"text",contextWindow:s.contextWindow?String(s.contextWindow):"",maxTokens:s.maxTokens?String(s.maxTokens):""}})}}function Nr({send:t,providers:s,providerStatus:n,providerKeys:a,fetchModelsResult:o,refreshProviderResult:l,cloneProviderResult:i,onClose:c}){const d=fe(),[u,f]=r.useState(null),[h,x]=r.useState({}),[v,S]=r.useState({}),[R,O]=r.useState(null),[y,C]=r.useState(!1),[z,G]=r.useState(0),[I,F]=r.useState(null),E=r.useRef(0),[K,j]=r.useState({});r.useRef(0);const H=r.useRef(0),[J,se]=r.useState(null),[W,V]=r.useState(null);r.useRef(0);const q=r.useRef(0),[k,w]=r.useState(null),[b,L]=r.useState(""),[A,ie]=r.useState(null);r.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"}),t({type:"list_provider_keys"})},[t]);const de=()=>{if(!u)return;const N=u.baseUrl.trim();if(!N){F({ok:!1,text:d("fetchModelsNeedBaseUrl")});return}if(y)return;C(!0),F(null);const Y=z+1;G(Y),t({type:"fetch_models",reqId:Y,baseUrl:N,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};r.useEffect(()=>{var N;if(!(!o||o.reqId===E.current))if(E.current=o.reqId,C(!1),o.ok&&((N=o.models)!=null&&N.length)){const Y=o.models;f(m=>{if(!m)return m;const P=m.models.map(ee=>{var pe;if(!ee.id.trim())return ee;const he=Y.find(De=>De.id===ee.id.trim());if(!he)return ee;const ke={...ee};return!ke.name&&he.name&&(ke.name=he.name),!ke.contextWindow&&he.contextWindow&&(ke.contextWindow=String(he.contextWindow)),!ke.maxTokens&&he.maxTokens&&(ke.maxTokens=String(he.maxTokens)),ke.input==="text"&&((pe=he.input)!=null&&pe.includes("image"))&&(ke.input="text-image"),!ke.reasoning&&he.reasoning&&(ke.reasoning=!0),ke}),g=new Set(P.map(ee=>ee.id.trim()).filter(Boolean)),D=Y.filter(ee=>!g.has(ee.id)).map(ee=>{var he;return{id:ee.id,name:ee.name??"",reasoning:ee.reasoning??!1,input:(he=ee.input)!=null&&he.includes("image")?"text-image":"text",contextWindow:ee.contextWindow?String(ee.contextWindow):"",maxTokens:ee.maxTokens?String(ee.maxTokens):""}}),Z=[...P,...D];return Z.some(ee=>ee.id.trim())?{...m,models:Z.filter(ee=>ee.id.trim())}:m}),F({ok:!0,text:d("fetchModelsOk",{n:Y.length})})}else F({ok:!1,text:o.error||d("fetchModelsEmpty")})},[o]);const me=N=>{const Y=(h[N.id]??"").trim();!Y||R||(O(N.id),t({type:"add_provider_key",provider:N.id,apiKey:Y,name:(v[N.id]??"").trim()||void 0}),setTimeout(()=>{O(null),x(m=>({...m,[N.id]:""})),S(m=>({...m,[N.id]:""})),t({type:"list_providers"}),t({type:"list_provider_keys"})},1500))},p=(N,Y)=>{t({type:"activate_provider_key",provider:N,keyName:Y}),t({type:"list_provider_keys"})},U=(N,Y)=>{window.confirm(d("removeKeyConfirm"))&&(t({type:"remove_provider_key",provider:N,keyName:Y}),t({type:"list_provider_keys"}))},B=()=>{if(!A)return;const N=A.providerId.trim();if(!N||!A.apiKey.trim())return;const Y=A.models.filter(P=>P.id.trim()).map(P=>({id:P.id.trim(),name:P.name.trim()||void 0,reasoning:P.reasoning||void 0,input:P.input==="text-image"?["text","image"]:void 0,contextWindow:P.contextWindow?Number(P.contextWindow):void 0,maxTokens:P.maxTokens?Number(P.maxTokens):void 0})),m={providerId:N,name:A.name.trim()||void 0,api:A.api.trim()||void 0,baseUrl:A.baseUrl.trim()||void 0,apiKey:A.apiKey.trim()||void 0,authHeader:A.authHeader||void 0,models:Y};t({type:"save_model_config",providerId:N,config:m}),ie(null),c()},Q=()=>{if(!u)return;const N=u.providerId.trim(),Y=u.models.filter(P=>P.id.trim()).map(P=>({id:P.id.trim(),name:P.name.trim()||void 0,reasoning:P.reasoning||void 0,input:P.input==="text-image"?["text","image"]:void 0,contextWindow:P.contextWindow?Number(P.contextWindow):void 0,maxTokens:P.maxTokens?Number(P.maxTokens):void 0})),m={providerId:N,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:Y};t({type:"save_model_config",providerId:N,config:m}),c()};r.useEffect(()=>{!l||l.reqId===H.current||(H.current=l.reqId,j({}))},[l]),r.useEffect(()=>{if(!(!i||i.reqId===q.current)){if(q.current=i.reqId,se(null),i.ok){const N=i.configs;if(N&&N.length>1){w(N.map(Y=>Pt({...Y,apiKey:""}))),L(""),V(null);return}if(i.config){ie(Pt({...i.config,apiKey:""})),V(null);return}}i.error&&V({ok:!1,text:i.error})}},[i]);const ne=N=>{window.confirm(d("clearKeyConfirm",{id:N}))&&t({type:"clear_provider_api_key",provider:N})},ae=N=>{window.confirm(d("deleteProviderConfirm",{id:N.providerId,n:N.models.length}))&&t({type:"delete_model_config",providerId:N.providerId})},ue=(N,Y)=>{u&&f({...u,models:u.models.map((m,P)=>P===N?{...m,...Y}:m)})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal model-modal",onClick:N=>N.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":d("close"),onClick:c,children:e.jsx(Te,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:A?"添加密钥":k?`批量创建供应商 (${k.length}个接口)`:d(u?"editProvider":"manageModelsTitle")})}),A?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsxs("p",{className:"modal-desc",style:{marginBottom:12},children:["为 ",e.jsx("strong",{children:A.api})," · ",A.baseUrl||"(无 baseUrl)"," · ",A.models.length," 个模型添加第二把密钥,只需指定新供应商名字和密钥即可。"]}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["供应商名字 ",e.jsx("em",{children:"(新 ID,如 opencode-2)"})]}),e.jsx("input",{type:"text",value:A.providerId,onChange:N=>ie({...A,providerId:N.target.value}),placeholder:"opencode-2"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:"API 密钥"}),e.jsx("input",{type:"password",value:A.apiKey,onChange:N=>ie({...A,apiKey:N.target.value}),placeholder:"sk-… 第二把 key"})]})]}),e.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:8},children:[A.models.slice(0,5).map(N=>N.id).join(", "),A.models.length>5?` … +${A.models.length-5}`:""]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>ie(null),children:d("cancel")}),e.jsx("button",{type:"button",className:"btn",onClick:()=>{const N=A;ie(null),f(N)},children:"高级编辑"}),e.jsx("button",{type:"button",className:"btn primary",disabled:!A.providerId.trim()||!A.apiKey.trim(),onClick:B,children:d("save")})]})]}):k?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsxs("p",{className:"modal-desc",style:{marginBottom:12},children:["该供应商含多种接口(",k.map(N=>N.api).join("、"),"),已按接口拆分为 ",k.length," 个自定义供应商,分别保存后才能让所有模型(如 muse-spark)都可用。统一填入第二把 API 密钥后一键保存。"]}),e.jsxs("label",{className:"field",style:{marginBottom:16},children:[e.jsxs("span",{className:"field-label",children:["统一 API 密钥(将应用到全部 ",k.length," 个供应商)"]}),e.jsx("input",{type:"password",value:b,onChange:N=>L(N.target.value),placeholder:"sk-… 第二把 key"})]}),e.jsx("div",{className:"provider-list",style:{marginBottom:16},children:k.map((N,Y)=>e.jsxs("div",{className:"provider-row",style:{flexDirection:"column",alignItems:"stretch",gap:6},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[e.jsx("strong",{children:N.providerId}),e.jsx("span",{style:{opacity:.7},children:N.api})]}),e.jsxs("div",{className:"provider-sub",style:{fontSize:12,opacity:.7},children:[N.baseUrl||"(无 baseUrl)"," · ",N.models.length," 个模型:",N.models.slice(0,3).map(m=>m.id).join(", "),N.models.length>3?` … +${N.models.length-3}`:""]}),e.jsx("input",{type:"text",value:N.providerId,onChange:m=>w(P=>P.map((g,D)=>D===Y?{...g,providerId:m.target.value}:g)),placeholder:"供应商 ID",style:{fontSize:12}}),e.jsx("input",{type:"text",value:N.baseUrl,onChange:m=>w(P=>P.map((g,D)=>D===Y?{...g,baseUrl:m.target.value}:g)),placeholder:"baseUrl 链接,如 https://api.opencode.ai/zen/v1 或 http://127.0.0.1:4096",style:{fontSize:12}})]},Y))})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>w(null),children:d("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!b.trim(),onClick:()=>{for(const N of k){const Y=N.providerId.trim();if(!Y)continue;const m=N.models.filter(g=>g.id.trim()).map(g=>({id:g.id.trim(),name:g.name.trim()||void 0,reasoning:g.reasoning||void 0,input:g.input==="text-image"?["text","image"]:void 0,contextWindow:g.contextWindow?Number(g.contextWindow):void 0,maxTokens:g.maxTokens?Number(g.maxTokens):void 0})),P={providerId:Y,name:N.name.trim()||void 0,api:N.api.trim()||void 0,baseUrl:N.baseUrl.trim()||void 0,apiKey:b.trim()||void 0,authHeader:N.authHeader||void 0,models:m};t({type:"save_model_config",providerId:Y,config:P})}w(null),c()},children:["一键保存全部 (",k.length,")"]})]})]}):u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[d("providerId")," ",e.jsx("em",{children:d("providerIdHint")})]}),e.jsx("input",{type:"text",value:u.providerId,disabled:s.some(N=>N.providerId===u.providerId),onChange:N=>f({...u,providerId:N.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:d("displayName")}),e.jsx("input",{type:"text",value:u.name,onChange:N=>f({...u,name:N.target.value}),placeholder:d("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:d("apiType")}),e.jsx("select",{value:u.api,onChange:N=>f({...u,api:N.target.value}),children:jr.map(N=>e.jsx("option",{value:N,children:N},N))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:d("baseUrlHint")})]}),e.jsx("input",{type:"text",value:u.baseUrl,onChange:N=>f({...u,baseUrl:N.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:d("apiKey")}),e.jsx("input",{type:"password",value:u.apiKey,onChange:N=>f({...u,apiKey:N.target.value}),placeholder:d("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:N=>f({...u,authHeader:N.target.checked})}),e.jsx("span",{children:d("authHeader")})]})]}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:d("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[I&&e.jsx("span",{className:`fetch-msg ${I.ok?"ok":"err"}`,title:I.text,children:I.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:y||!u.baseUrl.trim(),title:d("fetchModelsHint"),onClick:de,children:[e.jsx(Wt,{})," ",d(y?"fetchingModels":"fetchModels")]})]})]}),u.models.map((N,Y)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:N.id,onChange:m=>ue(Y,{id:m.target.value}),placeholder:d("modelIdReq")}),e.jsx("input",{type:"text",value:N.name,onChange:m=>ue(Y,{name:m.target.value}),placeholder:d("displayName")}),e.jsxs("select",{value:N.input,onChange:m=>ue(Y,{input:m.target.value}),children:[e.jsx("option",{value:"text",children:d("text")}),e.jsx("option",{value:"text-image",children:d("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:N.reasoning,onChange:m=>ue(Y,{reasoning:m.target.checked})}),e.jsx("span",{children:d("reasoning")})]}),e.jsx("input",{type:"number",value:N.contextWindow,onChange:m=>ue(Y,{contextWindow:m.target.value}),placeholder:d("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:N.maxTokens,onChange:m=>ue(Y,{maxTokens:m.target.value}),placeholder:d("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:d("removeModel"),onClick:()=>f({...u,models:u.models.filter((m,P)=>P!==Y)}),children:e.jsx(Le,{})})]},Y)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>f({...u,models:[...u.models,Vt()]}),children:[e.jsx($e,{})," ",d("addModel")]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>f(null),children:d("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(N=>N.id.trim()),onClick:Q,children:d("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-fixed-hint",children:e.jsxs("div",{className:"form-section-title",children:[d("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:d("hintKeyOnly")})]})}),e.jsxs("div",{className:"model-modal-body",children:[e.jsxs("div",{className:"provider-list",children:[n.length===0&&e.jsx("div",{className:"dd-loading",children:d("loading")}),n.map(N=>{const Y=a[N.id]??[];return e.jsxs("div",{className:"provider-row provider-key-row",children:[e.jsxs("div",{className:"provider-key-head",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:N.name}),e.jsxs("span",{className:"provider-sub",children:[N.id,N.configured&&e.jsx("span",{className:"auth-badge",children:d("configuredBadge")}),N.source&&!N.configured&&e.jsx("span",{className:"auth-badge dim",children:N.source})]})]}),N.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:d("clearKeyTitle"),onClick:()=>ne(N.id),children:[e.jsx(Le,{})," ",d("clearKey")]})]}),e.jsxs("div",{className:"provider-keys",children:[Y.length===0&&e.jsx("div",{className:"provider-key-empty",children:d("noKeyYet")}),Y.map(m=>e.jsxs("div",{className:`provider-key-item ${m.active?"active":""}`,children:[e.jsx("span",{className:"provider-key-dot",children:m.active?"●":"○"}),e.jsx("span",{className:"provider-key-label",children:m.name}),!m.active&&e.jsx("button",{type:"button",className:"iconbtn",title:d("activateKey"),onClick:()=>p(N.id,m.name),children:e.jsx(ot,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:d("removeKey"),onClick:()=>U(N.id,m.name),children:e.jsx(Le,{})})]},m.name)),e.jsxs("div",{className:"provider-add-key",children:[e.jsx("input",{type:"text",className:"key-input key-input-name",placeholder:d("keyNamePh"),value:v[N.id]??"",onChange:m=>S(P=>({...P,[N.id]:m.target.value}))}),e.jsx("input",{type:"password",className:"key-input key-input-value",placeholder:d("addKeyPlaceholder"),value:h[N.id]??"",onChange:m=>x(P=>({...P,[N.id]:m.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(h[N.id]??"").trim()||R===N.id,onClick:()=>me(N),children:[e.jsx($e,{})," ",R===N.id?d("savingKey"):d("addKey")]})]})]})]},N.id)})]}),e.jsx("div",{className:"form-section-title",children:d("customProviders")}),e.jsx("p",{className:"modal-desc",children:d("customDesc")}),s.length===0&&e.jsx("div",{className:"dd-loading",children:d("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:s.map(N=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:N.providerId}),e.jsxs("span",{className:"provider-sub",children:[N.api??"—",N.baseUrl?` · ${N.baseUrl}`:"",N.models.length>0&&` · ${d("modelsCount",{n:N.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:d("edit"),onClick:()=>f(Pt(N)),children:e.jsx(Ys,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:d("delete"),onClick:()=>ae(N),children:e.jsx(Le,{})})]})]},N.providerId))})]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>f(wr()),children:[e.jsx($e,{})," ",d("addProvider")]})})]})]})})}function Cr({plugin:t,send:s}){const n=fe(),a=t.settingsSchema??[],[o,l]=r.useState(()=>({...t.settingsValues??{}})),[i,c]=r.useState(!1);if(a.length===0)return null;const d=(x,v)=>l(S=>({...S,[x]:v})),u=a.some(x=>{var v;return o[x.key]!==((v=t.settingsValues)==null?void 0:v[x.key])}),f=()=>{c(!0),s({type:"plugin_settings",pluginId:t.id,values:o}),setTimeout(()=>c(!1),800)},h=()=>l({...t.settingsValues??{}});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:a.map(x=>e.jsxs("label",{className:"plugin-settings-field",title:x.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:x.label}),x.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!o[x.key],onChange:v=>d(x.key,v.target.checked)}):x.type==="select"?e.jsx("select",{value:String(o[x.key]??""),onChange:v=>d(x.key,v.target.value),children:(x.options??[]).map(v=>e.jsx("option",{value:v,children:v},v))}):e.jsx("input",{type:x.type==="password"?"password":x.type==="number"?"number":"text",value:String(o[x.key]??""),min:x.min,max:x.max,onChange:v=>d(x.key,x.type==="number"?Number(v.target.value):v.target.value)})]},x.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!u||i,onClick:f,children:n(i?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:h,children:n("pluginSettingsReset")})]})]})}function Sr(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function it({text:t}){const s=r.useRef(null),[n,a]=r.useState(!1),o=()=>{var i;const l=(i=s.current)==null?void 0:i.getBoundingClientRect();l&&a(window.innerWidth-l.right<340)};return e.jsxs("span",{ref:s,className:`set-tip${n?" flip":""}`,tabIndex:0,"aria-label":t,onMouseEnter:o,onFocus:o,children:["?",e.jsx("span",{className:"set-tip-bubble",role:"tooltip",children:t})]})}function Ae({title:t,subtitle:s,tip:n,enabled:a,onToggle:o,action:l}){const i=fe();return e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[t,n&&e.jsx(it,{text:n})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),l,e.jsx("button",{type:"button",className:`set-switch ${a?"on":""}`,role:"switch","aria-checked":a,title:i(a?"settingsEnabled":"settingsDisabled"),onClick:o,children:e.jsx("span",{className:"set-switch-knob"})})]})}function Tr({chat:t,send:s,terminal:n,onSwitchToTerminal:a,onClose:o}){var Y,m,P;const l=fe(),i=t.settings,c=t.engine==="dsh",[d,u]=r.useState("prompt"),f=r.useRef(null);r.useEffect(()=>{var g;(g=f.current)==null||g.scrollTo({top:0})},[d]),r.useEffect(()=>{d==="plugins"&&t.engine==="dsh"&&s({type:"dsh_patches_list"})},[d,t.engine,s]);const[h,x]=r.useState(""),[v,S]=r.useState("append"),R=r.useRef(!1),[O,y]=r.useState(""),[C,z]=r.useState("append"),G=r.useRef(!1),[I,F]=r.useState(""),E=r.useRef(!1),[K,j]=r.useState(""),[H,J]=r.useState(!1),[se,W]=r.useState(null),[V,q]=r.useState(null);r.useEffect(()=>{i&&(S(i.promptMode),!R.current&&(x(v==="append"||i.customSystemPrompt?i.customSystemPrompt:i.defaultSystemPrompt||""),z(i.visionBridgePromptMode),!G.current&&(y(C==="append"||i.visionBridgePrompt?i.visionBridgePrompt:i.visionBridgeDefaultPrompt||""),E.current||F(i.reviewPrompt))))},[i,v,C]);const[k,w]=r.useState(String((i==null?void 0:i.terminalBashIdleMs)??15e3));if(r.useEffect(()=>{w(String((i==null?void 0:i.terminalBashIdleMs)??15e3))},[i==null?void 0:i.terminalBashIdleMs]),!i)return null;const b=[{id:"prompt",icon:e.jsx(Qs,{}),label:l("settingsSystemPrompt")},{id:"terminal",icon:e.jsx(Je,{}),label:l("settingsTerminalTools")},{id:"display",icon:e.jsx(Xe,{}),label:l("settingsMessageDisplay")},{id:"skills",icon:e.jsx(rt,{}),label:l("settingsSkills"),count:i.skills.length},{id:"extensions",icon:e.jsx(ms,{}),label:l("settingsExtensions"),count:i.extensions.length},{id:"plugins",icon:e.jsx(Nt,{}),label:l("settingsUiPlugins"),count:t.plugins.length},{id:"review",icon:e.jsx(ut,{}),label:l("settingsReview"),count:i.reviewSkills.length},...c?[]:[{id:"vision",icon:e.jsx(Bt,{}),label:l("settingsVisionBridge")}],{id:"presets",icon:e.jsx(ei,{}),label:l("settingsPresets"),count:i.presets.length}],L=new Set(i.disabledSkills),A=new Set(i.disabledExtensions),ie=g=>s({type:"set_settings",...g}),de=g=>{const D=new Set(L);D.has(g.name)?D.delete(g.name):D.add(g.name),ie({disabledSkills:[...D]})},me=new Set(i.disabledPlugins??[]),p=g=>{const D=new Set(me);D.has(g.id)?D.delete(g.id):D.add(g.id),ie({disabledPlugins:[...D]})},U=g=>{const D=new Set(A);D.has(g.id)?D.delete(g.id):D.add(g.id),ie({disabledExtensions:[...D]})},B=(g,D)=>{var ke,pe;const Z={name:g,command:D,cwd:"${pwd}"};let ee;const he=t.terminals.find(De=>De.title===g);he?(n.restart(he.id),s({type:"run_command",terminalId:he.id,conversationId:he.conversationId,command:Z,cols:80,rows:24}),ee=he.id):(ee=He(),n.create({id:ee,conversationId:t.activeConversationId||((ke=t.state)==null?void 0:ke.conversationId)||"",title:g,cwd:((pe=t.state)==null?void 0:pe.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Z})),n.select(ee),a(),o()},Q=g=>{W(null),B(`${l("uninstallTitle")} ${g}`,`pi remove npm:${g}`)},ne=g=>{q(null),B(`${l("uninstallTitle")} ${g}`,`pi-web-ui uninstall ${g}`)},ae=(g,D)=>{B(`${l("pluginUpdate")} ${g}`,`pi-web-ui install ${D} --name ${g} --force`)},ue=g=>{const D=new Set(i.reviewSkills.filter(Z=>!Z.enabled).map(Z=>Z.name));D.has(g.name)?D.delete(g.name):D.add(g.name),ie({reviewDisabledSkills:[...D]})},N=()=>{const g=v==="replace"&&i.defaultSystemPrompt&&h===i.defaultSystemPrompt?"":h;ie({promptMode:v,customSystemPrompt:g})};return e.jsx("div",{className:"modal-backdrop",onClick:o,children:e.jsxs("div",{className:"modal settings-modal",onClick:g=>g.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":l("close"),onClick:o,children:e.jsx(Te,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(ft,{className:"modal-head-icon"}),e.jsx("h2",{children:l("settingsTitle")}),e.jsx(it,{text:l("settingsDesc")})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-rail","aria-label":l("settingsTitle"),children:b.map(g=>e.jsxs("button",{type:"button",className:`settings-tab${d===g.id?" active":""}`,"aria-current":d===g.id?"true":void 0,title:g.label,onClick:()=>u(g.id),children:[e.jsx("span",{className:"settings-tab-icon",children:g.icon}),e.jsx("span",{className:"settings-tab-label",children:g.label}),g.count!==void 0&&e.jsx("span",{className:"set-count",children:g.count})]},g.id))}),e.jsxs("div",{className:"modal-body",ref:f,children:[d==="prompt"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ut,{className:"set-section-icon"}),l("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:l("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:v,onChange:g=>{const D=g.target.value;S(D),ie({promptMode:D})},children:[e.jsx("option",{value:"append",children:l("promptModeAppend")}),e.jsx("option",{value:"replace",children:l("promptModeReplace")})]}),e.jsx(it,{text:l(v==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:l("promptPlaceholder"),value:h,onFocus:()=>R.current=!0,onBlur:()=>{R.current=!1,N()},onChange:g=>x(g.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":H,onClick:()=>J(g=>!g),children:[l("settingsViewPrompt")," ",H?"▴":"▾"]}),H&&e.jsxs("div",{className:"set-prompt-view",children:[e.jsxs("div",{className:"set-prompt-view-head",children:[e.jsx("span",{children:l("settingsViewPromptHint")}),e.jsx(ln,{text:i.effectiveSystemPrompt})]}),i.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:i.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:l("settingsViewPromptEmpty")})]})]}),d==="terminal"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Je,{className:"set-section-icon"}),l("settingsTerminalTools")]}),e.jsx(Ae,{title:l("terminalToolsEnabled"),tip:l("settingsTerminalToolsDesc"),enabled:i.terminalToolsEnabled,onToggle:()=>ie({terminalToolsEnabled:!i.terminalToolsEnabled})}),!i.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:l("terminalToolsOffHint")}),e.jsx(Ae,{title:l("terminalBashTakeover"),tip:l("terminalBashTakeoverDesc"),enabled:i.terminalBash,onToggle:()=>ie({terminalBash:!i.terminalBash})}),i.terminalBash&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:l("terminalBashIdleMs")}),e.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:k,onChange:g=>w(g.target.value),onBlur:()=>{const g=Math.max(0,Math.floor(Number(k)||0));w(String(g)),g!==i.terminalBashIdleMs&&ie({terminalBashIdleMs:g})}})]})]}),d==="display"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Xe,{className:"set-section-icon"}),l("settingsMessageDisplay")]}),e.jsx(Ae,{title:l("thinkingWrap"),tip:l("thinkingWrapDesc"),enabled:i.thinkingWrap??!0,onToggle:()=>ie({thinkingWrap:!(i.thinkingWrap??!0)})}),e.jsx(Ae,{title:l("toolsWrap"),tip:l("toolsWrapDesc"),enabled:i.toolsWrap??!0,onToggle:()=>ie({toolsWrap:!(i.toolsWrap??!0)})})]}),d==="skills"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(rt,{className:"set-section-icon"}),l("settingsSkills"),e.jsx("span",{className:"set-count",children:i.skills.length})]}),i.skills.length===0?e.jsx("p",{className:"set-empty",children:l(c?"dshSkillsNote":"noSkills")}):e.jsx("div",{className:"set-list",children:i.skills.map(g=>e.jsx(Ae,{title:g.name,subtitle:g.description,enabled:g.enabled,onToggle:()=>de(g)},g.name))})]}),d==="extensions"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ms,{className:"set-section-icon"}),l("settingsExtensions"),e.jsx("span",{className:"set-count",children:i.extensions.length})]}),i.extensions.length===0?e.jsx("p",{className:"set-empty",children:l(c?"dshExtensionsNote":"noExtensions")}):e.jsx("div",{className:"set-list",children:i.extensions.map(g=>{const D=g.id.startsWith("npm:")?g.id.slice(4):null;return e.jsx(Ae,{title:g.name,subtitle:g.path,enabled:g.enabled,onToggle:()=>U(g),action:D?se===g.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:l("uninstallConfirmHint"),onClick:()=>Q(D),children:l("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:l("uninstallHint"),onClick:()=>W(g.id),children:[e.jsx(Le,{}),l("uninstallExt")]}):void 0},g.id)})})]}),d==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Nt,{className:"set-section-icon"}),l("settingsUiPlugins"),e.jsx("span",{className:"set-count",children:t.plugins.length})]}),t.plugins.length===0?e.jsx("p",{className:"set-empty",children:l("noUiPlugins")}):e.jsx("div",{className:"set-list",children:t.plugins.map(g=>{var D;return e.jsxs(e.Fragment,{children:[e.jsx(Ae,{title:`${g.icon?`${g.icon} `:""}${g.name}`,subtitle:(g.error?`${g.id} · ${g.error}`:g.source?`${g.id} · ${g.source}`:`${g.id} · ${l("uiPluginNoSource")}`)+((D=g.permissions)!=null&&D.length?` · ${l("uiPluginPerms")}: ${g.permissions.join(", ")}`:""),enabled:!me.has(g.id)&&!g.error,onToggle:()=>!g.error&&p(g),action:e.jsxs("div",{className:"set-row-actions",children:[g.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:l("pluginUpdateHint"),onClick:()=>ae(g.id,g.source),children:[e.jsx(at,{}),l("pluginUpdate")]}),V===g.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:l("pluginUninstallHint"),onClick:()=>ne(g.id),children:l("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:l("pluginUninstallHint"),onClick:()=>q(g.id),children:[e.jsx(Le,{}),l("uninstallExt")]})]})},g.id),g.settingsSchema&&g.settingsSchema.length>0&&e.jsx(Cr,{plugin:g,send:s})]})})})]}),d==="plugins"&&t.engine==="dsh"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Nt,{className:"set-section-icon"}),l("dshPatches"),e.jsx(it,{text:l("dshPatchesDesc")}),e.jsx("span",{className:"set-count",children:((Y=t.dshPatches)==null?void 0:Y.files.length)??0}),e.jsxs("button",{type:"button",className:"set-uninstall",title:l("dshPatchesRescanHint"),onClick:()=>s({type:"dsh_patches_rescan"}),children:[e.jsx(at,{}),l("dshPatchesRescan")]})]}),(((m=t.dshPatches)==null?void 0:m.files.length)??0)===0?e.jsx("p",{className:"set-empty",children:l("dshPatchesEmpty")}):e.jsx("div",{className:"set-list",children:t.dshPatches.files.map(g=>e.jsx("div",{className:"set-row",children:e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:g.name}),e.jsxs("div",{className:"set-row-desc",children:[Sr(g.size)," · ",new Date(g.mtimeMs).toLocaleString()]})]})},g.name))}),e.jsxs("p",{className:"set-hint",children:[l("dshPatchesPath")," ",((P=t.dshPatches)==null?void 0:P.patchDir)??""]})]}),d==="review"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ut,{className:"set-section-icon"}),l("settingsReview"),e.jsx(it,{text:l("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:i.reviewSkills.length})]}),c&&e.jsx("p",{className:"set-hint",children:l("dshReviewPromptNote")}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:l("reviewPromptPlaceholder"),value:I,onFocus:()=>E.current=!0,onBlur:()=>{E.current=!1,ie({reviewPrompt:I})},onChange:g=>F(g.target.value)}),e.jsx("div",{className:"set-field-label",children:l("settingsReviewSkills")}),i.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:l("noSkills")}):e.jsx("div",{className:"set-list",children:i.reviewSkills.map(g=>e.jsx(Ae,{title:g.name,subtitle:g.description,enabled:g.enabled,onToggle:()=>ue(g)},`review-${g.name}`))})]}),d==="vision"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Bt,{className:"set-section-icon"}),l("settingsVisionBridge")]}),e.jsx(Ae,{title:l("visionBridgeEnabled"),tip:l("settingsVisionBridgeDesc"),enabled:i.visionBridgeEnabled,onToggle:()=>ie({visionBridgeEnabled:!i.visionBridgeEnabled})}),!i.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:l("visionBridgeOffHint")}),i.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:l("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:i.visionBridgeModel??"",onChange:g=>ie({visionBridgeModel:g.target.value||null}),children:[e.jsx("option",{value:"",children:l("visionBridgeAuto")}),i.visionModels.map(g=>e.jsx("option",{value:`${g.provider}/${g.id}`,children:g.label},`${g.provider}/${g.id}`))]})]}),i.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:l("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:C,onChange:g=>{const D=g.target.value;z(D),ie({visionBridgePromptMode:D})},children:[e.jsx("option",{value:"append",children:l("promptModeAppend")}),e.jsx("option",{value:"replace",children:l("promptModeReplace")})]})]}),i.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:l("visionBridgePromptPlaceholder"),value:O,onFocus:()=>G.current=!0,onBlur:()=>{G.current=!1;const g=C==="replace"&&i.visionBridgeDefaultPrompt&&O===i.visionBridgeDefaultPrompt?"":O;ie({visionBridgePromptMode:C,visionBridgePrompt:g})},onChange:g=>y(g.target.value)}),i.visionBridgeEnabled&&(i.visionModels.length===0?e.jsx("p",{className:"set-hint",children:l("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:l("visionBridgeCurrent",{model:i.visionBridgeModel??l("visionBridgeAuto")})}))]}),d==="presets"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(ft,{className:"set-section-icon"}),l("settingsPresets"),e.jsx("span",{className:"set-count",children:i.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:l("presetNamePlaceholder"),value:K,onChange:g=>j(g.target.value),onKeyDown:g=>{g.key==="Enter"&&K.trim()&&(s({type:"save_preset",name:K.trim()}),j(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!K.trim(),onClick:()=>{s({type:"save_preset",name:K.trim()}),j("")},children:[e.jsx($e,{})," ",l("saveAsPreset")]})]}),i.presets.length===0?e.jsx("p",{className:"set-empty",children:l("noPresets")}):e.jsx("div",{className:"set-list",children:i.presets.map(g=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:g.name}),e.jsxs("div",{className:"set-row-desc",children:[g.promptMode==="replace"?l("promptModeReplace"):l("promptModeAppend"),g.disabledSkills.length>0&&` · ${l("settingsSkills")} ${g.disabledSkills.length}`,g.disabledExtensions.length>0&&` · ${l("settingsExtensions")} ${g.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:g.name}),children:l("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:l("deletePreset"),onClick:()=>s({type:"delete_preset",name:g.name}),children:e.jsx(Le,{})})]})]},g.name))})]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:o,children:l("close")})})]})})}function Er(t,s){const n=Math.max(0,Date.now()-t),a=Math.floor(n/6e4);if(a<1)return s("bgTaskJustNow");if(a<60)return s("bgTaskMinutes",{n:a});const o=Math.floor(a/60);return o<24?s("bgTaskHours",{n:o}):s("bgTaskDays",{n:Math.floor(o/24)})}function Mr({servers:t,send:s,onClose:n}){const a=fe(),[o,l]=r.useState(new Set),i=c=>l(d=>{const u=new Set(d);return u.has(c)?u.delete(c):u.add(c),u});return r.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"bg-task-modal",onClick:c=>c.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(vt,{})," ",a("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:a("close"),onClick:n,children:e.jsx(Te,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(vt,{}),e.jsx("span",{children:a("bgTasksEmpty")}),e.jsx("small",{children:a("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(c=>{const d=!!c.taskId,u=c.taskId??String(c.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:d?c.plugin:a("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[d?e.jsxs("span",{className:"bg-task-port",title:c.taskId,children:["🧩 ",c.plugin]}):e.jsxs("span",{className:"bg-task-port",children:[":",c.port]}),c.name&&e.jsx("span",{className:"bg-task-name",children:c.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[!d&&e.jsxs("span",{children:[a("bgTaskPid")," ",c.pid]}),e.jsxs("span",{children:[a("bgTaskSince")," ",Er(c.since,a)]}),d&&c.status&&e.jsx("span",{className:"bg-task-status",children:c.status})]}),c.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${o.has(u)?"open":""}`,title:`${a("bgTaskCommand")}: ${c.command}`,onClick:()=>i(u),children:[e.jsx(Je,{}),e.jsx("code",{children:c.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:a("bgTaskStop"),onClick:()=>s(d?{type:"kill_background_server",taskId:c.taskId}:{type:"kill_background_server",port:c.port}),children:[e.jsx(gt,{}),e.jsx("span",{children:a("bgTaskStop")})]})]},u)})}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:a("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(at,{}),e.jsx("span",{children:a("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:a("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(gt,{}),e.jsx("span",{children:a("bgTaskStopAll")})]})]})]})})}function Rr(t,s){return t.toLowerCase().includes(s)}function Pr({open:t,send:s,projects:n,cwd:a,fileSearch:o,sessionSearch:l,onClose:i,onSwitchSession:c,onSwitchProject:d,onPreviewFile:u}){const f=fe(),h=r.useRef(null),[x,v]=r.useState(""),S=r.useDeferredValue(x),[R,O]=r.useState(0),y=r.useRef(1),C=r.useRef(0),z=r.useRef(null);r.useEffect(()=>{if(!t)return;s({type:"list_sessions"}),s({type:"list_projects"});const k=x.trim();if(k){const w=++y.current;C.current=w,I(!0),s({type:"search_files",reqId:w,query:k}),s({type:"search_sessions",reqId:w,query:k})}requestAnimationFrame(()=>{var w;return(w=h.current)==null?void 0:w.select()})},[t]);const[G,I]=r.useState(!1);r.useEffect(()=>{z.current&&clearTimeout(z.current);const k=S.trim();if(!k){I(!1);return}return z.current=setTimeout(()=>{const w=++y.current;C.current=w,I(!0),s({type:"search_files",reqId:w,query:k}),s({type:"search_sessions",reqId:w,query:k})},300),()=>{z.current&&clearTimeout(z.current)}},[S]);const F=S.trim().toLowerCase(),E=r.useMemo(()=>!F||!l||l.reqId!==C.current||!l.ok?[]:l.results,[l,F]),K=r.useMemo(()=>F?n.filter(k=>Rr(k.path,F)).slice(0,10):[],[n,F]),j=r.useMemo(()=>!F||!o||o.reqId!==C.current||!o.ok?[]:o.results,[o,F]);r.useEffect(()=>{o&&o.reqId===C.current&&l&&l.reqId===C.current&&C.current!==0&&I(!1)},[o,l]);const H=!!o&&o.ok&&o.truncated,J=r.useMemo(()=>[...E.map(k=>({kind:"session",path:k.path,anchors:k.anchors})),...K.map(k=>({kind:"project",path:k.path})),...j.filter(k=>k.type==="file").map(k=>({kind:"file",path:k.path,name:k.name}))],[E,K,j]);r.useEffect(()=>{O(0)},[S]);const se=r.useCallback(k=>{if(k)if(k.kind==="session")c(k.path,k.anchors),i();else if(k.kind==="project"){d(k.path),s({type:"list_sessions"}),s({type:"list_projects"});const w=S.trim();if(w){const b=++y.current;C.current=b,I(!0),s({type:"search_files",reqId:b,query:w}),s({type:"search_sessions",reqId:b,query:w})}}else u(k.path,k.name)},[c,d,u,s,S]);r.useEffect(()=>{if(!t)return;const k=w=>{w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),i()):w.key==="ArrowDown"?(w.preventDefault(),O(b=>Math.min(b+1,J.length-1))):w.key==="ArrowUp"?(w.preventDefault(),O(b=>Math.max(b-1,0))):w.key==="Enter"&&(w.preventDefault(),se(J[R]))};return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[J,R,se,i,t]);const W=E.length+K.length+j.length,V=(k,w,b)=>e.jsxs("div",{className:"gs-section-head",children:[b,e.jsx("span",{children:k}),e.jsx("em",{children:w})]});let q=-1;return t?e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:i,children:e.jsxs("div",{className:"gs-modal",onClick:k=>k.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(xt,{}),e.jsx("input",{ref:h,type:"text",value:x,placeholder:f("gsPlaceholder"),onChange:k=>v(k.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:f("close"),onClick:i,children:e.jsx(Te,{})})]}),e.jsxs("div",{className:"gs-results",children:[!F&&e.jsx("div",{className:"gs-empty",children:f("gsHint")}),F&&W===0&&!H&&e.jsx("div",{className:"gs-empty",children:f(G?"gsSearching":"gsNoResults")}),E.length>0&&e.jsxs("div",{className:"gs-section",children:[V(f("gsSessions"),E.length,e.jsx(Xe,{})),E.map(k=>{q++;const w=q;return e.jsxs("button",{type:"button",className:w===R?"gs-item active":"gs-item",onMouseEnter:()=>O(w),onClick:()=>se({kind:"session",path:k.path,anchors:k.anchors}),children:[e.jsxs("span",{className:"gs-item-title",children:[k.name||k.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:k.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:k.firstMessage})]},k.path)})]}),K.length>0&&e.jsxs("div",{className:"gs-section",children:[V(f("gsProjects"),K.length,e.jsx(Ze,{})),K.map(k=>{q++;const w=q,b=a&&k.path===a;return e.jsxs("button",{type:"button",className:w===R?"gs-item active":"gs-item",onMouseEnter:()=>O(w),onClick:()=>se({kind:"project",path:k.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[k.path.split(/[\\/]/).pop(),b&&e.jsx("em",{className:"gs-item-meta",children:f("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:k.path})]},k.path)})]}),(j.length>0||F&&H)&&e.jsxs("div",{className:"gs-section",children:[V(f("gsFiles"),j.length,e.jsx(Qs,{})),j.map(k=>{q++;const w=q;return e.jsxs("button",{type:"button",className:w===R?"gs-item active":"gs-item",disabled:k.type==="dir",title:k.type==="dir"?void 0:f("gsOpenPreview"),onMouseEnter:()=>O(w),onClick:()=>{k.type==="file"&&se({kind:"file",path:k.path,name:k.name})},children:[e.jsx("span",{className:"gs-item-title",children:k.name}),e.jsx("span",{className:"gs-item-sub",children:k.path})]},`${k.type}:${k.path}`)}),H&&e.jsx("div",{className:"gs-truncated",children:f("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",f("gsNavigate")]}),e.jsxs("span",{children:["Enter ",f("gsOpen")]}),e.jsxs("span",{children:["Esc ",f("gsCloseHint")]})]})]})}):null}const It=5e3;function Ir({file:t,content:s,send:n,onAddLines:a,onAttach:o,onClose:l}){const i=fe(),[c,d]=r.useState(null),[u,f]=r.useState(!1),[h,x]=r.useState(null),[v,S]=r.useState(!1),[R,O]=r.useState(!1),[y,C]=r.useState(!1),[z,G]=r.useState(""),[I,F]=r.useState(!0),E=r.useRef(!1),[K,j]=r.useState(!0),[H,J]=r.useState(!1),[se,W]=r.useState(100),V=r.useRef(0),q=r.useRef(!1),k=r.useRef(null);r.useEffect(()=>{f(!0),d(null),x(null),C(!1),G(""),F(!0),E.current=!1,n({type:"read_file",path:t.path})},[t.path,n]),r.useEffect(()=>{s&&s.path===t.path&&(d(s),y||G(s.text),f(!1))},[s,y,t.path]),r.useEffect(()=>{const D=Z=>{if(Z.key==="Escape"){Q();return}if((Z.ctrlKey||Z.metaKey)&&Z.key.toLowerCase()==="s"&&y){Z.preventDefault(),B();return}const ee=Z.target,he=ee&&(ee.tagName==="INPUT"||ee.tagName==="TEXTAREA"||ee.isContentEditable);(Z.ctrlKey||Z.metaKey)&&Z.key.toLowerCase()==="a"&&!he&&(Z.preventDefault(),ie())};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[l,c,y,z]),r.useEffect(()=>{const D=()=>{q.current=!1,S(!1)};return window.addEventListener("mouseup",D),()=>window.removeEventListener("mouseup",D)},[]);const w=r.useMemo(()=>{if(!c)return[];const D=c.text.split(`
|
|
321
|
+
`);return D.length>0&&D[D.length-1]===""&&D.pop(),D.slice(0,It)},[c]),b=(c==null?void 0:c.lines)??0,L=b>It,A=(D,Z)=>{if(Z){const ee=V.current>0?V.current:D;x({start:Math.min(ee,D),end:Math.max(ee,D)})}else V.current=D,x({start:D,end:D})},ie=()=>{w.length!==0&&(V.current=1,x({start:1,end:w.length}))},de=()=>{h&&(a(t.path,t.name,h.start,h.end),O(!0),k.current&&clearTimeout(k.current),k.current=setTimeout(()=>O(!1),1400))},me=c!==null&&c.kind==="text"&&!c.binary&&!c.truncated,p=()=>{G((c==null?void 0:c.text)??""),C(!1),E.current&&F(!0)},U=()=>{if(y){if(z!==((c==null?void 0:c.text)??"")&&!window.confirm(i("discardFileChanges")))return;p();return}!me||!c||(E.current=Lt(t.name)&&I,Lt(t.name)&&F(!1),x(null),G(c.text),C(!0))},B=()=>{!y||!c||!me||n({type:"write_file",path:t.path,text:z})&&(C(!1),E.current&&F(!0),x(null))},Q=()=>{y&&z!==((c==null?void 0:c.text)??"")&&!window.confirm(i("discardFileChanges"))||l()},ne=D=>{W(Math.min(200,Math.max(50,D)))},ae=h?h.end-h.start+1:0,ue=(c==null?void 0:c.binary)??!1,N=(c==null?void 0:c.truncated)??!1,Y=(c==null?void 0:c.kind)??"text",m=Lt(t.name),P=m&&I&&!y&&Y==="text"&&!ue,g=D=>bt(et(`/api/file?clientId=${encodeURIComponent(qt())}&path=${encodeURIComponent(D)}`));return e.jsx("div",{className:`fp-overlay ${H?"fullscreen":""}`,onMouseDown:D=>{D.target===D.currentTarget&&Q()},children:e.jsxs("div",{className:`fp ${H?"fullscreen":""}`,style:{"--fp-zoom":se/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:[c&&Y==="text"&&!ue&&i("fileLines",{n:b}),c&&` · ${Lr(c.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[m&&Y==="text"&&!ue&&c&&e.jsx("button",{type:"button",className:`fp-attach markdown ${I?"on":""}`,"data-tip":i(I?"showMarkdownSource":"showMarkdownPreview"),disabled:y,onClick:()=>F(D=>!D),children:I?e.jsx(Bt,{}):e.jsx(hi,{})}),Y==="text"&&!ue&&c&&e.jsx("button",{type:"button",className:`fp-attach edit ${y?"on":""}`,"data-tip":i(N?"fileEditTruncated":y?"exitEditFile":"editFile"),disabled:!me&&!y,onClick:U,children:e.jsx(_t,{})}),Y==="text"&&!ue&&!P&&e.jsx("button",{type:"button",className:`fp-attach wrap ${K?"on":""}`,"data-tip":i(K?"disableWrap":"enableWrap"),onClick:()=>j(D=>!D),children:e.jsx(mi,{})}),Y==="text"&&c&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":i("zoomOut"),disabled:se<=50,onClick:()=>ne(se-10),children:e.jsx(Qn,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:i("resetZoom"),onClick:()=>W(100),children:[se,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":i("zoomIn"),disabled:se>=200,onClick:()=>ne(se+10),children:e.jsx(Yn,{})})]}),Y!=="video"&&Y!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":i("attachInlineTip"),onClick:()=>o(t.path,t.name,"inline"),children:e.jsx($e,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":i("referenceTip"),onClick:()=>o(t.path,t.name,"reference"),children:e.jsx(Dt,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${H?"on":""}`,"data-tip":i(H?"exitFullscreen":"fullscreen"),onClick:()=>J(D=>!D),children:H?e.jsx(ii,{}):e.jsx(ri,{})}),e.jsx("button",{type:"button",className:"fp-close",title:i("close"),onClick:Q,children:e.jsx(Te,{})})]})]}),N&&Y==="text"&&!ue&&e.jsx("div",{className:"fp-notice",children:i("previewTruncated")}),u&&!c&&e.jsx("div",{className:"fp-empty",children:i("loading")}),!u&&Y==="none"&&!ue&&e.jsx("div",{className:"fp-empty",children:i("previewNotSupported")}),!u&&Y==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:g(t.path),alt:t.name})}),!u&&Y==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:g(t.path),controls:!0,preload:"metadata"})}),!u&&P&&c&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(jt,{text:c.text})})}),!u&&ue&&Y!=="image"&&Y!=="video"&&c&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[i("binaryFile"),c.truncated&&i("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:c.text})]}),!u&&y&&Y==="text"&&!ue&&c&&e.jsx("textarea",{className:`fp-editor ${K?"":"no-wrap"}`,value:z,onChange:D=>G(D.target.value),wrap:K?"soft":"off",spellCheck:!1,autoFocus:!0}),!u&&!P&&!y&&Y==="text"&&!ue&&c&&w.length===0&&e.jsx("div",{className:"fp-empty",children:i("emptyFile")}),!u&&!P&&!y&&Y==="text"&&!ue&&w.length>0&&e.jsxs("div",{className:`fp-code ${v?"dragging":""} ${K?"":"no-wrap"}`,onMouseDown:D=>{D.button===0&&D.preventDefault()},children:[w.map((D,Z)=>{const ee=Z+1,he=h!==null&&ee>=h.start&&ee<=h.end;return e.jsxs("div",{className:`fp-line ${he?"sel":""}`,onMouseDown:ke=>{ke.button===0&&(A(ee,ke.shiftKey),q.current=!0,S(!0))},onMouseEnter:()=>{q.current&&A(ee,!0)},children:[e.jsx("span",{className:"fp-num",children:ee}),e.jsx("span",{className:"fp-code-text",children:D})]},ee)}),L&&e.jsx("div",{className:"fp-lines-note",children:i("previewLinesTruncated",{n:It})})]}),e.jsx("div",{className:"fp-foot",children:y?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:i("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:U,children:i("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:z===((c==null?void 0:c.text)??""),onClick:B,children:[e.jsx(ti,{})," ",i("saveFile")]})]})]}):!P&&Y==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:h?i("selectedRange",{n:ae,start:h.start,end:h.end}):i("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:w.length===0,onClick:ie,children:i("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!h,onClick:()=>x(null),children:i("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!h||ue,onClick:de,children:[R?e.jsx(ot,{}):null,i(R?"addedToChat":"addToChat")]})]})]})})]})})}function Lt(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function Lr(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const Sn="pi-web-sounds",tt={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function Tn(){try{const t=localStorage.getItem(Sn);if(!t)return{...tt};const s=JSON.parse(t),n={...tt,...s};for(const a of["enabled","question","done","start","error"])typeof n[a]!="boolean"&&(n[a]=tt[a]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=tt.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...tt}}}function Dr(t){try{localStorage.setItem(Sn,JSON.stringify(t))}catch{}}let st=null;function Br(){try{if(!st){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;st=new t}return st.state==="suspended"&&st.resume(),st}catch{return null}}const _r=[{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}],$r=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],Fr=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],Hr={question:_r,done:Ar,start:$r,error:Fr};function Kr(t,s,n){const a=t.createOscillator(),o=t.createGain();a.type=s.type,a.frequency.value=s.freq;const l=t.currentTime+s.start,i=Math.max(1e-4,s.peak*n);o.gain.setValueAtTime(1e-4,l),o.gain.exponentialRampToValueAtTime(i,l+.012),o.gain.exponentialRampToValueAtTime(1e-4,l+s.dur),a.connect(o),o.connect(t.destination),a.start(l),a.stop(l+s.dur+.05)}function nt(t,s=Tn()){if(!s.enabled||!s[t])return;const n=Br();if(!n)return;const a=Math.max(0,Math.min(1,s.volume/100));for(const o of Hr[t])Kr(n,o,a)}const Kt="pi-web-ui:theme",En="dark",Bs="theme-stylesheet",_s="pi-web-ui:theme-change";function Mn(){try{const t=localStorage.getItem(Kt);if(t&&t!==En)return t}catch{}return null}function Or(t){try{t?localStorage.setItem(Kt,t):localStorage.removeItem(Kt)}catch{}}function Rn(t){let s=document.getElementById(Bs);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(_s));return}s||(s=document.createElement("link"),s.id=Bs,s.rel="stylesheet",document.head.appendChild(s)),s.href=et(`/themes/${encodeURIComponent(t)}.css`),s.onload=()=>window.dispatchEvent(new CustomEvent(_s))}async function Wr(){try{const t=await fetch(bt(et("/api/themes")));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function Ur(){const[t,s]=r.useState([]),[n,a]=r.useState(()=>Mn());return r.useEffect(()=>{let l=!1;return Wr().then(i=>{l||s(i)}),()=>{l=!0}},[]),r.useEffect(()=>{Rn(n),Or(n)},[n]),{themes:t,theme:n,switchTheme:l=>a(l===En?null:l)}}function Xr(){const t=getComputedStyle(document.documentElement),s=(n,a)=>t.getPropertyValue(n).trim()||a;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 qr=r.lazy(()=>Kn(()=>import("./TerminalPanel-CrduzEDu.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function zr({notice:t,onDismiss:s}){const n=fe(),[a,o]=r.useState(!1);r.useEffect(()=>{if(a)return;const i=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(i)},[a,t.id,t.level,s]);const l=t.level==="error"?vi:t.level==="warning"?xi:ci;return e.jsxs("div",{className:`notice notice-${t.level}${a?" paused":""}`,role:"status",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[e.jsx(l,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:t.text}),e.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>s(t.id),children:e.jsx(Te,{})})]})}const Vr=[],Pn=180,In=520,Ln=240,Dn=t=>`pi-web-ui:${t}-panel-width`;function As(t){const s=Number(localStorage.getItem(Dn(t)));return Number.isFinite(s)&&s>=Pn&&s<=In?s:Ln}const Ot=t=>`pi-web-ui:${t}-panel-collapsed`;function $s(t){return localStorage.getItem(Ot(t))==="1"}function Fs({side:t,width:s,onResize:n}){const a=fe(),o=r.useCallback(l=>{l.preventDefault();const i=l.clientX,c=s;let d=c;const u=h=>{const x=t==="left"?h.clientX-i:i-h.clientX;d=Math.min(In,Math.max(Pn,Math.round(c+x))),n(d)},f=()=>{window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",f),document.body.classList.remove("panel-resizing"),localStorage.setItem(Dn(t),String(d))};window.addEventListener("pointermove",u),window.addEventListener("pointerup",f),document.body.classList.add("panel-resizing")},[t,s,n]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:a("dragToResize"),onPointerDown:o,onDoubleClick:()=>n(Ln)})}function Hs({side:t,onClick:s}){const n=fe();return e.jsx("button",{type:"button",className:`panel-rail panel-rail-${t}`,title:n("expandPanel"),onClick:s,children:t==="left"?e.jsx(Xs,{}):e.jsx(Zs,{})})}function Gr(){var _e,Gt,Qt,Yt,Jt,Xt,Zt,es,ts,ss,ns,is,as,rs;const t=fe(),{chat:s,send:n,dismissNotice:a,pushNotice:o,terminal:l}=zi(),[i,c]=r.useState([]),[d,u]=r.useState(null),[f,h]=r.useState(!1),[x,v]=r.useState("chat"),S=r.useMemo(()=>s.plugins.filter(_=>{var X,oe;return!((oe=(X=s.settings)==null?void 0:X.disabledPlugins)!=null&&oe.includes(_.id))}),[s.plugins,(_e=s.settings)==null?void 0:_e.disabledPlugins]),[R,O]=r.useState([]);r.useEffect(()=>Ai(O),[]),r.useEffect(()=>{$i(S,s.pluginsEpoch)},[S,s.pluginsEpoch]);const[y,C]=r.useState(()=>As("left")),[z,G]=r.useState(()=>As("right")),I=r.useCallback(_=>C(_),[]),F=r.useCallback(_=>G(_),[]),[E,K]=r.useState(()=>$s("left")),[j,H]=r.useState(()=>$s("right")),J=r.useCallback(()=>{K(_=>(localStorage.setItem(Ot("left"),_?"0":"1"),!_))},[]),se=r.useCallback(()=>{H(_=>(localStorage.setItem(Ot("right"),_?"0":"1"),!_))},[]),[W,V]=r.useState(null),[q,k]=r.useState(()=>window.matchMedia("(max-width: 768px)").matches);r.useEffect(()=>{const _=window.matchMedia("(max-width: 768px)"),X=oe=>k(oe.matches);return _.addEventListener("change",X),()=>_.removeEventListener("change",X)},[]);const[w,b]=r.useState(!1),[L,A]=r.useState(!1),[ie,de]=r.useState(!1),[me,p]=r.useState(!1),[U,B]=r.useState(!1),[Q,ne]=r.useState(null);r.useEffect(()=>{if(!Q)return;const _=setTimeout(()=>ne(null),15e3);return()=>clearTimeout(_)},[Q]),r.useEffect(()=>{const _=X=>{var Oe,ls;const oe=X.detail,be=(oe==null?void 0:oe.title)||"插件命令",we=oe==null?void 0:oe.command;if(!we||!s.ready)return;const Me={name:be,command:we,cwd:"${pwd}"},Ne=s.terminals.find(wt=>wt.title===be);if(Ne)l.restart(Ne.id),n({type:"run_command",terminalId:Ne.id,conversationId:Ne.conversationId,command:Me,cols:80,rows:24});else{const wt=He();l.create({id:wt,conversationId:s.activeConversationId||((Oe=s.state)==null?void 0:Oe.conversationId)||"",title:be,cwd:((ls=s.state)==null?void 0:ls.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Me})}v("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",_),()=>window.removeEventListener("pi-web-ui:plugin-run-command",_)},[s,l,n]),r.useEffect(()=>{const _=X=>{!(X.ctrlKey||X.metaKey)||X.key.toLowerCase()!=="k"||(X.preventDefault(),B(oe=>!oe))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[]);const[ae,ue]=r.useState(Tn),{themes:N,theme:Y,switchTheme:m}=Ur(),P=r.useRef(null),g=r.useRef(null),D=r.useRef(0),Z=r.useRef(!1),ee=r.useRef(s.terminals);r.useEffect(()=>{Dr(ae)},[ae]),r.useEffect(()=>{var X;const _=ee.current;ee.current=s.terminals;for(const oe of s.terminals){const be=((X=oe.command)==null?void 0:X.command)??"",we=_.find(Me=>Me.id===oe.id);!(we!=null&&we.running)||oe.running||(be.startsWith("pi remove ")?n({type:"extensions_reload"}):be.startsWith("pi-web-ui install ")||be.startsWith("pi-web-ui uninstall ")?n({type:"plugins_reload"}):be.startsWith("npm i -g ")&&(n({type:"extensions_reload"}),n({type:"plugins_reload"}),n({type:"check_updates_all",force:!0})))}},[s.terminals,n]),r.useEffect(()=>{var oe;const _=((oe=s.state)==null?void 0:oe.isStreaming)??!1,X=P.current;P.current=_,X!==null&&(!X&&_?nt("start",ae):X&&!_&&nt("done",ae))},[(Gt=s.state)==null?void 0:Gt.isStreaming,ae]),r.useEffect(()=>{var X;const _=((X=s.dialog)==null?void 0:X.id)??null;_!==null&&_!==g.current&&nt("question",ae),g.current=_},[s.dialog,ae]),r.useEffect(()=>{const _=[...s.notices].reverse().find(X=>X.level==="error");_&&_.id!==D.current&&(D.current=_.id,nt("error",ae))},[s.notices,ae]);const he=(_,X,oe,be=!1,we)=>{const Me=`${_}|${oe}|${we?`${we.start}-${we.end}`:""}`;c(Ne=>Ne.some(Oe=>`${Oe.path}|${Oe.mode}|${Oe.lines?`${Oe.lines.start}-${Oe.lines.end}`:""}`===Me)?Ne:[...Ne,{path:_,name:X,mode:oe,isDir:be,...we?{lines:we}:{}}])},ke=_=>c(X=>X.filter(oe=>oe.key?oe.key!==_:oe.path!==_)),pe=r.useCallback(_=>(!_.type.startsWith("list_")&&!_.type.startsWith("get_")&&V(null),n(_)),[n]),De=r.useRef(0),Pe=r.useRef(0),Ie=_=>{var be;const X=Date.now();(be=s.state)!=null&&be.model&&!s.state.model.vision&&X-Pe.current>1e4&&(Pe.current=X,o("warning",t("imageNotSupported")));const oe=`paste-${++De.current}`;c(we=>[...we,{path:"",key:oe,name:_.name,mode:"inline",imageData:_.data,mimeType:_.mimeType}])},Ke=async _=>{for(const X of _){const oe=await un(X);if(!oe){o("error",t("imageLoadFailed",{name:X.name}));continue}Ie(oe)}},Be=20*1024*1024,ze=r.useRef(0),Ve=async _=>{if(_.size>Be){o("warning",t("fileTooLarge",{name:_.name,size:Be/1024/1024}));return}let X;try{X=(await new Promise((we,Me)=>{const Ne=new FileReader;Ne.onload=()=>we(Ne.result),Ne.onerror=()=>Me(Ne.error??new Error("read failed")),Ne.readAsDataURL(_)})).replace(/^data:[^;]*;base64,/,"")}catch{o("error",t("fileLoadFailed",{name:_.name}));return}const oe=`upload-${++ze.current}`;c(be=>[...be,{path:"",key:oe,name:_.name,mode:"inline",fileData:X,size:_.size,mimeType:_.type||void 0}])},M=async _=>{for(const X of _)Fe(X.type)?await Ke([X]):await Ve(X)},ge=r.useCallback((_,X,oe)=>{n({type:"edit_message",messageId:_,text:X,attachments:oe})},[n]),ce=r.useCallback((_,X)=>{n({type:"queue_remove",kind:_,text:X})},[n]),je=r.useCallback(()=>A(!0),[]),xe=r.useCallback(()=>c([]),[]),Ce=r.useCallback(ke,[]),T=r.useCallback(Ke,[Ke]),$=r.useCallback(M,[M]),re=(Qt=s.state)==null?void 0:Qt.model,le=(Yt=s.state)==null?void 0:Yt.thinkingLevel,ve=(Jt=s.state)==null?void 0:Jt.availableThinkingLevels,ye=r.useMemo(()=>re?{model:re,thinkingLevel:le??"off",availableThinkingLevels:ve??[]}:null,[re,le,ve]),Se=r.useCallback(()=>{var _,X;return!s.ready||s.terminals.length!==0?!1:(l.create({id:He(),conversationId:s.activeConversationId||((_=s.state)==null?void 0:_.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((X=s.state)==null?void 0:X.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,(Xt=s.state)==null?void 0:Xt.cwd,s.terminals.length,t,l]);return r.useEffect(()=>{if(Z.current){if(x!=="terminal"||s.terminals.length!==0){Z.current=!1;return}Se()&&(Z.current=!1)}},[s.terminals.length,Se,x]),e.jsxs("div",{className:"app",onDragOver:_=>{var X;Array.from(((X=_.dataTransfer)==null?void 0:X.types)??[]).includes("Files")&&(_.preventDefault(),h(!0))},onDragLeave:_=>{_.currentTarget.contains(_.relatedTarget)||h(!1)},onDrop:_=>{var we,Me;if(h(!1),!Array.from(((we=_.dataTransfer)==null?void 0:we.types)??[]).includes("Files"))return;_.preventDefault();const X=Array.from(((Me=_.dataTransfer)==null?void 0:Me.files)??[]);if(X.length===0){o("warning",t("foldersNotSupported"));return}const oe=X.filter(Ne=>Fe(Ne.type)),be=X.filter(Ne=>!Fe(Ne.type));oe.length>0&&Ke(oe),be.length>0&&M(be)},children:[f&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(Ci,{chat:s,send:n,terminal:l,view:x,plugins:S,onViewChange:_=>{Z.current=_==="terminal"&&s.terminals.length===0,Z.current&&Se()&&(Z.current=!1),v(_),V(null)},onOpenPanel:V,onOpenSettings:()=>de(!0),onOpenBgTasks:()=>p(!0),onOpenGlobalSearch:()=>B(!0),sound:ae,onSoundChange:ue,onSoundPreview:_=>nt(_,ae),themes:N,theme:Y,onThemeChange:m}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(_=>e.jsx(zr,{notice:_,onDismiss:a},_.id))}),e.jsx(Ga,{send:n,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${y}px`,"--right-w":`${z}px`},children:[W&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>V(null)}),e.jsxs("div",{className:`view-pane ${x==="chat"?"":"hidden"}`,children:[!q&&E&&e.jsx(Hs,{side:"left",onClick:J}),e.jsx("div",{className:`panel-drawer drawer-left ${W==="left"?"open":""}${q?"":E?" hidden":""}`,children:e.jsx(Ti,{collapsible:!q,onToggleCollapse:J,send:pe,active:!q||W==="left",ready:s.ready,status:s.status,cwd:((Zt=s.state)==null?void 0:Zt.cwd)??"",sessionFile:((es=s.state)==null?void 0:es.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!q&&e.jsx(Fs,{side:"left",width:y,onResize:I}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(er,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:ge,onKillBash:()=>n({type:"abort_bash"}),onRemoveQueued:ce,thinkingWrap:((ts=s.settings)==null?void 0:ts.thinkingWrap)??!0,toolsWrap:((ss=s.settings)==null?void 0:ss.toolsWrap)??!0,jumpTarget:Q,onJumpDone:()=>ne(null)},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(cr,{send:n,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId,engine:s.engine}),s.dialog&&e.jsx(fr,{dialog:s.dialog,send:n}),s.question&&e.jsx(xr,{question:s.question,send:n}),e.jsx(or,{send:n,ready:s.ready,streaming:((ns=s.state)==null?void 0:ns.isStreaming)??!1,messages:((is=s.state)==null?void 0:is.messages)??Vr,slashCommands:s.slashCommands,modelState:ye,models:s.models,modelsLoading:s.modelsLoading,providerKeys:s.providerKeys,attachments:i,onRemoveAttachment:Ce,onAddImageFiles:T,onAddLocalFiles:$,onNotice:o,onManageModels:je,onSent:xe})]}),!q&&e.jsx(Fs,{side:"right",width:z,onResize:F}),e.jsx("div",{className:`panel-drawer drawer-right ${W==="right"?"open":""}${q?"":j?" hidden":""}`,children:e.jsx(ta,{collapsible:!q,onToggleCollapse:se,send:pe,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((as=s.state)==null?void 0:as.cwd)??"",onAttach:(_,X,oe,be)=>{V(null),he(_,X,oe,be)},onPreview:(_,X)=>{V(null),u({path:_,name:X})},onNotice:(_,X)=>o(_,X)})}),!q&&j&&e.jsx(Hs,{side:"right",onClick:se})]}),e.jsx("div",{className:`view-pane ${x==="terminal"?"":"hidden"}`,children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(qr,{chat:s,send:n,terminal:l})})}),e.jsx("div",{className:`view-pane ${x==="git"?"":"hidden"}`,children:e.jsx(yr,{chat:s,send:n,terminal:l,active:x==="git",onSwitchToTerminal:()=>v("terminal")})}),R.map(_=>{const X=`plugin:${_.info.id}`;return e.jsx("div",{className:`view-pane ${x===X?"":"hidden"}`,children:e.jsx(kr,{entry:_,send:n})},_.info.id)})]})}),e.jsx(hr,{chat:s,send:n}),d&&e.jsx(Ir,{file:d,content:s.fileContent,send:n,onAddLines:(_,X,oe,be)=>he(_,X,"lines",!1,{start:oe,end:be}),onAttach:(_,X,oe)=>he(_,X,oe),onClose:()=>u(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!w&&!L&&e.jsx(br,{send:n,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>b(!0)}),L&&e.jsx(Nr,{send:n,providers:s.modelsConfig,providerStatus:s.providers,providerKeys:s.providerKeys,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>A(!1)}),ie&&e.jsx(Tr,{chat:s,send:n,terminal:l,onSwitchToTerminal:()=>v("terminal"),onClose:()=>de(!1)}),me&&e.jsx(Mr,{servers:s.bgServers,send:n,onClose:()=>p(!1)}),e.jsx(Pr,{open:U,send:n,projects:s.projects,cwd:((rs=s.state)==null?void 0:rs.cwd)??"",fileSearch:s.fileSearch,sessionSearch:s.sessionSearch,onClose:()=>B(!1),onSwitchSession:(_,X)=>{n({type:"switch_session",path:_});const oe=X&&X[0];ne(oe?{path:_,role:oe.role,timestamp:oe.timestamp}:null)},onSwitchProject:_=>{n({type:"set_cwd",path:_})},onPreviewFile:(_,X)=>{u({path:_,name:X})}})]})}Ei();Rn(Mn());$n.createRoot(document.getElementById("root")).render(e.jsx(r.StrictMode,{children:e.jsx(wi,{children:e.jsx(Gr,{})})}));export{at as F,_s as T,$e as a,Xr as b,Jr as c,Ys as d,Le as e,ai as f,Je as g,Te as h,He as r,fe as u};
|