pi-web-ui 0.43.0 → 0.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/client-state.js +2 -0
- package/dist/server/index.js +1 -0
- package/dist/server/settings-service.js +6 -0
- package/package.json +1 -1
- package/themes/md-preview.css +39 -0
- package/themes/white.css +39 -0
- package/web/dist/assets/{TerminalPanel-BeTRtKaL.js → TerminalPanel-BiBJ27RP.js} +1 -1
- package/web/dist/assets/index-Dys5fNYx.js +19 -0
- package/web/dist/index.html +1 -1
- package/web/dist/assets/index-DPc38E4m.js +0 -19
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-BeTRtKaL.js","assets/markdown-DRBrS2Nf.js","assets/xterm-D1D2FVe3.js","assets/react-C9ovnpIm.js","assets/TerminalPanel-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{R as De,a as r,j as e,M as js,b as nn,c as an}from"./markdown-DRBrS2Nf.js";import{r as ks}from"./react-C9ovnpIm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))l(c);new MutationObserver(c=>{for(const i of c)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&l(a)}).observe(document,{childList:!0,subtree:!0});function n(c){const i={};return c.integrity&&(i.integrity=c.integrity),c.referrerPolicy&&(i.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?i.credentials="include":c.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function l(c){if(c.ep)return;c.ep=!0;const i=n(c);fetch(c.href,i)}})();var Qe={},Ut;function rn(){if(Ut)return Qe;Ut=1;var t=ks();return Qe.createRoot=t.createRoot,Qe.hydrateRoot=t.hydrateRoot,Qe}var ln=rn();const on="modulepreload",cn=function(t){return"/"+t},qt={},ws=function(s,n,l){let c=Promise.resolve();if(n&&n.length>0){let a=function(m){return Promise.all(m.map(x=>Promise.resolve(x).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),d=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));c=a(n.map(m=>{if(m=cn(m),m in qt)return;qt[m]=!0;const x=m.endsWith(".css"),h=x?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${h}`))return;const v=document.createElement("link");if(v.rel=x?"stylesheet":on,x||(v.as="script"),v.crossOrigin="",v.href=m,d&&v.setAttribute("nonce",d),document.head.appendChild(v),x)return new Promise((C,N)=>{v.addEventListener("load",C),v.addEventListener("error",()=>N(new Error(`Unable to preload CSS for ${m}`)))})}))}function i(a){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=a,window.dispatchEvent(o),!o.defaultPrevented)throw a}return c.then(a=>{for(const o of a||[])o.status==="rejected"&&i(o.reason);return s().catch(i)})};var Ns={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},zt=De.createContext&&De.createContext(Ns),dn=["attr","size","title"];function un(t,s){if(t==null)return{};var n,l,c=mn(t,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(l=0;l<i.length;l++)n=i[l],s.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(c[n]=t[n])}return c}function mn(t,s){if(t==null)return{};var n={};for(var l in t)if({}.hasOwnProperty.call(t,l)){if(s.indexOf(l)!==-1)continue;n[l]=t[l]}return n}function Ze(){return Ze=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var l in n)({}).hasOwnProperty.call(n,l)&&(t[l]=n[l])}return t},Ze.apply(null,arguments)}function Kt(t,s){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);s&&(l=l.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),n.push.apply(n,l)}return n}function et(t){for(var s=1;s<arguments.length;s++){var n=arguments[s]!=null?arguments[s]:{};s%2?Kt(Object(n),!0).forEach(function(l){pn(t,l,n[l])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Kt(Object(n)).forEach(function(l){Object.defineProperty(t,l,Object.getOwnPropertyDescriptor(n,l))})}return t}function pn(t,s,n){return(s=hn(s))in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function hn(t){var s=gn(t,"string");return typeof s=="symbol"?s:s+""}function gn(t,s){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var l=n.call(t,s);if(typeof l!="object")return l;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Cs(t){return t&&t.map((s,n)=>De.createElement(s.tag,et({key:n},s.attr),Cs(s.child)))}function K(t){return s=>De.createElement(fn,Ze({attr:et({},t.attr)},s),Cs(t.child))}function fn(t){var s=n=>{var l=t.attr,c=t.size,i=t.title,a=un(t,dn),o=c||n.size||"1em",d;return n.className&&(d=n.className),t.className&&(d=(d?d+" ":"")+t.className),De.createElement("svg",Ze({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,l,a,{className:d,style:et(et({color:t.color||n.color},n.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&De.createElement("title",null,i),t.children)};return zt!==void 0?De.createElement(zt.Consumer,null,n=>s(n)):s(Ns)}function xn(t){return K({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 vn(t){return K({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 yt(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"},child:[]}]})(t)}function Ce(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"18",y1:"6",x2:"6",y2:"18"},child:[]},{tag:"line",attr:{x1:"6",y1:"6",x2:"18",y2:"18"},child:[]}]})(t)}function Ss(t){return K({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 K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 9.9-1"},child:[]}]})(t)}function $e(t){return K({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 K({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 Vt(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"6"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"2"},child:[]}]})(t)}function bn(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"5"},child:[]},{tag:"line",attr:{x1:"12",y1:"1",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"23"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},child:[]},{tag:"line",attr:{x1:"1",y1:"12",x2:"3",y2:"12"},child:[]},{tag:"line",attr:{x1:"21",y1:"12",x2:"23",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},child:[]}]})(t)}function tt(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]}]})(t)}function st(t){return K({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 jn(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"22",y1:"2",x2:"11",y2:"13"},child:[]},{tag:"polygon",attr:{points:"22 2 15 22 11 13 2 9 22 2"},child:[]}]})(t)}function nt(t){return K({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 kn(t){return K({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 rt(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"polyline",attr:{points:"1 20 1 14 7 14"},child:[]},{tag:"path",attr:{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"},child:[]}]})(t)}function Ue(t){return K({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 Ui(t){return K({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 Gt(t){return K({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 wn(t){return K({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 Nn(t){return K({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 Cn(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"},child:[]}]})(t)}function at(t){return K({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 Sn(t){return K({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 Tn(t){return K({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 En(t){return K({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 Mn(t){return K({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 bt(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"},child:[]},{tag:"path",attr:{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"},child:[]}]})(t)}function it(t){return K({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 Rn(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"},child:[]}]})(t)}function Pn(t){return K({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 Ln(t){return K({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 In(t){return K({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 Jt(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"},child:[]}]})(t)}function Xe(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"6",y1:"3",x2:"6",y2:"15"},child:[]},{tag:"circle",attr:{cx:"18",cy:"6",r:"3"},child:[]},{tag:"circle",attr:{cx:"6",cy:"18",r:"3"},child:[]},{tag:"path",attr:{d:"M18 9a9 9 0 0 1-9 9"},child:[]}]})(t)}function qe(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"},child:[]}]})(t)}function Ts(t){return K({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 Bn(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"},child:[]},{tag:"polyline",attr:{points:"14 2 14 8 20 8"},child:[]},{tag:"line",attr:{x1:"16",y1:"13",x2:"8",y2:"13"},child:[]},{tag:"line",attr:{x1:"16",y1:"17",x2:"8",y2:"17"},child:[]},{tag:"polyline",attr:{points:"10 9 9 9 8 9"},child:[]}]})(t)}function Es(t){return K({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 jt(t){return K({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 Qt(t){return K({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 Et(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"7 10 12 15 17 10"},child:[]},{tag:"line",attr:{x1:"12",y1:"15",x2:"12",y2:"3"},child:[]}]})(t)}function lt(t){return K({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 Dn(t){return K({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 Mt(t){return K({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 $n(t){return K({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 ot(t){return K({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 ct(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function Fe(t){return K({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 dt(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"20 6 9 17 4 12"},child:[]}]})(t)}function _n(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"},child:[]},{tag:"polyline",attr:{points:"22 4 12 14.01 9 11.01"},child:[]}]})(t)}function Ms(t){return K({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 Fn(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"},child:[]},{tag:"path",attr:{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"},child:[]}]})(t)}function Rs(t){return K({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 Ps(t){return K({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 An(t){return K({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 On(t){return K({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12.01",y2:"16"},child:[]}]})(t)}function _e(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let n=0;n<16;n++)t[n]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(n=>n.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Ie({trigger:t,open:s,onOpenChange:n,children:l,align:c="right",fit:i=!1,direction:a="down",menuClassName:o}){const d=r.useRef(null);return r.useEffect(()=>{if(!s)return;const m=h=>{d.current&&!d.current.contains(h.target)&&n(!1)},x=h=>{h.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",m),document.addEventListener("keydown",x),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("keydown",x)}},[s,n]),e.jsxs("div",{className:`dropdown ${c} ${i?"fit":""} ${a==="up"?"dd-up":""}`,ref:d,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!s),"aria-expanded":s,children:[t,e.jsx(Fe,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${o??""}`,children:l})]})}function Ne({active:t,disabled:s=!1,title:n,onClick:l,children:c}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:n,onClick:l,children:c})}const Ls="pi-web-ui:lang",Hn={cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",queueSteerTag:"插队",queueFollowTag:"排队",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",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)。",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",noOptions:"(无选项)",inputPlaceholder:"输入内容",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-web-ui 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",welcomeTitle:"pi 编码智能体",welcomeSub:"检查、编辑、运行 —— 随时待命",directory:"目录",clickToFill:"点击填入输入框",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:同时搜索历史对话、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索文件…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","ex.understand":"了解这个项目","ex.understand.prompt":"介绍一下这个项目:整体结构、主要模块和如何运行?","ex.debug":"排查一个问题","ex.debug.prompt":"帮我排查一个 bug,请先说明问题现象,我会补充细节。","ex.test":"编写测试","ex.test.prompt":"为项目的核心模块编写单元测试。","ex.review":"代码审查","ex.review.prompt":"审查最近改动的代码,指出潜在问题和改进建议。",error:"出错",done:"完成",running:"执行中…",toolQueued:"排队中",copyArgs:"复制参数",errorOutput:"错误输出",output:"输出",waitingOutput:"等待输出…",toolDoneWaitingModel:"已结束 · 等模型",waitingModel:"等待模型响应…",thinkingNow:"思考中",thinkingPreview:"思考:{preview}",commands:"命令",newCommand:"新建命令",newTerminal:"新建终端",name:"名称",command:"命令",cwdHint:"(${pwd} = 当前工作目录)",noCommands:"还没有命令,点 + 添加一个",clickToRun:"点击运行",edit:"编辑",delete:"删除",confirmQ:"确认?",builtinTerminal:"内置终端",termEmptySub:"点击左侧命令运行,或点右侧 + 新建终端",noTerminal:"暂无终端",exited:"(已退出{code})",closeTerminal:"关闭终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",exampleName:"例如:启动开发服务器",exampleCommand:"例如:npm run dev",scmTab:"Git",scmTitle:"源代码管理",scmRefreshTip:"重新查询 Git 状态与差异",scmCurrentBranch:"当前分支",scmUpstreamGone:"上游已删除",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"分离 HEAD",scmSelectBranch:"选择分支…",scmRemoteBranches:"远程分支",scmStageTip:"暂存 {path}",scmUnstageTip:"取消暂存 {path}",scmSwitch:"切换",scmSwitchBranch:"切换分支",scmSwitchBranchTip:"在终端中执行 git checkout {branch}",scmPush:"推送",scmPushTip:"在终端中执行 git push",scmPull:"拉取",scmPullTip:"在终端中执行 git pull",scmCommit:"提交",scmCommitTip:'在终端中执行 git add -A && git commit -m "…"(提交全部更改,含未跟踪)',scmCommitPlaceholder:"输入提交信息…",scmChanges:"更改",scmHistory:"提交树",scmCommitDetail:"提交详情",scmSelectCommitHint:"点击左侧提交查看详情",scmNoHistory:"暂无提交记录",scmNoChanges:"工作区干净,没有更改",scmNotGitRepo:"当前目录不是 Git 仓库",scmLoading:"查询中…",scmConnecting:"等待连接…",scmDiff:"差异",scmSelectFileHint:"点击左侧文件查看差异",scmNoDiff:"(无差异)",scmStaged:"已暂存",scmUnstaged:"未暂存",scmStagedUnstaged:"已暂存 + 未暂存",scmUntracked:"未跟踪",scmUntrackedNote:"未跟踪文件:差异不显示,提交时会一并包含",scmQueryFailed:"Git 查询失败:{error}",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"只需填入 API 密钥",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",cloneProvider:"复制为自定义",cloning:"复制中",cloneProviderTitle:"复制该内置供应商(baseUrl + 模型列表)为自定义供应商,填入另一个 API 密钥即可双 key 并存",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",customProviders:"自定义服务商",customDesc:"用于 Ollama / vLLM / 兼容 OpenAI 的代理等,写入 pi 的 models.json,保存后热重载、立即生效。",noCustomProviders:"还没有自定义服务商",modelsCount:"{n} 个模型",addProvider:"新增服务商",providerId:"服务商 ID",providerIdHint:"(必填,如 ollama / my-proxy)",displayName:"显示名",displayNamePh:"我的代理",apiType:"API 类型",baseUrlHint:"(OpenAI 兼容端点)",apiKeyHint:"sk-…(可留空,用 auth.json 的密钥)",authHeader:"自动添加 Authorization 请求头",modelsTitle:"模型",modelIdReq:"模型 ID(必填)",text:"文本",textImage:"文本+图片",contextWindow:"上下文",maxOutput:"最大输出",removeModel:"移除模型",addModel:"添加模型",deleteProviderConfirm:"删除服务商 {id} 及其 {n} 个模型?",fetchModels:"自动获取模型列表",fetchModelsHint:"从 baseUrl 的 /models 接口自动拉取模型 ID(服务端请求,不受 CORS 限制)",fetchingModels:"获取中…",fetchModelsOk:"已获取 {n} 个模型",fetchModelsEmpty:"接口未返回任何模型",fetchModelsErr:"获取失败:{msg}",fetchModelsNeedBaseUrl:"请先填写 baseUrl 再获取",goalBarTitle:"目标",goalBarPlaceholder:"设定一个目标,agent 完成后自动审查…",goalBarSet:"开始",goalBarClear:"取消",goalBarLocked:"锁定:应用到后续所有回合",goalBarUnlocked:"仅本回合(改完自动清除)",goalBarReviewModel:"审查模型",goalBarUseMainModel:"使用主模型",goalBarMaxRounds:"最大轮数",goalBarMaxRoundsTip:"最大审查重改轮数;0 或不填 = 不限(持续改到通过)",goalBarUnlimitedShort:"不限",goalBarReviewing:"审查中…",goalBarRound:"第 {n} 轮",goalBarActive:"目标生效中",goalBarPassed:"已通过",goalBarFailed:"未通过",goalBarStatusPending:"等待生成…",goalWizardBtn:"AI 提炼",goalWizardTip:"让 AI 通过问卷调研细化需求,收敛为目标",goalWizardRunning:"目标调研中",goalWizardAnswer:"回答",goalWizardCard:"目标调研",settings:"设置",settingsTitle:"设置",settingsDesc:"修改立即生效:系统提示词、技能与插件开关会重建当前会话;审查提示词与审查技能只影响后续目标审查(回复进行中则主会话变更自动延迟)。",settingsSystemPrompt:"系统提示词",settingsPromptMode:"模式",promptModeAppend:"追加",promptModeReplace:"替换",promptAppendHint:"追加模式:自定义内容拼接到默认系统提示词末尾(推荐,保留默认行为约束)。",promptReplaceHint:"替换模式:完全用自定义内容替换系统提示词(项目上下文与技能段仍会自动附加)。切换后输入框会显示原本的默认提示词,可直接修改;不改动失焦则仍使用默认。",promptPlaceholder:"输入自定义系统提示词…(失焦后自动应用)",settingsViewPrompt:"查看当前完整提示词",settingsViewPromptHint:"当前会话实际生效的完整系统提示词(含自定义追加/替换内容、项目上下文、技能说明与工具引导),只读。",settingsViewPromptEmpty:"会话尚未就绪,暂无系统提示词。",settingsSkills:"技能",settingsReview:"目标审查",settingsReviewDesc:"为独立的目标审查会话配置额外提示词和技能;不会改变主会话设置。",settingsReviewSkills:"审查可用技能",reviewPromptPlaceholder:"输入审查自定义提示词…(失焦后自动应用)",reviewPromptHint:"这些内容会追加到审查任务中;审查仍会强制要求输出 pass/fail JSON。技能开关仅对审查生效。",settingsVisionBridge:"视觉桥",settingsVisionBridgeDesc:"当前模型不支持识图时,把图片交给已配置的视觉模型转写为文字证据,再让模型回答",visionBridgeEnabled:"启用视觉桥",visionBridgeModel:"转写模型",visionBridgeAuto:"自动选择(按顺序)",visionBridgeNoModels:"未找到已配置的视觉模型:在模型配置里添加任意支持图片的模型(如 qwen-vl、GLM-4V、Gemini)即可自动启用",visionBridgeOffHint:"已关闭:图片将原样发送,纯文本模型可能看不到图片内容",visionBridgeCurrent:"当前转写模型:{model}",visionBridgePromptMode:"转写提示词",settingsTerminalTools:"终端工具",terminalToolsEnabled:"启用持久终端工具",settingsTerminalToolsDesc:"让 AI 在交互式程序(REPL/vim)、长驻服务、需要持续观察输出或你要求在可见终端操作时,使用内置终端;普通命令仍走一次性 bash 工具",terminalToolsOffHint:"已关闭:AI 无法使用 terminal_* 工具,也不会收到相关使用引导",terminalBashTakeover:"终端接管 bash",terminalBashTakeoverDesc:"bash 命令改在持久可见终端里执行:完整输出自动返回、shell 状态跨调用保留(cd/venv/ssh);命令静默超时自动转后台并在结束后主动通知 AI",terminalBashIdleMs:"静默转后台阈值(毫秒)",terminalBashIdleMsDesc:"命令连续无输出达到该时长即不再阻塞等待,转入后台继续运行并通知 AI;0 = 一直等到命令结束(默认 15000)",visionBridgePromptPlaceholder:"输入自定义转写提示词…(留空 = 使用内置默认提示词,失焦后自动应用)",visionBridgePromptAppendHint:"追加模式:自定义内容拼接到内置转写提示词末尾(推荐,保留默认的逐字转写约束)。",visionBridgePromptReplaceHint:"替换模式:完全用自定义内容替换内置转写提示词。切换后输入框会显示内置默认提示词,可直接修改;不改动失焦则仍使用默认。",uninstallExt:"卸载",uninstallConfirm:"确认卸载?",uninstallConfirmHint:"再次点击确认,将在终端执行 pi remove",uninstallHint:"通过可见终端执行 pi remove 卸载此包,完成后自动刷新列表",uninstallTitle:"卸载",pluginUpdate:"更新",pluginUpdateHint:"从安装来源重新拉取并覆盖安装(保留 config.json 配置),完成后自动重载插件列表",pluginUninstallHint:"在可见终端执行 pi-web-ui uninstall 卸载此插件(再次点击确认),完成后自动刷新列表",settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},Wn={cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",dragToResize:"Drag to resize · double-click to reset",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",githubRepo:"GitHub repository (xing-shuyin/pi-web-ui)",copy:"Copy",viewSwitch:"Switch view",chat:"Chat",terminal:"Terminal",selectModel:"Select model",availableModels:"Available models",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",placeholderStreaming:"The agent is working… press Enter to steer, or click Queue to send after the reply finishes",placeholderIdle:"Message pi — Enter to send, / for commands",placeholderConnecting:"Connecting to server…",stopAgent:"Stop agent",stop:"Stop",bgTasks:"Background tasks",bgTasksTip:"Servers the AI started in the background (npm run dev & etc.) — stop them individually or all at once; they survive the conversation",bgTasksEmpty:"No background tasks",bgTasksDesc:"Processes the AI started that are still listening (detected by port)",bgTaskPort:"Port",bgTaskPid:"PID",bgTaskSince:"Started",bgTaskStop:"Stop",bgTaskStopAll:"Stop all",bgTaskRefresh:"Refresh",bgTaskJustNow:"just now",bgTaskMinutes:"{n} min ago",bgTaskHours:"{n} hr ago",bgTaskDays:"{n} days ago",stopBash:"Stop",stopBashTip:"Stop the running bash command (conversation continues)",supplement:"Queue",supplementTip:"Add to queue: sent only after the whole run finishes (no interruption)",queueSteerTag:"Steer",queueFollowTag:"Queued",sendTip:"Send (Enter)",slashCommands:"Commands",slashMenuHint:"↑↓ select · Enter/Tab complete",slashHelpTitle:"pi commands",slashHelpHint:"Type / anytime to open the command list",slashLoading:"Loading commands… (available once connected)",slashBuiltin:"Builtin",slashExtension:"Extension",slashPrompt:"Template",slashSkill:"Skill",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).",rootDir:"Root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",previewFile:"Preview",downloadFile:"Download file",downloadFailed:"Download failed: {error}",protocolMismatch:"Page version differs from the server (the app was just updated). Refresh the page to restore full functionality.",selectLinesHint:"Click a line to select; drag or Shift+click for a range",enableWrap:"Enable line wrap",disableWrap:"Disable line wrap",selectedRange:"Selected {n} lines (lines {start}-{end})",fileLines:"{n} lines",selectAll:"Select all",clearSelection:"Clear",addToChat:"Add to chat",addedToChat:"Added",previewTruncated:"⚠ File too large — previewing the first 512KB",previewLinesTruncated:"… too many lines — showing the first {n}",binaryFile:"🔣 Binary file — first 4KB shown as hex",binaryHexTruncated:" (file larger — download for the full file)",previewNotSupported:"This file type can't be previewed (only images / videos / text)",emptyFile:"(empty file)",editFile:"Edit file",exitEditFile:"Exit editing",saveFile:"Save file",discardFileChanges:"Discard unsaved changes?",fileSaved:"Saved",fileEditTruncated:"The preview is incomplete, so this file can't be edited",showMarkdownSource:"Show Markdown source",showMarkdownPreview:"Show Markdown preview",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",zoomIn:"Increase font size",zoomOut:"Decrease font size",resetZoom:"Reset zoom",pluginRequest:"Plugin request",noOptions:"(no options)",inputPlaceholder:"Enter content",soundHeader:"Sound notifications",enableSound:"Enable sound",preview:"Preview",volume:"Volume","sound.question":"Question popup","sound.question.desc":"When ask_user_question appears","sound.done":"Reply finished","sound.done.desc":"When the agent finishes a turn","sound.start":"Reply started","sound.start.desc":"When the agent starts a new turn","sound.error":"Error","sound.error.desc":"When an error notice appears",setupTitle:"pi agent config not detected",setupDesc:"pi-web-ui needs pi's config directory (~/.pi/agent) and at least one API key to run the agent. pi has built-in providers such as openai, anthropic, and deepseek — just pick one and enter a key, no terminal needed.",installFailed:"✖ pi agent installation failed:",retryInstall:"Retry install",skip:"Skip",installDone:"✅ pi agent CLI installed. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",welcomeTitle:"pi coding agent",welcomeSub:"Inspect, edit, run — always ready",directory:"Directory",clickToFill:"Click to fill input",waitingResponse:"Waiting for model response…",backToBottom:"Back to bottom",questionNavTitle:"Questions",searchPlaceholder:"Search in conversation…",searchNoResults:"No results",searchModels:"Filter models…",noModelMatches:"No matching models",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search session history, recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching files…",gsTruncated:"Too many matches — showing a subset",gsCurrentProject:"current",gsOpenPreview:"Open file preview",gsNavigate:"select",gsOpen:"open",gsCloseHint:"close",bgTaskCommand:"Command",searchPrev:"Previous (Shift+Enter)",searchNext:"Next (Enter)",searchClose:"Close (Esc)",questionNavTip:"All questions in this conversation — hover to expand, click to jump","ex.understand":"Understand this project","ex.understand.prompt":"Introduce this project: overall structure, main modules, and how to run it?","ex.debug":"Debug an issue","ex.debug.prompt":"Help me debug a bug — describe the symptom first, and I'll add details.","ex.test":"Write tests","ex.test.prompt":"Write unit tests for the core modules.","ex.review":"Code review","ex.review.prompt":"Review the recently changed code and point out potential issues and improvements.",error:"Error",done:"Done",running:"Running…",toolQueued:"Queued",copyArgs:"Copy args",errorOutput:"Error output",output:"Output",waitingOutput:"Waiting for output…",toolDoneWaitingModel:"Done · waiting on model",waitingModel:"Waiting for model response…",thinkingNow:"Thinking",thinkingPreview:"Thinking: {preview}",commands:"Commands",newCommand:"New command",newTerminal:"New terminal",name:"Name",command:"Command",cwdHint:"(${pwd} = current working directory)",noCommands:"No commands yet — click + to add one",clickToRun:"Click to run",edit:"Edit",delete:"Delete",confirmQ:"Confirm?",builtinTerminal:"Built-in terminal",termEmptySub:"Click a command on the left to run it, or + on the right for a new terminal",noTerminal:"No terminals",exited:"(exited{code})",closeTerminal:"Close terminal",rerun:"Reload .pi/commands.json",terminalTitle:"Terminal {n}",exampleName:"e.g. start dev server",exampleCommand:"e.g. npm run dev",scmTab:"Git",scmTitle:"Source Control",scmRefreshTip:"Re-query git status & diff",scmCurrentBranch:"Current branch",scmUpstreamGone:"Upstream deleted",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"Detached HEAD",scmSelectBranch:"Select branch…",scmRemoteBranches:"Remote branches",scmStageTip:"Stage {path}",scmUnstageTip:"Unstage {path}",scmSwitch:"Switch",scmSwitchBranch:"Switch branch",scmSwitchBranchTip:"Runs git checkout {branch} in the terminal",scmPush:"Push",scmPushTip:"Runs git push in the terminal",scmPull:"Pull",scmPullTip:"Runs git pull in the terminal",scmCommit:"Commit",scmCommitTip:'Runs git add -A && git commit -m "…" in the terminal (commits all changes incl. untracked)',scmCommitPlaceholder:"Type a commit message…",scmChanges:"Changes",scmHistory:"Commit tree",scmCommitDetail:"Commit details",scmSelectCommitHint:"Click a commit on the left to view its details",scmNoHistory:"No commits yet",scmNoChanges:"Working tree clean — no changes",scmNotGitRepo:"Current directory is not a Git repository",scmLoading:"Querying…",scmConnecting:"Waiting for connection…",scmDiff:"Diff",scmSelectFileHint:"Click a file on the left to view its diff",scmNoDiff:"(no diff)",scmStaged:"Staged",scmUnstaged:"Unstaged",scmStagedUnstaged:"Staged + unstaged",scmUntracked:"Untracked",scmUntrackedNote:"Untracked file — not shown in diff, included on commit",scmQueryFailed:"Git query failed: {error}",scmTooManyFailures:"Git queries keep failing — click refresh to retry",scmRunsInTerminal:"Commit / branch switch / push / pull run in the terminal",scmViewTerminal:"Open terminal",editProvider:"Edit provider",builtinProviders:"Built-in providers",hintKeyOnly:"Just enter an API key",configuredBadge:"✓ Configured",keyReady:"Key ready",replaceKey:"Replace key",replaceKeyTitle:"Replace the saved key",clearKey:"Clear",clearKeyTitle:"Remove this provider's key stored in auth.json; it returns to unconfigured (env-var sourced keys can't be cleared here)",clearKeyConfirm:"Clear the stored key for {id}? Its models will leave the list until you configure it again.",cloneProvider:"Clone as custom",cloning:"Cloning",cloneProviderTitle:"Copy this built-in provider (baseUrl + model catalog) into a custom provider — paste another API key to run both keys side by side",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",customProviders:"Custom providers",customDesc:"For Ollama / vLLM / OpenAI-compatible proxies, etc. Written to pi's models.json — hot-reloaded immediately.",noCustomProviders:"No custom providers yet",modelsCount:"{n} models",addProvider:"Add provider",providerId:"Provider ID",providerIdHint:"(required, e.g. ollama / my-proxy)",displayName:"Display name",displayNamePh:"My proxy",apiType:"API type",baseUrlHint:"(OpenAI-compatible endpoint)",apiKeyHint:"sk-… (optional — uses the auth.json key)",authHeader:"Auto-add Authorization header",modelsTitle:"Models",modelIdReq:"Model ID (required)",text:"Text",textImage:"Text+image",contextWindow:"Context",maxOutput:"Max output",removeModel:"Remove model",addModel:"Add model",deleteProviderConfirm:"Delete provider {id} and its {n} models?",fetchModels:"Fetch model list",fetchModelsHint:"Pull model IDs from the baseUrl /models endpoint (server-side, no CORS)",fetchingModels:"Fetching…",fetchModelsOk:"Fetched {n} models",fetchModelsEmpty:"The endpoint returned no models",fetchModelsErr:"Fetch failed: {msg}",fetchModelsNeedBaseUrl:"Enter a baseUrl first",goalBarTitle:"Goal",goalBarPlaceholder:"Set a goal; the agent's output is auto-reviewed…",goalBarSet:"Start",goalBarClear:"Cancel",goalBarLocked:"Locked: applies to every later turn",goalBarUnlocked:"This turn only (cleared afterwards)",goalBarReviewModel:"Review model",goalBarUseMainModel:"Use the main model",goalBarMaxRounds:"Max rounds",goalBarMaxRoundsTip:"Max review-revision rounds; 0 or empty = unlimited (keep revising until it passes)",goalBarUnlimitedShort:"Unlimited",goalBarReviewing:"Reviewing…",goalBarRound:"Round {n}",goalBarActive:"Goal active",goalBarPassed:"Passed",goalBarFailed:"Failed",goalBarStatusPending:"Waiting to generate…",goalWizardBtn:"AI Scrape",goalWizardTip:"Let AI refine the requirement into a goal via a Q&A survey",goalWizardRunning:"Scoping the goal",goalWizardAnswer:"Answer",goalWizardCard:"Goal survey",settings:"Settings",settingsTitle:"Settings",settingsDesc:"Changes apply immediately: system prompt, skill and extension toggles rebuild the current session; review instructions and review skills affect later goal reviews (main-session changes are deferred while streaming).",settingsSystemPrompt:"System prompt",settingsPromptMode:"Mode",promptModeAppend:"Append",promptModeReplace:"Replace",promptAppendHint:"Append mode: your text is appended to the end of the default system prompt (recommended — keeps the default behavior constraints).",promptReplaceHint:"Replace mode: your text fully replaces the system prompt (project context and skills are still appended automatically). After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",promptPlaceholder:"Type a custom system prompt… (applied on blur)",settingsViewPrompt:"View the current full prompt",settingsViewPromptHint:"The full system prompt actually in effect for this conversation (custom append/replace text, project context, skills and tool guidance). Read-only.",settingsViewPromptEmpty:"Session not ready yet — no system prompt available.",settingsSkills:"Skills",settingsReview:"Goal review",settingsReviewDesc:"Configure extra instructions and skills for the isolated goal-review session; the main session is unaffected.",settingsReviewSkills:"Skills available to review",reviewPromptPlaceholder:"Type custom review instructions… (applied on blur)",reviewPromptHint:"These instructions are added to the review task; pass/fail JSON output is still enforced. Skill toggles apply only to review.",settingsVisionBridge:"Vision bridge",settingsVisionBridgeDesc:"When the current model can't see images, send them to a configured vision model and transcribe into text evidence first",visionBridgeEnabled:"Enable vision bridge",visionBridgeModel:"Transcription model",visionBridgeAuto:"Auto (in order)",visionBridgeNoModels:"No configured vision model found: add any image-capable model (e.g. qwen-vl, GLM-4V, Gemini) in Model config to enable automatically",visionBridgeOffHint:"Disabled: images are sent as-is, a text-only model may not see them",visionBridgeCurrent:"Current transcription model: {model}",visionBridgePromptMode:"Transcription prompt",settingsTerminalTools:"Terminal tools",terminalToolsEnabled:"Enable persistent terminal tools",settingsTerminalToolsDesc:"Let the AI use the built-in terminal for interactive programs (REPLs/vim), long-running servers, continuous output watching, or when you ask it to work in the visible terminal; ordinary commands still go through the one-shot bash tool",terminalToolsOffHint:"Disabled: the AI has no terminal_* tools and receives no usage guidance",terminalBashTakeover:"Terminal-backed bash",terminalBashTakeoverDesc:"Run bash commands inside the persistent visible terminal: full output returned automatically, shell state retained across calls (cd/venv/ssh); silent commands move to the background and notify the AI when they finish",terminalBashIdleMs:"Silence-to-background threshold (ms)",terminalBashIdleMsDesc:"When a command produces no output for this long, stop blocking and let it keep running in the background; the AI is notified when it finishes. 0 = always wait until completion (default 15000)",visionBridgePromptPlaceholder:"Type a custom transcription prompt… (empty = built-in default, applied on blur)",visionBridgePromptAppendHint:"Append mode: custom text is appended after the built-in transcription prompt (recommended — keeps the verbatim-transcription contract).",visionBridgePromptReplaceHint:"Replace mode: custom text replaces the built-in transcription prompt entirely. After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",uninstallExt:"Uninstall",uninstallConfirm:"Confirm?",uninstallConfirmHint:"Click again to confirm — runs pi remove in the terminal",uninstallHint:"Runs pi remove in a visible terminal, then refreshes the list automatically",uninstallTitle:"Uninstall",pluginUpdate:"Update",pluginUpdateHint:"Re-installs from the recorded source (--force, keeps config.json), then refreshes the plugin list automatically",pluginUninstallHint:"Runs pi-web-ui uninstall in a visible terminal (click again to confirm), then refreshes the list automatically",settingsExtensions:"Extensions",settingsUiPlugins:"UI plugins",noUiPlugins:"No UI plugins installed (<dataDir>/plugins/)",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",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…"},Is=r.createContext(null);function Un(){try{const t=localStorage.getItem(Ls);if(t==="zh"||t==="en")return t}catch{}return"zh"}function qn({children:t}){const[s,n]=r.useState(Un),l=r.useCallback(a=>{n(a);try{localStorage.setItem(Ls,a)}catch{}},[]),c=r.useCallback((a,o)=>{let d=Wn[a];if(s==="zh"&&(d=Hn[a]),o)for(const[m,x]of Object.entries(o))d=d.replaceAll(`{${m}}`,String(x));return d},[s]);r.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en"},[s]);const i=r.useMemo(()=>({locale:s,setLocale:l,t:c}),[s,l,c]);return e.jsx(Is.Provider,{value:i,children:t})}function Rt(){const t=r.useContext(Is);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function he(){return Rt().t}const zn=["off","minimal","low","medium","high","xhigh","max"],Bs=r.memo(function({state:s,models:n,modelsLoading:l,send:c,onManageModels:i,compact:a=!1}){const o=he(),d=s==null?void 0:s.model,m=d?`${d.provider}/${d.id}`:null,[x,h]=r.useState(!1),[v,C]=r.useState(!1),[N,_]=r.useState("");r.useEffect(()=>{x||_("")},[x]);const M=r.useMemo(()=>{const y=N.trim().toLowerCase();return y?n.filter(k=>k.name.toLowerCase().includes(y)||k.provider.toLowerCase().includes(y)||k.id.toLowerCase().includes(y)):n},[n,N]),[D,O]=r.useState(!1),p=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,E=zn.map(y=>({value:y,label:o(`thinking.${y}`),supported:p?p.has(y):!0})),P=y=>{var k;return((k=E.find(u=>u.value===y))==null?void 0:k.label)??y};return r.useEffect(()=>{x&&n.length===0&&!D&&!l&&(O(!0),c({type:"list_models"}))},[x,n.length,D,l,c]),r.useEffect(()=>{n.length>0&&O(!1)},[n.length]),e.jsxs(e.Fragment,{children:[e.jsxs(Ie,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(lt,{}),e.jsx("span",{className:"chip-model",children:d?d.name:o("selectModel")}),!a&&(d==null?void 0:d.vision)&&e.jsx("span",{className:"chip-vision",title:o("vision"),children:"🖼"}),!a&&d&&e.jsx("span",{className:"chip-sub",children:d.provider})]}),open:x,onOpenChange:h,menuClassName:"dd-menu-model",children:[e.jsx("div",{className:"dd-header",children:o("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(nt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:o("searchModels"),value:N,onChange:y=>_(y.target.value)})]}),e.jsxs("div",{className:"dd-model-scroll",children:[(D||l)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),n.length===0&&!D&&!l&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),M.length===0&&n.length>0&&e.jsx("div",{className:"dd-loading",children:o("noModelMatches")}),M.map(y=>e.jsx(Ne,{active:m===y.id,onClick:()=>{m!==y.id&&c({type:"set_model",modelId:y.id}),h(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:y.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:y.provider}),(y.reasoning||y.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[y.reasoning&&e.jsx("span",{className:"dd-model-badge",children:o("reasoning")}),y.vision&&e.jsx("span",{className:"dd-model-badge",children:o("vision")})]})]})]})},y.id))]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>c({type:"list_models"}),children:o("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{h(!1),i()},children:o("manageModels")})]})]}),e.jsxs(Ie,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(yt,{}),e.jsx("span",{className:"chip-sub",children:o("thinkingChip",{level:s?P(s.thinkingLevel):"—"})})]}),open:v,onOpenChange:C,children:[e.jsx("div",{className:"dd-header",children:o("thinkingLevel")}),E.map(y=>e.jsx(Ne,{active:(s==null?void 0:s.thinkingLevel)===y.value,disabled:!y.supported,title:y.supported?void 0:o("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==y.value&&c({type:"set_thinking",level:y.value}),C(!1)},children:y.label},y.value))]})]})}),Kn=[{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 Yt({settings:t,onChange:s,onPreview:n}){const l=he(),c=i=>s({...t,...i});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:l("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Ss,{className:"sound-icon"}),e.jsx("span",{children:l("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:i=>c({enabled:i.target.checked})})]}),Kn.map(({kind:i,labelKey:a,descKey:o})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:l(a)}),e.jsx("span",{className:"sound-desc",children:l(o)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:l("preview"),disabled:!t.enabled,onClick:d=>{d.preventDefault(),n(i)},children:l("preview")}),e.jsx("input",{type:"checkbox",checked:t[i],disabled:!t.enabled,onChange:d=>c({[i]:d.target.checked})})]})]},i)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:l("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:i=>c({volume:Number(i.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}function Vn({chat:t,send:s,terminal:n,view:l,plugins:c,onViewChange:i,onOpenPanel:a,onManageModels:o,onOpenSettings:d,onOpenBgTasks:m,onOpenGlobalSearch:x,sound:h,onSoundChange:v,onSoundPreview:C,themes:N,theme:_,onThemeChange:M}){var ge;const{locale:D,setLocale:O,t:p}=Rt(),[E,P]=r.useState(!1),[y,k]=r.useState(!1),[u,L]=r.useState(!1),[U,G]=r.useState(!1),[J,te]=r.useState(!1),oe=[{value:"zh",label:p("langZh")},{value:"en",label:p("langEn")}],I=t.ready?p("connected"):t.status==="closed"?p("reconnecting"):p("connecting"),F=t.ready?"ok":"busy",W=()=>{var S,A;if(!t.ready)return;const R=p("updateTabTitle"),j={name:R,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},q=t.terminals.find(se=>se.title===R);q?(n.restart(q.id),s({type:"run_command",terminalId:q.id,conversationId:q.conversationId,command:j,cols:80,rows:24})):n.create({id:_e(),conversationId:t.activeConversationId||((S=t.state)==null?void 0:S.conversationId)||"",title:R,cwd:((A=t.state)==null?void 0:A.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:j}),G(!1),te(!1),i("terminal")},re=()=>{var R,j;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dd-update",children:[e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:p("currentVersion")}),e.jsxs("b",{children:["v",((R=t.update)==null?void 0:R.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:p("latestVersion")}),e.jsx("b",{children:t.update===null?p("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:p("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:p("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:p("updateAvailable",{version:t.update.latest})}),((j=t.update)==null?void 0:j.latestPublishedAt)&&Date.now()-new Date(t.update.latestPublishedAt).getTime()<30*6e4&&e.jsx("div",{className:"dd-note warn",children:p("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:p("updateTerminalHint")})]}),e.jsxs("div",{className:"dd-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"check_update"}),children:t.update===null?p("checkingUpdate"):p("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:W,children:p("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:p("openHistory"),onClick:()=>a("left"),children:e.jsx(Sn,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${F}`,title:I}),e.jsx("span",{className:"conn-label",children:I})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":p("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="chat",className:l==="chat"?"active":"",onClick:()=>i("chat"),children:[e.jsx(at,{}),e.jsx("span",{children:p("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="terminal",className:l==="terminal"?"active":"",onClick:()=>i("terminal"),children:[e.jsx(Je,{}),e.jsx("span",{children:p("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":l==="git",className:l==="git"?"active":"",onClick:()=>i("git"),children:[e.jsx(Xe,{}),e.jsx("span",{children:p("scmTab")})]}),c.map(R=>{const j=R.error?`${R.name}: ${R.error}`:R.description?`${R.name} — ${R.description}`:R.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":l===`plugin:${R.id}`,className:`plugin-tab${l===`plugin:${R.id}`?" active":""}${R.error?" broken":""}`,title:j,onClick:()=>i(`plugin:${R.id}`),children:[R.icon?e.jsx("span",{"aria-hidden":!0,children:R.icon}):e.jsx(Ms,{}),e.jsx("span",{children:R.name})]},R.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:p("searchGlobalTip"),onClick:x,children:[e.jsx(nt,{}),e.jsx("span",{className:"chip-sub",children:p("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":p("bgTasksTip"),onClick:m,children:[e.jsx(it,{}),e.jsx("span",{className:"chip-sub",children:p("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(Bs,{state:t.state?{model:t.state.model,thinkingLevel:t.state.thinkingLevel,availableThinkingLevels:t.state.availableThinkingLevels}:null,models:t.models,modelsLoading:t.modelsLoading,send:s,onManageModels:o}),e.jsxs("button",{type:"button",className:"chip",title:p("settingsTitle"),onClick:d,children:[e.jsx(st,{}),e.jsx("span",{className:"chip-sub",children:p("settings")})]}),e.jsx(Ie,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ss,{}),e.jsx("span",{className:"chip-sub",children:p("sound")})]}),open:E,onOpenChange:P,children:e.jsx(Yt,{settings:h,onChange:v,onPreview:C})}),e.jsxs(Ie,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(In,{}),e.jsx("span",{className:"chip-sub",children:D==="zh"?p("langZh"):"EN"})]}),open:y,onOpenChange:k,children:[e.jsx("div",{className:"dd-header",children:p("language")}),oe.map(R=>e.jsx(Ne,{active:D===R.value,onClick:()=>{O(R.value),k(!1)},children:R.label},R.value))]}),e.jsxs(Ie,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(bn,{}),e.jsx("span",{className:"chip-sub",children:p("theme")})]}),open:u,onOpenChange:L,children:[e.jsx("div",{className:"dd-header",children:p("theme")}),e.jsx(Ne,{active:_===null,onClick:()=>{M(null),L(!1)},children:p("themeDefault")}),N.map(R=>e.jsx(Ne,{active:_===R.id,onClick:()=>{M(R.id),L(!1)},children:R.name},R.id))]}),e.jsxs(Ie,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Et,{}),e.jsxs("span",{className:"chip-sub",children:["v",((ge=t.update)==null?void 0:ge.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:p("updateAvailable",{version:t.update.latest??""})})]}),open:U,onOpenChange:R=>{G(R),R&&s({type:"check_update"})},fit:!0,children:[e.jsx("div",{className:"dd-header",children:p("update")}),re()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:p("githubRepo"),children:e.jsx(Jt,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":p("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(Ue,{}),e.jsx("span",{children:p("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(Ie,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Nn,{}),e.jsx("span",{className:"chip-sub",children:p("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:J,onOpenChange:R=>{te(R),R&&s({type:"check_update"})},children:[e.jsx("div",{className:"dd-header",children:p("sound")}),e.jsx("div",{className:"dd-header",children:p("settings")}),e.jsxs(Ne,{onClick:()=>{te(!1),d()},children:[e.jsx(st,{})," ",p("settingsTitle")]}),e.jsxs(Ne,{onClick:()=>{te(!1),x()},children:[e.jsx(nt,{})," ",p("searchGlobal")]}),e.jsxs(Ne,{onClick:()=>{te(!1),m()},children:[e.jsx(it,{})," ",p("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(Yt,{settings:h,onChange:v,onPreview:C}),e.jsx("div",{className:"dd-header",children:p("language")}),oe.map(R=>e.jsx(Ne,{active:D===R.value,onClick:()=>O(R.value),children:R.label},R.value)),e.jsx("div",{className:"dd-header",children:p("theme")}),e.jsx(Ne,{active:_===null,onClick:()=>{M(null),te(!1)},children:p("themeDefault")}),N.map(R=>e.jsx(Ne,{active:_===R.id,onClick:()=>{M(R.id),te(!1)},children:R.name},R.id)),e.jsx("div",{className:"dd-header",children:p("update")}),re(),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(Jt,{})," ",p("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:p("openFiles"),onClick:()=>a("right"),children:e.jsx(qe,{})})]})]})}function Xt(t){const s=new Date(t),n=new Date;return s.toDateString()===n.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}const Gn=r.memo(function({ready:s,status:n,cwd:l,sessionFile:c,conversations:i,sessions:a,projects:o,activeConversationId:d,send:m,active:x}){const h=he(),v=c,C=l,[N,_]=r.useState(null);r.useEffect(()=>{!x||!s||n!=="open"||l&&(m({type:"list_sessions"}),m({type:"list_projects"}))},[x,s,n,l,m]);const M=p=>{const E=p.name||p.firstMessage.trim();return E.length>0?E:h("emptyChat")},D=p=>p.split(/[\\/]/).pop()||p,O=(p,E,P,y)=>{const k=N===p;return e.jsx("button",{type:"button",className:`lp-del ${k?"confirm":""}`,title:k?P:E,onClick:u=>{u.stopPropagation(),k?(_(null),y()):_(p)},children:k?e.jsx(dt,{}):e.jsx($e,{})})};return e.jsxs("aside",{className:"panel panel-left",children:[o.length>0&&e.jsxs("div",{className:"panel-projects",children:[e.jsx("div",{className:"panel-section-title",children:h("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:o.map(p=>{const E=C===p.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>_(P=>P===`proj:${p.path}`?null:P),children:[e.jsxs("button",{type:"button",className:`project-item ${E?"active":""}`,title:p.path,onClick:()=>{E||m({type:"set_cwd",path:p.path})},children:[e.jsx(qe,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:D(p.path)}),e.jsx("span",{className:"project-path",children:p.path})]}),e.jsx("span",{className:"project-time",children:Xt(p.lastUsed)})]}),O(`proj:${p.path}`,h("deleteProject"),h("deleteProjectConfirm"),()=>m({type:"remove_project",path:p.path}))]},p.path)})})]}),i.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:h("runningConversations")}),i.map(p=>{const E=d===p.id;return e.jsxs("button",{type:"button",className:`session-item ${E?"active":""}`,title:p.title,onClick:()=>{E||m({type:"switch_conversation",id:p.id})},children:[e.jsx(at,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:p.title}),e.jsx("span",{className:"session-sub",children:E?h("current"):h("messageCount",{n:p.messageCount})})]}),p.isStreaming&&e.jsx("span",{className:"conv-streaming",title:h("streaming")})]},p.id)}),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:h("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[a.length===0&&e.jsx("div",{className:"panel-empty",children:h("noHistory")}),a.map(p=>{const E=v===p.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>_(P=>P===`sess:${p.path}`?null:P),children:[e.jsxs("button",{type:"button",className:`session-item ${E?"active":""}`,title:p.path,onClick:()=>{E||m({type:"switch_session",path:p.path})},children:[e.jsx(at,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:M(p)}),e.jsxs("span",{className:"session-sub",children:[E?h("current"):h("messageCount",{n:p.messageCount}),p.source==="tui"&&e.jsx("span",{className:"session-src",title:h("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:Xt(p.modified)})]}),O(`sess:${p.path}`,h("deleteSession"),h("deleteSessionConfirm"),()=>m({type:"delete_session",path:p.path}))]},p.path)})]})]})]})}),Ds="pi-web-ui:token";function Jn(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem(Ds,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function Qn(){try{return localStorage.getItem(Ds)??""}catch{return""}}function ut(t){const s=Qn();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}function Yn(t,s){const n=s.assistantMessageEvent,l=t.stats.tokens,c=s.usage!==null?{...l,...s.usage}:l,i=c===l?t.stats:{...t.stats,tokens:c};if(n.type!=="text_delta"&&n.type!=="thinking_delta")return i===t.stats?t:{...t,stats:i};const a=n.delta??"";if(!a)return i===t.stats?t:{...t,stats:i};const o=t.streamingMessage??null,d=o&&o.id===s.messageId?o:{id:s.messageId,content:[]},m=[...d.content],x=n.type==="thinking_delta"?"thinking":"text",h=n.contentIndex??m.length-1;return h>=0&&h<m.length&&m[h].type===x?m[h]=x==="thinking"?{type:"thinking",thinking:(m[h].thinking??"")+a}:{type:"text",text:(m[h].text??"")+a}:m.push(x==="thinking"?{type:"thinking",thinking:a}:{type:"text",text:a}),{...t,stats:i,streamingMessage:{...d,id:s.messageId,content:m}}}const kt="pi-web-ui:plugin-data";function Xn(t,s){window.dispatchEvent(new CustomEvent(kt,{detail:{pluginId:t,payload:s}}))}function Zn(t){const s=n=>{const l=n.detail;t(l.pluginId,l.payload)};return window.addEventListener(kt,s),()=>window.removeEventListener(kt,s)}const We=new Map,wt=new Set,Oe=new Set;let Zt=-1;function $s(){return[...We.values()]}function ea(){const t=$s();for(const s of wt)s(t)}function ta(t){return wt.add(t),t($s()),()=>wt.delete(t)}async function sa(t,s){s!==Zt&&(Zt=s,We.clear(),Oe.clear());const n=new Set(t.map(l=>l.id));for(const l of[...We.keys()])n.has(l)||We.delete(l);for(const l of[...Oe])n.has(l)||Oe.delete(l);await Promise.all(t.filter(l=>l.hasClient&&!l.error&&!We.has(l.id)&&!Oe.has(l.id)).map(async l=>{try{const i=(await ws(()=>import(`/plugins/${encodeURIComponent(l.id)}/client/entry.mjs?e=${s}`),[])).default;i&&typeof i.mount=="function"?We.set(l.id,{info:l,module:i}):(Oe.add(l.id),console.error(`[plugin:${l.id}] entry.mjs 缺少 default.mount`))}catch(c){Oe.add(l.id),console.error(`[plugin:${l.id}] 客户端加载失败:`,c)}})),ea()}function na(t,s){return{pluginId:t,send:n=>s({type:"plugin_message",pluginId:t,payload:n}),onData:n=>Zn((l,c)=>{l===t&&n(c)})}}const aa=9,ht=2e5,ia=2e5,ra={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 la(){const t=new Map,s=new Map,n=(l,c)=>`${l}:${c}`;return{write(l,c,i){const a=n(l,c),o=t.get(a);if(o&&o.size>0){for(const x of o)try{x.write(i)}catch{}return}const d=s.get(a)??"",m=d.length+i.length>ia?i:d+i;s.set(a,m)},register(l,c,i){const a=n(l,c);let o=t.get(a);o||(o=new Set,t.set(a,o)),o.add(i);const d=s.get(a);if(d){try{i.write(d)}catch{}s.delete(a)}return()=>{const m=t.get(a);m&&(m.delete(i),m.size===0&&t.delete(a)),s.delete(a)}},clear(){t.clear(),s.clear()}}}function es(t,s){const n=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&n.add(c.toolCallId),c.role==="bashExecution"&&n.add(`bash-${c.id}`);let l=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function ts(t,s){if(t.size===0)return t;const n=new Set;for(const c of s.messages)c.role==="toolResult"&&c.toolCallId&&n.add(c.toolCallId);let l=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),l=!0);return l?new Map(t):t}function oa(t,s){var n,l,c,i;switch(s.type){case"status":return{...t,status:s.status,ready:s.status==="open"?t.ready:!1,terminals:s.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:s.serverVersion,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==aa};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:es(t.liveOutputs,s.state),toolStatuses:ts(t.toolStatuses,s.state)};case"snapshot_delta":{const a=t.state,o=s.msg;if(!a||a.conversationId!==o.conversationId||a.rev!==o.baseRev)return t;const d={...a,...o.state,messages:o.appended.length>0?[...a.messages,...o.appended]:a.messages};return{...t,ready:!0,state:d,activeConversationId:d.conversationId,liveOutputs:es(t.liveOutputs,d),toolStatuses:ts(t.toolStatuses,d)}}case"tool_delta":{const a=t.liveOutputs.get(s.toolCallId),o=((a==null?void 0:a.text)??"")+s.delta,d=o.length>ht?`…[前 ${o.length-ht} 字符已省略]…
|
|
3
|
-
`+o.slice(o.length-ht):o,m=new Map(t.liveOutputs);return m.set(s.toolCallId,{toolName:s.toolName,text:d}),{...t,liveOutputs:m}}case"message_delta":{const a=t.state;return!a||a.conversationId!==s.msg.conversationId?t:{...t,state:Yn(a,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(a=>a.id!==s.id)};case"sessions":return{...t,sessions:s.sessions};case"conversations":return{...t,conversations:s.conversations,activeConversationId:s.activeId};case"projects":return{...t,projects:s.projects};case"files":return{...t,files:s.files};case"file_changed":return{...t,fileChanged:{path:s.path}};case"file_content":return{...t,fileContent:s.content};case"models":return{...t,models:s.models,modelsLoading:s.loading};case"models_config":return{...t,modelsConfig:s.providers};case"providers_status":return{...t,providers:s.providers};case"fetch_models_result":return{...t,fetchModelsResult:s.result};case"refresh_provider_result":return{...t,refreshProviderResult:s.result};case"clone_provider_result":return{...t,cloneProviderResult:s.result};case"install_result":return{...t,installResult:s.result};case"scm_data":return{...t,scmData:s.data};case"file_search_result":return{...t,fileSearch:s.result};case"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"commands":return{...t,commands:s.commands,commandsPath:s.path};case"slash_commands":return{...t,slashCommands:s.commands};case"goal_status":return{...t,goal:s.status};case"settings":return{...t,settings:s.settings};case"bg_servers":return{...t,bgServers:s.servers};case"plugins":return{...t,plugins:s.plugins,pluginsEpoch:s.epoch};case"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(a=>a.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(n=t.state)!=null&&n.conversationId)&&s.conversationId!==(t.activeConversationId||((l=t.state)==null?void 0:l.conversationId))?t:{...t,terminals:t.terminals.map(a=>a.id===s.terminalId?{...a,running:!1,exitCode:s.exitCode}:a)};case"terminal_restart":return{...t,terminals:t.terminals.map(a=>a.id===s.terminalId?{...a,running:!0,exitCode:null}:a)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(c=t.state)!=null&&c.conversationId)&&s.conversationId!==(t.activeConversationId||((i=t.state)==null?void 0:i.conversationId))?t:{...t,terminals:s.terminals.map(a=>{var o;return{...a,conversationId:s.conversationId??((o=t.state)==null?void 0:o.conversationId)??""}})};default:return t}}const ss="pi-web-client-id";let gt=null;function Pt(){if(gt)return gt;let t=null;try{t=sessionStorage.getItem(ss),t||(t=_e(),sessionStorage.setItem(ss,t))}catch{t=t??_e()}return gt=t,t}function ca(){const t=location.protocol==="https:"?"wss:":"ws:";return ut(`${t}//${location.host}/ws`)}function da(){const[t,s]=r.useReducer(oa,{status:"connecting",ready:!1,state:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:[],conversations:[],activeConversationId:"",projects:[],files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],installResult:null,pathCompletions:[],update:null,widgets:[],statuses:[],dialog:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],goal:ra,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,protocolMismatch:!1}),n=r.useRef(null),l=r.useRef(la()),c=r.useRef(0),i=r.useRef(null),a=r.useRef(!0),o=r.useRef(0),d=r.useRef(0),m=r.useRef(new Map),x=r.useRef(null),h=()=>{x.current||(x.current=setTimeout(()=>{x.current=null;const y=n.current;y&&y.readyState===WebSocket.OPEN&&y.send(JSON.stringify({type:"get_state"}))},300))},v=(y,k)=>{var U;const u=m.current,L=u.get(y);if(L!==void 0&&k!==L+1){const G=P.current.chat,J=G.activeConversationId||((U=G.state)==null?void 0:U.conversationId);y===J&&h()}u.set(y,k)},C=r.useCallback((y,k)=>{const u=++d.current;s({type:"notice",notice:{id:u,level:y,text:k}})},[]),N=r.useCallback(y=>{const k=n.current;return k&&k.readyState===WebSocket.OPEN?(k.send(JSON.stringify(y)),!0):!1},[]),_=r.useCallback(()=>{if(!a.current)return;s({type:"status",status:"connecting"});const y=new WebSocket(ca());n.current=y,y.onopen=()=>{n.current===y&&(s({type:"status",status:"open"}),c.current=0,o.current=Date.now(),y.send(JSON.stringify({type:"hello",clientId:Pt()})))},y.onmessage=k=>{if(n.current!==y)return;o.current=Date.now();let u;try{u=JSON.parse(k.data)}catch{return}switch(u.type){case"ready":s({type:"ready",serverVersion:u.serverVersion,protocolVersion:u.protocolVersion}),y.send(JSON.stringify({type:"get_state"})),y.send(JSON.stringify({type:"list_files"})),y.send(JSON.stringify({type:"list_models"})),y.send(JSON.stringify({type:"list_commands"})),y.send(JSON.stringify({type:"get_commands"})),y.send(JSON.stringify({type:"check_update"}));break;case"snapshot":m.current=new Map,s({type:"snapshot",state:u.state});break;case"snapshot_delta":{const L=P.current.chat.state;(!L||L.conversationId!==u.conversationId||L.rev!==u.baseRev)&&h(),s({type:"snapshot_delta",msg:u});break}case"tool_delta":v(u.conversationId,u.seq),s({type:"tool_delta",toolCallId:u.toolCallId,toolName:u.toolName,delta:u.delta});break;case"tool_status":s({type:"tool_status",status:u});break;case"message_delta":{v(u.conversationId,u.seq),s({type:"message_delta",msg:u});break}case"notice":{const L=++d.current;s({type:"notice",notice:{id:L,level:u.level,text:u.text}});break}case"sessions":s({type:"sessions",sessions:u.sessions});break;case"conversations":s({type:"conversations",conversations:u.conversations,activeId:u.activeId});break;case"projects":s({type:"projects",projects:u.projects});break;case"files":s({type:"files",files:u});break;case"file_changed":s({type:"file_changed",path:u.path});break;case"file_content":s({type:"file_content",content:u});break;case"models":s({type:"models",models:u.models,loading:!1});break;case"models_config":s({type:"models_config",providers:u.providers});break;case"providers_status":s({type:"providers_status",providers:u.providers});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:u.reqId,ok:u.ok,models:u.models,error:u.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:u.reqId,ok:u.ok,added:u.added,total:u.total,error:u.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:u.reqId,ok:u.ok,config:u.config,error:u.error}});break;case"scm_data":s({type:"scm_data",data:u});break;case"search_files_result":s({type:"file_search_result",result:{reqId:u.reqId,ok:u.ok,results:u.results,truncated:u.truncated}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:u});break;case"path_completions":s({type:"path_completions",completions:u.completions});break;case"update_status":s({type:"update_status",status:u});break;case"widgets":s({type:"widgets",widgets:u.widgets});break;case"statuses":s({type:"statuses",statuses:u.statuses});break;case"dialog":s({type:"dialog",dialog:{id:u.id,kind:u.kind,title:u.title,args:u.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"terminal_output":l.current.write(u.conversationId??P.current.chat.activeConversationId,u.terminalId,u.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:u.conversationId,terminalId:u.terminalId,exitCode:u.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:u.conversationId,terminals:u.terminals});break;case"commands":s({type:"commands",commands:u.commands,path:u.path});break;case"slash_commands":s({type:"slash_commands",commands:u.commands});break;case"goal_status":s({type:"goal_status",status:u.status});break;case"settings_state":s({type:"settings",settings:u.settings});break;case"bg_servers":s({type:"bg_servers",servers:u.servers});break;case"plugins":s({type:"plugins",plugins:u.plugins,epoch:u.epoch});break;case"plugin_data":Xn(u.pluginId,u.payload);break}},y.onclose=()=>{if(n.current===y&&(n.current=null),l.current.clear(),!a.current||n.current&&n.current!==y)return;s({type:"status",status:"closed"});const k=Math.min(1e3*2**c.current,1e4);c.current+=1,i.current=setTimeout(()=>{i.current=null,_()},k)},y.onerror=()=>{}},[]);r.useEffect(()=>{a.current=!0,_();const y=setInterval(()=>{if(!a.current)return;const k=n.current;k&&k.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&k.close()},5e3);return()=>{var k;a.current=!1,clearInterval(y),i.current&&(clearTimeout(i.current),i.current=null),(k=n.current)==null||k.close(),n.current=null}},[_]);const M=r.useCallback(y=>s({type:"dismiss_notice",id:y}),[]),D=r.useCallback(y=>s({type:"terminal_add",meta:y}),[]),O=r.useCallback(y=>s({type:"terminal_remove",id:y}),[]),p=r.useCallback(y=>s({type:"terminal_restart",terminalId:y}),[]),E=r.useCallback((y,k,u)=>l.current.register(y,k,u),[]),P=r.useRef({chat:t,send:N,pushNotice:C,dismissNotice:M,terminal:{create:D,close:O,register:E,restart:p}});return P.current={chat:t,send:N,pushNotice:C,dismissNotice:M,terminal:{create:D,close:O,register:E,restart:p}},P.current}const ua=200*1024*1024,ma=/windows/i.test(navigator.userAgent),pa=/[<>:"/\\|?*\u0000-\u001f]/g,ha=/[. ]+$/,ga=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function fa(t){const s=t.replace(pa,"_").replace(ha,"");return s?ga.test(s)?`_${s}`:s:"_"}function ns(t,s=!0){const n=new URLSearchParams({clientId:Pt(),path:t,...s?{download:"1"}:{}});return ut(`/api/file?${n}`)}async function xa(t,s){const n=ma?fa(s):s;try{const l=await fetch(ns(t));if(!l.ok)return{ok:!1,cancelled:!1,error:await l.text().catch(()=>"")||(l.status===404?"文件不存在":`HTTP ${l.status}`)};if(Number(l.headers.get("content-length")??"0")>ua)return window.location.assign(ns(t)),{ok:!0};const i=await l.blob();return window.showSaveFilePicker&&window.isSecureContext?va(i,n):Nt(i,n)}catch(l){return{ok:!1,cancelled:!1,error:l instanceof Error?l.message:String(l)}}}async function va(t,s){let n;const l=window.showSaveFilePicker;if(!l)return Nt(t,s);try{n=await l({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:Nt(t,s)}try{const c=await n.createWritable();return await c.write(t),await c.close(),{ok:!0}}catch(c){return{ok:!1,cancelled:!1,error:c instanceof Error?c.message:String(c)}}}function Nt(t,s){const n=URL.createObjectURL(t),l=document.createElement("a");return l.href=n,l.download=s,document.body.appendChild(l),l.click(),l.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}const ya=r.memo(function({files:s,fileChanged:n,widgets:l,cwd:c,send:i,onAttach:a,onPreview:o,onNotice:d}){const m=he(),[x,h]=r.useState(""),[v,C]=r.useState(null),[N,_]=r.useState(!1),M=1e4,D=r.useRef(0),O=r.useRef(void 0),p=r.useCallback((k,u)=>{const L=++D.current;h(k),u!=null&&u.silent||_(!0),i({type:"list_files",path:k===""?void 0:k})||D.current===L&&_(!1)},[i]);r.useEffect(()=>{s&&s.path===x&&_(!1)},[s,x]),r.useEffect(()=>{if(c!==O.current){O.current=c,p("",{silent:!0});return}const k=setInterval(()=>{document.visibilityState!=="hidden"&&p(x,{silent:!0})},M);return()=>clearInterval(k)},[c,x,p]),r.useEffect(()=>{n&&n.path===x&&p(x,{silent:!0})},[n,x,p]);const E=k=>p(k),P=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&p(s.parent)},y=x.split("/").filter(Boolean);return e.jsxs("aside",{className:"panel panel-right",children:[e.jsxs("div",{className:"panel-crumbs",children:[e.jsx("button",{type:"button",className:`crumb ${x===""?"active":""}`,onClick:()=>p(""),children:m("rootDir")}),y.map((k,u)=>{const L=y.slice(0,u+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(ct,{}),e.jsx("button",{type:"button",className:`crumb ${L===x?"active":""}`,onClick:()=>p(L),children:k})]},L)})]}),e.jsxs("div",{className:"panel-body",children:[N&&e.jsx("div",{className:"panel-empty",children:m("loading")}),!N&&s&&s.path===x&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:P,children:[e.jsx(qe,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(k=>k.type==="dir"?e.jsxs("div",{className:"file-item dir",children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>E(k.path),children:[e.jsx(qe,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:k.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":m("linkFolderTip"),onClick:()=>a(k.path,k.name,"reference",!0),children:e.jsx(bt,{})})]},k.path):e.jsxs("div",{className:"file-item file",children:[e.jsxs("button",{type:"button",className:"file-name",title:`${k.path} — ${m("previewFile")}`,onClick:()=>o(k.path,k.name),children:[e.jsx(Ts,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:k.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":m("downloadFile"),onClick:()=>{xa(k.path,k.name).then(u=>{u.ok||u.cancelled||d("error",m("downloadFailed",{error:u.error}))})},children:e.jsx(Et,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":m("attachInlineTip"),onClick:()=>a(k.path,k.name,"inline"),children:e.jsx(Ue,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":m("referenceTip"),onClick:()=>a(k.path,k.name,"reference"),children:e.jsx(bt,{})})]},k.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:m("filesTruncated")})]}),!N&&!s&&e.jsx("div",{className:"panel-empty",children:m("noFiles")})]}),l.filter(k=>k.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:l.filter(k=>k.lines.length>0).map(k=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:m("widgetExpand"),onClick:()=>C(k.key),children:[e.jsx("span",{children:k.key}),e.jsx(En,{})]}),e.jsx("pre",{className:"widget-lines",children:k.lines.join(`
|
|
4
|
-
`)})]},k.key))}),v&&(()=>{const k=l.find(u=>u.key===v);return k?e.jsx("div",{className:"modal-backdrop",onClick:()=>C(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:k.key}),e.jsx("button",{type:"button",className:"btn",title:m("close"),onClick:()=>C(null),children:e.jsx(Ce,{})})]}),e.jsx("pre",{className:"widget-expand-lines",children:k.lines.join(`
|
|
5
|
-
`)})]})}):null})()]})});var as=ks();const _s=r.memo(function({text:s}){const n=he(),[l,c]=r.useState(!1);return s?e.jsx("button",{type:"button",className:"copy-btn",title:n("copy"),onClick:()=>{navigator.clipboard.writeText(s).then(()=>{c(!0),setTimeout(()=>c(!1),1200)})},children:l?e.jsx(dt,{}):e.jsx(Mt,{})}):null}),Fs=[an],As=[[nn,{detect:!0,ignoreMissing:!0}]];function Os({text:t}){return e.jsx(js,{remarkPlugins:Fs,rehypePlugins:As,components:{pre:ba},children:t})}const mt=r.memo(function({text:s}){return e.jsx("div",{className:"md",children:e.jsx(Os,{text:s})})});function ba({children:t,...s}){return e.jsxs("div",{className:"codeblock",children:[e.jsx(_s,{text:Ct(t)}),e.jsx("pre",{...s,children:t})]})}function Ct(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(Ct).join("");if(t&&typeof t=="object"&&"props"in t){const s=t.props;return Ct(s==null?void 0:s.children)}return""}const ja=/^\s{0,3}(`{3,}|~{3,})/,ka=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function ft(t){return t.trim()===""}function is(t){const s=ja.exec(t);return s?s[1]:null}function wa(t){const s=t.split(`
|
|
6
|
-
`),n=[];let l=[],c=null;for(let i=0;i<s.length;i++){const a=s[i];if(c!==null){const d=is(a);d&&d[0]===c[0]&&d.length>=c.length&&(c=null),l.push(a);continue}const o=is(a);if(o&&!ft(a)){c=o,l.push(a);continue}if(ft(a)){let d=i;for(;d<s.length&&ft(s[d]);)d++;if(!(d<s.length&&ka.test(s[d]))&&l.length>0){n.push(l.join(`
|
|
7
|
-
`)),l=[];continue}l.push(a);continue}l.push(a)}return{frozen:n,active:l.join(`
|
|
8
|
-
`),inFence:c!==null}}const Na=r.memo(function({text:s}){return e.jsx(js,{remarkPlugins:Fs,rehypePlugins:As,children:s})}),rs=200;function Ca({text:t,inFence:s}){const[n,l]=r.useState(t),c=r.useRef(0),i=r.useRef(null);return r.useEffect(()=>{if(s)return;const a=Date.now()-c.current,o=()=>{c.current=Date.now(),l(t)};if(a>=rs){o();return}return i.current=setTimeout(o,rs-a),()=>{i.current&&clearTimeout(i.current)}},[t,s]),s?e.jsx("div",{className:"codeblock",children:e.jsx("pre",{children:e.jsx("code",{children:t})})}):e.jsx(Os,{text:n})}const Sa=r.memo(function({text:s}){const{frozen:n,active:l,inFence:c}=r.useMemo(()=>wa(s),[s]);return e.jsxs("div",{className:"md",children:[n.map((i,a)=>e.jsx(Na,{text:i},a)),l.length>0&&e.jsx(Ca,{text:l,inFence:c},n.length)]})});function Ta({thinking:t,streaming:s}){const n=he(),[l,c]=r.useState(s),i=t.split(`
|
|
9
|
-
`)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${l?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>c(a=>!a),children:[l?e.jsx(Fe,{}):e.jsx(ct,{}),e.jsx(lt,{className:"thinking-icon"}),e.jsx("span",{className:"thinking-label",children:s?e.jsxs("span",{className:"thinking-live-label",children:[n("thinkingNow"),e.jsx("span",{className:"dots"})]}):l?n("thinking"):n("thinkingPreview",{preview:i})})]}),l&&e.jsx("div",{className:"thinking-body",children:t})]})}const Ea={bash:"$",read:"📄",write:"✍️",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function Ma(t){return Ea[t]??"🛠"}const Ra=r.memo(function({block:s,view:n,onKillBash:l}){var E,P,y,k;const c=he(),[i,a]=r.useState(!0),[o,d]=r.useState(!1),m=!n.result&&n.streaming&&!n.status,x=s.name==="bash"&&m,h=n.result!==void 0,v=!n.result&&!!n.status,C=((E=n.result)==null?void 0:E.isError)??((P=n.status)==null?void 0:P.isError)??!1,N=n.result?n.result.content.map(u=>u.type==="text"?u.text:"").join(""):n.liveOutput??"",_=C?"err":h?"ok":m||v?"run":"idle";let M=c(C?"error":h?"done":m?"running":v?"toolDoneWaitingModel":"toolQueued");const D=v&&((y=n.status)==null?void 0:y.durationMs)!==void 0?La(n.status.durationMs):"";v&&D&&(M=`${M} · ${D}`);const O=v&&((k=n.status)==null?void 0:k.exitCode)!==void 0?`exit ${n.status.exitCode}`:"",p=()=>{s.argumentsText&&(navigator.clipboard.writeText(s.argumentsText),d(!0),setTimeout(()=>d(!1),1200))};return e.jsxs("div",{className:`toolcall ${_}`,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:[M,O&&e.jsx("em",{className:"toolcall-exit",children:O})]}),e.jsx("span",{className:"toolcall-spacer"}),x&&l&&e.jsxs("button",{type:"button",className:"toolcall-kill",title:c("stopBashTip"),onClick:l,children:[e.jsx(tt,{}),e.jsx("span",{children:c("stopBash")})]}),e.jsx("button",{type:"button",className:"toolcall-copy",title:c("copyArgs"),onClick:p,children:o?e.jsx(_n,{}):e.jsx(Mt,{})}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>a(u=>!u),children:i?e.jsx(Fe,{}):e.jsx(ct,{})})]}),i&&e.jsxs("div",{className:"toolcall-body",children:[s.argumentsText&&e.jsx("div",{className:"toolcall-args",children:s.name==="bash"&&s.argumentsText.startsWith("{")?e.jsx(Pa,{args:s.argumentsText}):e.jsx("pre",{children:s.argumentsText})}),N.length>0&&e.jsxs("div",{className:"toolcall-output",children:[e.jsxs("div",{className:"toolcall-output-label",children:[c(C?"errorOutput":"output"),(m||v)&&e.jsx("span",{className:"cursor"})]}),e.jsx("pre",{children:N})]}),m&&N.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",c("waitingOutput")]}),v&&N.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",c("waitingModel")]})]})]})});function Pa({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 La(t){if(t===void 0)return"";const s=t/1e3;if(s<60)return`${s.toFixed(1)}s`;const n=Math.floor(s/60),l=Math.round(s%60);return`${n}m ${String(l).padStart(2,"0")}s`}const Ia=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function Lt(t){var n;const s=t.match(Ia);return s?{name:s[1],location:s[2],content:s[3],userMessage:((n=s[4])==null?void 0:n.trim())||void 0}:null}const Ba=1568,Da=2*1024*1024;function Re(t){return t.startsWith("image/")&&t!=="image/svg+xml"&&t!=="image/svg"}async function Hs(t){if(!t.type.startsWith("image/"))return null;let s;try{s=await createImageBitmap(t,{imageOrientation:"from-image"})}catch{return null}try{const n=Math.min(1,Ba/Math.max(s.width,s.height)),l=Math.max(1,Math.round(s.width*n)),c=Math.max(1,Math.round(s.height*n)),i=t.type==="image/jpeg"||t.type==="image/jpg"?[["image/jpeg",.85],["image/jpeg",.6],["image/webp",.8]]:[["image/png",1],["image/jpeg",.85],["image/jpeg",.6]];let a=null;for(const[o,d]of i){const m=document.createElement("canvas");m.width=l,m.height=c;const x=m.getContext("2d");if(!x)continue;o!=="image/png"&&(x.fillStyle="#ffffff",x.fillRect(0,0,l,c)),x.drawImage(s,0,0,l,c);const h=m.toDataURL(o,d),v=h.match(/^data:([^;]+);base64,/),C=v?v[1]:o,N=h.replace(/^data:[^;]*;base64,/,""),_=Math.floor(N.length*3/4);if(a={data:N,mimeType:C,name:t.name,size:_},_<=Da)return a}return a}finally{s.close()}}const $a=20*1024*1024;function Ge(t){return t.type==="text"&&typeof t.text=="string"?t:null}function Ws(t){return t.type==="thinking"&&typeof t.thinking=="string"?t:null}function Us(t){return t.type==="toolCall"&&typeof t.id=="string"&&typeof t.name=="string"?t:null}function qs(t){return t.type==="image"&&typeof t.dataUrl=="string"?t:null}function zs(t){return t.type==="bash"&&typeof t.command=="string"?t:null}function _a(t){return t.imageData?"image":t.uploadPath?"upload":t.fileData?"file":"path"}function Fa(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 ls=r.memo(function({message:s,toolResults:n,liveOutputs:l,toolStatuses:c,streaming:i,isLast:a,onEdit:o,onKillBash:d,onCollapse:m,questionAttachments:x,qnIndex:h,qnActive:v,onJump:C}){const N=he(),[_,M]=r.useState(!1),[D,O]=r.useState(""),[p,E]=r.useState([]),[P,y]=r.useState(!1),[k,u]=r.useState(null),L=S=>{u(S),window.setTimeout(()=>u(A=>A===S?null:A),4e3)};if(s.role==="toolResult")return null;const U=s.role==="custom"&&s.customType==="file",G=s.content.map(S=>{var A;return((A=Ge(S))==null?void 0:A.text)??""}).filter(Boolean).join(`
|
|
10
|
-
`),J=s.role==="user"?Lt(G):null,te=J?J.userMessage??`skill:${J.name}`:G.split(`
|
|
11
|
-
`).join(" ").trim(),oe=i&&a&&s.content.length===0,I=s.role==="user"&&!i&&!oe&&!!o,F=async S=>{const A=[];for(const se of S){if(!Re(se.type))continue;const de=await Hs(se);de&&A.push({path:"",imageData:de.data,mimeType:de.mimeType,name:de.name})}A.length>0&&E(se=>[...se,...A])},W=async S=>{if(S.size>$a){L(N("fileTooLarge",{name:S.name,size:20}));return}let A;try{A=(await new Promise((de,f)=>{const B=new FileReader;B.onload=()=>de(B.result),B.onerror=()=>f(B.error??new Error("read failed")),B.readAsDataURL(S)})).replace(/^data:[^;]*;base64,/,"")}catch{L(N("fileLoadFailed",{name:S.name}));return}E(se=>[...se,{path:"",fileData:A,name:S.name,size:S.size,mimeType:S.type||void 0}])},re=async S=>{const A=[];for(const se of S)Re(se.type)?A.push(se):W(se);A.length>0&&await F(A)},ge=()=>{O(J?`/skill:${J.name}${J.userMessage?` ${J.userMessage}`:""}`:s.content.map(S=>{var A;return((A=Ge(S))==null?void 0:A.text)??""}).filter(Boolean).join(`
|
|
12
|
-
`)),E(x??[]),M(!0)},R=()=>{const S=D.trim();S&&(o==null||o(s.id,S,p.length>0?p:void 0),M(!1))},j=s.role==="custom"&&(s.customType==="goal-review"||s.customType==="goal-wizard"),q=s.role==="custom"&&s.customType==="goal-wizard";return e.jsxs("div",{className:`msg msg-${s.role}${j?" 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"?q?N("goalWizardCard"):j?N("goalBarTitle"):s.customType==="file"?N("attachment"):`${N("plugin")} · ${s.customType??N("unknown")}`:Ks(s.role,N)}),s.model&&e.jsx("span",{className:"msg-model",children:s.model}),s.timestamp&&e.jsx("span",{className:"msg-time",children:Wa(s.timestamp)}),m&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:N("collapseMsg"),onClick:()=>m(s.id),children:[e.jsx(ot,{})," ",N("collapseMsg")]}),h!==void 0&&C&&e.jsxs("button",{type:"button",className:`qn-tag ${v?"active":""}`,title:`${h+1}. ${te}`,"aria-label":`${h+1}. ${te}`,onClick:()=>C(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:_?e.jsxs("div",{className:`msg-editor${P?" drag-over":""}`,onDragOver:S=>{S.preventDefault(),S.stopPropagation(),y(!0)},onDragLeave:S=>{S.currentTarget.contains(S.relatedTarget)||y(!1)},onDrop:S=>{var A;S.preventDefault(),S.stopPropagation(),y(!1),re(Array.from(((A=S.dataTransfer)==null?void 0:A.files)??[]))},children:[p.length>0&&e.jsx("div",{className:"msg-editor-images",children:p.map((S,A)=>{var de;const se=_a(S);return e.jsxs("span",{className:`msg-editor-img ${se==="image"?"":"file-chip"}`,title:Fa(S,N),children:[se==="image"?e.jsx("img",{src:`data:${S.mimeType??"image/png"};base64,${S.imageData}`,alt:S.name}):e.jsxs("span",{className:"msg-editor-file",children:[e.jsx("span",{className:"msg-editor-file-icon",children:se==="path"?S.mode==="reference"?"🔗":"📎":"📄"}),e.jsx("span",{className:"msg-editor-file-name",children:S.name??((de=S.path)==null?void 0:de.split("/").pop())})]}),e.jsx("button",{type:"button",className:"msg-editor-img-remove",title:N("removeAttachment"),onClick:()=>E(f=>f.filter((B,ne)=>ne!==A)),children:e.jsx(Ce,{})})]},`${S.name??S.path??"att"}-${A}`)})}),k&&e.jsx("div",{className:"msg-editor-notice",children:k}),e.jsx("textarea",{className:"msg-editor-input",value:D,autoFocus:!0,placeholder:N("editPlaceholder"),rows:Math.max(2,Math.min(10,D.split(`
|
|
13
|
-
`).length+1)),onChange:S=>O(S.target.value),onPaste:S=>{var se;const A=[];for(const de of((se=S.clipboardData)==null?void 0:se.items)??[])if(de.kind==="file"&&Re(de.type)){const f=de.getAsFile();f&&A.push(f)}A.length!==0&&(S.preventDefault(),F(A))},onKeyDown:S=>{S.key==="Enter"&&(S.metaKey||S.ctrlKey)?(S.preventDefault(),R()):S.key==="Escape"&&M(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(Ln,{})," ",N("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>M(!1),children:N("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!D.trim(),title:N("reaskFromHere"),onClick:R,children:[e.jsx(jt,{})," ",N("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),U?e.jsx(Aa,{message:s}):J?e.jsxs(e.Fragment,{children:[e.jsx(Ha,{block:J}),J.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(mt,{text:J.userMessage})}),s.content.map((S,A)=>S.type==="text"?null:e.jsx(cs,{block:S,toolResults:n,liveOutputs:l,toolStatuses:c,streaming:i,isLast:a,onKillBash:d},`${s.id}-${A}`))]}):s.content.map((S,A)=>e.jsx(cs,{block:S,toolResults:n,liveOutputs:l,toolStatuses:c,streaming:i,isLast:a,onKillBash:d},`${s.id}-${A}`)),oe&&e.jsxs("div",{className:"thinking-wait",children:[N("thinkingWait"),e.jsx("span",{className:"dot"})]}),i&&a&&!oe&&e.jsx("span",{className:"stream-cursor"})]})}),I&&!_&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:N("editReaskTip"),onClick:ge,children:[e.jsx(jt,{})," ",N("editReask")]})})]})});function Aa({message:t}){const s=he(),[n,l]=r.useState(!1),c=t.details??{},i=c.name??c.path??s("attachment"),a=c.type==="folder",o=c.mode==="reference",d=c.mode==="bridged",m=t.content.filter(C=>C.type==="text").map(C=>C.text).join(`
|
|
14
|
-
`),x=Oa(m),h=t.content.find(C=>C.type==="image"),v=x.split(`
|
|
15
|
-
`).length;return e.jsxs("div",{className:`attachcard ${o?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>l(C=>!C),children:[e.jsx("span",{className:"attachcard-icon",children:a?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:i}),c.path&&e.jsx("span",{className:"attachcard-path",children:c.path}),e.jsx("span",{className:`attachcard-mode ${c.mode==="lines"?"lines":o?"ref":d?"bridged":"inline"}`,children:o?a?s("folderRefShort"):`${s("refOnlyShort")} · ${os(c.size)}`:d?s("bridgedVision"):h?s("image"):c.mode==="lines"?s("inlineLinesRange",{start:c.startLine??1,end:c.endLine??c.lines??1}):s("inlineLines",{n:c.lines??v})}),!o&&(n?e.jsx(Fe,{}):e.jsx(ct,{}))]}),!o&&n&&(d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:s("bridgedVisionDetail")}),(h==null?void 0:h.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:h.dataUrl,alt:i})}),x&&e.jsx("pre",{className:"attachcard-content",children:x})]}):h!=null&&h.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:h.dataUrl,alt:i})}):e.jsx("pre",{className:"attachcard-content",children:x})),o&&e.jsx("div",{className:"attachcard-refnote",children:a?s("folderNotExpanded"):s("fileNotExpanded",{size:os(c.size)})})]})}function os(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function Oa(t){const s=t.match(/^\s*<file path="[^"]*"(?:\s+lines="[^"]*")?>\s*```\s*\n?([\s\S]*?)\n?```\s*<\/file>\s*$/);if(s)return s[1].trim();const n=t.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return n?n[1].trim():t.trim()}function Ha({block:t}){const s=he(),[n,l]=r.useState(!1);return e.jsxs("div",{className:`skillcard${n?" expanded":""}`,children:[e.jsxs("button",{type:"button",className:"skillcard-head",onClick:()=>l(c=>!c),title:t.location,children:[e.jsx("span",{className:"skillcard-icon",children:e.jsx(Fn,{})}),e.jsx("span",{className:"skillcard-name",children:t.name}),e.jsx("span",{className:"skillcard-path",children:t.location}),e.jsxs("span",{className:"skillcard-action",children:[n?e.jsx(ot,{}):e.jsx(Fe,{}),s(n?"collapseMsg":"expandMsg")]})]}),n&&e.jsx("div",{className:"skillcard-body",children:e.jsx(mt,{text:t.content})})]})}function cs({block:t,toolResults:s,liveOutputs:n,toolStatuses:l,streaming:c,isLast:i,onKillBash:a}){const o=he(),d=Ge(t);if(d){const C=c&&i;return e.jsxs("div",{className:"msg-text",children:[C?e.jsx(Sa,{text:d.text}):e.jsx(mt,{text:d.text}),d.truncated&&e.jsx("div",{className:"trunc-note",children:o("truncated")})]})}const m=Ws(t);if(m)return e.jsx(Ta,{thinking:m.thinking,streaming:c&&i});const x=Us(t);if(x){const C=s.get(x.id),N=n.get(x.id),_={result:C,liveOutput:N==null?void 0:N.text,streaming:c,status:l.get(x.id)};return e.jsx(Ra,{block:x,view:_,onKillBash:a})}const h=qs(t);if(h&&h.dataUrl)return e.jsx("div",{className:"msg-image",children:e.jsx("img",{src:h.dataUrl,alt:"attachment"})});const v=zs(t);return v?e.jsxs("div",{className:"bashblock",children:[e.jsxs("div",{className:"bashblock-command",children:[e.jsx("span",{className:"bashblock-prompt",children:"$"}),e.jsx("code",{children:v.command}),v.exitCode!==void 0&&e.jsx("span",{className:`bashblock-exit ${v.exitCode===0?"ok":"err"}`,children:o("exitCode",{code:v.exitCode})}),v.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:o("cancelled")})]}),v.output&&e.jsx("pre",{className:"bashblock-output",children:v.output}),v.truncated&&e.jsx("div",{className:"trunc-note",children:o("outputTruncated")})]}):null}function Ks(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 Wa(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n}:${l}`}function ds(t,s,n){let l=!1;for(const c of s){const i=c;if(i.type!=="image"||typeof i.dataUrl!="string"||!i.dataUrl.startsWith("data:"))continue;const a=i.dataUrl.match(/^data:([^;]*);base64,(.+)$/);a&&(l=!0,t.push({path:"",imageData:a[2],mimeType:a[1]||"image/png",name:n??`image.${(a[1]||"image/png").split("/")[1]??"png"}`}))}return l}function Ua(t){const s=new Map;for(let n=0;n<t.length;n++){const l=t[n];if(l.role!=="user"||!l.id)continue;const c=[];ds(c,l.content);for(let i=n+1;i<t.length&&t[i].role==="custom"&&t[i].customType==="file";i++){const a=t[i].details??{};if(!ds(c,t[i].content,a.name)){if(a.upload&&a.path){c.push({path:"",uploadPath:a.path,name:a.name??a.path,size:a.size});continue}if(a.path&&a.mode){const o=a.mode==="inline"||a.mode==="lines"?a.mode:"reference",d={path:a.path,mode:o};a.mode==="lines"&&typeof a.startLine=="number"&&typeof a.endLine=="number"&&(d.lines={start:a.startLine,end:a.endLine}),c.push(d)}}}c.length>0&&s.set(l.id,c)}return s}const qa=r.memo(function({message:s,onExpand:n}){const l=he();let c="";for(const h of s.content){const v=Ge(h);if(v&&v.text.trim()){const C=Lt(v.text);C?c=`skill:${C.name}`+(C.userMessage?` · ${C.userMessage.replace(/\s+/g," ").trim()}`:""):c=v.text.replace(/\s+/g," ").trim();break}}if(!c&&s.role==="custom"&&s.customType==="file"){const h=s.details??{};c=h.name??h.path??""}c.length>90&&(c=`${c.slice(0,90)}…`);let a=0,o=0,d=0,m=0;for(const h of s.content)Ws(h)?a++:Us(h)?o++:zs(h)?d++:qs(h)&&m++;const x=[];return a&&x.push(`${l("thinking")} ${a}`),o&&x.push(`${l("toolCalls")} ${o}`),d&&x.push(`${l("bashRuns")} ${d}`),m&&x.push(`${l("images")} ${m}`),e.jsxs("button",{type:"button",className:"msg-collapsed","data-msg-id":s.id,title:`${l("expandMsg")} · ${c||x.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"?l("attachment"):Ks(s.role,l)}),e.jsxs("span",{className:"msg-collapsed-body",children:[c&&e.jsx("span",{className:"msg-collapsed-preview",children:c}),x.length>0&&e.jsx("span",{className:"msg-collapsed-chips",children:x.map((h,v)=>e.jsx("span",{className:"msg-collapsed-chip",children:h},v))})]}),s.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:za(s.timestamp)}):null,e.jsxs("span",{className:"msg-collapsed-action",children:[e.jsx(Fe,{})," ",l("expandMsg")]})]})});function za(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),l=String(s.getMinutes()).padStart(2,"0");return`${n}:${l}`}const Ka=r.memo(function({id:s,show:n,height:l,containerRef:c,onMeasured:i,lazyRef:a,children:o}){const d=r.useRef(null),m=r.useRef(null);return r.useLayoutEffect(()=>{const x=m.current;if(m.current=n,!n||x!==!1)return;const h=d.current,v=c.current;if(!h||!v)return;const C=h.offsetHeight;i==null||i(s,C);const N=C-l;if(N!==0){const _=h.parentElement;_&&_.getBoundingClientRect().bottom<=v.getBoundingClientRect().top&&(v.scrollTop+=N)}},[n]),n?e.jsx("div",{ref:a,"data-lazy-id":s,children:e.jsx("div",{ref:d,children:o})}):e.jsx("div",{ref:a,className:"msg-lazy-ph","data-msg-id":s,"data-lazy-id":s,style:{height:l},"aria-hidden":"true"})});function Va(t,s,n,l){const c=[],i=[];let a=0;for(const o of t){if(n.has(o.id))continue;o.top<s.bottom&&o.bottom>s.top?l.has(o.id)&&c.push(o.id):l.has(o.id)||(i.push(o.id),o.bottom<=s.top&&(a+=o.bottom-o.top))}return{show:c,hide:i,shrinkAbove:a}}function Ga(t,s){if(s.show.length===0&&s.hide.length===0)return t;const n=new Set(t);for(const l of s.show)n.delete(l);for(const l of s.hide)n.add(l);return n}function Ja(t,s,n){const l=new Set;let c=0;for(let i=t.length-1;i>=0&&!(i<t.length-1&&c>=n);i--){const a=t[i];l.add(a.id),c+=s.get(a.id)??Vs(a.role,a.customType)}return l}function Vs(t,s){switch(t){case"user":return 72;case"assistant":return 280;case"toolResult":return 8;case"custom":return s==="file"?96:72;default:return 60}}function Qa(t){if(t.role==="toolResult")return"";const s=[];for(const n of t.content)Ya(n,s);return t.errorMessage&&s.push(t.errorMessage),s.join(`
|
|
16
|
-
`)}function Ya(t,s){if(typeof t.text=="string"){s.push(t.text);return}switch(t.type){case"thinking":typeof t.thinking=="string"&&s.push(t.thinking);break;case"toolCall":{typeof t.name=="string"&&s.push(t.name),typeof t.argumentsText=="string"&&s.push(t.argumentsText);break}case"bash":typeof t.command=="string"&&s.push(t.command),typeof t.output=="string"&&s.push(t.output);break}}function Xa(t,s){const n=s.trim().toLowerCase();if(!n)return 0;const l=t.toLowerCase();let c=0,i=l.indexOf(n);for(;i!==-1;)c++,i=l.indexOf(n,i+n.length);return c}function Za(t,s){const n=s.trim().toLowerCase();if(!n)return[];const l=[];for(const c of t){const i=Qa(c);if(!i)continue;const a=Xa(i,n);for(let o=0;o<a;o++)l.push({messageId:c.id,occurrence:o})}return l}function ei(t,s){var a;const n=new Map,l=[],c=s.toLowerCase();if(!c)return{byMsg:n,all:l};const i=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(o){const d=o.parentElement;return!d||d.closest(".search-bar")?NodeFilter.FILTER_REJECT:(o.textContent??"").toLowerCase().includes(c)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let o=i.nextNode();o;o=i.nextNode()){const d=(o.textContent??"").toLowerCase(),m=(a=o.parentElement)==null?void 0:a.closest("[data-msg-id]");if(!m)continue;const x=m.getAttribute("data-msg-id")??"";let h=d.indexOf(c);for(;h!==-1;){const v=document.createRange();v.setStart(o,h),v.setEnd(o,h+c.length),l.push(v);const C=n.get(x);C?C.push(v):n.set(x,[v]),h=d.indexOf(c,h+c.length)}}return{byMsg:n,all:l}}function He(t,s){const n=CSS;if(!n.highlights)return;if(s.length===0){n.highlights.delete(t);return}const l=window.Highlight;l&&n.highlights.set(t,new l(...s))}function ti({containerRef:t,messages:s,open:n,onClose:l,onEnsureExpanded:c}){const i=he(),a=r.useRef(null),[o,d]=r.useState(""),[m,x]=r.useState(0),h=r.useDeferredValue(o),v=n?h.trim():"",C=r.useMemo(()=>n?Za(s,v):[],[s,v,n]),N=r.useRef(C);N.current=C;const _=r.useRef(m);_.current=m,r.useEffect(()=>{n&&(x(0),requestAnimationFrame(()=>{var p;return(p=a.current)==null?void 0:p.select()}))},[n]),r.useEffect(()=>{if(!n)return;const p=E=>{E.key==="Escape"&&(E.preventDefault(),E.stopPropagation(),l())};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,l]),r.useEffect(()=>(n||(He("msg-search",[]),He("msg-search-active",[])),()=>{He("msg-search",[]),He("msg-search-active",[])}),[n]);const M=r.useCallback(p=>{const E=t.current;if(!E)return;const P=E.querySelector(`[data-msg-id="${p}"]`);P&&(P.classList.remove("msg-flash"),P.offsetWidth,P.classList.add("msg-flash"))},[t]);r.useLayoutEffect(()=>{if(!n||!v)return;const p=t.current;if(!p)return;let E=!1,P=0;return P=requestAnimationFrame(()=>{var G;if(E)return;const{byMsg:y,all:k}=ei(p,v);He("msg-search",k);const u=N.current,L=u[Math.min(_.current,u.length-1)];if(!L)return;const U=(G=y.get(L.messageId))==null?void 0:G[L.occurrence];if(U){He("msg-search-active",[U]);const J=U.startContainer.parentElement??p.querySelector(`[data-msg-id="${L.messageId}"]`);J==null||J.scrollIntoView({block:"center"})}else M(L.messageId)}),()=>{E=!0,cancelAnimationFrame(P)}},[n,v,C,t,M]);const D=r.useCallback(p=>{const E=N.current;if(E.length===0)return;const P=(_.current+p+E.length)%E.length;x(P),c(E[P].messageId)},[c]);if(!n)return null;const O=C.length;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:a,className:"search-input",type:"text",value:o,placeholder:i("searchPlaceholder"),onChange:p=>{d(p.target.value),x(0)},onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),D(p.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${O===0?"empty":""}`,children:O===0?i("searchNoResults"):`${Math.min(m+1,O)}/${O}`}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchPrev"),disabled:O===0,onClick:()=>D(-1),children:e.jsx(ot,{})}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchNext"),disabled:O===0,onClick:()=>D(1),children:e.jsx(Fe,{})}),e.jsx("button",{type:"button",className:"search-btn",title:i("searchClose"),onClick:l,children:e.jsx(Ce,{})})]})}const us=new Map,si=15,ms=30,ps=1200,ni=1600;function hs(t){return t.content.some(s=>s.type==="toolCall")}const ai=[{key:"ex.understand",icon:"🔍"},{key:"ex.debug",icon:"🐛"},{key:"ex.test",icon:"🧪"},{key:"ex.review",icon:"🧹"}];function ii(t){return ai.map(({key:s,icon:n})=>({icon:n,text:t(s),prompt:t(`${s}.prompt`)}))}function ri({state:t,liveOutputs:s,toolStatuses:n,onEdit:l,onKillBash:c}){const i=he(),a=r.useRef(null),[o,d]=r.useState(!0),m=r.useRef(!0),x=r.useRef(0),h=r.useRef(!1),[v,C]=r.useState(()=>new Set),[N,_]=r.useState(!1),M=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,D=r.useMemo(()=>{const w=new Map;for(const $ of t.messages)$.role==="toolResult"&&$.toolCallId&&w.set($.toolCallId,$);return w},[t.messages]),O=r.useMemo(()=>Ua(t.messages),[t.messages]),p=M.length>0?M[M.length-1].id:null,E=t.messages.length>ms?Math.max(0,t.messages.length-si):0,[P,y]=r.useState(()=>new Set),[k,u]=r.useState(()=>new Set),L=r.useRef(new Map),U=r.useRef(new Map),G=r.useRef(0),J=r.useRef(P);J.current=P;const te=t.messages.length>ms&&!N,oe=r.useRef(te);oe.current=te;const I=Ja(t.messages,L.current,ni),F=r.useRef(I);F.current=I;const W=r.useCallback(()=>{const w=a.current;if(!w)return;if(!oe.current){y(pe=>pe.size?new Set:pe);return}const $=w.getBoundingClientRect(),ae={top:$.top-ps,bottom:$.bottom+ps},ie=[];for(const[pe,ve]of U.current){const b=ve.getBoundingClientRect();ie.push({id:pe,top:b.top,bottom:b.bottom}),J.current.has(pe)||L.current.set(pe,b.bottom-b.top)}const me=Va(ie,ae,F.current,J.current);for(const pe of me.hide){const ve=U.current.get(pe);ve&&L.current.set(pe,ve.offsetHeight)}y(pe=>Ga(pe,me))},[]),re=r.useCallback(()=>{G.current||(G.current=requestAnimationFrame(()=>{G.current=0,W()}))},[W]);r.useLayoutEffect(()=>{W()},[W]);const ge=r.useRef(N);r.useLayoutEffect(()=>{ge.current&&!N&&W(),ge.current=N},[N,W]);const R=r.useCallback((w,$)=>{L.current.set(w,$)},[]),j=r.useCallback(w=>{w&&U.current.set(w.dataset.lazyId??"",w)},[]);r.useEffect(()=>{const w=new Set(t.messages.map($=>$.id));for(const[$,ae]of U.current)w.has($)||(U.current.delete($),L.current.delete($));y($=>{let ae=!1;const ie=new Set;for(const me of $)w.has(me)?ie.add(me):ae=!0;return ae?ie:$})},[t.messages,v]),r.useEffect(()=>()=>cancelAnimationFrame(G.current),[]);const q=r.useMemo(()=>{const w=[];for(const $ of t.messages){if($.role!=="user")continue;const ae=$.content.map(pe=>{var ve;return((ve=Ge(pe))==null?void 0:ve.text)??""}).filter(Boolean).join(" "),ie=Lt(ae),me=ie?ie.userMessage??`skill:${ie.name}`:ae.trim();me&&w.push({id:$.id,text:me})}return w},[t.messages]),S=r.useMemo(()=>{const w=new Map;return q.forEach(($,ae)=>w.set($.id,ae)),w},[q]),[A,se]=r.useState(-1),de=r.useRef(-1),f=r.useRef(q);r.useEffect(()=>{f.current=q},[q]);const B=r.useCallback(()=>{const w=a.current,$=f.current;if(!w||$.length===0)return;const ae=w.getBoundingClientRect().top,ie=140;let me=-1;for(let pe=0;pe<$.length;pe++){const ve=w.querySelector(`[data-msg-id="${$[pe].id}"]`);if(ve)if(ve.getBoundingClientRect().top<=ae+ie)me=pe;else break}me!==de.current&&(de.current=me,se(me))},[]);r.useEffect(()=>{B()},[q,B]);const ne=r.useCallback(w=>{C($=>$.has(w)?$:new Set($).add(w))},[]),g=r.useCallback(w=>{const $=t.messages.findIndex(ae=>ae.id===w);$>=0&&$<E&&!v.has(w)&&as.flushSync(()=>ne(w))},[t.messages,E,v,ne]);r.useEffect(()=>{const w=$=>{if(!($.ctrlKey||$.metaKey)||$.key.toLowerCase()!=="f")return;const ae=$.target;ae&&(ae.tagName==="INPUT"||ae.tagName==="TEXTAREA"||ae.isContentEditable)||($.preventDefault(),_(!0))};return window.addEventListener("keydown",w),()=>window.removeEventListener("keydown",w)},[]);const z=r.useCallback(w=>{C($=>{if(!$.has(w))return $;const ae=new Set($);return ae.delete(w),ae})},[]),V=r.useCallback(w=>{const $=t.messages.findIndex(ie=>ie.id===w);as.flushSync(()=>{$>=0&&$<E&&!v.has(w)&&ne(w),u(ie=>ie.has(w)?ie:new Set(ie).add(w))});const ae=f.current.findIndex(ie=>ie.id===w);de.current=ae,se(ae),requestAnimationFrame(()=>{var me,pe,ve;const ie=(me=a.current)==null?void 0:me.querySelector(`[data-msg-id="${w}"]`);ie&&((pe=a.current)==null||pe.querySelectorAll(".msg-flash").forEach(b=>b.classList.remove("msg-flash")),ie.scrollIntoView({block:"start"}),ie.classList.remove("msg-flash"),ie.offsetWidth,ie.classList.add("msg-flash"),ie!==((ve=a.current)==null?void 0:ve.lastElementChild)&&(h.current=!0))})},[t.messages,E,v,ne]),Z=r.useCallback(()=>{const w=a.current;if(!w)return;const $=w.scrollTop-x.current;x.current=w.scrollTop;const ae=w.scrollHeight-w.scrollTop-w.clientHeight<80;$<-4&&$>-500?h.current=!0:ae&&$>=0&&(h.current=!1),m.current=ae&&!h.current,d(m.current),B(),re()},[B,re]),ue=r.useRef(!1);r.useEffect(()=>{const w=ue.current;if(ue.current=!!t.isStreaming,w&&!t.isStreaming&&!h.current){const $=()=>{const ie=a.current;ie&&!h.current&&(ie.scrollTop=ie.scrollHeight,m.current=!0,d(!0))};requestAnimationFrame(()=>requestAnimationFrame($));const ae=setTimeout($,180);return()=>clearTimeout(ae)}},[t.isStreaming]),r.useEffect(()=>{const w=a.current;w&&m.current&&(w.scrollTop=w.scrollHeight)},[M,t.isStreaming,s]);const be=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");r.useEffect(()=>{const w=a.current;w&&m.current&&(w.scrollTop=w.scrollHeight)},[be]);const Q=r.useCallback(()=>{const w=a.current;w&&(w.scrollTop=w.scrollHeight),m.current=!0,h.current=!1,d(!0)},[]),le=r.useRef(null);r.useEffect(()=>{const w=le.current,$=a.current;if(!w||!$)return;const ae=ie=>{ie.preventDefault();const me=w.querySelector(".qn-list");if(me&&me.contains(ie.target)&&me.scrollHeight>me.clientHeight){me.scrollTop+=ie.deltaY;return}$.scrollTop+=ie.deltaY};return w.addEventListener("wheel",ae,{passive:!1}),()=>w.removeEventListener("wheel",ae)},[]);const[ee,Te]=r.useState(0);r.useEffect(()=>{const w=()=>{var $;Te((($=a.current)==null?void 0:$.clientHeight)??0),re()};return w(),window.addEventListener("resize",w),()=>window.removeEventListener("resize",w)},[re]);const Ee=q.length,Pe=r.useMemo(()=>Ee===0?27:Math.max(4,Math.min(27,Math.floor(((ee||600)-16)/Ee)-3)),[Ee,ee]),Ae=Pe<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:"messages",ref:a,onScroll:Z,children:[t.messages.length===0&&!t.streamingMessage&&e.jsxs("div",{className:"empty-state",children:[e.jsx("div",{className:"empty-logo-wrap",children:e.jsx("div",{className:"empty-logo",children:"π"})}),e.jsx("h2",{className:"empty-title",children:i("welcomeTitle")}),e.jsx("p",{className:"empty-sub",children:i("welcomeSub")}),e.jsxs("div",{className:"empty-cwd",children:[e.jsx("span",{className:"empty-cwd-label",children:i("directory")}),e.jsx("span",{className:"empty-cwd-path",children:t.cwd})]}),e.jsx("div",{className:"empty-examples",children:ii(i).map(w=>e.jsxs("button",{type:"button",className:"empty-example",title:i("clickToFill"),onClick:()=>window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:w.prompt})),children:[e.jsx("span",{className:"empty-example-icon",children:w.icon}),e.jsx("span",{className:"empty-example-text",children:w.text})]},w.prompt))})]}),t.messages.map((w,$)=>{const ae=$<E,ie=ae&&v.has(w.id);if(ae&&!ie)return w.role==="toolResult"?null:e.jsx(qa,{message:w,onExpand:ne},w.id);const me=w.role==="user"?S.get(w.id):void 0,pe=!te||I.has(w.id)||k.has(w.id)||!P.has(w.id);return e.jsx(Ka,{id:w.id,show:pe,height:L.current.get(w.id)??Vs(w.role,w.customType),containerRef:a,onMeasured:R,lazyRef:j,children:e.jsx(ls,{message:w,qnIndex:me,qnActive:me!==void 0?me===A:void 0,onJump:V,toolResults:D,liveOutputs:hs(w)?s:us,toolStatuses:n,streaming:t.isStreaming,onKillBash:c,isLast:w.id===p,onEdit:l,questionAttachments:O.get(w.id),onCollapse:ie?z:void 0},w.id)},w.id)}),t.streamingMessage&&e.jsx(ls,{message:t.streamingMessage,toolResults:D,liveOutputs:hs(t.streamingMessage)?s:us,toolStatuses:n,streaming:!0,isLast:!0,onEdit:l,onKillBash:c},t.streamingMessage.id),t.isStreaming&&M.length===0&&e.jsx("div",{className:"streaming-wait",children:i("waitingResponse")}),t.queue.steering.map((w,$)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:i("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:w})]})},`q-steer-${$}`)),t.queue.followUp.map((w,$)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:i("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:w})]})},`q-fu-${$}`))]}),!o&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:Q,children:[e.jsx(Ps,{})," ",i("backToBottom")]}),e.jsx(ti,{containerRef:a,messages:M,open:N,onClose:()=>_(!1),onEnsureExpanded:g}),q.length>0&&e.jsxs("div",{className:`qn-rail ${Ae?"many":""}`,ref:le,"aria-label":i("questionNavTitle"),style:{"--rail-gap":`${Pe}px`},children:[q.map((w,$)=>e.jsx("button",{type:"button",className:`qn-bar ${$===A?"active":""}`,"aria-label":`${$+1}. ${w.text}`,onClick:()=>V(w.id),children:e.jsxs("span",{className:"qn-bar-text",children:[$+1,". ",w.text]})},w.id)),Ae&&e.jsx("div",{className:"qn-list",children:q.map((w,$)=>e.jsxs("button",{type:"button",className:`qn-list-item ${$===A?"active":""}`,"aria-label":`${$+1}. ${w.text}`,onClick:()=>V(w.id),children:[e.jsx("span",{className:"qn-list-idx",children:$+1}),e.jsx("span",{className:"qn-list-text",children:w.text})]},w.id))})]})]})}const li=r.memo(function({ready:s,streaming:n,messages:l,slashCommands:c,modelState:i,models:a,modelsLoading:o,send:d,attachments:m,onRemoveAttachment:x,onAddImageFiles:h,onAddLocalFiles:v,onNotice:C,onSent:N,onManageModels:_}){const M=he(),{locale:D}=Rt(),O=g=>D==="en"&&g.descriptionEn?g.descriptionEn:g.description??"",p=g=>D==="en"&&g.argumentHintEn?g.argumentHintEn:g.argumentHint??"",[E,P]=r.useState(""),[y,k]=r.useState(!1),[u,L]=r.useState(null),[U,G]=r.useState(0),[J,te]=r.useState(!1),[oe,I]=r.useState(void 0),F=r.useRef(null),W=r.useRef(null),re=r.useRef(null),ge={builtin:M("slashBuiltin"),extension:M("slashExtension"),prompt:M("slashPrompt"),skill:M("slashSkill"),plugin:M("slashPlugin")},R=g=>{const z=g.match(/^\/([^\s]*)$/);if(z&&s){const V=z[1].toLowerCase(),Z=c.filter(ue=>ue.name.toLowerCase().startsWith(V));L(Z.length>0?Z:null),G(0)}else L(null)};r.useEffect(()=>{var z;const g=(z=re.current)==null?void 0:z.querySelector(".slash-item.active");g==null||g.scrollIntoView({block:"nearest"})},[U,u]);const j=g=>{var be;const z=u??[],V=g??z[U%Math.max(z.length,1)];if(!V){L(null);return}const Z=E.match(/^\/([^\s]*)([\s\S]*)$/),ue=Z?Z[2]:"";P(`/${V.name} ${ue}`),L(null),(be=F.current)==null||be.focus()},q=async()=>{const z=[...l].reverse().find(Z=>Z.role==="assistant"&&Z.content.some(ue=>ue.type==="text"&&ue.text)),V=z==null?void 0:z.content.filter(Z=>Z.type==="text").map(Z=>Z.text).join(`
|
|
17
|
-
`);if(!V){C("warning",M("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(V),C("info",M("slashCopied"))}catch{C("error",M("slashCopyFailed"))}},S=g=>{if(!g||g.length===0){C("warning",M("foldersNotSupported"));return}const z=Array.from(g).filter(Z=>Re(Z.type)),V=Array.from(g).filter(Z=>!Re(Z.type));z.length>0&&h(z),V.length>0&&v(V)},A=g=>{var Z;const z=(Z=g.clipboardData)==null?void 0:Z.items;if(!z)return;const V=[];for(const ue of z)if(ue.kind==="file"&&Re(ue.type)){const be=ue.getAsFile();be&&V.push(be)}V.length!==0&&(g.preventDefault(),h(V))},se=s,de=r.useRef(E);r.useEffect(()=>{de.current=E},[E]),r.useEffect(()=>{R(de.current)},[c]),r.useEffect(()=>{const g=z=>{var Z;const V=z.detail;P(V),(Z=F.current)==null||Z.focus()};return window.addEventListener("pi-web:fill",g),()=>window.removeEventListener("pi-web:fill",g)},[]),r.useEffect(()=>{if(!J)return;const g=z=>{z.key==="Escape"&&te(!1)};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[J]),r.useEffect(()=>{const g=F.current;if(!g)return;g.style.height="auto";const z=g.scrollHeight>220;g.style.height=`${Math.min(g.scrollHeight,220)}px`,g.style.overflowY=z?"auto":"hidden"},[E]);const f=(g=!1)=>{var Z,ue,be,Q,le;const z=E.trim(),V=m.some(ee=>ee.imageData||ee.fileData);if(!(!se||!z&&!V)){if(z==="/help"){const ee=(ue=(Z=F.current)==null?void 0:Z.closest(".inputbox"))==null?void 0:ue.getBoundingClientRect();I(ee==null?void 0:ee.width),te(!0),P(""),(be=F.current)==null||be.focus();return}if(z==="/copy"){P(""),(Q=F.current)==null||Q.focus(),q();return}d({type:"prompt",text:z,queue:g,attachments:m.map(ee=>ee.imageData?{path:"",imageData:ee.imageData,mimeType:ee.mimeType,name:ee.name}:ee.fileData?{path:"",fileData:ee.fileData,mimeType:ee.mimeType,name:ee.name,size:ee.size}:{path:ee.path,mode:ee.mode,...ee.lines?{lines:ee.lines}:{}})})&&(P(""),N(),(le=F.current)==null||le.focus())}},B=g=>{if(!g.nativeEvent.isComposing){if(u&&u.length>0)switch(g.key){case"ArrowDown":g.preventDefault(),G(z=>(z+1)%u.length);return;case"ArrowUp":g.preventDefault(),G(z=>(z-1+u.length)%u.length);return;case"Tab":case"Enter":g.preventDefault(),j();return;case"Escape":g.preventDefault(),L(null);return}g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),f())}},ne=()=>e.jsx("div",{className:"inputbox-actions",children:n?e.jsxs(e.Fragment,{children:[E.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:M("supplementTip"),onClick:()=>f(!0),children:[e.jsx(jn,{})," ",M("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:M("stopAgent"),onClick:()=>d({type:"abort"}),children:e.jsx(tt,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:M("sendTip"),disabled:!se||!E.trim()&&!m.some(g=>g.imageData||g.fileData),onClick:()=>f(),children:e.jsx(Rs,{})})});return e.jsxs("div",{className:`inputbar${y?" drop-active":""}`,onDragOver:g=>{g.preventDefault(),g.stopPropagation(),k(!0)},onDragLeave:g=>{g.currentTarget.contains(g.relatedTarget)||k(!1)},onDrop:g=>{var z;g.preventDefault(),g.stopPropagation(),k(!1),S(((z=g.dataTransfer)==null?void 0:z.files)??null)},children:[y&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",M("dropHereToAttach")]})}),m.length>0&&e.jsxs("div",{className:"attach-row",children:[m.map(g=>e.jsxs("span",{className:`attach-chip ${g.imageData?"image":g.fileData?"file":g.mode}`,title:g.imageData?M("attachImage",{name:g.name}):g.fileData?M("attachFile",{name:g.name}):g.isDir?M("folderRef",{path:g.path}):g.mode==="reference"?M("refOnly",{path:g.path}):g.mode==="lines"&&g.lines?M("attachLines",{path:g.path,start:g.lines.start,end:g.lines.end}):M("attachContent",{path:g.path}),children:[g.imageData?"🖼":g.fileData?"📄":g.isDir?"📁":g.mode==="reference"?"🔗":"📎"," ",g.name,g.mode==="lines"&&g.lines&&e.jsxs("span",{className:"attach-range",children:["L",g.lines.start,"-",g.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:M("removeAttachment"),onClick:()=>x(g.key??g.path),children:"×"})]},g.key??`${g.path}|${g.mode}|${g.lines?`${g.lines.start}-${g.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:M("attachHint")})]}),u&&u.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:re,"aria-label":M("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:M("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>L(null),children:"Esc"})]}),u.map((g,z)=>e.jsxs("button",{type:"button",className:`slash-item${z===U?" active":""}`,onMouseEnter:()=>G(z),onClick:()=>j(g),children:[e.jsxs("span",{className:"slash-name",children:["/",g.name]}),e.jsx("span",{className:`slash-source ${g.source}`,children:ge[g.source]}),e.jsxs("span",{className:"slash-desc",children:[O(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:p(g)})]})]},g.name))]}),J&&e.jsx("div",{className:"modal-backdrop",onClick:()=>te(!1),children:e.jsxs("div",{className:"slash-help",style:oe?{width:oe}:void 0,onClick:g=>g.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",M("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>te(!1),children:M("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:M("slashLoading")}):c.map(g=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",g.name]}),e.jsx("span",{className:`slash-source ${g.source}`,children:ge[g.source]}),e.jsxs("span",{className:"slash-help-desc",children:[O(g),g.argumentHint&&e.jsx("span",{className:"slash-hint",children:p(g)})]})]},g.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:W,type:"file",multiple:!0,hidden:!0,onChange:g=>{S(g.target.files),g.target.value=""}}),e.jsxs("div",{className:"inputbox-row",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:M("uploadFile"),disabled:!se,onClick:()=>{var g;return(g=W.current)==null?void 0:g.click()},children:e.jsx(Gt,{})}),e.jsx("textarea",{ref:F,value:E,rows:1,placeholder:M(se?n?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!se,onChange:g=>{P(g.target.value),R(g.target.value)},onKeyDown:B,onPaste:A}),ne()]}),e.jsxs("div",{className:"input-tools",children:[e.jsx("div",{className:"input-tools-left",children:e.jsx(Bs,{state:i,models:a,modelsLoading:o,send:d,onManageModels:_,compact:!0})}),e.jsxs("div",{className:"input-tools-right",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:M("uploadFile"),disabled:!se,onClick:()=>{var g;return(g=W.current)==null?void 0:g.click()},children:e.jsx(Gt,{})}),ne()]})]})]})]})}),oi=r.memo(function({goal:s,models:n,modelsLoading:l,activeConversationId:c,send:i}){var G,J,te,oe,I,F;const a=he(),o=!s.conversationId||s.conversationId===c,d=s.goal!==null&&o,[m,x]=r.useState(""),[h,v]=r.useState(s.reviewModel??""),[C,N]=r.useState(s.maxRounds),[_,M]=r.useState(s.locked),[D,O]=r.useState(!1),[p,E]=r.useState(!1),[P,y]=r.useState(!0);r.useEffect(()=>{v(s.reviewModel??""),N(s.maxRounds||0),M(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),r.useEffect(()=>{D&&n.length===0&&!p&&!l&&(E(!0),i({type:"list_models"}))},[D,n.length,p,l,i]),r.useEffect(()=>{n.length>0&&E(!1)},[n.length]);const k=()=>{var W;return h?((W=n.find(re=>re.id===h))==null?void 0:W.name)??h:a("goalBarUseMainModel")},u=()=>{const W=m.trim();W&&(i({type:"set_goal",goal:W,...h?{reviewModel:h}:{},maxRounds:C,locked:_}),x(""),y(!1))},L=()=>{const W=m.trim();W&&(i({type:"start_goal_wizard",text:W,...h?{wizardModel:h}:{},maxRounds:C,locked:_}),x(""),y(!1))},U=(((G=s.wizard)==null?void 0:G.active)??!1)&&o;return U?e.jsx("div",{className:`goalbar goalbar-active ${U?"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:((J=s.wizard)==null?void 0:J.draft)??"",children:[a("goalWizardRunning"),": ",(te=s.wizard)==null?void 0:te.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[a("goalBarRound",{n:(((oe=s.wizard)==null?void 0:oe.step)??0)+1})," ","/ ",((I=s.wizard)==null?void 0:I.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((F=s.wizard)==null?void 0:F.status)||a("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:a("goalBarClear"),onClick:()=>{i({type:"clear_goal"}),y(!0)},children:e.jsx(Ce,{})})]})}):d?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:[a("goalBarReviewing")," ",a("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?a("goalBarPassed"):s.verdict==="fail"?a("goalBarFailed"):`${a("goalBarRound",{n:s.round||1})} · ${s.locked?a("goalBarLocked"):a("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:s.status}),e.jsx("button",{type:"button",className:"goalbar-x",title:a("goalBarClear"),disabled:s.reviewing,onClick:()=>{i({type:"clear_goal"}),y(!0)},children:e.jsx(Ce,{})})]})}):P?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:a("goalBarPlaceholder"),onClick:()=>y(!1),children:[e.jsx(Vt,{})," ",e.jsx("span",{children:a("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx(Vt,{})}),e.jsx("input",{className:"goalbar-input",value:m,placeholder:a("goalBarPlaceholder"),onChange:W=>x(W.target.value),onKeyDown:W=>{W.key==="Enter"&&u()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!m.trim(),onClick:u,children:a("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!m.trim(),title:a("goalWizardTip"),onClick:L,children:["🔍 ",a("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:a(_?"goalBarLocked":"goalBarUnlocked"),onClick:()=>M(W=>(i({type:"set_goal_prefs",locked:!W}),!W)),children:_?e.jsx(Mn,{}):e.jsx(yn,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:a("goalBarClear"),onClick:()=>y(!0),children:e.jsx(ot,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[e.jsxs(Ie,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[a("goalBarReviewModel"),": ",e.jsx("b",{children:k()})]}),open:D,onOpenChange:O,direction:"up",children:[e.jsx("div",{className:"dd-header",children:a("goalBarReviewModel")}),(p||l)&&e.jsx("div",{className:"dd-loading",children:a("loading")}),n.length===0&&!p&&!l&&e.jsx("div",{className:"dd-loading",children:a("noModels")}),e.jsx(Ne,{active:h==="",onClick:()=>{v(""),O(!1),i({type:"set_goal_prefs",reviewModel:""})},children:a("goalBarUseMainModel")}),n.map(W=>e.jsx(Ne,{active:h===W.id,onClick:()=>{v(W.id),O(!1),i({type:"set_goal_prefs",reviewModel:W.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:W.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:W.provider})})]})},W.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>i({type:"list_models"}),children:a("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:a("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:a("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:C,placeholder:a("goalBarUnlimitedShort"),onChange:W=>{const re=parseInt(W.target.value,10);if(Number.isNaN(re)||re<0){N(0);return}N(re)},onBlur:()=>i({type:"set_goal_prefs",maxRounds:C}),onKeyDown:W=>{W.key==="Enter"&&(i({type:"set_goal_prefs",maxRounds:C}),W.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:a(_?"goalBarLocked":"goalBarUnlocked")})]})]})});function ci({chat:t,send:s}){const n=he(),l=t.state,[c,i]=r.useState(!1),[a,o]=r.useState(""),[d,m]=r.useState(0),x=r.useRef(null),h=t.pathCompletions;if(r.useEffect(()=>{if(!c)return;const u=setTimeout(()=>{s({type:"complete_path",path:a})},150);return()=>clearTimeout(u)},[a,c,s]),r.useEffect(()=>m(0),[h]),r.useEffect(()=>{const u=document.querySelector(`.status-completions .pc-item[data-idx="${d}"]`);u==null||u.scrollIntoView({block:"nearest"})},[d]),!l)return null;const v=l.stats,C=t.ready?"ok":"busy",N=t.ready?n("connected"):n("connecting"),_=v.contextUsage,M=_.tokens!==null&&_.percent!==null?`${gs(_.tokens)} / ${gs(_.contextWindow)}`:"—",D=_.percent??null,O=D===null?"":D>=80?"warn":D>=50?"mid":"ok",p=l.queue.steering.length+l.queue.followUp.length,E=()=>{o(l.cwd),i(!0)},P=(u,L)=>{var G;const U=u.includes("\\")?"\\":"/";o(L?`${u}${U}`:u),m(0),(G=x.current)==null||G.focus()},y=u=>{const L=u.trim();L&&L!==l.cwd&&s({type:"set_cwd",path:L}),i(!1)},k=u=>{if(u.key==="ArrowDown")u.preventDefault(),m(L=>Math.min(L+1,h.length-1));else if(u.key==="ArrowUp")u.preventDefault(),m(L=>Math.max(L-1,0));else if(u.key==="Tab"&&h.length>0){u.preventDefault();const L=h[Math.min(d,h.length-1)];P(L.path,L.type==="dir")}else if(u.key==="Enter"&&!u.nativeEvent.isComposing){const L=a.trim();if(L.endsWith("/")||L.endsWith("\\"))y(L);else if(h.some(U=>U.path===L))y(L);else if(h.length>0&&h[d]){u.preventDefault();const U=h[d];P(U.path,U.type==="dir")}else y(L)}else u.key==="Escape"&&(h.length>0?(u.stopPropagation(),s({type:"complete_path",path:""})):i(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${C}`,title:N}),e.jsx("span",{className:"status-item",children:N}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-ctx",title:n("contextUsage"),children:[n("context"),e.jsx("span",{className:`ctx-bar ${O}`,children:D!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(D,100)}%`}})}),M]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("cumulativeCost"),children:["$",di(v.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("sessionMessages"),children:[n("messages")," ",v.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(u=>u.text).join(" · ")})]}),l.isStreaming&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item working",children:[e.jsx("span",{className:"working-spin"}),n("working"),p>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",p," ",n("queued")]})]})]}),c?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:x,className:"status-cwd-input",value:a,autoFocus:!0,placeholder:n("enterPath"),onChange:u=>o(u.target.value),onKeyDown:k,onBlur:()=>i(!1)}),h.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:u=>u.preventDefault(),children:h.map((u,L)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":L,className:`pc-item ${L===d?"sel":""}`,onMouseEnter:()=>m(L),onClick:()=>P(u.path,u.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:u.type==="dir"?e.jsx(qe,{}):e.jsx(Ts,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:u.name}),e.jsx("span",{className:"pc-path",children:u.path})]})]})},u.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:n("cwdTip",{path:l.cwd}),onClick:E,children:["📁 ",l.cwd]})]})}function gs(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function di(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function ui({dialog:t,send:s}){const n=he(),[l,c]=r.useState(""),[i,a]=r.useState(0),o=x=>{s({type:"dialog_response",id:t.id,value:x})};r.useEffect(()=>{c(""),a(0);const x=h=>{h.key==="Escape"&&o(null)};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[t.id]);const d=Array.isArray(t.args[0])?t.args[0]:[],m=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("pluginRequest")}),t.title&&t.title!==n("pluginRequest")&&e.jsx("span",{className:"dialog-title",children:t.title}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>o(null),children:"✕"})]}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[d.map((x,h)=>e.jsx("button",{type:"button",className:`dialog-option ${h===i?"sel":""}`,onMouseEnter:()=>a(h),onClick:()=>o(x),children:x},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:m}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(!1),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(!0),children:n("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:l,placeholder:m||n("inputPlaceholder"),autoFocus:!0,onChange:x=>c(x.target.value),onKeyDown:x=>{x.key==="Enter"&&!x.nativeEvent.isComposing&&o(l)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>o(null),children:n("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>o(l),children:n("ok")})]})]})]})}function mi(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 pi({chat:t,send:s,terminal:n,active:l,onSwitchToTerminal:c}){var pe,ve;const i=he(),[a,o]=r.useState(null),[d,m]=r.useState([]),[x,h]=r.useState(""),[v,C]=r.useState(new Map),[N,_]=r.useState("changes"),[M,D]=r.useState([]),[O,p]=r.useState(null),[E,P]=r.useState(""),[y,k]=r.useState(!1),[u,L]=r.useState(null),[U,G]=r.useState(null),[J,te]=r.useState(!1),[oe,I]=r.useState(!1),[F,W]=r.useState(!1),[re,ge]=r.useState(null),[R,j]=r.useState(!1),[q,S]=r.useState(""),A=r.useRef(0),se=r.useRef(-1),de=r.useRef(-1),f=r.useRef(-1),B=r.useRef(-1),ne=r.useRef(void 0),g=r.useRef(null),z=r.useRef([]),V=r.useCallback(b=>{if(b.reqId===se.current){if(se.current=-1,I(!1),ge(null),!b.ok){ge(b.error??"查询失败");return}if(b.notRepo){j(!0),o(null),m([]),C(new Map),D([]),p(null),P(""),G(null);return}j(!1);const ce={branch:b.branch??"",detached:!!b.detached,upstream:b.upstream??null,ahead:b.ahead??0,behind:b.behind??0,upstreamGone:!!b.upstreamGone,files:(b.files??[]).map(fe=>({...fe}))},Y=(b.branches??[]).map(fe=>({...fe})),ke=new Map;for(const[fe,we]of Object.entries(b.stats??{}))ke.set(fe,{add:we[0],del:we[1]});o(ce),m(Y),C(ke),h(fe=>{var we;return ce.detached?fe||"":ce.branch&&Y.some(Me=>Me.name===ce.branch)?ce.branch:fe&&Y.some(Me=>Me.name===fe)?fe:((we=Y[0])==null?void 0:we.name)??""}),G(fe=>fe&&!ce.files.some(we=>we.path===fe.file.path)?null:fe)}else if(b.reqId===de.current){if(de.current=-1,te(!1),!b.ok){ge(b.error??"查询失败");return}const ce=g.current;if(!ce)return;G({file:ce,staged:b.stagedText??"",worktree:b.worktreeText??"",untracked:!1})}else if(b.reqId===B.current){if(B.current=-1,W(!1),!b.ok){ge(b.error??"查询失败");return}D((b.history??[]).map(ce=>({...ce})))}else if(b.reqId===f.current){if(f.current=-1,k(!1),!b.ok){ge(b.error??"查询失败");return}P(b.text??"")}},[]);r.useEffect(()=>{const b=t.scmData;b&&b.type==="scm_data"&&V(b)},[t.scmData,V]);const Z=r.useCallback((b,ce)=>{if(!t.ready||t.status!=="open")return!1;const Y=++A.current;return s({...b,reqId:Y})?(ce.current=Y,!0):(A.current-=1,!1)},[t.ready,t.status,s]),ue=r.useCallback((b=!1,ce=!1)=>{var Y;!t.ready||t.status!=="open"||(Y=t.state)!=null&&Y.cwd&&(ne.current!==void 0&&ne.current!==t.state.cwd&&(o(null),m([]),C(new Map),D([]),W(!1),B.current=-1,p(null),P(""),G(null),L(null)),ne.current=t.state.cwd,ge(null),Z({type:"scm_status"},se)&&(ce||I(!0)))},[t.ready,(pe=t.state)==null?void 0:pe.cwd,t.status,Z]),be=r.useCallback(b=>{if(L(b),p(null),g.current=b,b.x==="?"&&b.y==="?"){G({file:b,staged:"",worktree:"",untracked:!0});return}te(!0),ge(null),Z({type:"scm_filediff",path:b.path},de)||te(!1)},[Z]),Q=r.useCallback(b=>{p(b),L(null),G(null),P(""),k(!0),ge(null),Z({type:"scm_commit",hash:b.hash},f)||k(!1)},[Z]),le=r.useCallback((b,ce)=>{var fe,we;if(!t.ready)return;const Y={name:b,command:ce,cwd:"${pwd}"},ke=t.terminals.find(Me=>Me.title===b);if(ke)n.restart(ke.id),s({type:"run_command",terminalId:ke.id,conversationId:ke.conversationId,command:Y,cols:80,rows:24});else{const Me=_e();n.create({id:Me,conversationId:t.activeConversationId||((fe=t.state)==null?void 0:fe.conversationId)||"",title:b,cwd:((we=t.state)==null?void 0:we.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Y})}c()},[t.ready,(ve=t.state)==null?void 0:ve.cwd,t.terminals,c,s,n]),ee=r.useCallback(()=>{const b=q.trim();if(!b||R)return;const ce=b.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");le("git commit",`git add -A && git commit -m "${ce}"`),S("")},[q,R,le]),Te=b=>`'${b.replace(/'/g,"'\\''")}`,Ee=r.useCallback(b=>{R||le("git add",`git add -- ${Te(b.path)}`)},[R,le]),Pe=r.useCallback(b=>{R||le("git reset",`git reset HEAD -- ${Te(b.path)}`)},[R,le]),Ae=r.useCallback(()=>{if(!x||R)return;const b=d.find(ce=>ce.name===x);if(b!=null&&b.remote&&typeof b.remote=="string"){const ce=x.slice(b.remote.length+1);le("git checkout",`git checkout -b ${ce} ${x} || git checkout ${x}`)}else le("git checkout",`git checkout ${x}`)},[x,d,R,le]),w=r.useCallback(()=>le("git push","git push"),[le]),$=r.useCallback(()=>le("git pull","git pull"),[le]),ae=r.useCallback(()=>{Z({type:"scm_history"},B)||(B.current=-1)},[Z]);r.useEffect(()=>{l&&ue()},[l,ue]),r.useEffect(()=>{N==="history"&&a&&ae()},[N,a,ae]),r.useEffect(()=>{t.scmDirty>0&&l&&ue(!1,!0)},[t.scmDirty]),r.useEffect(()=>{if(!l||!t.ready||t.status!=="open")return;const b=setInterval(()=>{document.visibilityState!=="hidden"&&ue(!1,!0)},3e4);return()=>clearInterval(b)},[l,t.ready,t.status,ue]),r.useEffect(()=>{const b=z.current;if(z.current=t.terminals,!l)return;t.terminals.some(Y=>{var fe;return Y.running!==!1?!1:((fe=b.find(we=>we.id===Y.id))==null?void 0:fe.running)===!0&&/^git /.test(Y.title)})&&t.ready&&t.status==="open"&&(ue(!1,!0),N==="history"&&a&&ae())},[t.terminals,l,t.ready,t.status,ue,N,a,ae]);const ie={staged:i("scmStaged"),unstaged:i("scmUnstaged"),untracked:i("scmUntracked"),both:i("scmStagedUnstaged")},me=b=>{const ce=b.split(`
|
|
18
|
-
`);return e.jsx("pre",{className:"scm-diff-pre",children:ce.map((Y,ke)=>{let fe="";return Y.startsWith("diff --git")||Y.startsWith("index ")||Y.startsWith("new file")||Y.startsWith("deleted file")||Y.startsWith("old mode")||Y.startsWith("new mode")||Y.startsWith("similarity index")||Y.startsWith("rename ")||Y.startsWith("copy ")||Y.startsWith("Binary files")||Y.startsWith("---")||Y.startsWith("+++")?fe="hdr":Y.startsWith("@@")?fe="hunk":Y.startsWith("+")?fe="add":Y.startsWith("-")&&(fe="del"),e.jsx("div",{className:`scm-diff-line ${fe}`,children:Y||" "},ke)})})};return e.jsxs("div",{className:"scm-view",children:[e.jsxs("div",{className:"scm-header",children:[e.jsxs("div",{className:"scm-title-row",children:[e.jsxs("span",{className:"scm-title",children:[e.jsx(Xe,{}),i("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":N==="changes",className:N==="changes"?"active":"",onClick:()=>{_("changes"),ge(null)},children:i("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":N==="history",className:N==="history"?"active":"",onClick:()=>{_("history"),ge(null)},children:i("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:i("scmRefreshTip"),disabled:oe,onClick:()=>ue(!0),children:e.jsx(rt,{className:oe?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:i("scmCurrentBranch"),children:[e.jsx(Xe,{}),a?a.detached?i("scmDetached"):a.branch:"…",(a==null?void 0:a.upstream)&&e.jsx("span",{className:"scm-upstream",children:a.upstreamGone?i("scmUpstreamGone"):a.ahead>0||a.behind>0?i("scmAheadBehind",{ahead:a.ahead,behind:a.behind}):a.upstream})]}),e.jsxs("select",{className:"scm-select",value:x,disabled:R||d.length===0,title:i("scmSwitchBranch"),onChange:b=>h(b.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:i("scmSelectBranch")}),d.filter(b=>!b.remote).map(b=>e.jsx("option",{value:b.name,children:b.current?`* ${b.name}`:b.name},b.name)),d.some(b=>b.remote)&&e.jsx("optgroup",{label:i("scmRemoteBranches"),children:d.filter(b=>b.remote).map(b=>e.jsx("option",{value:b.name,children:b.name},b.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!x||x===(a==null?void 0:a.branch)||R,title:i("scmSwitchBranchTip",{branch:x}),onClick:Ae,children:[e.jsx(Xe,{}),i("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!a||a.detached||R,title:i("scmPushTip"),onClick:w,children:[e.jsx(Rs,{}),i("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!a||a.detached||R,title:i("scmPullTip"),onClick:$,children:[e.jsx(Ps,{}),i("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:q,placeholder:i("scmCommitPlaceholder"),disabled:R,onChange:b=>S(b.target.value),onKeyDown:b=>{b.key==="Enter"&&!b.nativeEvent.isComposing&&ee()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!q.trim()||R,title:i("scmCommitTip"),onClick:ee,children:[e.jsx(dt,{}),i("scmCommit")]})]})]}),e.jsxs("div",{className:"scm-body",children:[N==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmHistory")}),M.length>0&&e.jsx("span",{className:"scm-files-count",children:M.length})]}),e.jsx("div",{className:"scm-history-list",children:R?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):!a||F?e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")}):M.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoHistory")}):M.map(b=>e.jsxs("button",{type:"button",className:`scm-commit ${(O==null?void 0:O.hash)===b.hash?"active":""}`,onClick:()=>Q(b),title:b.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:b.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:b.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[b.shortHash," · ",b.author," · ",b.date]}),b.decorations&&e.jsx("span",{className:"scm-commit-refs",children:b.decorations})]})]},b.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmChanges")}),a&&a.files.length>0&&e.jsx("span",{className:"scm-files-count",children:a.files.length})]}),e.jsx("div",{className:"scm-files-list",children:R?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):a?a.files.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoChanges")}):a.files.map(b=>{const ce=mi(b),Y=v.get(b.path);return e.jsxs("div",{className:`scm-file ${(u==null?void 0:u.path)===b.path?"active":""}`,title:ie[ce],onClick:()=>be(b),children:[e.jsx("span",{className:`scm-file-xy ${ce==="untracked"?"q":"x"}`,children:b.x!==" "?b.x:" "}),e.jsx("span",{className:`scm-file-xy ${ce==="untracked"?"q":"y"}`,children:b.y!==" "?b.y:" "}),e.jsx("span",{className:"scm-file-path",children:b.path}),Y&&(Y.add>0||Y.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[Y.add>0&&e.jsxs("span",{className:"add",children:["+",Y.add]}),Y.del>0&&e.jsxs("span",{className:"del",children:["-",Y.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(b.y!==" "||ce==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:i("scmStageTip",{path:b.path}),onClick:ke=>{ke.stopPropagation(),Ee(b)},children:"+"}),ce==="staged"||ce==="both"?e.jsx("button",{type:"button",className:"scm-act",title:i("scmUnstageTip",{path:b.path}),onClick:ke=>{ke.stopPropagation(),Pe(b)},children:"−"}):null]})]},b.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:N==="history"?O?`${O.shortHash} ${O.subject}`:i("scmCommitDetail"):u?u.path:i("scmDiff")}),(N==="history"?y:J)&&e.jsx("span",{className:"scm-diff-loading",children:i("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:N==="history"?e.jsxs(e.Fragment,{children:[re&&e.jsx("div",{className:"scm-error",children:re}),!O&&!re&&e.jsx("div",{className:"scm-empty",children:i("scmSelectCommitHint")}),O&&y&&!re&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),O&&!y&&!re&&E?me(E):null]}):e.jsxs(e.Fragment,{children:[re&&e.jsx("div",{className:"scm-error",children:re}),!u&&!re&&e.jsx("div",{className:"scm-empty",children:i("scmSelectFileHint")}),u&&!U&&!re&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),u&&U&&U.untracked&&e.jsx("div",{className:"scm-empty",children:i("scmUntrackedNote")}),u&&U&&!U.untracked&&e.jsxs(e.Fragment,{children:[U.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmStaged")}),me(U.staged)]}),U.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmUnstaged")}),me(U.worktree)]}),!U.staged&&!U.worktree&&e.jsx("div",{className:"scm-empty",children:i("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(Je,{}),e.jsx("span",{children:i("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:c,children:i("scmViewTerminal")})]})]})}function hi({entry:t,send:s}){const n=r.useRef(null);return r.useEffect(()=>{const l=n.current;if(!l)return;let c;try{c=t.module.mount(l,na(t.info.id,i=>s(i)))}catch(i){console.error(`[plugin:${t.info.id}] mount failed:`,i),l.textContent=`插件 ${t.info.name} 挂载失败`}return()=>{if(typeof c=="function")try{c()}catch(i){console.error(`[plugin:${t.info.id}] cleanup failed:`,i)}l.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:n})}function gi({send:t,piConfigured:s,providers:n,installResult:l,onClose:c}){const i=he(),[a,o]=r.useState(!1),[d,m]=r.useState(""),[x,h]=r.useState(""),[v,C]=r.useState(!1);r.useEffect(()=>{t({type:"list_providers"})},[t]),r.useEffect(()=>{s&&c()},[s,c]),r.useEffect(()=>{l&&o(!1)},[l]),r.useEffect(()=>{var p;!d&&n.length>0&&m(((p=n.find(E=>!E.configured))==null?void 0:p.id)??n[0].id)},[n,d]);const N=()=>{a||(o(!0),t({type:"install_pi_agent"}))},_=()=>{!x.trim()||v||(C(!0),t({type:"set_provider_api_key",provider:d.trim(),apiKey:x.trim()}),setTimeout(()=>C(!1),3e3))},M=()=>{t({type:"get_state"}),t({type:"list_providers"})},D=n.find(p=>p.id===d),O=l!==null&&!l.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:c,children:e.jsx(Ce,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(lt,{className:"modal-head-icon"}),e.jsx("h2",{children:i("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:i("setupDesc")}),O?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:i("installFailed")}),e.jsx("pre",{className:"setup-detail",children:l.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:a,onClick:N,children:i("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:c,children:i("skip")})]})]}):l!=null&&l.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:i("installDone")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:i("provider")}),e.jsxs("select",{value:d,onChange:p=>m(p.target.value),children:[n.length===0&&e.jsx("option",{value:"",children:i("loading")}),n.map(p=>e.jsxs("option",{value:p.id,children:[p.name,"(",p.id,")",p.configured?` · ${i("configured")}`:""]},p.id))]}),(D==null?void 0:D.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:x,onChange:p=>h(p.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!x.trim()||v||!d,onClick:_,children:i(v?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:M,children:[e.jsx(rt,{})," ",i("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:a,onClick:N,children:i(a?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:c,children:i("skip")})]})]})})}const fi=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],It=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),xi=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[It()]});function fs(t){return{providerId:t.providerId,name:t.name??"",api:t.api??"openai-completions",baseUrl:t.baseUrl??"",apiKey:t.apiKey??"",authHeader:t.authHeader??!1,models:(t.models.length?t.models:[It()]).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 vi({send:t,providers:s,providerStatus:n,fetchModelsResult:l,refreshProviderResult:c,cloneProviderResult:i,onClose:a}){const o=he(),[d,m]=r.useState(null),[x,h]=r.useState({}),[v,C]=r.useState(null),[N,_]=r.useState({}),[M,D]=r.useState(!1),[O,p]=r.useState(0),[E,P]=r.useState(null),y=r.useRef(0),[k,u]=r.useState({});r.useRef(0);const L=r.useRef(0),[U,G]=r.useState(null),J=r.useRef(0),te=r.useRef(0);r.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const oe=()=>{if(!d)return;const j=d.baseUrl.trim();if(!j){P({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(M)return;D(!0),P(null);const q=O+1;p(q),t({type:"fetch_models",reqId:q,baseUrl:j,apiKey:d.apiKey.trim()||void 0,authHeader:d.authHeader,api:d.api})};r.useEffect(()=>{var j;if(!(!l||l.reqId===y.current))if(y.current=l.reqId,D(!1),l.ok&&((j=l.models)!=null&&j.length)){const q=l.models;m(S=>{if(!S)return S;const A=S.models.map(B=>{var z;if(!B.id.trim())return B;const ne=q.find(V=>V.id===B.id.trim());if(!ne)return B;const g={...B};return!g.name&&ne.name&&(g.name=ne.name),!g.contextWindow&&ne.contextWindow&&(g.contextWindow=String(ne.contextWindow)),!g.maxTokens&&ne.maxTokens&&(g.maxTokens=String(ne.maxTokens)),g.input==="text"&&((z=ne.input)!=null&&z.includes("image"))&&(g.input="text-image"),!g.reasoning&&ne.reasoning&&(g.reasoning=!0),g}),se=new Set(A.map(B=>B.id.trim()).filter(Boolean)),de=q.filter(B=>!se.has(B.id)).map(B=>{var ne;return{id:B.id,name:B.name??"",reasoning:B.reasoning??!1,input:(ne=B.input)!=null&&ne.includes("image")?"text-image":"text",contextWindow:B.contextWindow?String(B.contextWindow):"",maxTokens:B.maxTokens?String(B.maxTokens):""}}),f=[...A,...de];return f.some(B=>B.id.trim())?{...S,models:f.filter(B=>B.id.trim())}:S}),P({ok:!0,text:o("fetchModelsOk",{n:q.length})})}else P({ok:!1,text:l.error||o("fetchModelsEmpty")})},[l]);const I=j=>{const q=(x[j.id]??"").trim();!q||v||(C(j.id),t({type:"set_provider_api_key",provider:j.id,apiKey:q}),setTimeout(()=>{C(null),h(S=>({...S,[j.id]:""})),_(S=>({...S,[j.id]:!1})),t({type:"list_providers"})},1500))},F=()=>{if(!d)return;const j=d.providerId.trim(),q=d.models.filter(A=>A.id.trim()).map(A=>({id:A.id.trim(),name:A.name.trim()||void 0,reasoning:A.reasoning||void 0,input:A.input==="text-image"?["text","image"]:void 0,contextWindow:A.contextWindow?Number(A.contextWindow):void 0,maxTokens:A.maxTokens?Number(A.maxTokens):void 0})),S={providerId:j,name:d.name.trim()||void 0,api:d.api.trim()||void 0,baseUrl:d.baseUrl.trim()||void 0,apiKey:d.apiKey.trim()||void 0,authHeader:d.authHeader||void 0,models:q};t({type:"save_model_config",providerId:j,config:S}),a()};r.useEffect(()=>{!c||c.reqId===L.current||(L.current=c.reqId,u({}))},[c]);const W=j=>{if(U)return;G(j.id);const q=++J.current+Date.now();t({type:"clone_provider",provider:j.id,reqId:q})};r.useEffect(()=>{!i||i.reqId===te.current||(te.current=i.reqId,G(null),i.ok&&i.config&&m(fs({...i.config,apiKey:""})))},[i]);const re=j=>{window.confirm(o("clearKeyConfirm",{id:j}))&&t({type:"clear_provider_api_key",provider:j})},ge=j=>{window.confirm(o("deleteProviderConfirm",{id:j.providerId,n:j.models.length}))&&t({type:"delete_model_config",providerId:j.providerId})},R=(j,q)=>{d&&m({...d,models:d.models.map((S,A)=>A===j?{...S,...q}:S)})};return e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"modal model-modal",onClick:j=>j.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:a,children:e.jsx(Ce,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:o(d?"editProvider":"manageModelsTitle")})}),d?e.jsxs("div",{className:"provider-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[o("providerId")," ",e.jsx("em",{children:o("providerIdHint")})]}),e.jsx("input",{type:"text",value:d.providerId,disabled:s.some(j=>j.providerId===d.providerId),onChange:j=>m({...d,providerId:j.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("displayName")}),e.jsx("input",{type:"text",value:d.name,onChange:j=>m({...d,name:j.target.value}),placeholder:o("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiType")}),e.jsx("select",{value:d.api,onChange:j=>m({...d,api:j.target.value}),children:fi.map(j=>e.jsx("option",{value:j,children:j},j))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:o("baseUrlHint")})]}),e.jsx("input",{type:"text",value:d.baseUrl,onChange:j=>m({...d,baseUrl:j.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKey")}),e.jsx("input",{type:"password",value:d.apiKey,onChange:j=>m({...d,apiKey:j.target.value}),placeholder:o("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:d.authHeader,onChange:j=>m({...d,authHeader:j.target.checked})}),e.jsx("span",{children:o("authHeader")})]})]}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:o("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[E&&e.jsx("span",{className:`fetch-msg ${E.ok?"ok":"err"}`,title:E.text,children:E.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:M||!d.baseUrl.trim(),title:o("fetchModelsHint"),onClick:oe,children:[e.jsx(Et,{})," ",o(M?"fetchingModels":"fetchModels")]})]})]}),d.models.map((j,q)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:j.id,onChange:S=>R(q,{id:S.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:j.name,onChange:S=>R(q,{name:S.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:j.input,onChange:S=>R(q,{input:S.target.value}),children:[e.jsx("option",{value:"text",children:o("text")}),e.jsx("option",{value:"text-image",children:o("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:j.reasoning,onChange:S=>R(q,{reasoning:S.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:j.contextWindow,onChange:S=>R(q,{contextWindow:S.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:j.maxTokens,onChange:S=>R(q,{maxTokens:S.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>m({...d,models:d.models.filter((S,A)=>A!==q)}),children:e.jsx($e,{})})]},q)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>m({...d,models:[...d.models,It()]}),children:[e.jsx(Ue,{})," ",o("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>m(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!d.providerId.trim()||!d.models.some(j=>j.id.trim()),onClick:F,children:o("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-section-title",children:[o("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:o("hintKeyOnly")})]}),e.jsxs("div",{className:"provider-list",children:[n.length===0&&e.jsx("div",{className:"dd-loading",children:o("loading")}),n.map(j=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:j.name}),e.jsxs("span",{className:"provider-sub",children:[j.id,j.configured&&e.jsx("span",{className:"auth-badge",children:o("configuredBadge")}),j.source&&!j.configured&&e.jsx("span",{className:"auth-badge dim",children:j.source})]})]}),e.jsxs("div",{className:"provider-actions",children:[j.configured&&!N[j.id]?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"auth-badge",children:o("keyReady")}),e.jsxs("button",{type:"button",className:"btn sm",title:o("replaceKeyTitle"),onClick:()=>_(q=>({...q,[j.id]:!0})),children:[e.jsx(Qt,{})," ",o("replaceKey")]}),j.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>re(j.id),children:[e.jsx($e,{})," ",o("clearKey")]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"password",className:"key-input",placeholder:o("pasteKey"),value:x[j.id]??"",onChange:q=>h(S=>({...S,[j.id]:q.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(x[j.id]??"").trim()||v===j.id,onClick:()=>I(j),children:[e.jsx(Rn,{})," ",v===j.id?o("savingKey"):o("saveKey")]})]}),e.jsxs("button",{type:"button",className:"btn sm",disabled:U!==null,title:o("cloneProviderTitle"),onClick:()=>W(j),children:[e.jsx(Mt,{})," ",U===j.id?o("cloning"):o("cloneProvider")]})]})]},j.id))]}),e.jsx("div",{className:"form-section-title",children:o("customProviders")}),e.jsx("p",{className:"modal-desc",children:o("customDesc")}),s.length===0&&e.jsx("div",{className:"dd-loading",children:o("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:s.map(j=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:j.providerId}),e.jsxs("span",{className:"provider-sub",children:[j.api??"—",j.baseUrl?` · ${j.baseUrl}`:"",j.models.length>0&&` · ${o("modelsCount",{n:j.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:o("edit"),onClick:()=>m(fs(j)),children:e.jsx(Qt,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>ge(j),children:e.jsx($e,{})})]})]},j.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>m(xi()),children:[e.jsx(Ue,{})," ",o("addProvider")]})})]})]})})}function yi({plugin:t,send:s}){const n=he(),l=t.settingsSchema??[],[c,i]=r.useState(()=>({...t.settingsValues??{}})),[a,o]=r.useState(!1);if(l.length===0)return null;const d=(v,C)=>i(N=>({...N,[v]:C})),m=l.some(v=>{var C;return c[v.key]!==((C=t.settingsValues)==null?void 0:C[v.key])}),x=()=>{o(!0),s({type:"plugin_settings",pluginId:t.id,values:c}),setTimeout(()=>o(!1),800)},h=()=>i({...t.settingsValues??{}});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:l.map(v=>e.jsxs("label",{className:"plugin-settings-field",title:v.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:v.label}),v.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!c[v.key],onChange:C=>d(v.key,C.target.checked)}):v.type==="select"?e.jsx("select",{value:String(c[v.key]??""),onChange:C=>d(v.key,C.target.value),children:(v.options??[]).map(C=>e.jsx("option",{value:C,children:C},C))}):e.jsx("input",{type:v.type==="password"?"password":v.type==="number"?"number":"text",value:String(c[v.key]??""),min:v.min,max:v.max,onChange:C=>d(v.key,v.type==="number"?Number(C.target.value):C.target.value)})]},v.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!m||a,onClick:x,children:n(a?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:h,children:n("pluginSettingsReset")})]})]})}function St({text:t}){const s=r.useRef(null),[n,l]=r.useState(!1),c=()=>{var a;const i=(a=s.current)==null?void 0:a.getBoundingClientRect();i&&l(window.innerWidth-i.right<340)};return e.jsxs("span",{ref:s,className:`set-tip${n?" flip":""}`,tabIndex:0,"aria-label":t,onMouseEnter:c,onFocus:c,children:["?",e.jsx("span",{className:"set-tip-bubble",role:"tooltip",children:t})]})}function Be({title:t,subtitle:s,tip:n,enabled:l,onToggle:c,action:i}){const a=he();return e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[t,n&&e.jsx(St,{text:n})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),i,e.jsx("button",{type:"button",className:`set-switch ${l?"on":""}`,role:"switch","aria-checked":l,title:a(l?"settingsEnabled":"settingsDisabled"),onClick:c,children:e.jsx("span",{className:"set-switch-knob"})})]})}function bi({chat:t,send:s,terminal:n,onSwitchToTerminal:l,onClose:c}){const i=he(),a=t.settings,[o,d]=r.useState(""),[m,x]=r.useState("append"),h=r.useRef(!1),[v,C]=r.useState(""),[N,_]=r.useState("append"),M=r.useRef(!1),[D,O]=r.useState(""),p=r.useRef(!1),[E,P]=r.useState(""),[y,k]=r.useState(!1),[u,L]=r.useState(null),[U,G]=r.useState(null);r.useEffect(()=>{a&&(x(a.promptMode),!h.current&&(d(m==="append"||a.customSystemPrompt?a.customSystemPrompt:a.defaultSystemPrompt||""),_(a.visionBridgePromptMode),!M.current&&(C(N==="append"||a.visionBridgePrompt?a.visionBridgePrompt:a.visionBridgeDefaultPrompt||""),p.current||O(a.reviewPrompt))))},[a,m,N]);const[J,te]=r.useState(String((a==null?void 0:a.terminalBashIdleMs)??15e3));if(r.useEffect(()=>{te(String((a==null?void 0:a.terminalBashIdleMs)??15e3))},[a==null?void 0:a.terminalBashIdleMs]),!a)return null;const oe=new Set(a.disabledSkills),I=new Set(a.disabledExtensions),F=f=>s({type:"set_settings",...f}),W=f=>{const B=new Set(oe);B.has(f.name)?B.delete(f.name):B.add(f.name),F({disabledSkills:[...B]})},re=new Set(a.disabledPlugins??[]),ge=f=>{const B=new Set(re);B.has(f.id)?B.delete(f.id):B.add(f.id),F({disabledPlugins:[...B]})},R=f=>{const B=new Set(I);B.has(f.id)?B.delete(f.id):B.add(f.id),F({disabledExtensions:[...B]})},j=(f,B)=>{var z,V;const ne={name:f,command:B,cwd:"${pwd}"},g=t.terminals.find(Z=>Z.title===f);g?(n.restart(g.id),s({type:"run_command",terminalId:g.id,conversationId:g.conversationId,command:ne,cols:80,rows:24})):n.create({id:_e(),conversationId:t.activeConversationId||((z=t.state)==null?void 0:z.conversationId)||"",title:f,cwd:((V=t.state)==null?void 0:V.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:ne}),l(),c()},q=f=>{L(null),j(`${i("uninstallTitle")} ${f}`,`pi remove npm:${f}`)},S=f=>{G(null),j(`${i("uninstallTitle")} ${f}`,`pi-web-ui uninstall ${f}`)},A=(f,B)=>{j(`${i("pluginUpdate")} ${f}`,`pi-web-ui install ${B} --name ${f} --force`)},se=f=>{const B=new Set(a.reviewSkills.filter(ne=>!ne.enabled).map(ne=>ne.name));B.has(f.name)?B.delete(f.name):B.add(f.name),F({reviewDisabledSkills:[...B]})},de=()=>{const f=m==="replace"&&a.defaultSystemPrompt&&o===a.defaultSystemPrompt?"":o;F({promptMode:m,customSystemPrompt:f})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal settings-modal",onClick:f=>f.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:c,children:e.jsx(Ce,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(st,{className:"modal-head-icon"}),e.jsx("h2",{children:i("settingsTitle")})]}),e.jsx("p",{className:"modal-desc",children:i("settingsDesc")}),e.jsxs("div",{className:"modal-body",children:[e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(yt,{className:"set-section-icon"}),i("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:m,onChange:f=>{const B=f.target.value;x(B),F({promptMode:B})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]}),e.jsx(St,{text:i(m==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:i("promptPlaceholder"),value:o,onFocus:()=>h.current=!0,onBlur:()=>{h.current=!1,de()},onChange:f=>d(f.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":y,onClick:()=>k(f=>!f),children:[i("settingsViewPrompt")," ",y?"▴":"▾"]}),y&&e.jsxs("div",{className:"set-prompt-view",children:[e.jsxs("div",{className:"set-prompt-view-head",children:[e.jsx("span",{children:i("settingsViewPromptHint")}),e.jsx(_s,{text:a.effectiveSystemPrompt})]}),a.effectiveSystemPrompt?e.jsx("pre",{className:"set-prompt-view-text",children:a.effectiveSystemPrompt}):e.jsx("p",{className:"set-empty",children:i("settingsViewPromptEmpty")})]})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Je,{className:"set-section-icon"}),i("settingsTerminalTools")]}),e.jsx(Be,{title:i("terminalToolsEnabled"),tip:i("settingsTerminalToolsDesc"),enabled:a.terminalToolsEnabled,onToggle:()=>F({terminalToolsEnabled:!a.terminalToolsEnabled})}),!a.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:i("terminalToolsOffHint")}),e.jsx(Be,{title:i("terminalBashTakeover"),tip:i("terminalBashTakeoverDesc"),enabled:a.terminalBash,onToggle:()=>F({terminalBash:!a.terminalBash})}),a.terminalBash&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"tb-idle-ms",children:i("terminalBashIdleMs")}),e.jsx("input",{id:"tb-idle-ms",className:"set-input",type:"number",min:0,step:1e3,value:J,onChange:f=>te(f.target.value),onBlur:()=>{const f=Math.max(0,Math.floor(Number(J)||0));te(String(f)),f!==a.terminalBashIdleMs&&F({terminalBashIdleMs:f})}})]})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(lt,{className:"set-section-icon"}),i("settingsSkills"),e.jsx("span",{className:"set-count",children:a.skills.length})]}),a.skills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:a.skills.map(f=>e.jsx(Be,{title:f.name,subtitle:f.description,enabled:f.enabled,onToggle:()=>W(f)},f.name))})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(wn,{className:"set-section-icon"}),i("settingsExtensions"),e.jsx("span",{className:"set-count",children:a.extensions.length})]}),a.extensions.length===0?e.jsx("p",{className:"set-empty",children:i("noExtensions")}):e.jsx("div",{className:"set-list",children:a.extensions.map(f=>{const B=f.id.startsWith("npm:")?f.id.slice(4):null;return e.jsx(Be,{title:f.name,subtitle:f.path,enabled:f.enabled,onToggle:()=>R(f),action:B?u===f.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>q(B),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("uninstallHint"),onClick:()=>L(f.id),children:[e.jsx($e,{}),i("uninstallExt")]}):void 0},f.id)})})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ms,{className:"set-section-icon"}),i("settingsUiPlugins"),e.jsx("span",{className:"set-count",children:t.plugins.length})]}),t.plugins.length===0?e.jsx("p",{className:"set-empty",children:i("noUiPlugins")}):e.jsx("div",{className:"set-list",children:t.plugins.map(f=>{var B;return e.jsxs(e.Fragment,{children:[e.jsx(Be,{title:`${f.icon?`${f.icon} `:""}${f.name}`,subtitle:(f.error?`${f.id} · ${f.error}`:f.source?`${f.id} · ${f.source}`:`${f.id} · ${i("uiPluginNoSource")}`)+((B=f.permissions)!=null&&B.length?` · ${i("uiPluginPerms")}: ${f.permissions.join(", ")}`:""),enabled:!re.has(f.id)&&!f.error,onToggle:()=>!f.error&&ge(f),action:e.jsxs("div",{className:"set-row-actions",children:[f.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>A(f.id,f.source),children:[e.jsx(rt,{}),i("pluginUpdate")]}),U===f.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>S(f.id),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>G(f.id),children:[e.jsx($e,{}),i("uninstallExt")]})]})},f.id),f.settingsSchema&&f.settingsSchema.length>0&&e.jsx(yi,{plugin:f,send:s})]})})})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(yt,{className:"set-section-icon"}),i("settingsReview"),e.jsx(St,{text:i("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:a.reviewSkills.length})]}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:i("reviewPromptPlaceholder"),value:D,onFocus:()=>p.current=!0,onBlur:()=>{p.current=!1,F({reviewPrompt:D})},onChange:f=>O(f.target.value)}),e.jsx("div",{className:"set-field-label",children:i("settingsReviewSkills")}),a.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:i("noSkills")}):e.jsx("div",{className:"set-list",children:a.reviewSkills.map(f=>e.jsx(Be,{title:f.name,subtitle:f.description,enabled:f.enabled,onToggle:()=>se(f)},`review-${f.name}`))})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Es,{className:"set-section-icon"}),i("settingsVisionBridge")]}),e.jsx(Be,{title:i("visionBridgeEnabled"),tip:i("settingsVisionBridgeDesc"),enabled:a.visionBridgeEnabled,onToggle:()=>F({visionBridgeEnabled:!a.visionBridgeEnabled})}),!a.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:i("visionBridgeOffHint")}),a.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:a.visionBridgeModel??"",onChange:f=>F({visionBridgeModel:f.target.value||null}),children:[e.jsx("option",{value:"",children:i("visionBridgeAuto")}),a.visionModels.map(f=>e.jsx("option",{value:`${f.provider}/${f.id}`,children:f.label},`${f.provider}/${f.id}`))]})]}),a.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:N,onChange:f=>{const B=f.target.value;_(B),F({visionBridgePromptMode:B})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]})]}),a.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:i("visionBridgePromptPlaceholder"),value:v,onFocus:()=>M.current=!0,onBlur:()=>{M.current=!1;const f=N==="replace"&&a.visionBridgeDefaultPrompt&&v===a.visionBridgeDefaultPrompt?"":v;F({visionBridgePromptMode:N,visionBridgePrompt:f})},onChange:f=>C(f.target.value)}),a.visionBridgeEnabled&&(a.visionModels.length===0?e.jsx("p",{className:"set-hint",children:i("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:i("visionBridgeCurrent",{model:a.visionBridgeModel??i("visionBridgeAuto")})}))]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(st,{className:"set-section-icon"}),i("settingsPresets"),e.jsx("span",{className:"set-count",children:a.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:i("presetNamePlaceholder"),value:E,onChange:f=>P(f.target.value),onKeyDown:f=>{f.key==="Enter"&&E.trim()&&(s({type:"save_preset",name:E.trim()}),P(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!E.trim(),onClick:()=>{s({type:"save_preset",name:E.trim()}),P("")},children:[e.jsx(Ue,{})," ",i("saveAsPreset")]})]}),a.presets.length===0?e.jsx("p",{className:"set-empty",children:i("noPresets")}):e.jsx("div",{className:"set-list",children:a.presets.map(f=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:f.name}),e.jsxs("div",{className:"set-row-desc",children:[f.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend"),f.disabledSkills.length>0&&` · ${i("settingsSkills")} ${f.disabledSkills.length}`,f.disabledExtensions.length>0&&` · ${i("settingsExtensions")} ${f.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:f.name}),children:i("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("deletePreset"),onClick:()=>s({type:"delete_preset",name:f.name}),children:e.jsx($e,{})})]})]},f.name))})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:c,children:i("close")})})]})})}function ji(t,s){const n=Math.max(0,Date.now()-t),l=Math.floor(n/6e4);if(l<1)return s("bgTaskJustNow");if(l<60)return s("bgTaskMinutes",{n:l});const c=Math.floor(l/60);return c<24?s("bgTaskHours",{n:c}):s("bgTaskDays",{n:Math.floor(c/24)})}function ki({servers:t,send:s,onClose:n}){const l=he(),[c,i]=r.useState(new Set),a=o=>i(d=>{const m=new Set(d);return m.has(o)?m.delete(o):m.add(o),m});return r.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:n,children:e.jsxs("div",{className:"bg-task-modal",onClick:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(it,{})," ",l("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:l("close"),onClick:n,children:e.jsx(Ce,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(it,{}),e.jsx("span",{children:l("bgTasksEmpty")}),e.jsx("small",{children:l("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(o=>{const d=!!o.taskId,m=o.taskId??String(o.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:d?o.plugin:l("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:o.taskId,children:["🧩 ",o.plugin]}):e.jsxs("span",{className:"bg-task-port",children:[":",o.port]}),o.name&&e.jsx("span",{className:"bg-task-name",children:o.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[!d&&e.jsxs("span",{children:[l("bgTaskPid")," ",o.pid]}),e.jsxs("span",{children:[l("bgTaskSince")," ",ji(o.since,l)]}),d&&o.status&&e.jsx("span",{className:"bg-task-status",children:o.status})]}),o.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${c.has(m)?"open":""}`,title:`${l("bgTaskCommand")}: ${o.command}`,onClick:()=>a(m),children:[e.jsx(Je,{}),e.jsx("code",{children:o.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:l("bgTaskStop"),onClick:()=>s(d?{type:"kill_background_server",taskId:o.taskId}:{type:"kill_background_server",port:o.port}),children:[e.jsx(tt,{}),e.jsx("span",{children:l("bgTaskStop")})]})]},m)})}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:l("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(rt,{}),e.jsx("span",{children:l("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:l("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(tt,{}),e.jsx("span",{children:l("bgTaskStopAll")})]})]})]})})}function Ye(t,s){return t.toLowerCase().includes(s)}function wi({send:t,sessions:s,projects:n,cwd:l,fileSearch:c,onClose:i,onSwitchSession:a,onSwitchProject:o,onPreviewFile:d}){const m=he(),x=r.useRef(null),[h,v]=r.useState(""),C=r.useDeferredValue(h),[N,_]=r.useState(0),M=r.useRef(1),D=r.useRef(0),O=r.useRef(null);r.useEffect(()=>{t({type:"list_sessions"}),t({type:"list_projects"}),requestAnimationFrame(()=>{var I;return(I=x.current)==null?void 0:I.focus()})},[]);const[p,E]=r.useState(!1);r.useEffect(()=>{O.current&&clearTimeout(O.current);const I=C.trim();if(I)return O.current=setTimeout(()=>{const F=++M.current;D.current=F,E(!0),t({type:"search_files",reqId:F,query:I})},300),()=>{O.current&&clearTimeout(O.current)}},[C]);const P=C.trim().toLowerCase(),y=r.useMemo(()=>P?s.filter(I=>Ye(I.firstMessage??"",P)||Ye(I.name??"",P)||Ye(I.path.split(/[\\/]/).pop()??"",P)).slice(0,20):[],[s,P]),k=r.useMemo(()=>P?n.filter(I=>Ye(I.path,P)).slice(0,10):[],[n,P]),u=r.useMemo(()=>!P||!c||c.reqId!==D.current||!c.ok?[]:c.results,[c,P]);r.useEffect(()=>{c&&c.reqId===D.current&&D.current!==0&&E(!1)},[c]);const L=!!c&&c.ok&&c.truncated,U=r.useMemo(()=>[...y.map(I=>({kind:"session",path:I.path})),...k.map(I=>({kind:"project",path:I.path})),...u.filter(I=>I.type==="file").map(I=>({kind:"file",path:I.path,name:I.name}))],[y,k,u]);r.useEffect(()=>{_(0)},[C]);const G=r.useCallback(I=>{I&&(I.kind==="session"?a(I.path):I.kind==="project"?o(I.path):d(I.path,I.name),i())},[a,o,d,i]);r.useEffect(()=>{const I=F=>{F.key==="Escape"?(F.preventDefault(),F.stopPropagation(),i()):F.key==="ArrowDown"?(F.preventDefault(),_(W=>Math.min(W+1,U.length-1))):F.key==="ArrowUp"?(F.preventDefault(),_(W=>Math.max(W-1,0))):F.key==="Enter"&&(F.preventDefault(),G(U[N]))};return window.addEventListener("keydown",I,!0),()=>window.removeEventListener("keydown",I,!0)},[U,N,G,i]);const J=y.length+k.length+u.length,te=(I,F,W)=>e.jsxs("div",{className:"gs-section-head",children:[W,e.jsx("span",{children:I}),e.jsx("em",{children:F})]});let oe=-1;return e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:i,children:e.jsxs("div",{className:"gs-modal",onClick:I=>I.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(nt,{}),e.jsx("input",{ref:x,type:"text",value:h,placeholder:m("gsPlaceholder"),onChange:I=>v(I.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:m("close"),onClick:i,children:e.jsx(Ce,{})})]}),e.jsxs("div",{className:"gs-results",children:[!P&&e.jsx("div",{className:"gs-empty",children:m("gsHint")}),P&&J===0&&!L&&e.jsx("div",{className:"gs-empty",children:m(p?"gsSearching":"gsNoResults")}),y.length>0&&e.jsxs("div",{className:"gs-section",children:[te(m("gsSessions"),y.length,e.jsx(at,{})),y.map(I=>{oe++;const F=oe;return e.jsxs("button",{type:"button",className:F===N?"gs-item active":"gs-item",onMouseEnter:()=>_(F),onClick:()=>G({kind:"session",path:I.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[I.name||I.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:I.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:I.firstMessage})]},I.path)})]}),k.length>0&&e.jsxs("div",{className:"gs-section",children:[te(m("gsProjects"),k.length,e.jsx(qe,{})),k.map(I=>{oe++;const F=oe,W=l&&I.path===l;return e.jsxs("button",{type:"button",className:F===N?"gs-item active":"gs-item",onMouseEnter:()=>_(F),onClick:()=>G({kind:"project",path:I.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[I.path.split(/[\\/]/).pop(),W&&e.jsx("em",{className:"gs-item-meta",children:m("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:I.path})]},I.path)})]}),(u.length>0||P&&L)&&e.jsxs("div",{className:"gs-section",children:[te(m("gsFiles"),u.length,e.jsx(Bn,{})),u.map(I=>{oe++;const F=oe;return e.jsxs("button",{type:"button",className:F===N?"gs-item active":"gs-item",disabled:I.type==="dir",title:I.type==="dir"?void 0:m("gsOpenPreview"),onMouseEnter:()=>_(F),onClick:()=>{I.type==="file"&&G({kind:"file",path:I.path,name:I.name})},children:[e.jsx("span",{className:"gs-item-title",children:I.name}),e.jsx("span",{className:"gs-item-sub",children:I.path})]},`${I.type}:${I.path}`)}),L&&e.jsx("div",{className:"gs-truncated",children:m("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",m("gsNavigate")]}),e.jsxs("span",{children:["Enter ",m("gsOpen")]}),e.jsxs("span",{children:["Esc ",m("gsCloseHint")]})]})]})})}const xt=5e3;function Ni({file:t,content:s,send:n,onAddLines:l,onAttach:c,onClose:i}){const a=he(),[o,d]=r.useState(null),[m,x]=r.useState(!1),[h,v]=r.useState(null),[C,N]=r.useState(!1),[_,M]=r.useState(!1),[D,O]=r.useState(!1),[p,E]=r.useState(""),[P,y]=r.useState(!0),k=r.useRef(!1),[u,L]=r.useState(!0),[U,G]=r.useState(!1),[J,te]=r.useState(100),oe=r.useRef(0),I=r.useRef(!1),F=r.useRef(null);r.useEffect(()=>{x(!0),d(null),v(null),O(!1),E(""),y(!0),k.current=!1,n({type:"read_file",path:t.path})},[t.path,n]),r.useEffect(()=>{s&&s.path===t.path&&(d(s),D||E(s.text),x(!1))},[s,D,t.path]),r.useEffect(()=>{const Q=le=>{if(le.key==="Escape"){f();return}if((le.ctrlKey||le.metaKey)&&le.key.toLowerCase()==="s"&&D){le.preventDefault(),de();return}const ee=le.target,Te=ee&&(ee.tagName==="INPUT"||ee.tagName==="TEXTAREA"||ee.isContentEditable);(le.ctrlKey||le.metaKey)&&le.key.toLowerCase()==="a"&&!Te&&(le.preventDefault(),j())};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[i,o,D,p]),r.useEffect(()=>{const Q=()=>{I.current=!1,N(!1)};return window.addEventListener("mouseup",Q),()=>window.removeEventListener("mouseup",Q)},[]);const W=r.useMemo(()=>{if(!o)return[];const Q=o.text.split(`
|
|
19
|
-
`);return Q.length>0&&Q[Q.length-1]===""&&Q.pop(),Q.slice(0,xt)},[o]),re=(o==null?void 0:o.lines)??0,ge=re>xt,R=(Q,le)=>{if(le){const ee=oe.current>0?oe.current:Q;v({start:Math.min(ee,Q),end:Math.max(ee,Q)})}else oe.current=Q,v({start:Q,end:Q})},j=()=>{W.length!==0&&(oe.current=1,v({start:1,end:W.length}))},q=()=>{h&&(l(t.path,t.name,h.start,h.end),M(!0),F.current&&clearTimeout(F.current),F.current=setTimeout(()=>M(!1),1400))},S=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,A=()=>{E((o==null?void 0:o.text)??""),O(!1),k.current&&y(!0)},se=()=>{if(D){if(p!==((o==null?void 0:o.text)??"")&&!window.confirm(a("discardFileChanges")))return;A();return}!S||!o||(k.current=vt(t.name)&&P,vt(t.name)&&y(!1),v(null),E(o.text),O(!0))},de=()=>{!D||!o||!S||n({type:"write_file",path:t.path,text:p})&&(O(!1),k.current&&y(!0),v(null))},f=()=>{D&&p!==((o==null?void 0:o.text)??"")&&!window.confirm(a("discardFileChanges"))||i()},B=Q=>{te(Math.min(200,Math.max(50,Q)))},ne=h?h.end-h.start+1:0,g=(o==null?void 0:o.binary)??!1,z=(o==null?void 0:o.truncated)??!1,V=(o==null?void 0:o.kind)??"text",Z=vt(t.name),ue=Z&&P&&!D&&V==="text"&&!g,be=Q=>ut(`/api/file?clientId=${encodeURIComponent(Pt())}&path=${encodeURIComponent(Q)}`);return e.jsx("div",{className:`fp-overlay ${U?"fullscreen":""}`,onMouseDown:Q=>{Q.target===Q.currentTarget&&f()},children:e.jsxs("div",{className:`fp ${U?"fullscreen":""}`,style:{"--fp-zoom":J/100},children:[e.jsxs("div",{className:"fp-head",children:[e.jsx("span",{className:"fp-name",title:t.path,children:t.name}),e.jsx("span",{className:"fp-path",children:t.path}),e.jsxs("span",{className:"fp-meta",children:[o&&V==="text"&&!g&&a("fileLines",{n:re}),o&&` · ${Ci(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[Z&&V==="text"&&!g&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${P?"on":""}`,"data-tip":a(P?"showMarkdownSource":"showMarkdownPreview"),disabled:D,onClick:()=>y(Q=>!Q),children:P?e.jsx(Es,{}):e.jsx($n,{})}),V==="text"&&!g&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${D?"on":""}`,"data-tip":a(z?"fileEditTruncated":D?"exitEditFile":"editFile"),disabled:!S&&!D,onClick:se,children:e.jsx(jt,{})}),V==="text"&&!g&&!ue&&e.jsx("button",{type:"button",className:`fp-attach wrap ${u?"on":""}`,"data-tip":a(u?"disableWrap":"enableWrap"),onClick:()=>L(Q=>!Q),children:e.jsx(Dn,{})}),V==="text"&&o&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":a("zoomOut"),disabled:J<=50,onClick:()=>B(J-10),children:e.jsx(xn,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:a("resetZoom"),onClick:()=>te(100),children:[J,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":a("zoomIn"),disabled:J>=200,onClick:()=>B(J+10),children:e.jsx(vn,{})})]}),V!=="video"&&V!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":a("attachInlineTip"),onClick:()=>c(t.path,t.name,"inline"),children:e.jsx(Ue,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":a("referenceTip"),onClick:()=>c(t.path,t.name,"reference"),children:e.jsx(bt,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${U?"on":""}`,"data-tip":a(U?"exitFullscreen":"fullscreen"),onClick:()=>G(Q=>!Q),children:U?e.jsx(Cn,{}):e.jsx(Tn,{})}),e.jsx("button",{type:"button",className:"fp-close",title:a("close"),onClick:f,children:e.jsx(Ce,{})})]})]}),z&&V==="text"&&!g&&e.jsx("div",{className:"fp-notice",children:a("previewTruncated")}),m&&!o&&e.jsx("div",{className:"fp-empty",children:a("loading")}),!m&&V==="none"&&!g&&e.jsx("div",{className:"fp-empty",children:a("previewNotSupported")}),!m&&V==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:be(t.path),alt:t.name})}),!m&&V==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:be(t.path),controls:!0,preload:"metadata"})}),!m&&ue&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(mt,{text:o.text})})}),!m&&g&&V!=="image"&&V!=="video"&&o&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[a("binaryFile"),o.truncated&&a("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:o.text})]}),!m&&D&&V==="text"&&!g&&o&&e.jsx("textarea",{className:`fp-editor ${u?"":"no-wrap"}`,value:p,onChange:Q=>E(Q.target.value),wrap:u?"soft":"off",spellCheck:!1,autoFocus:!0}),!m&&!ue&&!D&&V==="text"&&!g&&o&&W.length===0&&e.jsx("div",{className:"fp-empty",children:a("emptyFile")}),!m&&!ue&&!D&&V==="text"&&!g&&W.length>0&&e.jsxs("div",{className:`fp-code ${C?"dragging":""} ${u?"":"no-wrap"}`,onMouseDown:Q=>{Q.button===0&&Q.preventDefault()},children:[W.map((Q,le)=>{const ee=le+1,Te=h!==null&&ee>=h.start&&ee<=h.end;return e.jsxs("div",{className:`fp-line ${Te?"sel":""}`,onMouseDown:Ee=>{Ee.button===0&&(R(ee,Ee.shiftKey),I.current=!0,N(!0))},onMouseEnter:()=>{I.current&&R(ee,!0)},children:[e.jsx("span",{className:"fp-num",children:ee}),e.jsx("span",{className:"fp-code-text",children:Q})]},ee)}),ge&&e.jsx("div",{className:"fp-lines-note",children:a("previewLinesTruncated",{n:xt})})]}),e.jsx("div",{className:"fp-foot",children:D?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:a("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:se,children:a("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:p===((o==null?void 0:o.text)??""),onClick:de,children:[e.jsx(kn,{})," ",a("saveFile")]})]})]}):!ue&&V==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:h?a("selectedRange",{n:ne,start:h.start,end:h.end}):a("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:W.length===0,onClick:j,children:a("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!h,onClick:()=>v(null),children:a("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!h||g,onClick:q,children:[_?e.jsx(dt,{}):null,a(_?"addedToChat":"addToChat")]})]})]})})]})})}function vt(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function Ci(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const Gs="pi-web-sounds",ze={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function Js(){try{const t=localStorage.getItem(Gs);if(!t)return{...ze};const s=JSON.parse(t),n={...ze,...s};for(const l of["enabled","question","done","start","error"])typeof n[l]!="boolean"&&(n[l]=ze[l]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=ze.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...ze}}}function Si(t){try{localStorage.setItem(Gs,JSON.stringify(t))}catch{}}let Ke=null;function Ti(){try{if(!Ke){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;Ke=new t}return Ke.state==="suspended"&&Ke.resume(),Ke}catch{return null}}const Ei=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],Mi=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],Ri=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],Pi=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],Li={question:Ei,done:Mi,start:Ri,error:Pi};function Ii(t,s,n){const l=t.createOscillator(),c=t.createGain();l.type=s.type,l.frequency.value=s.freq;const i=t.currentTime+s.start,a=Math.max(1e-4,s.peak*n);c.gain.setValueAtTime(1e-4,i),c.gain.exponentialRampToValueAtTime(a,i+.012),c.gain.exponentialRampToValueAtTime(1e-4,i+s.dur),l.connect(c),c.connect(t.destination),l.start(i),l.stop(i+s.dur+.05)}function Ve(t,s=Js()){if(!s.enabled||!s[t])return;const n=Ti();if(!n)return;const l=Math.max(0,Math.min(1,s.volume/100));for(const c of Li[t])Ii(n,c,l)}const Tt="pi-web-ui:theme",Qs="dark",xs="theme-stylesheet",vs="pi-web-ui:theme-change";function Ys(){try{const t=localStorage.getItem(Tt);if(t&&t!==Qs)return t}catch{}return null}function Bi(t){try{t?localStorage.setItem(Tt,t):localStorage.removeItem(Tt)}catch{}}function Xs(t){let s=document.getElementById(xs);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(vs));return}s||(s=document.createElement("link"),s.id=xs,s.rel="stylesheet",document.head.appendChild(s)),s.href=`/themes/${encodeURIComponent(t)}.css`,s.onload=()=>window.dispatchEvent(new CustomEvent(vs))}async function Di(){try{const t=await fetch(ut("/api/themes"));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function $i(){const[t,s]=r.useState([]),[n,l]=r.useState(()=>Ys());return r.useEffect(()=>{let i=!1;return Di().then(a=>{i||s(a)}),()=>{i=!0}},[]),r.useEffect(()=>{Xs(n),Bi(n)},[n]),{themes:t,theme:n,switchTheme:i=>l(i===Qs?null:i)}}function qi(){const t=getComputedStyle(document.documentElement),s=(n,l)=>t.getPropertyValue(n).trim()||l;return{background:s("--term-bg","#0b0d12"),foreground:s("--term-fg","#e6e8ef"),cursor:s("--term-cursor","#8b5cf6"),cursorAccent:s("--term-cursor-accent","#0b0d12"),selectionBackground:s("--term-selection","rgba(139, 92, 246, 0.35)"),black:s("--term-black","#1a1d26"),red:s("--term-red","#f87171"),green:s("--term-green","#34d399"),yellow:s("--term-yellow","#fbbf24"),blue:s("--term-blue","#60a5fa"),magenta:s("--term-magenta","#c084fc"),cyan:s("--term-cyan","#22d3ee"),white:s("--term-white","#e6e8ef"),brightBlack:s("--term-bright-black","#6b7284"),brightRed:s("--term-bright-red","#f87171"),brightGreen:s("--term-bright-green","#34d399"),brightYellow:s("--term-bright-yellow","#fbbf24"),brightBlue:s("--term-bright-blue","#60a5fa"),brightMagenta:s("--term-bright-magenta","#c084fc"),brightCyan:s("--term-bright-cyan","#22d3ee"),brightWhite:s("--term-bright-white","#ffffff")}}const _i=r.lazy(()=>ws(()=>import("./TerminalPanel-BeTRtKaL.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function Fi({notice:t,onDismiss:s}){const n=he(),[l,c]=r.useState(!1);r.useEffect(()=>{if(l)return;const a=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(a)},[l,t.id,t.level,s]);const i=t.level==="error"?On:t.level==="warning"?An:Pn;return e.jsxs("div",{className:`notice notice-${t.level}${l?" paused":""}`,role:"status",onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),children:[e.jsx(i,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:t.text}),e.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>s(t.id),children:e.jsx(Ce,{})})]})}const Ai=[],Zs=180,en=520,tn=240,sn=t=>`pi-web-ui:${t}-panel-width`;function ys(t){const s=Number(localStorage.getItem(sn(t)));return Number.isFinite(s)&&s>=Zs&&s<=en?s:tn}function bs({side:t,width:s,onResize:n}){const l=he(),c=r.useCallback(i=>{i.preventDefault();const a=i.clientX,o=s;let d=o;const m=h=>{const v=t==="left"?h.clientX-a:a-h.clientX;d=Math.min(en,Math.max(Zs,Math.round(o+v))),n(d)},x=()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",x),document.body.classList.remove("panel-resizing"),localStorage.setItem(sn(t),String(d))};window.addEventListener("pointermove",m),window.addEventListener("pointerup",x),document.body.classList.add("panel-resizing")},[t,s,n]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:l("dragToResize"),onPointerDown:c,onDoubleClick:()=>n(tn)})}function Oi(){var ke,fe,we,Me,Bt,Dt,$t,_t,Ft,At,Ot,Ht;const t=he(),{chat:s,send:n,dismissNotice:l,pushNotice:c,terminal:i}=da(),[a,o]=r.useState([]),[d,m]=r.useState(null),[x,h]=r.useState(!1),[v,C]=r.useState("chat"),N=r.useMemo(()=>s.plugins.filter(T=>{var H,X;return!((X=(H=s.settings)==null?void 0:H.disabledPlugins)!=null&&X.includes(T.id))}),[s.plugins,(ke=s.settings)==null?void 0:ke.disabledPlugins]),[_,M]=r.useState([]);r.useEffect(()=>ta(M),[]),r.useEffect(()=>{sa(N,s.pluginsEpoch)},[N,s.pluginsEpoch]);const[D,O]=r.useState(()=>ys("left")),[p,E]=r.useState(()=>ys("right")),P=r.useCallback(T=>O(T),[]),y=r.useCallback(T=>E(T),[]),[k,u]=r.useState(null),[L,U]=r.useState(()=>window.matchMedia("(max-width: 768px)").matches);r.useEffect(()=>{const T=window.matchMedia("(max-width: 768px)"),H=X=>U(X.matches);return T.addEventListener("change",H),()=>T.removeEventListener("change",H)},[]);const[G,J]=r.useState(!1),[te,oe]=r.useState(!1),[I,F]=r.useState(!1),[W,re]=r.useState(!1),[ge,R]=r.useState(!1);r.useEffect(()=>{const T=H=>{var Le,Wt;const X=H.detail,xe=(X==null?void 0:X.title)||"插件命令",ye=X==null?void 0:X.command;if(!ye||!s.ready)return;const Se={name:xe,command:ye,cwd:"${pwd}"},je=s.terminals.find(pt=>pt.title===xe);if(je)i.restart(je.id),n({type:"run_command",terminalId:je.id,conversationId:je.conversationId,command:Se,cols:80,rows:24});else{const pt=_e();i.create({id:pt,conversationId:s.activeConversationId||((Le=s.state)==null?void 0:Le.conversationId)||"",title:xe,cwd:((Wt=s.state)==null?void 0:Wt.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Se})}C("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",T),()=>window.removeEventListener("pi-web-ui:plugin-run-command",T)},[s,i,n]),r.useEffect(()=>{const T=H=>{!(H.ctrlKey||H.metaKey)||H.key.toLowerCase()!=="k"||(H.preventDefault(),R(X=>!X))};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[]);const[j,q]=r.useState(Js),{themes:S,theme:A,switchTheme:se}=$i(),de=r.useRef(null),f=r.useRef(null),B=r.useRef(0),ne=r.useRef(!1),g=r.useRef(s.terminals);r.useEffect(()=>{Si(j)},[j]),r.useEffect(()=>{var H;const T=g.current;g.current=s.terminals;for(const X of s.terminals){const xe=((H=X.command)==null?void 0:H.command)??"",ye=T.find(Se=>Se.id===X.id);!(ye!=null&&ye.running)||X.running||(xe.startsWith("pi remove ")?n({type:"extensions_reload"}):(xe.startsWith("pi-web-ui install ")||xe.startsWith("pi-web-ui uninstall "))&&n({type:"plugins_reload"}))}},[s.terminals,n]),r.useEffect(()=>{var X;const T=((X=s.state)==null?void 0:X.isStreaming)??!1,H=de.current;de.current=T,H!==null&&(!H&&T?Ve("start",j):H&&!T&&Ve("done",j))},[(fe=s.state)==null?void 0:fe.isStreaming,j]),r.useEffect(()=>{var H;const T=((H=s.dialog)==null?void 0:H.id)??null;T!==null&&T!==f.current&&Ve("question",j),f.current=T},[s.dialog,j]),r.useEffect(()=>{const T=[...s.notices].reverse().find(H=>H.level==="error");T&&T.id!==B.current&&(B.current=T.id,Ve("error",j))},[s.notices,j]);const z=(T,H,X,xe=!1,ye)=>{const Se=`${T}|${X}|${ye?`${ye.start}-${ye.end}`:""}`;o(je=>je.some(Le=>`${Le.path}|${Le.mode}|${Le.lines?`${Le.lines.start}-${Le.lines.end}`:""}`===Se)?je:[...je,{path:T,name:H,mode:X,isDir:xe,...ye?{lines:ye}:{}}])},V=T=>o(H=>H.filter(X=>X.key?X.key!==T:X.path!==T)),Z=r.useCallback(T=>(!T.type.startsWith("list_")&&!T.type.startsWith("get_")&&u(null),n(T)),[n]),ue=r.useRef(0),be=r.useRef(0),Q=T=>{var xe;const H=Date.now();(xe=s.state)!=null&&xe.model&&!s.state.model.vision&&H-be.current>1e4&&(be.current=H,c("warning",t("imageNotSupported")));const X=`paste-${++ue.current}`;o(ye=>[...ye,{path:"",key:X,name:T.name,mode:"inline",imageData:T.data,mimeType:T.mimeType}])},le=async T=>{for(const H of T){const X=await Hs(H);if(!X){c("error",t("imageLoadFailed",{name:H.name}));continue}Q(X)}},ee=20*1024*1024,Te=r.useRef(0),Ee=async T=>{if(T.size>ee){c("warning",t("fileTooLarge",{name:T.name,size:ee/1024/1024}));return}let H;try{H=(await new Promise((ye,Se)=>{const je=new FileReader;je.onload=()=>ye(je.result),je.onerror=()=>Se(je.error??new Error("read failed")),je.readAsDataURL(T)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",t("fileLoadFailed",{name:T.name}));return}const X=`upload-${++Te.current}`;o(xe=>[...xe,{path:"",key:X,name:T.name,mode:"inline",fileData:H,size:T.size,mimeType:T.type||void 0}])},Pe=async T=>{for(const H of T)Re(H.type)?await le([H]):await Ee(H)},Ae=r.useCallback((T,H,X)=>{n({type:"edit_message",messageId:T,text:H,attachments:X})},[n]),w=r.useCallback(()=>oe(!0),[]),$=r.useCallback(()=>o([]),[]),ae=r.useCallback(V,[]),ie=r.useCallback(le,[le]),me=r.useCallback(Pe,[Pe]),pe=(we=s.state)==null?void 0:we.model,ve=(Me=s.state)==null?void 0:Me.thinkingLevel,b=(Bt=s.state)==null?void 0:Bt.availableThinkingLevels,ce=r.useMemo(()=>pe?{model:pe,thinkingLevel:ve??"off",availableThinkingLevels:b??[]}:null,[pe,ve,b]),Y=r.useCallback(()=>{var T,H;return!s.ready||s.terminals.length!==0?!1:(i.create({id:_e(),conversationId:s.activeConversationId||((T=s.state)==null?void 0:T.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((H=s.state)==null?void 0:H.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,(Dt=s.state)==null?void 0:Dt.cwd,s.terminals.length,t,i]);return r.useEffect(()=>{if(ne.current){if(v!=="terminal"||s.terminals.length!==0){ne.current=!1;return}Y()&&(ne.current=!1)}},[s.terminals.length,Y,v]),e.jsxs("div",{className:"app",onDragOver:T=>{var H;Array.from(((H=T.dataTransfer)==null?void 0:H.types)??[]).includes("Files")&&(T.preventDefault(),h(!0))},onDragLeave:T=>{T.currentTarget.contains(T.relatedTarget)||h(!1)},onDrop:T=>{var ye,Se;if(h(!1),!Array.from(((ye=T.dataTransfer)==null?void 0:ye.types)??[]).includes("Files"))return;T.preventDefault();const H=Array.from(((Se=T.dataTransfer)==null?void 0:Se.files)??[]);if(H.length===0){c("warning",t("foldersNotSupported"));return}const X=H.filter(je=>Re(je.type)),xe=H.filter(je=>!Re(je.type));X.length>0&&le(X),xe.length>0&&Pe(xe)},children:[x&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(Vn,{chat:s,send:n,terminal:i,view:v,plugins:N,onViewChange:T=>{ne.current=T==="terminal"&&s.terminals.length===0,ne.current&&Y()&&(ne.current=!1),C(T),u(null)},onOpenPanel:u,onManageModels:()=>oe(!0),onOpenSettings:()=>F(!0),onOpenBgTasks:()=>re(!0),onOpenGlobalSearch:()=>R(!0),sound:j,onSoundChange:q,onSoundPreview:T=>Ve(T,j),themes:S,theme:A,onThemeChange:se}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(T=>e.jsx(Fi,{notice:T,onDismiss:l},T.id))}),e.jsxs("div",{className:"layout",style:{"--left-w":`${D}px`,"--right-w":`${p}px`},children:[k&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>u(null)}),e.jsxs("div",{className:`view-pane ${v==="chat"?"":"hidden"}`,children:[e.jsx("div",{className:`panel-drawer drawer-left ${k==="left"?"open":""}`,children:e.jsx(Gn,{send:Z,active:!L||k==="left",ready:s.ready,status:s.status,cwd:(($t=s.state)==null?void 0:$t.cwd)??"",sessionFile:((_t=s.state)==null?void 0:_t.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!L&&e.jsx(bs,{side:"left",width:D,onResize:P}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(ri,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:Ae,onKillBash:()=>n({type:"abort_bash"})},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(oi,{send:n,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId}),s.dialog&&e.jsx(ui,{dialog:s.dialog,send:n}),e.jsx(li,{send:n,ready:s.ready,streaming:((Ft=s.state)==null?void 0:Ft.isStreaming)??!1,messages:((At=s.state)==null?void 0:At.messages)??Ai,slashCommands:s.slashCommands,modelState:ce,models:s.models,modelsLoading:s.modelsLoading,attachments:a,onRemoveAttachment:ae,onAddImageFiles:ie,onAddLocalFiles:me,onNotice:c,onManageModels:w,onSent:$})]}),!L&&e.jsx(bs,{side:"right",width:p,onResize:y}),e.jsx("div",{className:`panel-drawer drawer-right ${k==="right"?"open":""}`,children:e.jsx(ya,{send:Z,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((Ot=s.state)==null?void 0:Ot.cwd)??"",onAttach:(T,H,X,xe)=>{u(null),z(T,H,X,xe)},onPreview:(T,H)=>{u(null),m({path:T,name:H})},onNotice:(T,H)=>c(T,H)})})]}),e.jsx("div",{className:`view-pane ${v==="terminal"?"":"hidden"}`,children:e.jsx(r.Suspense,{fallback:null,children:e.jsx(_i,{chat:s,send:n,terminal:i})})}),e.jsx("div",{className:`view-pane ${v==="git"?"":"hidden"}`,children:e.jsx(pi,{chat:s,send:n,terminal:i,active:v==="git",onSwitchToTerminal:()=>C("terminal")})}),_.map(T=>{const H=`plugin:${T.info.id}`;return e.jsx("div",{className:`view-pane ${v===H?"":"hidden"}`,children:e.jsx(hi,{entry:T,send:n})},T.info.id)})]}),e.jsx(ci,{chat:s,send:n}),d&&e.jsx(Ni,{file:d,content:s.fileContent,send:n,onAddLines:(T,H,X,xe)=>z(T,H,"lines",!1,{start:X,end:xe}),onAttach:(T,H,X)=>z(T,H,X),onClose:()=>m(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!G&&!te&&e.jsx(gi,{send:n,piConfigured:s.state.piConfigured,providers:s.providers,installResult:s.installResult,onClose:()=>J(!0)}),te&&e.jsx(vi,{send:n,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>oe(!1)}),I&&e.jsx(bi,{chat:s,send:n,terminal:i,onSwitchToTerminal:()=>C("terminal"),onClose:()=>F(!1)}),W&&e.jsx(ki,{servers:s.bgServers,send:n,onClose:()=>re(!1)}),ge&&e.jsx(wi,{send:n,sessions:s.sessions,projects:s.projects,cwd:((Ht=s.state)==null?void 0:Ht.cwd)??"",fileSearch:s.fileSearch,onClose:()=>R(!1),onSwitchSession:T=>{n({type:"switch_session",path:T})},onSwitchProject:T=>{n({type:"set_cwd",path:T})},onPreviewFile:(T,H)=>{m({path:T,name:H})}})]})}Jn();Xs(Ys());ln.createRoot(document.getElementById("root")).render(e.jsx(r.StrictMode,{children:e.jsx(qn,{children:e.jsx(Oi,{})})}));export{rt as F,vs as T,Ue as a,qi as b,Ui as c,Qt as d,$e as e,Ce as f,Sn as g,Je as h,_e as r,he as u};
|