pi-web-ui 0.64.1 → 0.64.2
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/attachments.js +13 -8
- package/dist/server/files-service.js +230 -38
- package/dist/server/index.js +46 -11
- package/package.json +1 -1
- package/web/dist/assets/{TerminalPanel-C5VIdPmn.js → TerminalPanel-BXISCcrQ.js} +1 -1
- package/web/dist/assets/index-BxuvIAJQ.js +326 -0
- package/web/dist/index.html +1 -1
- package/web/dist/assets/index-BmDs6ukf.js +0 -326
|
@@ -1,326 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-C5VIdPmn.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 Qe,a as l,j as e,M as an,b as ai,c as ri}from"./markdown-DRBrS2Nf.js";import{r as rn}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"]'))r(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"&&r(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 r(c){if(c.ep)return;c.ep=!0;const i=n(c);fetch(c.href,i)}})();var mt={},ys;function li(){if(ys)return mt;ys=1;var t=rn();return mt.createRoot=t.createRoot,mt.hydrateRoot=t.hydrateRoot,mt}var oi=li();const ci="modulepreload",di=function(t){return"/"+t},vs={},ui=function(s,n,r){let c=Promise.resolve();if(n&&n.length>0){let a=function(m){return Promise.all(m.map(y=>Promise.resolve(y).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};document.getElementsByTagName("link");const o=document.querySelector("meta[property=csp-nonce]"),u=(o==null?void 0:o.nonce)||(o==null?void 0:o.getAttribute("nonce"));c=a(n.map(m=>{if(m=di(m),m in vs)return;vs[m]=!0;const y=m.endsWith(".css"),f=y?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${f}`))return;const g=document.createElement("link");if(g.rel=y?"stylesheet":ci,y||(g.as="script"),g.crossOrigin="",g.href=m,u&&g.setAttribute("nonce",u),document.head.appendChild(g),y)return new Promise((v,T)=>{g.addEventListener("load",v),g.addEventListener("error",()=>T(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 ln={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ks=Qe.createContext&&Qe.createContext(ln),pi=["attr","size","title"];function mi(t,s){if(t==null)return{};var n,r,c=hi(t,s);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(r=0;r<i.length;r++)n=i[r],s.indexOf(n)===-1&&{}.propertyIsEnumerable.call(t,n)&&(c[n]=t[n])}return c}function hi(t,s){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(s.indexOf(r)!==-1)continue;n[r]=t[r]}return n}function xt(){return xt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var n=arguments[s];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},xt.apply(null,arguments)}function bs(t,s){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);s&&(r=r.filter(function(c){return Object.getOwnPropertyDescriptor(t,c).enumerable})),n.push.apply(n,r)}return n}function yt(t){for(var s=1;s<arguments.length;s++){var n=arguments[s]!=null?arguments[s]:{};s%2?bs(Object(n),!0).forEach(function(r){gi(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):bs(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function gi(t,s,n){return(s=fi(s))in t?Object.defineProperty(t,s,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[s]=n,t}function fi(t){var s=xi(t,"string");return typeof s=="symbol"?s:s+""}function xi(t,s){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,s);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function on(t){return t&&t.map((s,n)=>Qe.createElement(s.tag,yt({key:n},s.attr),on(s.child)))}function te(t){return s=>Qe.createElement(yi,xt({attr:yt({},t.attr)},s),on(t.child))}function yi(t){var s=n=>{var r=t.attr,c=t.size,i=t.title,a=mi(t,pi),o=c||n.size||"1em",u;return n.className&&(u=n.className),t.className&&(u=(u?u+" ":"")+t.className),Qe.createElement("svg",xt({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},n.attr,r,a,{className:u,style:yt(yt({color:t.color||n.color},n.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),i&&Qe.createElement("title",null,i),t.children)};return ks!==void 0?Qe.createElement(ks.Consumer,null,n=>s(n)):s(ln)}function vi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"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 ki(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]},{tag:"line",attr:{x1:"11",y1:"8",x2:"11",y2:"14"},child:[]},{tag:"line",attr:{x1:"8",y1:"11",x2:"14",y2:"11"},child:[]}]})(t)}function gt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"},child:[]}]})(t)}function Ee(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"18",y1:"6",x2:"6",y2:"18"},child:[]},{tag:"line",attr:{x1:"6",y1:"6",x2:"18",y2:"18"},child:[]}]})(t)}function cn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"},child:[]},{tag:"path",attr:{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"},child:[]}]})(t)}function js(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"},child:[]},{tag:"circle",attr:{cx:"9",cy:"7",r:"4"},child:[]},{tag:"path",attr:{d:"M23 21v-2a4 4 0 0 0-3-3.87"},child:[]},{tag:"path",attr:{d:"M16 3.13a4 4 0 0 1 0 7.75"},child:[]}]})(t)}function bi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"17 8 12 3 7 8"},child:[]},{tag:"line",attr:{x1:"12",y1:"3",x2:"12",y2:"15"},child:[]}]})(t)}function ji(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 9.9-1"},child:[]}]})(t)}function Be(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(t)}function et(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"4 17 10 11 4 5"},child:[]},{tag:"line",attr:{x1:"12",y1:"19",x2:"20",y2:"19"},child:[]}]})(t)}function ws(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"6"},child:[]},{tag:"circle",attr:{cx:"12",cy:"12",r:"2"},child:[]}]})(t)}function Ns(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"},child:[]},{tag:"line",attr:{x1:"7",y1:"7",x2:"7.01",y2:"7"},child:[]}]})(t)}function wi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"5"},child:[]},{tag:"line",attr:{x1:"12",y1:"1",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"23"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"},child:[]},{tag:"line",attr:{x1:"1",y1:"12",x2:"3",y2:"12"},child:[]},{tag:"line",attr:{x1:"21",y1:"12",x2:"23",y2:"12"},child:[]},{tag:"line",attr:{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"},child:[]},{tag:"line",attr:{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"},child:[]}]})(t)}function vt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]}]})(t)}function Ni(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"4",y1:"21",x2:"4",y2:"14"},child:[]},{tag:"line",attr:{x1:"4",y1:"10",x2:"4",y2:"3"},child:[]},{tag:"line",attr:{x1:"12",y1:"21",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"3"},child:[]},{tag:"line",attr:{x1:"20",y1:"21",x2:"20",y2:"16"},child:[]},{tag:"line",attr:{x1:"20",y1:"12",x2:"20",y2:"3"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"7",y2:"14"},child:[]},{tag:"line",attr:{x1:"9",y1:"8",x2:"15",y2:"8"},child:[]},{tag:"line",attr:{x1:"17",y1:"16",x2:"23",y2:"16"},child:[]}]})(t)}function kt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"3"},child:[]},{tag:"path",attr:{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"},child:[]}]})(t)}function dn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"22",y1:"2",x2:"11",y2:"13"},child:[]},{tag:"polygon",attr:{points:"22 2 15 22 11 13 2 9 22 2"},child:[]}]})(t)}function bt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"11",cy:"11",r:"8"},child:[]},{tag:"line",attr:{x1:"21",y1:"21",x2:"16.65",y2:"16.65"},child:[]}]})(t)}function Ci(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"},child:[]},{tag:"polyline",attr:{points:"17 21 17 13 7 13 7 21"},child:[]},{tag:"polyline",attr:{points:"7 3 7 8 15 8"},child:[]}]})(t)}function un(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"1 4 1 10 7 10"},child:[]},{tag:"path",attr:{d:"M3.51 15a9 9 0 1 0 2.13-9.36L1 10"},child:[]}]})(t)}function at(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"23 4 23 10 17 10"},child:[]},{tag:"polyline",attr:{points:"1 20 1 14 7 14"},child:[]},{tag:"path",attr:{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"},child:[]}]})(t)}function He(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"line",attr:{x1:"5",y1:"12",x2:"19",y2:"12"},child:[]}]})(t)}function Dl(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"5 3 19 12 5 21 5 3"},child:[]}]})(t)}function Si(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"},child:[]}]})(t)}function Cs(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"16.5",y1:"9.4",x2:"7.5",y2:"4.21"},child:[]},{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(t)}function Ti(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"19",cy:"12",r:"1"},child:[]},{tag:"circle",attr:{cx:"5",cy:"12",r:"1"},child:[]}]})(t)}function Ei(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"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 tt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"},child:[]}]})(t)}function Pi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"3",y1:"12",x2:"21",y2:"12"},child:[]},{tag:"line",attr:{x1:"3",y1:"6",x2:"21",y2:"6"},child:[]},{tag:"line",attr:{x1:"3",y1:"18",x2:"21",y2:"18"},child:[]}]})(t)}function Mi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"},child:[]}]})(t)}function Ri(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"15 3 21 3 21 9"},child:[]},{tag:"polyline",attr:{points:"9 21 3 21 3 15"},child:[]},{tag:"line",attr:{x1:"21",y1:"3",x2:"14",y2:"10"},child:[]},{tag:"line",attr:{x1:"3",y1:"21",x2:"10",y2:"14"},child:[]}]})(t)}function Ii(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M7 11V7a5 5 0 0 1 10 0v4"},child:[]}]})(t)}function Kt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"},child:[]},{tag:"path",attr:{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"},child:[]}]})(t)}function jt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polygon",attr:{points:"12 2 2 7 12 12 22 7 12 2"},child:[]},{tag:"polyline",attr:{points:"2 17 12 22 22 17"},child:[]},{tag:"polyline",attr:{points:"2 12 12 17 22 12"},child:[]}]})(t)}function Li(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12.01",y2:"8"},child:[]}]})(t)}function Di(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"},child:[]},{tag:"circle",attr:{cx:"8.5",cy:"8.5",r:"1.5"},child:[]},{tag:"polyline",attr:{points:"21 15 16 10 5 21"},child:[]}]})(t)}function Ai(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"3",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"3",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"14",y:"14",width:"7",height:"7"},child:[]},{tag:"rect",attr:{x:"3",y:"14",width:"7",height:"7"},child:[]}]})(t)}function Bi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"2",y1:"12",x2:"22",y2:"12"},child:[]},{tag:"path",attr:{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"},child:[]}]})(t)}function Ss(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M9 19c-5 1.5-5-2.5-7-3m14 6v-3.87a3.37 3.37 0 0 0-.94-2.61c3.14-.35 6.44-1.54 6.44-7A5.44 5.44 0 0 0 20 4.77 5.07 5.07 0 0 0 19.91 1S18.73.65 16 2.48a13.38 13.38 0 0 0-7 0C6.27.65 5.09 1 5.09 1A5.07 5.07 0 0 0 5 4.77a5.44 5.44 0 0 0-1.5 3.78c0 5.42 3.3 6.61 6.44 7A3.37 3.37 0 0 0 9 18.13V22"},child:[]}]})(t)}function ft(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"6",y1:"3",x2:"6",y2:"15"},child:[]},{tag:"circle",attr:{cx:"18",cy:"6",r:"3"},child:[]},{tag:"circle",attr:{cx:"6",cy:"18",r:"3"},child:[]},{tag:"path",attr:{d:"M18 9a9 9 0 0 1-9 9"},child:[]}]})(t)}function Ye(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"},child:[]}]})(t)}function _i(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"},child:[]},{tag:"polyline",attr:{points:"13 2 13 9 20 9"},child:[]}]})(t)}function pn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"},child:[]},{tag:"polyline",attr:{points:"14 2 14 8 20 8"},child:[]},{tag:"line",attr:{x1:"16",y1:"13",x2:"8",y2:"13"},child:[]},{tag:"line",attr:{x1:"16",y1:"17",x2:"8",y2:"17"},child:[]},{tag:"polyline",attr:{points:"10 9 9 9 8 9"},child:[]}]})(t)}function Wt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"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 Ut(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M12 20h9"},child:[]},{tag:"path",attr:{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"},child:[]}]})(t)}function wt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"},child:[]}]})(t)}function Zt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"},child:[]},{tag:"polyline",attr:{points:"7 10 12 15 17 10"},child:[]},{tag:"line",attr:{x1:"12",y1:"15",x2:"12",y2:"3"},child:[]}]})(t)}function rt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"4",y:"4",width:"16",height:"16",rx:"2",ry:"2"},child:[]},{tag:"rect",attr:{x:"9",y:"9",width:"6",height:"6"},child:[]},{tag:"line",attr:{x1:"9",y1:"1",x2:"9",y2:"4"},child:[]},{tag:"line",attr:{x1:"15",y1:"1",x2:"15",y2:"4"},child:[]},{tag:"line",attr:{x1:"9",y1:"20",x2:"9",y2:"23"},child:[]},{tag:"line",attr:{x1:"15",y1:"20",x2:"15",y2:"23"},child:[]},{tag:"line",attr:{x1:"20",y1:"9",x2:"23",y2:"9"},child:[]},{tag:"line",attr:{x1:"20",y1:"14",x2:"23",y2:"14"},child:[]},{tag:"line",attr:{x1:"1",y1:"9",x2:"4",y2:"9"},child:[]},{tag:"line",attr:{x1:"1",y1:"14",x2:"4",y2:"14"},child:[]}]})(t)}function Fi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 10 4 15 9 20"},child:[]},{tag:"path",attr:{d:"M20 4v7a4 4 0 0 1-4 4H4"},child:[]}]})(t)}function mn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"rect",attr:{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"},child:[]},{tag:"path",attr:{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"},child:[]}]})(t)}function $i(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"16 18 22 12 16 6"},child:[]},{tag:"polyline",attr:{points:"8 6 2 12 8 18"},child:[]}]})(t)}function Ts(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"polyline",attr:{points:"12 6 12 12 16 14"},child:[]}]})(t)}function hn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"13 17 18 12 13 7"},child:[]},{tag:"polyline",attr:{points:"6 17 11 12 6 7"},child:[]}]})(t)}function gn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"11 17 6 12 11 7"},child:[]},{tag:"polyline",attr:{points:"18 17 13 12 18 7"},child:[]}]})(t)}function dt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"18 15 12 9 6 15"},child:[]}]})(t)}function Nt(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 18 15 12 9 6"},child:[]}]})(t)}function Ge(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"6 9 12 15 18 9"},child:[]}]})(t)}function ut(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"20 6 9 17 4 12"},child:[]}]})(t)}function Hi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"},child:[]},{tag:"polyline",attr:{points:"22 4 12 14.01 9 11.01"},child:[]}]})(t)}function Et(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"},child:[]},{tag:"polyline",attr:{points:"3.27 6.96 12 12.01 20.73 6.96"},child:[]},{tag:"line",attr:{x1:"12",y1:"22.08",x2:"12",y2:"12"},child:[]}]})(t)}function Oi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"},child:[]},{tag:"path",attr:{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"},child:[]}]})(t)}function Ki(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"},child:[]},{tag:"path",attr:{d:"M13.73 21a2 2 0 0 1-3.46 0"},child:[]}]})(t)}function fn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"19",x2:"12",y2:"5"},child:[]},{tag:"polyline",attr:{points:"5 12 12 5 19 12"},child:[]}]})(t)}function xn(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"line",attr:{x1:"12",y1:"5",x2:"12",y2:"19"},child:[]},{tag:"polyline",attr:{points:"19 12 12 19 5 12"},child:[]}]})(t)}function Wi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"21 8 21 21 3 21 3 8"},child:[]},{tag:"rect",attr:{x:"1",y:"3",width:"22",height:"5"},child:[]},{tag:"line",attr:{x1:"10",y1:"12",x2:"14",y2:"12"},child:[]}]})(t)}function Ui(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"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 qi(t){return te({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"circle",attr:{cx:"12",cy:"12",r:"10"},child:[]},{tag:"line",attr:{x1:"12",y1:"8",x2:"12",y2:"12"},child:[]},{tag:"line",attr:{x1:"12",y1:"16",x2:"12.01",y2:"16"},child:[]}]})(t)}function zi(t){return t.map(s=>s.kind==="package"?`pi update npm:${s.name}`:`npm i -g ${s.name}@latest`).join("; ")}function Ue(){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 ze({trigger:t,open:s,onOpenChange:n,children:r,align:c="right",fit:i=!1,direction:a="down",menuClassName:o,menuRef:u,menuStyle:m}){const y=l.useRef(null);return l.useEffect(()=>{if(!s)return;const f=v=>{y.current&&!y.current.contains(v.target)&&n(!1)},g=v=>{v.key==="Escape"&&n(!1)};return document.addEventListener("mousedown",f),document.addEventListener("keydown",g),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",g)}},[s,n]),e.jsxs("div",{className:`dropdown ${c} ${i?"fit":""} ${a==="up"?"dd-up":""}`,ref:y,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>n(!s),"aria-expanded":s,children:[t,e.jsx(Ge,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:`dd-menu ${o??""}`,ref:u,style:m,children:r})]})}function Re({active:t,disabled:s=!1,title:n,onClick:r,children:c}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:n,onClick:r,children:c})}const yn="pi-web-ui:lang",Es={docTitle:"pi-web-ui — pi 编码智能体",cancel:"取消",ok:"确定",save:"保存",close:"关闭",widgetExpand:"点击放大查看完整输出",collapsePanel:"收起面板",expandPanel:"展开面板",dragToResize:"拖拽调整宽度 · 双击复位",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",allProviders:"全部",providers:"服务商",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",engineBadge:"引擎",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",cwdGoUp:"上级目录",cwdPickCurrent:"选择当前目录",cwdChoose:"选择",cwdEnter:"进入",cwdEmpty:"(空目录)",cwdNewFolder:"新建文件夹",cwdNewName:"文件夹名称",cwdCreate:"创建",cwdCancel:"取消",cacheHit:"缓存命中",cacheHitTip:"缓存读取 {read} · 缓存写入 {write} · 未命中 {miss}(共 {input} 输入 token)",tps:"t/s",rateTip:"实时生成速率(估算)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",placeholderStreaming:"智能体正在工作中…回车插队发送,或点「排队」等回答结束后发送",placeholderIdle:"给 pi 发送消息 — Enter 发送,/ 查看命令",placeholderConnecting:"正在连接服务器…",stopAgent:"停止智能体",stop:"停止",bgTasks:"后台任务",bgTasksTip:"AI 在后台启动的服务(npm run dev & 等)——可逐个停止或全部关闭,对话结束后仍保留",bgTasksEmpty:"暂无后台任务",bgTasksDesc:"AI 运行中启动并仍在监听的进程(按监听端口检测)",bgTaskPort:"端口",bgTaskPid:"PID",bgTaskSince:"启动",bgTaskStop:"停止",bgTaskStopAll:"全部关闭",bgTaskRefresh:"刷新",bgTaskJustNow:"刚刚",bgTaskMinutes:"{n} 分钟前",bgTaskHours:"{n} 小时前",bgTaskDays:"{n} 天前",stopBash:"停止",stopBashTip:"停止正在运行的 bash 命令(对话继续)",supplement:"排队",supplementTip:"加入队列:AI 回答完全结束后才发送(不打断)",queueSteerTag:"插队",queueFollowTag:"排队",queueRemoveTip:"移除此排队消息",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashPlugin:"插件",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",subagentBadge:"子代理",subagentTitle:"子代理 · {title}",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",deleteProject:"从最近项目移出",deleteProjectConfirm:"确认移出",deleteSession:"删除该对话记录(不可恢复)",deleteSessionConfirm:"确认删除",renameSession:"重命名该对话",renameSessionPlaceholder:"输入新名称…",renameSessionConfirm:"重命名",dismissConversation:"从运行列表移出(历史记录保留)",dismissConversationConfirm:"确认移出",collapseSection:"折叠",expandSection:"展开",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/Ctrl+Enter 提交 · Esc 取消",editAttachmentHint:"原附件已保留,可粘贴/拖入新图片或文件 · ⌘/Ctrl+Enter 提交 · Esc 取消",expandMsg:"展开",collapseMsg:"收起",toolCalls:"工具调用",bashRuns:"终端运行",images:"图片",update:"更新",updateTip:"检查并更新 pi-web-ui",currentVersion:"当前版本",latestVersion:"最新版本",checkingUpdate:"检查中…",checkUpdate:"检查更新",upToDate:"已是最新版本",updateAvailable:"发现新版本 v{version}",updateJustPublished:"v{version} 刚刚发布,npm 缓存可能尚未同步——若未检测到新版本,请稍后重新检查",updateNow:"在终端中更新",updateTabTitle:"更新 pi-web-ui",updateTerminalHint:"点击后会在可见终端中运行 npm i -g pi-web-ui@latest;完成后重启服务生效(pi-web-ui server restart)。",updatesAllTitle:"全部组件更新",updatesAllBadge:"{n} 个更新",updatesAllUpToDate:"全部组件均为最新",kindWebUi:"Web 界面",kindPiCore:"核心",kindPackage:"组件",updatesAllRefresh:"重新检查全部",updateCheckFailed:"检查失败",updateBtn:"更新",updateAllBtn:"全部更新",updatePkgTabTitle:"更新 {name}",updateAllTabTitle:"更新全部组件",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",fileNotFoundShort:"文件不存在",pluginMountFailed:"插件 {name} 挂载失败",liveOutputOmitted:`…[前 {n} 字符已省略]…
|
|
3
|
-
`,uploadToFolder:"上传文件到此文件夹",uploadToCurrentDir:"上传文件到当前目录",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",modelQuestion:"模型提问",modelQuestionCustom:"补充回答(可选)",modelQuestionSubmit:"提交回答",noOptions:"(无选项)",inputPlaceholder:"输入内容",questionTimeout:"⏳ 剩余 {s} 秒,超时将自动取消",questionTimeoutExpired:"提问已超时,正在恢复对话…",modelNoVision:"当前模型 {name} 不支持图片,请切换到 DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH 引擎使用运行时内置技能(dsh-skill),暂不支持在设置面板启停",dshExtensionsNote:"DSH 引擎无 pi 扩展体系,能力由运行时内置(MCP/subagent/goal/plan/skill 等)",dshReviewPromptNote:"DSH 无独立审查会话:此指令将随目标轮次附加到系统提示词,供模型在目标轮次中遵守",dshVisionHiddenNote:"DSH 引擎直接支持图片输入(仅 DeepSeek V4 Flash Vision (exp) 模型),无需视觉桥转写",dshNoReviewModel:"DSH 无独立审查模型:目标由模型自判定完成/受阻,轮次上限即自动迭代次数",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量",notifyHeader:"桌面通知",notifyEnable:"启用桌面通知(PWA)",notifyEnableDesc:"会话完成或需要你输入时,即使切到其他应用也会提醒(需授权,仅页面前台无焦点时触发)。",notifyDenied:"通知权限已被拒绝 —— 请在浏览器/系统设置里为本站点开启通知。",notifyUnsupported:"此浏览器不支持通知。",notifyDoneTitle:"任务完成",notifyDoneBody:"会话已完成,等待你的输入。",notifyQuestionTitle:"需要你回答",notifyQuestionBody:"pi 正在等你回答一个问题。",notifyErrorTitle:"出错了",notifyErrorBody:"一个会话报告了错误。","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-web-ui 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",cliReadyHint:"✅ 本地已检测到 pi agent,选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",directory:"目录",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",searchPlaceholder:"在对话中搜索…",searchNoResults:"无结果",searchModels:"搜索模型…",noModelMatches:"无匹配模型",modelUsedCount:"已用 {n} 次",searchGlobal:"搜索",searchGlobalTip:"全局搜索:对话 / 项目 / 文件(Ctrl+K)",gsPlaceholder:"搜索项目、历史对话、工作区文件…",gsHint:"输入关键词:搜索历史对话全文(含 AI 回复)、最近项目与当前项目的文件名",gsSessions:"对话",gsProjects:"项目",gsFiles:"文件",gsNoResults:"无匹配结果",gsSearching:"正在搜索…",gsTruncated:"匹配过多,仅显示部分结果",gsCurrentProject:"当前",gsOpenPreview:"打开文件预览",gsNavigate:"选择",gsOpen:"打开",gsCloseHint:"关闭",bgTaskCommand:"命令行",searchPrev:"上一个(Shift+Enter)",searchNext:"下一个(Enter)",searchClose:"关闭(Esc)",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","tpl.title":"提示词模板","tpl.hint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.clickCard":"点击填入输入框","tpl.editTpl":"编辑 / 删除模板","tpl.openPicker":"提示词模板(常用提示词,随时取用)","tpl.pickerTitle":"提示词模板","tpl.pickerHint":"点击卡片直接填入输入框,✏️ 可编辑或删除 · 也能新增自己的模板","tpl.add":"新建模板","tpl.addDesc":"把常用工作流存成模板","tpl.reset":"恢复默认模板","tpl.resetConfirm":"确认恢复默认?","tpl.builtin":"内置","tpl.custom":"自定义","tpl.newTitle":"新建提示词模板","tpl.editTitle":"编辑提示词模板","tpl.fieldIcon":"图标","tpl.fieldTitle":"标题","tpl.fieldTitlePh":"卡片上显示的短标题","tpl.fieldDesc":"说明","tpl.fieldDescPh":"一句话说明,显示在卡片上","tpl.fieldPrompt":"提示词","tpl.fieldPromptPh":"完整提示词 —— 发送给智能体的内容","tpl.required":"标题和提示词不能为空","tpl.save":"保存修改","tpl.fill":"填入输入框","tpl.fillTip":"填入输入框,可再编辑后发送","tpl.sendNow":"直接发送","tpl.sendTip":"立即作为新对话发送","tpl.delete":"删除","tpl.deleteTip":"删除这个自定义模板","tpl.remove":"移出模板库","tpl.removeTip":"把内置模板移出模板库,可在底部「恢复默认模板」找回","tpl.restore":"恢复默认","tpl.restoreTip":"撤掉你的修改,恢复内置默认","tpl.sk.setup":"仓库初始化","tpl.sk.setup.desc":"让仓库了解它的构建与约定","tpl.sk.setup.prompt":`请先扫描这个仓库,建立「其他工作流都能用」的基础上下文,输出一份简明报告:
|
|
4
|
-
|
|
5
|
-
1. 项目类型、技术栈与目录结构
|
|
6
|
-
2. 构建 / 测试 / 运行 / 格式化的具体命令
|
|
7
|
-
3. 代码约定与命名规范
|
|
8
|
-
4. 任务 / issue 的存放位置与格式
|
|
9
|
-
5. 目前已知的坑或遗留问题
|
|
10
|
-
|
|
11
|
-
先只报告,不修改任何文件。`,"tpl.sk.ask":"技能导航","tpl.sk.ask.desc":"告诉我该用哪个流程","tpl.sk.ask.prompt":"我先描述当前要解决的情况,你先判断最适合的工作流(需求澄清 / 拆解计划 / 测试驱动 / 排错 / 架构 / 审查 / 交接等),说明为什么推荐它、会怎么做,等我确认后按它执行。","tpl.sk.grilldocs":"需求拷问·落档","tpl.sk.grilldocs.desc":"边盘问需求边记录决策","tpl.sk.grilldocs.prompt":"动手前,请用拷问的方式向我盘问这个计划(一次一个问题),直到达成共识。同时把过程中的关键术语和已定决策记录下来(例如写入 CONTEXT.md 或 ADR 文件),让后续所有工作都基于同一套「共享语言」。每个问题先给出你的推荐答案。","tpl.sk.tospec":"转规格说明","tpl.sk.tospec.desc":"把讨论结果整理成规格书","tpl.sk.tospec.prompt":`请把我们在对话中已经达成的共识,整理成一份结构化的规格说明书:
|
|
12
|
-
|
|
13
|
-
1. 背景与目标
|
|
14
|
-
2. 明确的目标与非目标
|
|
15
|
-
3. 用户与使用场景
|
|
16
|
-
4. 边界条件与失败场景
|
|
17
|
-
5. 验收标准(怎样算完成)
|
|
18
|
-
6. 接口 / 数据结构概要
|
|
19
|
-
|
|
20
|
-
先输出规格让我评审,确认后再继续。`,"tpl.sk.totickets":"拆工单","tpl.sk.totickets.desc":"把规格拆成可构建的小任务","tpl.sk.totickets.prompt":`请把这份规格说明拆成一组小工单,供逐个构建:
|
|
21
|
-
|
|
22
|
-
1. 每个工单足够小、可独立验收
|
|
23
|
-
2. 标注依赖顺序(哪些必须先做)
|
|
24
|
-
3. 每个工单含:做什么、验收标准、涉及文件
|
|
25
|
-
4. 识别出可并行的工单
|
|
26
|
-
|
|
27
|
-
先输出工单列表,我确认顺序后再执行。`,"tpl.sk.implement":"规格落地","tpl.sk.implement.desc":"按规格测试优先实现","tpl.sk.implement.prompt":`请按这份规格说明实现,测试优先:
|
|
28
|
-
|
|
29
|
-
1. 先为每个工单写会失败的测试(覆盖正常、边界、错误分支)
|
|
30
|
-
2. 用最小实现让测试通过
|
|
31
|
-
3. 重构并保持测试通过
|
|
32
|
-
4. 逐工单推进,每完成一个简要汇报
|
|
33
|
-
|
|
34
|
-
最后对照验收标准逐条确认。`,"tpl.sk.codeview":"代码审查","tpl.sk.codeview.desc":"对照规格与标准审查 diff","tpl.sk.codeview.prompt":`请审查最近改动的 diff:
|
|
35
|
-
|
|
36
|
-
1. 对照规格说明,实现是否完全覆盖、有无偏差
|
|
37
|
-
2. 正确性:边界、空值、并发与时序
|
|
38
|
-
3. 安全:输入校验、注入、敏感信息
|
|
39
|
-
4. 性能与可读性:是否遵循项目约定
|
|
40
|
-
5. 测试:关键路径是否有覆盖
|
|
41
|
-
|
|
42
|
-
按严重程度分级列出问题,每条给出具体修改建议。`,"tpl.sk.wayfinder":"大任务地图","tpl.sk.wayfinder.desc":"把大工程画成决策地图","tpl.sk.wayfinder.prompt":`这是一个大型任务。请先把它画成一张「决策地图」:
|
|
43
|
-
|
|
44
|
-
1. 拆出所有需要做出的决策点及其依赖关系
|
|
45
|
-
2. 为每个决策点列出选项、权衡与你的推荐
|
|
46
|
-
3. 标注哪些可以并行推进、哪些必须串行
|
|
47
|
-
4. 输出一份路径规划,我逐项确认后再动手。`,"tpl.sk.prototype":"快速原型","tpl.sk.prototype.desc":"用一次性代码验证设计假设","tpl.sk.prototype.prompt":`请针对这个设计问题写一个最小原型来验证假设:
|
|
48
|
-
|
|
49
|
-
1. 只验证关键假设,不做完整实现
|
|
50
|
-
2. 用最简单的方式(可硬编码、可牺牲边界情况)
|
|
51
|
-
3. 运行并告诉我结论:假设成立吗?有哪些权衡?
|
|
52
|
-
4. 验证完的原型可以删除,或等确认后再正式实现。`,"tpl.sk.research":"有据调研","tpl.sk.research.desc":"读一手来源给出带引用的答案","tpl.sk.research.prompt":`请调研这个问题,优先读一手来源(官方文档 / 源码 / 规范):
|
|
53
|
-
|
|
54
|
-
1. 给出带来源链接的答案
|
|
55
|
-
2. 明确区分:事实、合理推断、仍不确定
|
|
56
|
-
3. 列出主要选项及其权衡
|
|
57
|
-
4. 避免用二手内容拼凑,找不到就直接说没找到。`,"tpl.sk.arch":"架构体检","tpl.sk.arch.desc":"找出值得重构的模块(报告)","tpl.sk.arch.prompt":`对整个代码库做一次架构体检:
|
|
58
|
-
|
|
59
|
-
1. 找出「深模块被破坏」的迹象:过长的函数与类、明显的重复、命名混乱、隐藏的耦合
|
|
60
|
-
2. 按严重程度与影响范围分级,输出一份可视化改进报告
|
|
61
|
-
3. 对每一项给出最小可行的重构方案与理由
|
|
62
|
-
4. 先报告再动手,重构前确认范围。`,"tpl.sk.debug":"系统化排错","tpl.sk.debug.desc":"从可复现的失败开始诊断","tpl.sk.debug.prompt":`请系统化诊断这个 bug:
|
|
63
|
-
|
|
64
|
-
1. 先复现,给出可复现的步骤或输入(没有就先造最小复现)
|
|
65
|
-
2. 二分或排除法缩小范围到具体模块
|
|
66
|
-
3. 提出假设,用日志 / 断言 / 最小样例验证,不凭感觉改
|
|
67
|
-
4. 定位根因后解释,再做最小修复
|
|
68
|
-
5. 补回归测试防止复发。`,"tpl.sk.merge":"解决合并冲突","tpl.sk.merge.desc":"逐个 hunk 完成合并/变基","tpl.sk.merge.prompt":`请帮我解决这个合并 / 变基冲突:
|
|
69
|
-
|
|
70
|
-
1. 逐个冲突 hunk 处理,先读懂双方各自的意图
|
|
71
|
-
2. 选择或合并出保留正确语义的代码,不盲目取一边
|
|
72
|
-
3. 处理完运行测试与构建确认没问题
|
|
73
|
-
4. 最后总结每处冲突的取舍原因。`,"tpl.sk.triage":"工单分流","tpl.sk.triage.desc":"把原始 issue 整理成可领取的工作","tpl.sk.triage.prompt":`请把这些原始 issue / 反馈整理成可执行的工作项:
|
|
74
|
-
|
|
75
|
-
1. 去重、合并相关的条目
|
|
76
|
-
2. 分类(bug / 功能 / 改进 / 问题)
|
|
77
|
-
3. 按影响与紧急度标优先级
|
|
78
|
-
4. 每个工作项补上:复现信息或期望、验收标准
|
|
79
|
-
|
|
80
|
-
输出整理后的清单。`,"tpl.sk.wizard":"设置向导","tpl.sk.wizard.desc":"生成引导人类完成设置的脚本","tpl.sk.wizard.prompt":`请为一个需要手动操作的设置流程生成一个引导向导(脚本或文档):
|
|
81
|
-
|
|
82
|
-
1. 一步步引导,每步说明为什么
|
|
83
|
-
2. 每步带校验,输错给出可操作的提示
|
|
84
|
-
3. 支持撤销 / 回退到上一步
|
|
85
|
-
4. 结束时做一次自检并给出验证方法。`,"tpl.sk.grillme":"需求拷问","tpl.sk.grillme.desc":"动手前盘问对齐想法","tpl.sk.grillme.prompt":`开始之前,请不遗余力地盘问我这个想法的每一个方面,直到我们达成共识(一次只问一个问题,每个问题先给推荐答案):
|
|
86
|
-
|
|
87
|
-
1. 目标与非目标
|
|
88
|
-
2. 用户与场景
|
|
89
|
-
3. 边界与失败模式
|
|
90
|
-
4. 约束与依赖
|
|
91
|
-
5. 验收标准
|
|
92
|
-
|
|
93
|
-
达成共识后再给实现计划,等确认再写代码。`,"tpl.sk.handoff":"交接","tpl.sk.handoff.desc":"把长会话写成交接文档","tpl.sk.handoff.prompt":`请把当前会话整理成一份交接文档,让另一个 agent / 同事能无缝继续:
|
|
94
|
-
|
|
95
|
-
1. 背景与目标
|
|
96
|
-
2. 已完成的工作与关键决策(附原因)
|
|
97
|
-
3. 未完成项与下一步
|
|
98
|
-
4. 已知风险与待确认问题
|
|
99
|
-
5. 如何验证当前状态(命令等)
|
|
100
|
-
|
|
101
|
-
输出为结构化文档。`,"tpl.sk.questionnaire":"转问卷","tpl.sk.questionnaire.desc":"把开放问题变成可填问卷","tpl.sk.questionnaire.prompt":`请把需要别人提供的信息整理成一份可填写的问卷:
|
|
102
|
-
|
|
103
|
-
1. 每个问题说明背景和用途
|
|
104
|
-
2. 标注必填 / 选填
|
|
105
|
-
3. 给出示例答案降低理解成本
|
|
106
|
-
4. 分组排序,先简单后复杂
|
|
107
|
-
|
|
108
|
-
输出一份文档,对方可以照着填。`,"tpl.sk.teach":"持续学习","tpl.sk.teach.desc":"跨多次会话循序渐进学习","tpl.sk.teach.prompt":`请按循序渐进的方式教我:
|
|
109
|
-
|
|
110
|
-
1. 先定学习路径和目标
|
|
111
|
-
2. 一次只讲一小节,讲完给个小练习
|
|
112
|
-
3. 基于上一节的内容递进,主动提问确认理解
|
|
113
|
-
4. 每节结束总结要点
|
|
114
|
-
|
|
115
|
-
适合跨多次会话推进。`,"tpl.sk.ww":"说人话","tpl.sk.ww.desc":"用大白话重讲刚才的解释","tpl.sk.ww.prompt":`请把刚才的解释用最简单的语言重新讲一遍:
|
|
116
|
-
|
|
117
|
-
1. 避免术语,必须用时先给一句话定义
|
|
118
|
-
2. 用类比或具体例子说明
|
|
119
|
-
3. 明确指出哪部分仍是猜测 / 不确定
|
|
120
|
-
4. 用最短的话说完核心意思。`,"tpl.sk.wfa":"写给 agent 的文档","tpl.sk.wfa.desc":"按 agent 易读的原则写文档","tpl.sk.wfa.prompt":`请按「写给 agent 阅读」的原则写这份文档 / 说明:
|
|
121
|
-
|
|
122
|
-
1. 目标与使用场景写在最前
|
|
123
|
-
2. 指令具体、可验证,避免歧义和空话
|
|
124
|
-
3. 给正反例帮助理解
|
|
125
|
-
4. 结构化:标题、步骤、清单
|
|
126
|
-
5. 标注哪些是硬性要求、哪些是可选。`,"tpl.sk.codesign":"深模块设计","tpl.sk.codesign.desc":"用深模块原则审查与设计","tpl.sk.codesign.prompt":`请用「深模块」设计原则审查 / 设计:
|
|
127
|
-
|
|
128
|
-
1. 识别模块对外暴露的接口是否比内部实现更简单
|
|
129
|
-
2. 找出把复杂度泄漏到外部的模块
|
|
130
|
-
3. 给出每个模块的职责边界与改进方案
|
|
131
|
-
4. 平衡内聚与复用,避免过度抽象
|
|
132
|
-
|
|
133
|
-
输出审查结论与重构建议。`,"tpl.sk.domain":"领域建模","tpl.sk.domain.desc":"打磨项目用词并写下来","tpl.sk.domain.prompt":`请帮我梳理这个项目的领域语言:
|
|
134
|
-
|
|
135
|
-
1. 找出核心术语及当前叫法
|
|
136
|
-
2. 识别同词异义 / 异词同义造成的混乱
|
|
137
|
-
3. 统一推荐用词,写进术语表
|
|
138
|
-
4. 说明每个术语的边界(不是什么)
|
|
139
|
-
|
|
140
|
-
输出一份领域术语表。`,"tpl.sk.grilling":"拷问流程","tpl.sk.grilling.desc":"用拷问压测一个计划","tpl.sk.grilling.prompt":`请对下面这个计划做压力测试(拷问):
|
|
141
|
-
|
|
142
|
-
1. 逐项检查假设:如果它是错的会怎样?
|
|
143
|
-
2. 找漏洞:边界、失败模式、依赖、时序
|
|
144
|
-
3. 质疑决策:为什么这样?有没有更简单的路?
|
|
145
|
-
4. 每次只提出一个最尖锐的问题,等我回答
|
|
146
|
-
|
|
147
|
-
直到这个计划经得起推敲。`,"tpl.sk.tdd":"测试驱动","tpl.sk.tdd.desc":"红-绿-重构的规则","tpl.sk.tdd.prompt":`请用 TDD(红-绿-重构)完成:
|
|
148
|
-
|
|
149
|
-
1. 先写会失败的测试,覆盖正常路径、边界与错误分支
|
|
150
|
-
2. 用最小实现让测试通过
|
|
151
|
-
3. 重构并保持测试通过
|
|
152
|
-
|
|
153
|
-
避免三种反模式:与实现耦合的测试、空洞断言(永远为真)、横向切片(只测表面)。每步汇报并运行测试。`,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})",exitBanner:"[进程已退出,退出码 {code}]",closeTerminal:"关闭终端",renameTerminal:"重命名终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",aiBashGroup:"终端接管 bash",exampleName:"例如:启动开发服务器",exampleCommand:"例如:npm run dev",scmTab:"Git",scmTitle:"源代码管理",scmRefreshTip:"重新查询 Git 状态与差异",scmCurrentBranch:"当前分支",scmUpstreamGone:"上游已删除",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"分离 HEAD",scmSelectBranch:"选择分支…",scmRemoteBranches:"远程分支",scmStageTip:"暂存 {path}",scmUnstageTip:"取消暂存 {path}",scmSwitch:"切换",scmSwitchBranch:"切换分支",scmSwitchBranchTip:"在终端中执行 git checkout {branch}",scmPush:"推送",scmPushTip:"在终端中执行 git push",scmPull:"拉取",scmPullTip:"在终端中执行 git pull",scmCommit:"提交",scmCommitTip:'在终端中执行 git commit -m "…"(仅提交已暂存的更改)',scmCommitAll:"全部提交",scmCommitAllTip:'在终端中执行 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}",scmQueryFailedShort:"查询失败",pluginCommandFallback:"插件命令",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"只需填入 API 密钥",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",cloneProvider:"添加密钥",cloning:"添加中",cloneProviderTitle:"为该供应商添加第二把密钥(自动复制 baseUrl 与模型列表,可改名后保存)",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",addKey:"添加密钥",addKeyPlaceholder:"粘贴密钥值…",keyNamePh:"名称(可留空,如 备用)",providerIdPlaceholder:"供应商 ID",baseUrlExamplePh:"baseUrl 链接,如 https://api.opencode.ai/zen/v1 或 http://127.0.0.1:4096",saveAllBatch:"一键保存全部({n})",netDisconnected:"网络连接已断开,请重连后重试",advancedEdit:"高级编辑",batchCreateProviders:"批量创建供应商({n}个接口)",secondKeyTitle:"为 {api} · {baseUrl} · {n} 个模型添加第二把密钥,只需指定新供应商名字和密钥即可。",noBaseUrlShort:"(无 baseUrl)",providerNameLabel:"供应商名字",providerNameHint:"(新 ID,如 opencode-2)",apiKeyLabel:"API 密钥",secondKeyPlaceholder:"sk-… 第二把 key",batchDesc:"该供应商含多种接口({apis}),已按接口拆分为 {n} 个自定义供应商,分别保存后才能让所有模型(如 muse-spark)都可用。统一填入第二把 API 密钥后一键保存。",batchKeyLabel:"统一 API 密钥(将应用到全部 {n} 个供应商)",modelsCountShort:"{n} 个模型:",noKeyYet:"尚无密钥,添加一把即可用",activateKey:"设为当前",removeKey:"移除",removeKeyConfirm:"确定移除该密钥?移除后需重新配置才能使用。",customProviders:"自定义服务商",customDesc:"用于 Ollama / vLLM / 兼容 OpenAI 的代理等,写入 pi 的 models.json,保存后热重载、立即生效。",noCustomProviders:"还没有自定义服务商",modelsCount:"{n} 个模型",addProvider:"新增服务商",providerId:"服务商 ID",providerIdHint:"(必填,如 ollama / my-proxy)",displayName:"显示名",displayNamePh:"我的代理",apiType:"API 类型",baseUrlHint:"(OpenAI 兼容端点)",apiKeyHint:"sk-…(可留空,用 auth.json 的密钥)",authHeader:"自动添加 Authorization 请求头",modelsTitle:"模型",modelIdReq:"模型 ID(必填)",text:"文本",textImage:"文本+图片",contextWindow:"上下文",maxOutput:"最大输出",removeModel:"移除模型",addModel:"添加模型",deleteProviderConfirm:"删除服务商 {id} 及其 {n} 个模型?",fetchModels:"自动获取模型列表",fetchModelsHint:"从 baseUrl 的 /models 接口自动拉取模型 ID(服务端请求,不受 CORS 限制)",fetchingModels:"获取中…",fetchModelsOk:"已获取 {n} 个模型",fetchModelsEmpty:"接口未返回任何模型",fetchModelsErr:"获取失败:{msg}",fetchModelsNeedBaseUrl:"请先填写 baseUrl 再获取",goalBarTitle:"目标",goalBarPlaceholder:"设定一个目标,agent 完成后自动审查…",goalBarSet:"开始",goalBarClear:"取消",goalBarLocked:"锁定:应用到后续所有回合",goalBarUnlocked:"仅本回合(改完自动清除)",goalBarReviewModel:"审查模型",goalBarUseMainModel:"使用主模型",goalBarMaxRounds:"最大轮数",goalBarMaxRoundsTip:"最大审查重改轮数;0 或不填 = 不限(持续改到通过)",goalBarUnlimitedShort:"不限",goalBarReviewing:"审查中…",goalBarRound:"第 {n} 轮",goalBarActive:"目标生效中",goalBarPassed:"已通过",goalBarFailed:"未通过",goalBarStatusPending:"等待生成…",goalWizardBtn:"AI 提炼",goalWizardTip:"让 AI 通过问卷调研细化需求,收敛为目标",goalWizardRunning:"目标调研中",goalWizardAnswer:"回答",goalWizardCard:"目标调研",settings:"设置",settingsTitle:"设置",settingsDesc:"修改立即生效:系统提示词、技能与插件开关会重建当前会话;审查提示词与审查技能只影响后续目标审查(回复进行中则主会话变更自动延迟)。",settingsSystemPrompt:"系统提示词",settingsPromptHistory:"输入历史",settingsPromptHistoryDesc:"用 ↑↓ 在输入框循环历史提问,全局跨对话共享(localStorage)",promptHistoryMax:"最大条数",promptHistoryMaxHint:"超过上限时最旧的自动丢弃,可设 1–500",promptHistoryCharLimit:"限制单条字数",promptHistoryCharLimitHint:"开启后超长输入截断后保存,避免大段粘贴占满存储",promptHistoryCharLimitPlaceholder:"最大字数(100–20000)",promptHistoryClear:"清空历史",promptHistoryClearConfirm:"确认清空?",promptHistoryCleared:"已清空输入历史",promptHistoryCount:"当前 {n} 条",promptHistoryEmpty:"暂无历史记录,上/下键暂无可循环内容",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:"转写提示词",settingsMarkers:"标记工具",settingsMarkersDesc:"让 AI 用 [[todo:...]] / [[svc:...]] / [[notify:...]] / [[conv:rename:...]] 内联标记在正文里改状态,无需工具往返。全局关闭则全部停用;分组开关可细粒度控制。",markersEnabled:"启用标记工具(全局)",markersEnabledDesc:"关闭后 AI 不再收到任何标记引导,解析也跳过(所有标记原文原样保留,不执行)。",markersOffHint:"已全局关闭:所有标记停用,AI 不会写标记,也不会触发任务/重命名等副作用。",markerGroupTodo:"任务标记 todo",markerGroupSvc:"后台服务标记 svc",markerGroupNotify:"提醒标记 notify",markerGroupRename:"重命名标记 conv/rename",markerRenameTip:"[[conv:rename:新标题]] 或 [[rename:set:标题]] 重命名当前对话(标题 ≤80 字)",settingsTerminalTools:"终端工具",terminalToolsEnabled:"启用持久终端工具",settingsTerminalToolsDesc:"让 AI 在交互式程序(REPL/vim)、长驻服务、需要持续观察输出或你要求在可见终端操作时,使用内置终端;普通命令仍走一次性 bash 工具",terminalToolsOffHint:"已关闭:AI 无法使用 terminal_* 工具,也不会收到相关使用引导",settingsMessageDisplay:"消息显示",thinkingWrap:"完整显示思考",thinkingWrapDesc:"开启:思考内容始终完整展开并自动换行(流式推理过程也实时可见);关闭:折叠成一行摘要,流式中一行实时显示最新文本",toolsWrap:"完整显示工具",toolsWrapDesc:"开启:工具调用始终完整展开显示参数和输出;关闭:默认折叠,点击展开",terminalBashTakeover:"终端接管 bash",terminalBashTakeoverDesc:"此开关决定 bash 是否覆盖为终端版:关 = 原生 SDK bash(纯进程、不开终端);开 = 跑进可见终端,且 persist 参数在本开关的基础上决定一次性(false,命令跑完进程退出、输出留档)还是持久(true,shell 状态跨调用保留、静默自动转后台并通知 AI)",terminalBashIdleMs:"静默转后台阈值(毫秒)",terminalBashIdleMsDesc:"持久终端模式下,命令连续无输出达到该时长即不再阻塞等待,转入后台继续运行并通知 AI;0 = 一直等到命令结束(默认 15000)",visionBridgePromptPlaceholder:"输入自定义转写提示词…(留空 = 使用内置默认提示词,失焦后自动应用)",visionBridgePromptAppendHint:"追加模式:自定义内容拼接到内置转写提示词末尾(推荐,保留默认的逐字转写约束)。",visionBridgePromptReplaceHint:"替换模式:完全用自定义内容替换内置转写提示词。切换后输入框会显示内置默认提示词,可直接修改;不改动失焦则仍使用默认。",uninstallExt:"卸载",uninstallConfirm:"确认卸载?",uninstallConfirmHint:"再次点击确认,将在终端执行 pi remove",uninstallHint:"通过可见终端执行 pi remove 卸载此包,完成后自动刷新列表",uninstallTitle:"卸载",pluginUpdate:"更新",pluginUpdateHint:"从安装来源重新拉取并覆盖安装(保留 config.json 配置),完成后自动重载插件列表",pluginUninstallHint:"在可见终端执行 pi-web-ui uninstall 卸载此插件(再次点击确认),完成后自动刷新列表",settingsExtensions:"插件",settingsUiPlugins:"界面插件",noUiPlugins:"未安装界面组件(<dataDir>/plugins/)",dshPatches:"DSH 用户补丁",dshPatchesDesc:"启动时按文件名序加载的 Cordis patch(<dataDir>/dsh-patches/*.yml)。新增/修改后点「重扫」重启运行时生效;失败的文件会被跳过并打印到运行时 stderr。",dshPatchesRescan:"重扫",dshPatchesRescanHint:"重新扫描补丁目录并重启 DSH 运行时使新补丁生效",dshPatchesEmpty:"未放置补丁文件",dshPatchesPath:"补丁目录:",uiPluginNoSource:"手工安装,无来源信息,无法在线更新",uiPluginPerms:"能力声明",pluginSettingsSave:"保存插件设置",pluginSettingsSaving:"保存中…",pluginSettingsReset:"恢复默认",settingsPresets:"预设",settingsSubagentTemplates:"子代理模板",settingsSubagentTemplatesDesc:"配置子代理预设(角色系统提示词 + 技能/扩展白名单)。AI 派生子代理时可选用模板(subagent_spawn 的 template 参数),也可不传按默认运行;停用的模板保留在面板但对 AI 不可见。",noSubagentTemplates:"还没有子代理模板。AI 派生子代理时可选用模板(角色提示词 + 技能/扩展白名单),也可以不传 template 按默认配置运行。",subagentTemplateNew:"新建模板",subagentTemplateEdit:"编辑",subagentTemplateClosed:"已停用",tplDefaultBadge:"默认",subagentTemplateOffHint:"关闭的模板保留在面板、可随时重新启用,但 AI 工具查询不到、不能选择",subagentTemplateEnable:"启用",subagentTemplateDisable:"停用",tplNamePlaceholder:"模板名(AI 用 subagent_spawn 的 template 参数引用)…",tplDescriptionPlaceholder:"简介(AI 据此判断适用场景)…",tplPromptModeLabel:"系统提示词模式",tplSystemPromptLabel:"系统提示词",tplSystemPromptPlaceholder:"模板角色系统提示词…(append 模式可留空)",tplWhitelistHint:"白名单:勾选 = 子代理只启用这些;全部不勾 = 跟随主会话设置",tplSkillsLabel:"技能白名单",tplExtensionsLabel:"扩展白名单",tplSave:"保存模板",tplCancel:"取消编辑",tplDelete:"删除模板",tplInherit:"跟随主会话",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},Ps={docTitle:"pi-web-ui — pi coding agent",cancel:"Cancel",ok:"OK",save:"Save",close:"Close",widgetExpand:"Click to view full output",collapsePanel:"Collapse panel",expandPanel:"Expand panel",dragToResize:"Drag to resize · double-click to reset",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",githubRepo:"GitHub repository (xing-shuyin/pi-web-ui)",copy:"Copy",viewSwitch:"Switch view",chat:"Chat",terminal:"Terminal",selectModel:"Select model",availableModels:"Available models",allProviders:"All",providers:"Providers",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",engineBadge:"Engine",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",cwdGoUp:"Up one level",cwdPickCurrent:"Select this folder",cwdChoose:"Select",cwdEnter:"Enter",cwdEmpty:"(empty)",cwdNewFolder:"New folder",cwdNewName:"Folder name",cwdCreate:"Create",cwdCancel:"Cancel",cacheHit:"Cache hit",cacheHitTip:"read {read} · write {write} · miss {miss} (of {input} input tokens)",tps:"t/s",rateTip:"Live generation rate (estimated)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",placeholderStreaming:"The agent is working… press Enter to steer, or click Queue to send after the reply finishes",placeholderIdle:"Message pi — Enter to send, / for commands",placeholderConnecting:"Connecting to server…",stopAgent:"Stop agent",stop:"Stop",bgTasks:"Background tasks",bgTasksTip:"Servers the AI started in the background (npm run dev & etc.) — stop them individually or all at once; they survive the conversation",bgTasksEmpty:"No background tasks",bgTasksDesc:"Processes the AI started that are still listening (detected by port)",bgTaskPort:"Port",bgTaskPid:"PID",bgTaskSince:"Started",bgTaskStop:"Stop",bgTaskStopAll:"Stop all",bgTaskRefresh:"Refresh",bgTaskJustNow:"just now",bgTaskMinutes:"{n} min ago",bgTaskHours:"{n} hr ago",bgTaskDays:"{n} days ago",stopBash:"Stop",stopBashTip:"Stop the running bash command (conversation continues)",supplement:"Queue",supplementTip:"Add to queue: sent only after the whole run finishes (no interruption)",queueSteerTag:"Steer",queueFollowTag:"Queued",queueRemoveTip:"Remove this queued message",sendTip:"Send (Enter)",slashCommands:"Commands",slashMenuHint:"↑↓ select · Enter/Tab complete",slashHelpTitle:"pi commands",slashHelpHint:"Type / anytime to open the command list",slashLoading:"Loading commands… (available once connected)",slashBuiltin:"Builtin",slashExtension:"Extension",slashPrompt:"Template",slashSkill:"Skill",slashPlugin:"Plugin",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",subagentBadge:"Subagent",subagentTitle:"Subagent · {title}",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",renameSession:"Rename this chat",renameSessionPlaceholder:"Type a new name…",renameSessionConfirm:"Rename",dismissConversation:"Dismiss from running (keep in history)",dismissConversationConfirm:"Confirm dismiss",collapseSection:"Collapse",expandSection:"Expand",emptyChat:"Empty chat",editReask:"Edit & re-ask",editReaskTip:"Edit this question and re-ask from here (forks a new conversation; the original is kept)",reaskFromHere:"Re-ask from here",editPlaceholder:"Edit the question…",editHint:"⌘/Ctrl+Enter to submit · Esc to cancel",editAttachmentHint:"Original attachments kept — paste/drop images or files · ⌘/Ctrl+Enter to submit · Esc to cancel",expandMsg:"Expand",collapseMsg:"Collapse",toolCalls:"tool calls",bashRuns:"bash runs",images:"images",update:"Update",updateTip:"Check & update pi-web-ui",currentVersion:"Current version",latestVersion:"Latest version",checkingUpdate:"Checking…",checkUpdate:"Check for updates",upToDate:"You're up to date",updateAvailable:"New version v{version} available",updateJustPublished:"v{version} was just published — npm cache may lag; if the new version isn't detected yet, re-check in a moment",updateNow:"Update in terminal",updateTabTitle:"Update pi-web-ui",updateTerminalHint:"Clicking runs npm i -g pi-web-ui@latest in a visible terminal; restart the service afterwards to take effect (pi-web-ui server restart).",updatesAllTitle:"Component updates",updatesAllBadge:"{n} updates",updatesAllUpToDate:"All components up to date",kindWebUi:"Web UI",kindPiCore:"Core",kindPackage:"Package",updatesAllRefresh:"Re-check all",updateCheckFailed:"Check failed",updateBtn:"Update",updateAllBtn:"Update all",updatePkgTabTitle:"Update {name}",updateAllTabTitle:"Update all components",rootDir:"Root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",previewFile:"Preview",downloadFile:"Download file",downloadFailed:"Download failed: {error}",fileNotFoundShort:"File not found",pluginMountFailed:"Plugin {name} failed to mount",liveOutputOmitted:`…[{n} chars omitted above]…
|
|
154
|
-
`,uploadToFolder:"Upload files to this folder",uploadToCurrentDir:"Upload files to current directory",protocolMismatch:"Page version differs from the server (the app was just updated). Refresh the page to restore full functionality.",selectLinesHint:"Click a line to select; drag or Shift+click for a range",enableWrap:"Enable line wrap",disableWrap:"Disable line wrap",selectedRange:"Selected {n} lines (lines {start}-{end})",fileLines:"{n} lines",selectAll:"Select all",clearSelection:"Clear",addToChat:"Add to chat",addedToChat:"Added",previewTruncated:"⚠ File too large — previewing the first 512KB",previewLinesTruncated:"… too many lines — showing the first {n}",binaryFile:"🔣 Binary file — first 4KB shown as hex",binaryHexTruncated:" (file larger — download for the full file)",previewNotSupported:"This file type can't be previewed (only images / videos / text)",emptyFile:"(empty file)",editFile:"Edit file",exitEditFile:"Exit editing",saveFile:"Save file",discardFileChanges:"Discard unsaved changes?",fileSaved:"Saved",fileEditTruncated:"The preview is incomplete, so this file can't be edited",showMarkdownSource:"Show Markdown source",showMarkdownPreview:"Show Markdown preview",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",zoomIn:"Increase font size",zoomOut:"Decrease font size",resetZoom:"Reset zoom",pluginRequest:"Plugin request",modelQuestion:"Model question",modelQuestionCustom:"Custom answer (optional)",modelQuestionSubmit:"Submit answer",questionTimeout:"⏳ {s}s left — auto-cancels on timeout",questionTimeoutExpired:"Question timed out, resuming conversation…",modelNoVision:"Current model {name} doesn't support images — switch to DeepSeek V4 Flash Vision (exp)",dshSkillsNote:"DSH uses runtime-built-in skills (dsh-skill); toggling is not supported in settings yet",dshExtensionsNote:"DSH has no pi extension system; capabilities are runtime-built-in (MCP/subagent/goal/plan/skill…)",dshReviewPromptNote:"DSH has no separate reviewer: this text is appended to the system prompt for goal rounds",dshVisionHiddenNote:"DSH supports real image input (DeepSeek V4 Flash Vision (exp) only) — no vision bridge needed",dshNoReviewModel:"DSH has no separate reviewer model — the model self-certifies goal completion; max rounds = auto-iteration count",noOptions:"(no options)",inputPlaceholder:"Enter content",soundHeader:"Sound notifications",enableSound:"Enable sound",preview:"Preview",volume:"Volume",notifyHeader:"Desktop notifications",notifyEnable:"Enable desktop notifications",notifyEnableDesc:"Ping you when a session finishes or needs your input, even while you're in another app. Requires permission; only fires when this page is not focused.",notifyDenied:"Notification permission was blocked — enable notifications for this site in your browser / system settings.",notifyUnsupported:"Notifications are not supported by this browser.",notifyDoneTitle:"Task finished",notifyDoneBody:"The session finished and is ready for your input.",notifyQuestionTitle:"Needs your input",notifyQuestionBody:"pi is waiting for your answer to a question.",notifyErrorTitle:"Something went wrong",notifyErrorBody:"A session reported an error.","sound.question":"Question popup","sound.question.desc":"When ask_user_question appears","sound.done":"Reply finished","sound.done.desc":"When the agent finishes a turn","sound.start":"Reply started","sound.start.desc":"When the agent starts a new turn","sound.error":"Error","sound.error.desc":"When an error notice appears",setupTitle:"pi agent config not detected",setupDesc:"pi-web-ui needs pi's config directory (~/.pi/agent) and at least one API key to run the agent. pi has built-in providers such as openai, anthropic, and deepseek — just pick one and enter a key, no terminal needed.",installFailed:"✖ pi agent installation failed:",retryInstall:"Retry install",skip:"Skip",installDone:"✅ pi agent CLI installed. Pick a provider and enter an API key to start chatting:",cliReadyHint:"✅ pi agent CLI already installed locally. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",directory:"Directory",waitingResponse:"Waiting for model response…",backToBottom:"Back to bottom",questionNavTitle:"Questions",searchPlaceholder:"Search in conversation…",searchNoResults:"No results",searchModels:"Filter models…",noModelMatches:"No matching models",modelUsedCount:"used {n}×",searchGlobal:"Search",searchGlobalTip:"Global search: sessions / projects / files (Ctrl+K)",gsPlaceholder:"Search projects, past conversations, workspace files…",gsHint:"Type to search full conversation text (AI replies included), recent projects and file names in the current workspace at once",gsSessions:"Conversations",gsProjects:"Projects",gsFiles:"Files",gsNoResults:"No matches",gsSearching:"Searching…",gsTruncated:"Too many matches — showing a subset",gsCurrentProject:"current",gsOpenPreview:"Open file preview",gsNavigate:"select",gsOpen:"open",gsCloseHint:"close",bgTaskCommand:"Command",searchPrev:"Previous (Shift+Enter)",searchNext:"Next (Enter)",searchClose:"Close (Esc)",questionNavTip:"All questions in this conversation — hover to expand, click to jump","tpl.title":"Prompt templates","tpl.hint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.clickCard":"Click to fill the input","tpl.editTpl":"Edit / delete template","tpl.openPicker":"Prompt templates (reusable prompts, anytime)","tpl.pickerTitle":"Prompt templates","tpl.pickerHint":"Click a card to fill the input; ✏️ to edit or delete; add your own too","tpl.add":"New template","tpl.addDesc":"Save a workflow you use often","tpl.reset":"Restore defaults","tpl.resetConfirm":"Restore defaults?","tpl.builtin":"Built-in","tpl.custom":"Custom","tpl.newTitle":"New prompt template","tpl.editTitle":"Edit prompt template","tpl.fieldIcon":"Icon","tpl.fieldTitle":"Title","tpl.fieldTitlePh":"Short title shown on the card","tpl.fieldDesc":"Description","tpl.fieldDescPh":"One-liner shown on the card","tpl.fieldPrompt":"Prompt","tpl.fieldPromptPh":"The full prompt sent to the agent","tpl.required":"Title and prompt are required","tpl.save":"Save","tpl.fill":"Fill input","tpl.fillTip":"Fill the input so you can tweak it before sending","tpl.sendNow":"Send now","tpl.sendTip":"Send immediately as a new conversation","tpl.delete":"Delete","tpl.deleteTip":"Delete this custom template","tpl.remove":"Remove from library","tpl.removeTip":"Remove this built-in template; restore later via “Restore defaults”","tpl.restore":"Restore default","tpl.restoreTip":"Discard your edits and restore the built-in default","tpl.sk.setup":"Repo setup","tpl.sk.setup.desc":"Give the repo a baseline that other workflows can use","tpl.sk.setup.prompt":`Scan this repository and build the baseline context other workflows rely on, then report concisely:
|
|
155
|
-
|
|
156
|
-
1. Project type, tech stack and directory layout
|
|
157
|
-
2. Concrete commands for build / test / run / format
|
|
158
|
-
3. Code conventions and naming rules
|
|
159
|
-
4. Where tasks / issues live and their format
|
|
160
|
-
5. Known pitfalls or leftover issues
|
|
161
|
-
|
|
162
|
-
Report only — do not modify any files.`,"tpl.sk.ask":"Skill navigator","tpl.sk.ask.desc":"Tell me which workflow to use","tpl.sk.ask.prompt":"I'll describe the situation I'm in; you decide the best workflow (clarify requirements / plan & execute / TDD / debugging / architecture / review / handoff, etc.), explain why you recommend it and how you'd run it, then execute it after I confirm.","tpl.sk.grilldocs":"Grill & record","tpl.sk.grilldocs.desc":"Interview the plan and record decisions","tpl.sk.grilldocs.prompt":"Before starting, grill me about this plan (one question at a time) until we reach shared understanding. Record key terms and settled decisions as you go (e.g. into CONTEXT.md or an ADR file) so all later work shares one vocabulary. Give your recommended answer with each question.","tpl.sk.tospec":"To spec","tpl.sk.tospec.desc":"Turn the agreed discussion into a written spec","tpl.sk.tospec.prompt":`Turn the consensus we reached into a structured specification:
|
|
163
|
-
|
|
164
|
-
1. Background and goals
|
|
165
|
-
2. Explicit goals and non-goals
|
|
166
|
-
3. Users and usage scenarios
|
|
167
|
-
4. Edge cases and failure modes
|
|
168
|
-
5. Acceptance criteria (what counts as done)
|
|
169
|
-
6. Interface / data-shape overview
|
|
170
|
-
|
|
171
|
-
Output the spec for my review first, then continue only after I confirm.`,"tpl.sk.totickets":"To tickets","tpl.sk.totickets.desc":"Split the spec into small buildable tickets","tpl.sk.totickets.prompt":`Split this spec into a set of small tickets an agent can build one by one:
|
|
172
|
-
|
|
173
|
-
1. Each ticket small enough to be independently accepted
|
|
174
|
-
2. Annotate dependency order (what must come first)
|
|
175
|
-
3. Each ticket has: what to do, acceptance criteria, files involved
|
|
176
|
-
4. Flag which tickets can run in parallel
|
|
177
|
-
|
|
178
|
-
Output the ticket list; I'll confirm the order before you execute.`,"tpl.sk.implement":"Implement spec","tpl.sk.implement.desc":"Build the finished spec, test-first","tpl.sk.implement.prompt":`Implement per this spec, test-first:
|
|
179
|
-
|
|
180
|
-
1. Write failing tests for each ticket first (happy path, edges, error branches)
|
|
181
|
-
2. Make them pass with the minimal implementation
|
|
182
|
-
3. Refactor while keeping tests green
|
|
183
|
-
4. Proceed ticket by ticket, reporting briefly after each
|
|
184
|
-
|
|
185
|
-
Finally check every acceptance criterion explicitly.`,"tpl.sk.codeview":"Code review","tpl.sk.codeview.desc":"Review the diff against the spec and your standards","tpl.sk.codeview.prompt":`Review the recently changed diff:
|
|
186
|
-
|
|
187
|
-
1. Against the spec: is the implementation complete and faithful?
|
|
188
|
-
2. Correctness: edges, nulls, concurrency and timing
|
|
189
|
-
3. Security: input validation, injection, sensitive data
|
|
190
|
-
4. Performance & readability: does it follow project conventions?
|
|
191
|
-
5. Tests: are critical paths covered?
|
|
192
|
-
|
|
193
|
-
List issues by severity, each with a concrete suggestion.`,"tpl.sk.wayfinder":"Wayfinder","tpl.sk.wayfinder.desc":"Chart a large effort as a map of decisions","tpl.sk.wayfinder.prompt":`This is a large task. First chart it as a decision map:
|
|
194
|
-
|
|
195
|
-
1. List every decision point and its dependencies
|
|
196
|
-
2. For each decision give options, trade-offs and your recommendation
|
|
197
|
-
3. Mark what can run in parallel vs. what must be sequential
|
|
198
|
-
4. Output a path plan; I'll confirm each item before you start.`,"tpl.sk.prototype":"Prototype","tpl.sk.prototype.desc":"Answer a design question with throwaway code","tpl.sk.prototype.prompt":`Write a minimal prototype to validate the design assumption:
|
|
199
|
-
|
|
200
|
-
1. Validate only the key assumption, not the full implementation
|
|
201
|
-
2. Use the simplest means (hard-coding and skipped edge cases are fine)
|
|
202
|
-
3. Run it and tell me the verdict: does the assumption hold? trade-offs?
|
|
203
|
-
4. The prototype can be deleted, or made production-ready only after I confirm.`,"tpl.sk.research":"Research","tpl.sk.research.desc":"Get a cited answer from primary sources","tpl.sk.research.prompt":`Research this question, preferring primary sources (official docs / source / specs):
|
|
204
|
-
|
|
205
|
-
1. Give an answer with source links
|
|
206
|
-
2. Distinguish facts, reasonable inference, and what's still uncertain
|
|
207
|
-
3. List the main options and their trade-offs
|
|
208
|
-
4. Don't stitch together secondary content; say so if you can't find it.`,"tpl.sk.arch":"Architecture review","tpl.sk.arch.desc":"Find the modules worth refactoring (report)","tpl.sk.arch.prompt":`Do an architecture review of the whole codebase:
|
|
209
|
-
|
|
210
|
-
1. Find signs of broken deep modules: oversized functions/classes, duplication, poor naming, hidden coupling
|
|
211
|
-
2. Prioritize improvements by severity and blast radius; produce a visual report
|
|
212
|
-
3. For each item give the minimal viable refactor with rationale
|
|
213
|
-
4. Report before changing anything; confirm scope before refactoring.`,"tpl.sk.debug":"Diagnose bugs","tpl.sk.debug.desc":"Diagnose from a repro that fails","tpl.sk.debug.prompt":`Diagnose this bug systematically:
|
|
214
|
-
|
|
215
|
-
1. Reproduce it first (build a minimal repro if none exists)
|
|
216
|
-
2. Narrow to a specific module via bisection or elimination
|
|
217
|
-
3. Form hypotheses and verify with logs / assertions / a minimal sample — no guessing
|
|
218
|
-
4. Once the root cause is found, explain it, then make the minimal fix
|
|
219
|
-
5. Add a regression test to prevent recurrence.`,"tpl.sk.merge":"Resolve merge conflicts","tpl.sk.merge.desc":"Finish a merge or rebase conflict hunk by hunk","tpl.sk.merge.prompt":`Help me resolve this merge / rebase conflict:
|
|
220
|
-
|
|
221
|
-
1. Handle each conflict hunk, reading both sides' intent first
|
|
222
|
-
2. Choose or merge to keep correct semantics — don't blindly pick one side
|
|
223
|
-
3. Run tests and build afterwards to confirm
|
|
224
|
-
4. Finally summarize the rationale for each resolution.`,"tpl.sk.triage":"Triage","tpl.sk.triage.desc":"Sort raw issues into work someone can pick up","tpl.sk.triage.prompt":`Turn these raw issues / feedback into actionable work items:
|
|
225
|
-
|
|
226
|
-
1. Deduplicate and merge related entries
|
|
227
|
-
2. Categorize (bug / feature / improvement / question)
|
|
228
|
-
3. Prioritize by impact and urgency
|
|
229
|
-
4. For each item add: repro info or expectation, acceptance criteria
|
|
230
|
-
|
|
231
|
-
Output the cleaned list.`,"tpl.sk.wizard":"Setup wizard","tpl.sk.wizard.desc":"Generate a script that walks a human through setup","tpl.sk.wizard.prompt":`Create a guided wizard (script or doc) for a manual setup flow:
|
|
232
|
-
|
|
233
|
-
1. Guide step by step, explaining why at each step
|
|
234
|
-
2. Validate each step; on wrong input give actionable hints
|
|
235
|
-
3. Support undo / going back a step
|
|
236
|
-
4. End with a self-check and how to verify.`,"tpl.sk.grillme":"Grill me","tpl.sk.grillme.desc":"Align on an idea before committing","tpl.sk.grillme.prompt":`Before starting, interview me relentlessly about every aspect of this idea until we reach shared understanding (one question at a time, each with your recommended answer):
|
|
237
|
-
|
|
238
|
-
1. Goals and non-goals
|
|
239
|
-
2. Users and scenarios
|
|
240
|
-
3. Edge cases and failure modes
|
|
241
|
-
4. Constraints and dependencies
|
|
242
|
-
5. Acceptance criteria
|
|
243
|
-
|
|
244
|
-
Then give an implementation plan and wait for my confirmation before writing code.`,"tpl.sk.handoff":"Handoff","tpl.sk.handoff.desc":"Write up a long session so another agent can continue","tpl.sk.handoff.prompt":`Turn this session into a handoff doc so another agent / teammate can continue seamlessly:
|
|
245
|
-
|
|
246
|
-
1. Background and goals
|
|
247
|
-
2. Work done and key decisions (with reasons)
|
|
248
|
-
3. Outstanding items and next steps
|
|
249
|
-
4. Known risks and open questions
|
|
250
|
-
5. How to verify current state (commands, etc.)
|
|
251
|
-
|
|
252
|
-
Output as a structured document.`,"tpl.sk.questionnaire":"To questionnaire","tpl.sk.questionnaire.desc":"Turn open questions into a doc someone fills in","tpl.sk.questionnaire.prompt":`Turn the info you need from someone into a fillable questionnaire:
|
|
253
|
-
|
|
254
|
-
1. Explain the background and purpose of each question
|
|
255
|
-
2. Mark required / optional
|
|
256
|
-
3. Give example answers to lower friction
|
|
257
|
-
4. Group and order: easy first, hard later
|
|
258
|
-
|
|
259
|
-
Output a doc they can fill in directly.`,"tpl.sk.teach":"Teach","tpl.sk.teach.desc":"Learn a topic across sessions that build on each other","tpl.sk.teach.prompt":`Teach me this topic incrementally:
|
|
260
|
-
|
|
261
|
-
1. First set a learning path and goal
|
|
262
|
-
2. Teach one small section at a time, then a quick exercise
|
|
263
|
-
3. Build on the previous section and ask questions to confirm understanding
|
|
264
|
-
4. Summarize key points at the end of each section
|
|
265
|
-
|
|
266
|
-
Works well across multiple sessions.`,"tpl.sk.ww":"Wait, what?","tpl.sk.ww.desc":"Say the last explanation again in plain English","tpl.sk.ww.prompt":`Re-explain what you just said in the simplest terms:
|
|
267
|
-
|
|
268
|
-
1. Avoid jargon; define any term you must use in one sentence
|
|
269
|
-
2. Use an analogy or concrete example
|
|
270
|
-
3. Be clear about what is still guesswork / uncertain
|
|
271
|
-
4. Keep the core point as short as possible.`,"tpl.sk.wfa":"Writing for agents","tpl.sk.wfa.desc":"Write docs that follow agent-friendly principles","tpl.sk.wfa.prompt":`Write this doc / explanation following “written for agents to read” principles:
|
|
272
|
-
|
|
273
|
-
1. Put the goal and usage up front
|
|
274
|
-
2. Make instructions concrete and verifiable — no vagueness
|
|
275
|
-
3. Give positive and negative examples
|
|
276
|
-
4. Structure with headings, steps and checklists
|
|
277
|
-
5. Mark what's required vs. optional.`,"tpl.sk.codesign":"Deep-module design","tpl.sk.codesign.desc":"Review & design with deep-module principles","tpl.sk.codesign.prompt":`Review / design using the “deep module” principle:
|
|
278
|
-
|
|
279
|
-
1. Check whether each module's public interface is simpler than its implementation
|
|
280
|
-
2. Find modules that leak complexity outward
|
|
281
|
-
3. Give responsibility boundaries and improvement plans
|
|
282
|
-
4. Balance cohesion and reuse without over-abstracting
|
|
283
|
-
|
|
284
|
-
Output the review conclusions and refactor suggestions.`,"tpl.sk.domain":"Domain modeling","tpl.sk.domain.desc":"Sharpen the words a project uses and write them down","tpl.sk.domain.prompt":`Help me clean up this project's domain language:
|
|
285
|
-
|
|
286
|
-
1. Find the core terms and their current spellings
|
|
287
|
-
2. Spot confusion from same-word-different-meaning / different-word-same-meaning
|
|
288
|
-
3. Recommend one canonical term each, into a glossary
|
|
289
|
-
4. State each term's boundary (what it is not)
|
|
290
|
-
|
|
291
|
-
Output a domain glossary.`,"tpl.sk.grilling":"Grilling","tpl.sk.grilling.desc":"Stress-test a plan with an interview","tpl.sk.grilling.prompt":`Stress-test this plan with an interview:
|
|
292
|
-
|
|
293
|
-
1. Check each assumption: what if it's wrong?
|
|
294
|
-
2. Hunt for holes: edges, failure modes, dependencies, timing
|
|
295
|
-
3. Challenge decisions: why this way? is there a simpler path?
|
|
296
|
-
4. Ask one sharp question at a time and wait for my answer
|
|
297
|
-
|
|
298
|
-
Keep going until the plan holds up.`,"tpl.sk.tdd":"Test-driven","tpl.sk.tdd.desc":"The rules of the red-green-refactor loop","tpl.sk.tdd.prompt":`Implement using TDD (red-green-refactor):
|
|
299
|
-
|
|
300
|
-
1. First write failing tests covering the happy path, edge cases and error branches
|
|
301
|
-
2. Make them pass with the minimal implementation
|
|
302
|
-
3. Refactor while keeping tests green
|
|
303
|
-
|
|
304
|
-
Avoid three test anti-patterns: tests coupled to the implementation, tautological assertions (always true), and horizontal slicing (surface only). Report after each step and run the tests.`,error:"Error",done:"Done",running:"Running…",toolQueued:"Queued",copyArgs:"Copy args",errorOutput:"Error output",output:"Output",waitingOutput:"Waiting for output…",toolDoneWaitingModel:"Done · waiting on model",waitingModel:"Waiting for model response…",thinkingNow:"Thinking",thinkingPreview:"Thinking: {preview}",commands:"Commands",newCommand:"New command",newTerminal:"New terminal",name:"Name",command:"Command",cwdHint:"(${pwd} = current working directory)",noCommands:"No commands yet — click + to add one",clickToRun:"Click to run",edit:"Edit",delete:"Delete",confirmQ:"Confirm?",builtinTerminal:"Built-in terminal",termEmptySub:"Click a command on the left to run it, or + on the right for a new terminal",noTerminal:"No terminals",exited:"(exited{code})",exitBanner:"[Process exited with code {code}]",closeTerminal:"Close terminal",renameTerminal:"Rename terminal",rerun:"Reload .pi/commands.json",terminalTitle:"Terminal {n}",aiBashGroup:"Terminal-backed bash",exampleName:"e.g. start dev server",exampleCommand:"e.g. npm run dev",scmTab:"Git",scmTitle:"Source Control",scmRefreshTip:"Re-query git status & diff",scmCurrentBranch:"Current branch",scmUpstreamGone:"Upstream deleted",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"Detached HEAD",scmSelectBranch:"Select branch…",scmRemoteBranches:"Remote branches",scmStageTip:"Stage {path}",scmUnstageTip:"Unstage {path}",scmSwitch:"Switch",scmSwitchBranch:"Switch branch",scmSwitchBranchTip:"Runs git checkout {branch} in the terminal",scmPush:"Push",scmPushTip:"Runs git push in the terminal",scmPull:"Pull",scmPullTip:"Runs git pull in the terminal",scmCommit:"Commit",scmCommitTip:'Runs git commit -m "…" in the terminal (commits staged changes only)',scmCommitAll:"Commit All",scmCommitAllTip:'Runs git add -A && git commit -m "…" in the terminal (stages all changes incl. untracked and commits)',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 — stage it with + to include (or use Commit All)",scmQueryFailed:"Git query failed: {error}",scmQueryFailedShort:"Query failed",pluginCommandFallback:"Plugin command",scmTooManyFailures:"Git queries keep failing — click refresh to retry",scmRunsInTerminal:"Commit / branch switch / push / pull run in the terminal",scmViewTerminal:"Open terminal",editProvider:"Edit provider",builtinProviders:"Built-in providers",hintKeyOnly:"Just enter an API key",configuredBadge:"✓ Configured",keyReady:"Key ready",replaceKey:"Replace key",replaceKeyTitle:"Replace the saved key",clearKey:"Clear",clearKeyTitle:"Remove this provider's key stored in auth.json; it returns to unconfigured (env-var sourced keys can't be cleared here)",clearKeyConfirm:"Clear the stored key for {id}? Its models will leave the list until you configure it again.",cloneProvider:"Add key",cloning:"Adding",cloneProviderTitle:"Add a second API key for this provider (baseUrl and model list are copied automatically)",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",addKey:"Add key",addKeyPlaceholder:"Paste the key value…",keyNamePh:"Name (optional, e.g. backup)",providerIdPlaceholder:"Provider ID",baseUrlExamplePh:"baseUrl, e.g. https://api.opencode.ai/zen/v1 or http://127.0.0.1:4096",saveAllBatch:"Save all ({n})",netDisconnected:"Network disconnected — reconnect and retry",advancedEdit:"Advanced edit",batchCreateProviders:"Batch-create providers ({n} APIs)",secondKeyTitle:"Add a second key for {api} · {baseUrl} · {n} models — just name the new provider and enter the key.",noBaseUrlShort:"(no baseUrl)",providerNameLabel:"Provider name",providerNameHint:"(new ID, e.g. opencode-2)",apiKeyLabel:"API key",secondKeyPlaceholder:"sk-… second key",batchDesc:"This provider has multiple APIs ({apis}); it was split into {n} custom providers. Save each so all models (e.g. muse-spark) work. Enter one shared second key to save all at once.",batchKeyLabel:"Shared API key (applies to all {n} providers)",modelsCountShort:"{n} models: ",noKeyYet:"No key yet — add one to use this provider",activateKey:"Set active",removeKey:"Remove",removeKeyConfirm:"Remove this key? It must be re-configured to be used again.",customProviders:"Custom providers",customDesc:"For Ollama / vLLM / OpenAI-compatible proxies, etc. Written to pi's models.json — hot-reloaded immediately.",noCustomProviders:"No custom providers yet",modelsCount:"{n} models",addProvider:"Add provider",providerId:"Provider ID",providerIdHint:"(required, e.g. ollama / my-proxy)",displayName:"Display name",displayNamePh:"My proxy",apiType:"API type",baseUrlHint:"(OpenAI-compatible endpoint)",apiKeyHint:"sk-… (optional — uses the auth.json key)",authHeader:"Auto-add Authorization header",modelsTitle:"Models",modelIdReq:"Model ID (required)",text:"Text",textImage:"Text+image",contextWindow:"Context",maxOutput:"Max output",removeModel:"Remove model",addModel:"Add model",deleteProviderConfirm:"Delete provider {id} and its {n} models?",fetchModels:"Fetch model list",fetchModelsHint:"Pull model IDs from the baseUrl /models endpoint (server-side, no CORS)",fetchingModels:"Fetching…",fetchModelsOk:"Fetched {n} models",fetchModelsEmpty:"The endpoint returned no models",fetchModelsErr:"Fetch failed: {msg}",fetchModelsNeedBaseUrl:"Enter a baseUrl first",goalBarTitle:"Goal",goalBarPlaceholder:"Set a goal; the agent's output is auto-reviewed…",goalBarSet:"Start",goalBarClear:"Cancel",goalBarLocked:"Locked: applies to every later turn",goalBarUnlocked:"This turn only (cleared afterwards)",goalBarReviewModel:"Review model",goalBarUseMainModel:"Use the main model",goalBarMaxRounds:"Max rounds",goalBarMaxRoundsTip:"Max review-revision rounds; 0 or empty = unlimited (keep revising until it passes)",goalBarUnlimitedShort:"Unlimited",goalBarReviewing:"Reviewing…",goalBarRound:"Round {n}",goalBarActive:"Goal active",goalBarPassed:"Passed",goalBarFailed:"Failed",goalBarStatusPending:"Waiting to generate…",goalWizardBtn:"AI Scrape",goalWizardTip:"Let AI refine the requirement into a goal via a Q&A survey",goalWizardRunning:"Scoping the goal",goalWizardAnswer:"Answer",goalWizardCard:"Goal survey",settings:"Settings",settingsTitle:"Settings",settingsDesc:"Changes apply immediately: system prompt, skill and extension toggles rebuild the current session; review instructions and review skills affect later goal reviews (main-session changes are deferred while streaming).",settingsSystemPrompt:"System prompt",settingsPromptHistory:"Input history",settingsPromptHistoryDesc:"Cycle previous prompts with ↑/↓ in the input — global across conversations (localStorage)",promptHistoryMax:"Max entries",promptHistoryMaxHint:"Oldest entries are dropped when exceeded (1–500)",promptHistoryCharLimit:"Limit characters per entry",promptHistoryCharLimitHint:"When enabled, overlong prompts are truncated before saving",promptHistoryCharLimitPlaceholder:"Max chars (100–20000)",promptHistoryClear:"Clear history",promptHistoryClearConfirm:"Confirm clear?",promptHistoryCleared:"Input history cleared",promptHistoryCount:"{n} entries",promptHistoryEmpty:"No history yet — ↑/↓ has nothing to cycle",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",settingsMarkers:"Markers",settingsMarkersDesc:"Let the AI write [[todo:...]] / [[svc:...]] / [[notify:...]] / [[conv:rename:...]] inline markers in replies to update state without a tool round-trip. Global off disables all; per-marker toggles give fine control.",markersEnabled:"Markers enabled (global)",markersEnabledDesc:"Off = no marker guidance injected and no parsing; markers stay as plain text.",markersOffHint:"Globally off: all markers disabled — the AI won't write markers and no side effects fire.",markerGroupTodo:"todo — tasks",markerGroupSvc:"svc — background services",markerGroupNotify:"notify — non-blocking hints",markerGroupRename:"conv/rename — rename chat",markerRenameTip:"[[conv:rename:Title]] or [[rename:set:Title]] renames the current conversation (≤80 chars)",settingsTerminalTools:"Terminal tools",terminalToolsEnabled:"Enable persistent terminal tools",settingsTerminalToolsDesc:"Let the AI use the built-in terminal for interactive programs (REPLs/vim), long-running servers, continuous output watching, or when you ask it to work in the visible terminal; ordinary commands still go through the one-shot bash tool",terminalToolsOffHint:"Disabled: the AI has no terminal_* tools and receives no usage guidance",settingsMessageDisplay:"Message display",thinkingWrap:"Show full thinking",thinkingWrapDesc:"On: thinking always expands fully and wraps (live reasoning visible while streaming); Off: collapses to a one-line summary with the latest text shown live while streaming",toolsWrap:"Show full tools",toolsWrapDesc:"On: tool calls always expand fully showing arguments and output; Off: collapsed by default, click to expand",terminalBashTakeover:"Terminal-backed bash",terminalBashTakeoverDesc:"This switch decides whether bash is overridden to a terminal version: OFF = native SDK bash (process spawn, no terminal); ON = runs in a visible terminal, where the persist parameter decides (on top of the switch) one-shot (false — process exits when the command finishes, output retained) vs persistent (true — shell state retained across calls, silent commands move to the background and notify the AI)",terminalBashIdleMs:"Silence-to-background threshold (ms)",terminalBashIdleMsDesc:"In persistent-terminal mode, when a command produces no output for this long, stop blocking and let it keep running in the background; the AI is notified when it finishes. 0 = always wait until completion (default 15000)",visionBridgePromptPlaceholder:"Type a custom transcription prompt… (empty = built-in default, applied on blur)",visionBridgePromptAppendHint:"Append mode: custom text is appended after the built-in transcription prompt (recommended — keeps the verbatim-transcription contract).",visionBridgePromptReplaceHint:"Replace mode: custom text replaces the built-in transcription prompt entirely. After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",uninstallExt:"Uninstall",uninstallConfirm:"Confirm?",uninstallConfirmHint:"Click again to confirm — runs pi remove in the terminal",uninstallHint:"Runs pi remove in a visible terminal, then refreshes the list automatically",uninstallTitle:"Uninstall",pluginUpdate:"Update",pluginUpdateHint:"Re-installs from the recorded source (--force, keeps config.json), then refreshes the plugin list automatically",pluginUninstallHint:"Runs pi-web-ui uninstall in a visible terminal (click again to confirm), then refreshes the list automatically",settingsExtensions:"Extensions",settingsUiPlugins:"UI plugins",noUiPlugins:"No UI plugins installed (<dataDir>/plugins/)",dshPatches:"DSH user patches",dshPatchesDesc:"Cordis patches loaded at runtime boot, in filename order (<dataDir>/dsh-patches/*.yml). New/edited files take effect after 'Rescan' restarts the runtime; broken files are skipped and logged to runtime stderr.",dshPatchesRescan:"Rescan",dshPatchesRescanHint:"Re-scan the patch directory and restart the DSH runtime so new patches take effect",dshPatchesEmpty:"No patch files yet",dshPatchesPath:"Patch directory: ",uiPluginNoSource:"Installed manually — no recorded source, online update unavailable",uiPluginPerms:"Permissions",pluginSettingsSave:"Save plugin settings",pluginSettingsSaving:"Saving…",pluginSettingsReset:"Reset defaults",settingsPresets:"Presets",settingsSubagentTemplates:"Subagent templates",settingsSubagentTemplatesDesc:"Presets for spawned subagents (role system prompt + skills/extensions whitelist). AI may pick a template (subagent_spawn template param) or spawn without one; disabled templates stay in the panel but are invisible to AI tools.",noSubagentTemplates:"No subagent templates yet. AI can pick a template when spawning a subagent (role prompt + skills/extensions whitelist), or spawn without a template param for default config.",subagentTemplateNew:"New template",subagentTemplateEdit:"Edit",subagentTemplateClosed:"Disabled",tplDefaultBadge:"Built-in",subagentTemplateOffHint:"Disabled templates stay in the panel and can be re-enabled, but AI tools can't see or pick them",subagentTemplateEnable:"Enable",subagentTemplateDisable:"Disable",tplNamePlaceholder:"Template name (referenced by AI via subagent_spawn's template param)…",tplDescriptionPlaceholder:"Description (AI uses it to judge when to pick this template)…",tplPromptModeLabel:"System prompt mode",tplSystemPromptLabel:"System prompt",tplSystemPromptPlaceholder:"Template role system prompt… (may be empty in append mode)",tplWhitelistHint:"Whitelist: checked = the subagent only gets these; none checked = follow the main session settings",tplSkillsLabel:"Skills whitelist",tplExtensionsLabel:"Extensions whitelist",tplSave:"Save template",tplCancel:"Cancel edit",tplDelete:"Delete template",tplInherit:"Follow main session",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…"},vn=l.createContext(null);function Vi(){try{const t=localStorage.getItem(yn);if(t==="zh"||t==="en")return t}catch{}return"zh"}function Gi({children:t}){const[s,n]=l.useState(Vi),r=l.useCallback(a=>{n(a);try{localStorage.setItem(yn,a)}catch{}},[]),c=l.useCallback((a,o)=>{let u=Ps[a];if(s==="zh"&&(u=Es[a]),o)for(const[m,y]of Object.entries(o))u=u.replaceAll(`{${m}}`,String(y));return u},[s]);l.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en",document.title=s==="zh"?Es.docTitle:Ps.docTitle},[s]);const i=l.useMemo(()=>({locale:s,setLocale:r,t:c}),[s,r,c]);return e.jsx(vn.Provider,{value:i,children:t})}function pt(){const t=l.useContext(vn);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function xe(){return pt().t}const Qi=[{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 Ms({settings:t,onChange:s,onPreview:n}){const r=xe(),c=i=>s({...t,...i});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:r("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(cn,{className:"sound-icon"}),e.jsx("span",{children:r("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:i=>c({enabled:i.target.checked})})]}),Qi.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:r(a)}),e.jsx("span",{className:"sound-desc",children:r(o)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:r("preview"),disabled:!t.enabled,onClick:u=>{u.preventDefault(),n(i)},children:r("preview")}),e.jsx("input",{type:"checkbox",checked:t[i],disabled:!t.enabled,onChange:u=>c({[i]:u.target.checked})})]})]},i)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:r("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,"%"]})]})]})}let Pt=null;function Yi(t){if(t===void 0){const n=globalThis.document;if(n&&typeof n.baseURI=="string"&&n.baseURI)try{t=new URL(n.baseURI).pathname}catch{}if(t===void 0)return"/"}if(!t||t==="/")return"/";let s=t.replace(/index\.html$/i,"");return s.endsWith("/")||(s+="/"),s}function kn(){return Pt===null&&(Pt=Yi()),Pt}function Ji(t,s){return s==="/"?t:s+t.replace(/^\/+/,"")}function Ve(t){return Ji(t,kn())}const bn="pi-web-notify",Mt={enabled:!1};function jn(){try{const t=localStorage.getItem(bn);if(!t)return{...Mt};const s=JSON.parse(t);return{enabled:typeof s.enabled=="boolean"?s.enabled:Mt.enabled}}catch{return{...Mt}}}function Rs(t){try{localStorage.setItem(bn,JSON.stringify(t))}catch{}}function lt(){return typeof window<"u"&&"Notification"in window}function Xi(){return lt()?Notification.permission:"denied"}async function Zi(){if(!lt())return"denied";try{return await Notification.requestPermission()}catch{return"denied"}}async function Rt(t,s){var r;if(!lt()||document.hasFocus()||!jn().enabled||Notification.permission!=="granted")return;const n={body:s,icon:Ve("/icons/icon-192.png"),badge:Ve("/icons/icon-192.png"),tag:"pi-web-ui"};try{const c=await((r=navigator.serviceWorker)==null?void 0:r.getRegistration());c&&typeof c.showNotification=="function"?c.showNotification(t,n):new Notification(t,n)}catch{}}function Is(){const t=xe(),[s,n]=l.useState(jn),[r,c]=l.useState(()=>lt()?Xi():"denied"),i=async a=>{const o={...s,enabled:a};if(n(o),Rs(o),a){const u=await Zi();if(c(u),u!=="granted"){const m={...o,enabled:!1};n(m),Rs(m)}}};return e.jsxs("div",{className:"sound-menu",style:{borderTop:"1px solid var(--border-color, rgba(255,255,255,.08))",marginTop:6,paddingTop:6},children:[e.jsx("div",{className:"dd-header",children:t("notifyHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Ki,{className:"sound-icon"}),e.jsx("span",{children:t("notifyEnable")})]}),e.jsx("input",{type:"checkbox",checked:s.enabled,onChange:a=>i(a.target.checked)})]}),e.jsx("div",{className:"sound-desc",style:{padding:"2px 8px 4px",opacity:.7,fontSize:"0.82em"},children:t("notifyEnableDesc")}),!lt()&&e.jsx("div",{className:"sound-desc",style:{padding:"0 8px 4px",opacity:.7,fontSize:"0.82em"},children:t("notifyUnsupported")}),r==="denied"&&e.jsx("div",{className:"sound-desc",style:{padding:"0 8px 4px",opacity:.7,fontSize:"0.82em"},children:t("notifyDenied")})]})}function ea({chat:t,send:s,terminal:n,view:r,plugins:c,onViewChange:i,onOpenPanel:a,onOpenSettings:o,onOpenBgTasks:u,onOpenGlobalSearch:m,sound:y,onSoundChange:f,onSoundPreview:g,themes:v,theme:T,onThemeChange:D}){var R;const{locale:O,setLocale:N,t:j}=pt(),[V,q]=l.useState(!1),[J,K]=l.useState(!1),[E,H]=l.useState(!1),[k,A]=l.useState(!1),[F,X]=l.useState(!1),$=[{value:"zh",label:j("langZh")},{value:"en",label:j("langEn")}],Y=t.ready?j("connected"):t.status==="closed"?j("reconnecting"):j("connecting"),Q=t.ready?"ok":"busy",P=()=>{var B,se;if(!t.ready)return;const d=j("updateTabTitle"),b={name:d,command:"npm i -g pi-web-ui@latest",cwd:"${pwd}"},w=t.terminals.find(G=>G.title===d);w?(n.restart(w.id),s({type:"run_command",terminalId:w.id,conversationId:w.conversationId,command:b,cols:80,rows:24})):n.create({id:Ue(),conversationId:t.activeConversationId||((B=t.state)==null?void 0:B.conversationId)||"",title:d,cwd:((se=t.state)==null?void 0:se.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:b}),A(!1),X(!1),i("terminal")},I=(d,b)=>{var se,G;if(!t.ready||d.length===0)return;const w={name:b,command:zi(d),cwd:"${pwd}"},B=t.terminals.find(ie=>ie.title===b);B?(n.restart(B.id),s({type:"run_command",terminalId:B.id,conversationId:B.conversationId,command:w,cols:80,rows:24})):n.create({id:Ue(),conversationId:t.activeConversationId||((se=t.state)==null?void 0:se.conversationId)||"",title:b,cwd:((G=t.state)==null?void 0:G.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:w}),A(!1),X(!1),i("terminal")},C=t.updatesAll??[],W=C.filter(d=>!d.upToDate&&!d.error).length,U=C.filter(d=>!d.upToDate&&!d.error&&d.kind!=="webui"),ne=()=>e.jsxs("div",{className:"dd-updates-all",children:[e.jsx("div",{className:"dd-header",children:j("updatesAllTitle")}),t.updatesAll===null?e.jsx("div",{className:"dd-note",children:j("checkingUpdate")}):C.length===0?e.jsx("div",{className:"dd-note",children:j("updatesAllUpToDate")}):e.jsx("ul",{className:"dd-all-list",children:C.map(d=>e.jsxs("li",{className:`dd-all-item${d.error?" err":d.upToDate?"":" warn"}`,children:[e.jsx("span",{className:"dd-all-name",title:d.name,children:d.name}),e.jsx("span",{className:"dd-all-kind",children:d.kind==="webui"?j("kindWebUi"):d.kind==="pi-core"?j("kindPiCore"):j("kindPackage")}),e.jsx("span",{className:"dd-all-vers",children:d.error?j("updateCheckFailed"):d.upToDate?`v${d.current}`:e.jsxs(e.Fragment,{children:["v",d.current," → v",d.latest]})}),d.kind!=="webui"&&!d.upToDate&&!d.error&&e.jsx("button",{type:"button",className:"dd-update-btn",onClick:()=>I([d],j("updatePkgTabTitle",{name:d.name})),children:j("updateBtn")})]},`${d.kind}:${d.name}`))}),e.jsxs("div",{className:"dd-actions",children:[U.length>0&&e.jsx("button",{type:"button",className:"dd-refresh accent",style:{flex:1},onClick:()=>I(U,j("updateAllTabTitle")),children:j("updateAllBtn")}),e.jsx("button",{type:"button",className:"dd-refresh",style:U.length>0?{flex:1}:void 0,onClick:()=>s({type:"check_updates_all",force:!0}),children:j("updatesAllRefresh")})]})]}),x=()=>{var d,b;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dd-update",children:[e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:j("currentVersion")}),e.jsxs("b",{children:["v",((d=t.update)==null?void 0:d.current)??"…"]})]}),e.jsxs("div",{className:"dd-row",children:[e.jsx("span",{children:j("latestVersion")}),e.jsx("b",{children:t.update===null?j("checkingUpdate"):t.update.error?t.update.error:t.update.latest?`v${t.update.latest}`:j("checkingUpdate")})]}),t.update&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:j("upToDate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:j("updateAvailable",{version:t.update.latest})}),((b=t.update)==null?void 0:b.latestPublishedAt)&&Date.now()-new Date(t.update.latestPublishedAt).getTime()<30*6e4&&e.jsx("div",{className:"dd-note warn",children:j("updateJustPublished",{version:t.update.latest??""})}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note",children:j("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?j("checkingUpdate"):j("checkUpdate")}),t.update&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:"dd-refresh accent",onClick:P,children:j("updateNow")})]})]})};return e.jsxs("header",{className:"topbar",children:[e.jsxs("div",{className:"brand",children:[e.jsx("button",{type:"button",className:"panel-toggle",title:j("openHistory"),onClick:()=>a("left"),children:e.jsx(Pi,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${Q}`,title:Y}),e.jsx("span",{className:"conn-label",children:Y})]}),e.jsxs("div",{className:"topbar-actions",children:[e.jsxs("div",{className:"view-switch",role:"tablist","aria-label":j("viewSwitch"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":r==="chat",className:r==="chat"?"active":"",onClick:()=>i("chat"),children:[e.jsx(tt,{}),e.jsx("span",{children:j("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":r==="terminal",className:r==="terminal"?"active":"",onClick:()=>i("terminal"),children:[e.jsx(et,{}),e.jsx("span",{children:j("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":r==="git",className:r==="git"?"active":"",onClick:()=>i("git"),children:[e.jsx(ft,{}),e.jsx("span",{children:j("scmTab")})]}),c.map(d=>{const b=d.error?`${d.name}: ${d.error}`:d.description?`${d.name} — ${d.description}`:d.name;return e.jsxs("button",{type:"button",role:"tab","aria-selected":r===`plugin:${d.id}`,className:`plugin-tab${r===`plugin:${d.id}`?" active":""}${d.error?" broken":""}`,title:b,onClick:()=>i(`plugin:${d.id}`),children:[d.icon?e.jsx("span",{"aria-hidden":!0,children:d.icon}):null,e.jsx("span",{children:d.name})]},d.id)})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip",title:j("searchGlobalTip"),onClick:m,children:[e.jsx(bt,{}),e.jsx("span",{className:"chip-sub",children:j("searchGlobal")})]}),e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":j("bgTasksTip"),onClick:u,children:[e.jsx(jt,{}),e.jsx("span",{className:"chip-sub",children:j("bgTasks")}),t.bgServers.length>0&&e.jsx("span",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsxs("button",{type:"button",className:"chip",title:j("settingsTitle"),onClick:o,children:[e.jsx(kt,{}),e.jsx("span",{className:"chip-sub",children:j("settings")})]}),e.jsxs(ze,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(cn,{}),e.jsx("span",{className:"chip-sub",children:j("sound")})]}),open:V,onOpenChange:q,children:[e.jsx(Ms,{settings:y,onChange:f,onPreview:g}),e.jsx(Is,{})]}),e.jsxs(ze,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Bi,{}),e.jsx("span",{className:"chip-sub",children:O==="zh"?j("langZh"):"EN"})]}),open:J,onOpenChange:K,children:[e.jsx("div",{className:"dd-header",children:j("language")}),$.map(d=>e.jsx(Re,{active:O===d.value,onClick:()=>{N(d.value),K(!1)},children:d.label},d.value))]}),e.jsxs(ze,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(wi,{}),e.jsx("span",{className:"chip-sub",children:j("theme")})]}),open:E,onOpenChange:H,children:[e.jsx("div",{className:"dd-header",children:j("theme")}),e.jsx(Re,{active:T===null,onClick:()=>{D(null),H(!1)},children:j("themeDefault")}),v.map(d=>e.jsx(Re,{active:T===d.id,onClick:()=>{D(d.id),H(!1)},children:O==="en"?d.nameEn??d.name:d.name},d.id))]}),e.jsxs(ze,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Zt,{}),e.jsxs("span",{className:"chip-sub",children:["v",((R=t.update)==null?void 0:R.current)??"…"]}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot",title:j("updateAvailable",{version:t.update.latest??""})}),W>0&&e.jsx("span",{className:"update-badge",children:j("updatesAllBadge",{n:W})})]}),open:k,onOpenChange:d=>{A(d),d&&(s({type:"check_update"}),s({type:"check_updates_all"}))},fit:!0,children:[e.jsx("div",{className:"dd-header",children:j("update")}),x(),ne()]}),e.jsx("a",{className:"chip github",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",title:j("githubRepo"),children:e.jsx(Ss,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":j("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(He,{}),e.jsx("span",{children:j("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(ze,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ti,{}),e.jsx("span",{className:"chip-sub",children:j("more")}),t.update&&!t.update.upToDate&&e.jsx("span",{className:"update-dot"})]}),open:F,onOpenChange:d=>{X(d),d&&(s({type:"check_update"}),s({type:"check_updates_all"}))},children:[e.jsx("div",{className:"dd-header",children:j("sound")}),e.jsx("div",{className:"dd-header",children:j("settings")}),e.jsxs(Re,{onClick:()=>{X(!1),o()},children:[e.jsx(kt,{})," ",j("settingsTitle")]}),e.jsxs(Re,{onClick:()=>{X(!1),m()},children:[e.jsx(bt,{})," ",j("searchGlobal")]}),e.jsxs(Re,{onClick:()=>{X(!1),u()},children:[e.jsx(jt,{})," ",j("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(Ms,{settings:y,onChange:f,onPreview:g}),e.jsx(Is,{}),e.jsx("div",{className:"dd-header",children:j("language")}),$.map(d=>e.jsx(Re,{active:O===d.value,onClick:()=>N(d.value),children:d.label},d.value)),e.jsx("div",{className:"dd-header",children:j("theme")}),e.jsx(Re,{active:T===null,onClick:()=>{D(null),X(!1)},children:j("themeDefault")}),v.map(d=>e.jsx(Re,{active:T===d.id,onClick:()=>{D(d.id),X(!1)},children:O==="en"?d.nameEn??d.name:d.name},d.id)),e.jsx("div",{className:"dd-header",children:j("update")}),x(),ne(),e.jsxs("a",{className:"dd-refresh dd-more-link",href:"https://github.com/xing-shuyin/pi-web-ui",target:"_blank",rel:"noreferrer noopener",children:[e.jsx(Ss,{})," ",j("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:j("openFiles"),onClick:()=>a("right"),children:e.jsx(Ye,{})})]})]})}function Ls(t){const s=new Date(t),n=new Date;return s.toDateString()===n.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function ta(t,s){const n=new Map;for(const c of t){const i=n.get(c.cwd)??[];i.push(c),n.set(c.cwd,i)}const r=[...n.entries()].map(([c,i])=>({cwd:c,isCurrent:c===s,convs:i}));return r.sort((c,i)=>c.isCurrent?-1:i.isCurrent?1:c.cwd<i.cwd?-1:c.cwd>i.cwd?1:0),r}const sa="pi-web-ui:lp-collapse-projects",na="pi-web-ui:lp-collapse-convs",ia="pi-web-ui:lp-collapse-sessions";function It(t,s=!1){const[n,r]=l.useState(()=>{try{const i=localStorage.getItem(t);if(i==="1")return!0;if(i==="0")return!1}catch{}return s}),c=l.useCallback(()=>{r(i=>{const a=!i;try{localStorage.setItem(t,a?"1":"0")}catch{}return a})},[t]);return[n,c]}const wn="pi-web-ui:lp-sizes",qt={projects:1,convs:1,sessions:1};function aa(){try{const t=localStorage.getItem(wn);if(t){const s=JSON.parse(t);return{projects:typeof s.projects=="number"&&s.projects>0?s.projects:1,convs:typeof s.convs=="number"&&s.convs>0?s.convs:1,sessions:typeof s.sessions=="number"&&s.sessions>0?s.sessions:1}}}catch{}return{...qt}}const ra=l.memo(function({ready:s,status:n,cwd:r,sessionFile:c,conversations:i,sessions:a,projects:o,activeConversationId:u,send:m,active:y,collapsible:f,onToggleCollapse:g}){const v=xe(),T=c,D=r,[O,N]=l.useState(null),[j,V]=l.useState(null),[q,J]=l.useState(""),[K,E]=It(sa,!1),[H,k]=It(na,!1),[A,F]=It(ia,!1),X=l.useRef(null),[$,Y]=l.useState(()=>aa());l.useEffect(()=>{try{localStorage.setItem(wn,JSON.stringify($))}catch{}},[$]);const Q=l.useCallback((d,b)=>w=>{w.preventDefault();const B=w.currentTarget,se=w.clientY,G={...$},ie=X.current;if(!ie)return;const ye=32,le=72,we=[{key:"projects",visible:o.length>0,collapsed:K},{key:"convs",visible:i.length>0,collapsed:H},{key:"sessions",visible:!0,collapsed:A}].filter(me=>me.visible),ve=we.filter(me=>me.collapsed).length,re=we.filter(me=>!me.collapsed).map(me=>me.key).reduce((me,ke)=>me+(G[ke]??1),0)||1,h=Math.max(120,ie.clientHeight-ve*ye),z=(G[d]??1)+(G[b]??1),pe=le/h*re;B.classList.add("dragging"),document.body.classList.add("lp-resizing");const ce=me=>{const Me=(me.clientY-se)/h*re;let he=(G[d]??1)+Me;const Ie=z-pe;he=Math.max(pe,Math.min(Ie,he));const Le=z-he;Y(_e=>({..._e,[d]:he,[b]:Le}))},fe=()=>{window.removeEventListener("pointermove",ce),window.removeEventListener("pointerup",fe),B.classList.remove("dragging"),document.body.classList.remove("lp-resizing")};window.addEventListener("pointermove",ce),window.addEventListener("pointerup",fe)},[$,o.length,i.length,K,H,A]);l.useEffect(()=>{!y||!s||n!=="open"||r&&(m({type:"list_sessions"}),m({type:"list_projects"}))},[y,s,n,r,m]);const P=d=>{const b=d.name||d.firstMessage.trim();return b.length>0?b:v("emptyChat")},I=d=>d.split(/[\\/]/).pop()||d,C=(d,b,w,B,se)=>{const G=O===d;return e.jsx("button",{type:"button",className:`lp-del ${G?"confirm":""}`,title:G?w:b,onClick:ie=>{ie.stopPropagation(),G?(N(null),B()):N(d)},children:G?e.jsx(ut,{}):se??e.jsx(Be,{})})},W=(d,b,w,B)=>e.jsxs("button",{type:"button",className:"lp-section-title panel-section-title",onClick:w,title:v(b?"expandSection":"collapseSection"),children:[e.jsxs("span",{className:"lp-section-title-text",children:[d,B!==void 0?` (${B})`:""]}),e.jsx("span",{className:"lp-section-chevron",children:b?e.jsx(Ge,{}):e.jsx(dt,{})})]}),ne=[{key:"projects",visible:o.length>0,collapsed:K},{key:"convs",visible:i.length>0,collapsed:H},{key:"sessions",visible:!0,collapsed:A}].filter(d=>d.visible).filter(d=>!d.collapsed),x=ne.reduce((d,b)=>d+($[b.key]??1),0)||1,R=d=>ne.length<=1?1:($[d]??1)/x*ne.length;return e.jsxs("aside",{ref:X,className:"panel panel-left lp-panel",children:[f&&g&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:v("collapsePanel"),onClick:g,children:e.jsx(gn,{})}),o.length>0&&e.jsxs("div",{className:`lp-section panel-projects ${K?"collapsed":""}`,style:K?void 0:{flex:`${R("projects")} 1 0px`},children:[W(v("recentProjects"),K,E,o.length),!K&&e.jsx("div",{className:"lp-section-body projects-scroll",children:o.map(d=>{const b=D===d.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>N(w=>w===`proj:${d.path}`?null:w),children:[e.jsxs("button",{type:"button",className:`project-item ${b?"active":""}`,title:d.path,onClick:()=>{b||m({type:"set_cwd",path:d.path})},children:[e.jsx(Ye,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:I(d.path)}),e.jsx("span",{className:"project-path",children:d.path})]}),e.jsx("span",{className:"project-time",children:Ls(d.lastUsed)})]}),C(`proj:${d.path}`,v("deleteProject"),v("deleteProjectConfirm"),()=>m({type:"remove_project",path:d.path}))]},d.path)})})]}),o.length>0&&!K&&(i.length>0?!H:!A)&&e.jsx("div",{className:"lp-sash",onPointerDown:Q("projects",i.length>0?"convs":"sessions"),onDoubleClick:()=>Y({...qt}),title:v("dragToResize")}),i.length>0&&e.jsxs("div",{className:`lp-section lp-section-convs panel-convs ${H?"collapsed":""}`,style:H?void 0:{flex:`${R("convs")} 1 0px`},children:[W(v("runningConversations"),H,k,i.length),!H&&e.jsx("div",{className:"lp-section-body convs-scroll",children:ta(i,r).map(d=>e.jsxs("div",{className:"panel-conv-group",children:[!d.isCurrent&&e.jsx("div",{className:"panel-conv-group-title",title:d.cwd,children:I(d.cwd)}),d.convs.map(b=>{const w=u===b.id;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>N(B=>B===`conv:${b.id}`?null:B),children:[e.jsxs("button",{type:"button",className:`session-item ${w?"active":""}`,title:`${b.title}${d.isCurrent?"":` — ${d.cwd}`}`,onClick:()=>{w||m({type:"switch_conversation",id:b.id})},children:[e.jsx(tt,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[j===`conv:${b.id}`?e.jsx("input",{autoFocus:!0,className:"session-rename-input",value:q,placeholder:v("renameSessionPlaceholder"),onClick:B=>B.stopPropagation(),onChange:B=>J(B.target.value),onKeyDown:B=>{if(B.stopPropagation(),B.key==="Enter"&&!B.nativeEvent.isComposing){const se=q.trim();se&&m({type:"rename_conversation",id:b.id,name:se}),V(null)}else B.key==="Escape"&&V(null)},onBlur:()=>V(null)}):e.jsxs("span",{className:"session-title",children:[b.isSubagent&&e.jsx("span",{className:"subagent-badge",children:v("subagentBadge")}),b.title]}),j===`conv:${b.id}`?null:e.jsx("span",{className:"session-sub",children:w?v("current"):v("messageCount",{n:b.messageCount})})]}),b.isStreaming&&e.jsx("span",{className:"conv-streaming",title:v("streaming")})]}),e.jsx("button",{type:"button",className:"lp-del lp-rename",title:v("renameSession"),onClick:B=>{B.stopPropagation(),N(null),J(b.title),V(`conv:${b.id}`)},children:e.jsx(wt,{})}),!b.isStreaming&&!w&&C(`conv:${b.id}`,v("dismissConversation"),v("dismissConversationConfirm"),()=>m({type:"dismiss_conversation",id:b.id}),e.jsx(Ee,{})),b.isStreaming&&e.jsx("span",{className:"lp-row-stalled",title:v("streaming"),style:{position:"absolute",right:28,top:"50%",transform:"translateY(-50%)"}})]},b.id)})]},d.cwd))})]}),i.length>0&&!H&&!A&&e.jsx("div",{className:"lp-sash",onPointerDown:Q("convs","sessions"),onDoubleClick:()=>Y({...qt}),title:v("dragToResize")}),e.jsxs("div",{className:`lp-section lp-section-sessions panel-sessions ${A?"collapsed":""}`,style:A?void 0:{flex:`${R("sessions")} 1 0px`},children:[W(v("historySessions"),A,F,a.length),!A&&e.jsxs("div",{className:"lp-section-body sessions-scroll",children:[a.length===0&&e.jsx("div",{className:"panel-empty",children:v("noHistory")}),a.map(d=>{const b=T===d.path;return e.jsxs("div",{className:"lp-row",onMouseLeave:()=>N(w=>w===`sess:${d.path}`?null:w),children:[e.jsxs("button",{type:"button",className:`session-item ${b?"active":""}`,title:d.path,onClick:()=>{j||b||m({type:"switch_session",path:d.path})},children:[e.jsx(tt,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[j===d.path?e.jsx("input",{autoFocus:!0,className:"session-rename-input",value:q,placeholder:v("renameSessionPlaceholder"),onClick:w=>w.stopPropagation(),onChange:w=>J(w.target.value),onKeyDown:w=>{if(w.stopPropagation(),w.key==="Enter"&&!w.nativeEvent.isComposing){const B=q.trim();B&&m({type:"rename_session",path:d.path,name:B}),V(null)}else w.key==="Escape"&&V(null)},onBlur:()=>V(null)}):e.jsx("span",{className:"session-title",children:P(d)}),j===d.path?null:e.jsxs("span",{className:"session-sub",children:[b?v("current"):v("messageCount",{n:d.messageCount}),d.source==="tui"&&e.jsx("span",{className:"session-src",title:v("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:Ls(d.modified)})]}),e.jsx("button",{type:"button",className:"lp-del lp-rename",title:v("renameSession"),onClick:w=>{w.stopPropagation(),N(null),J(d.name??""),V(d.path)},children:e.jsx(wt,{})}),C(`sess:${d.path}`,v("deleteSession"),v("deleteSessionConfirm"),()=>m({type:"delete_session",path:d.path}))]},d.path)})]})]})]})}),Nn="pi-web-ui:token";function la(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem(Nn,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function oa(){try{return localStorage.getItem(Nn)??""}catch{return""}}function Ct(t){const s=oa();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}function ca(t,s){const n=s.assistantMessageEvent,r=t.stats.tokens,c=s.usage!==null?{...r,...s.usage}:r,i=c===r?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,u=o&&o.id===s.messageId?o:{id:s.messageId,content:[]},m=[...u.content],y=n.type==="thinking_delta"?"thinking":"text",f=n.contentIndex??m.length-1;return f>=0&&f<m.length&&m[f].type===y?m[f]=y==="thinking"?{type:"thinking",thinking:(m[f].thinking??"")+a}:{type:"text",text:(m[f].text??"")+a}:m.push(y==="thinking"?{type:"thinking",thinking:a}:{type:"text",text:a}),{...t,stats:i,streamingMessage:{...u,id:s.messageId,content:m}}}const zt="pi-web-ui:plugin-data";function da(t,s){window.dispatchEvent(new CustomEvent(zt,{detail:{pluginId:t,payload:s}}))}function ua(t){const s=n=>{const r=n.detail;t(r.pluginId,r.payload)};return window.addEventListener(zt,s),()=>window.removeEventListener(zt,s)}const Ze=new Map,Vt=new Set,Je=new Set;let Ds=-1;function Cn(){return[...Ze.values()]}function pa(){const t=Cn();for(const s of Vt)s(t)}function ma(t){return Vt.add(t),t(Cn()),()=>Vt.delete(t)}async function ha(t,s){s!==Ds&&(Ds=s,Ze.clear(),Je.clear());const n=new Set(t.map(r=>r.id));for(const r of[...Ze.keys()])n.has(r)||Ze.delete(r);for(const r of[...Je])n.has(r)||Je.delete(r);await Promise.all(t.filter(r=>r.hasClient&&!r.error&&!Ze.has(r.id)&&!Je.has(r.id)).map(async r=>{try{const i=(await import(Ve(`/plugins/${encodeURIComponent(r.id)}/client/entry.mjs?e=${s}`))).default;i&&typeof i.mount=="function"?Ze.set(r.id,{info:r,module:i}):(Je.add(r.id),console.error(`[plugin:${r.id}] entry.mjs 缺少 default.mount`))}catch(c){Je.add(r.id),console.error(`[plugin:${r.id}] 客户端加载失败:`,c)}})),pa()}function ga(t,s){return{pluginId:t,send:n=>s({type:"plugin_message",pluginId:t,payload:n}),onData:n=>ua((r,c)=>{r===t&&n(c)})}}const fa=11,Lt=2e5,xa=2e5,ya="LIVE_OMIT",va={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 ka(){const t=new Map,s=new Map,n=(r,c)=>`${r}:${c}`;return{write(r,c,i){const a=n(r,c),o=t.get(a);if(o&&o.size>0){for(const y of o)try{y.write(i)}catch{}return}const u=s.get(a)??"",m=u.length+i.length>xa?i:u+i;s.set(a,m)},register(r,c,i){const a=n(r,c);let o=t.get(a);o||(o=new Set,t.set(a,o)),o.add(i);const u=s.get(a);if(u){try{i.write(u)}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 As(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 r=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),r=!0);return r?new Map(t):t}function Bs(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 r=!1;for(const c of t.keys())n.has(c)&&(t.delete(c),r=!0);return r?new Map(t):t}function ba(t,s){var n,r,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,engine:s.engine,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==fa};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:As(t.liveOutputs,s.state),toolStatuses:Bs(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 u={...a,...o.state,messages:o.appended.length>0?[...a.messages,...o.appended]:a.messages};return{...t,ready:!0,state:u,activeConversationId:u.conversationId,liveOutputs:As(t.liveOutputs,u),toolStatuses:Bs(t.toolStatuses,u)}}case"tool_delta":{const a=t.liveOutputs.get(s.toolCallId),o=((a==null?void 0:a.text)??"")+s.delta,u=o.length>Lt?`…[${ya}:${o.length-Lt}]…
|
|
305
|
-
`+o.slice(o.length-Lt):o,m=new Map(t.liveOutputs);return m.set(s.toolCallId,{toolName:s.toolName,text:u}),{...t,liveOutputs:m}}case"message_delta":{const a=t.state;return!a||a.conversationId!==s.msg.conversationId?t:{...t,state:ca(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"provider_keys":return{...t,providerKeys:s.keys};case"fetch_models_result":return{...t,fetchModelsResult:s.result};case"refresh_provider_result":return{...t,refreshProviderResult:s.result};case"clone_provider_result":return{...t,cloneProviderResult:s.result};case"install_result":return{...t,installResult:s.result};case"scm_data":return{...t,scmData:s.data};case"file_search_result":return{...t,fileSearch:s.result};case"session_search_result":return{...t,sessionSearch:s.result};case"scm_changed":return{...t,scmDirty:t.scmDirty+1};case"path_completions":return{...t,pathCompletions:s.completions};case"update_status":return{...t,update:s.status};case"update_status_all":return{...t,updatesAll:s.items};case"updates_check_started":return{...t,updatesAll:null};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"question":return{...t,question:s.question};case"commands":return{...t,commands:s.commands,commandsPath:s.path};case"slash_commands":return{...t,slashCommands:s.commands};case"goal_status":return{...t,goal:s.status};case"settings":return{...t,settings:s.settings};case"bg_servers":return{...t,bgServers:s.servers};case"plugins":return{...t,plugins:s.plugins,pluginsEpoch:s.epoch};case"dsh_patches":return{...t,dshPatches:{patchDir:s.patchDir,files:s.files}};case"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(a=>a.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(n=t.state)!=null&&n.conversationId)&&s.conversationId!==(t.activeConversationId||((r=t.state)==null?void 0:r.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)??""}})};case"terminal_active":return{...t,terminalActiveId:s.id};default:return t}}const _s="pi-web-client-id";let Dt=null;function es(){if(Dt)return Dt;let t=null;try{t=sessionStorage.getItem(_s),t||(t=Ue(),sessionStorage.setItem(_s,t))}catch{t=t??Ue()}return Dt=t,t}function ja(){const t=location.protocol==="https:"?"wss:":"ws:";return Ct(`${t}//${location.host}${Ve("/ws")}`)}function wa(){const[t,s]=l.useReducer(ba,{status:"connecting",ready:!1,state:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:[],conversations:[],activeConversationId:"",projects:[],files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},installResult:null,pathCompletions:[],update:null,updatesAll:null,widgets:[],statuses:[],dialog:null,question:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],terminalActiveId:null,goal:va,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,plugins:[],pluginsEpoch:0,dshPatches:null,protocolMismatch:!1}),n=l.useRef(null),r=l.useRef(ka()),c=l.useRef(0),i=l.useRef(null),a=l.useRef(!0),o=l.useRef(0),u=l.useRef(0),m=l.useRef(new Map),y=l.useRef(null),f=()=>{y.current||(y.current=setTimeout(()=>{y.current=null;const E=n.current;E&&E.readyState===WebSocket.OPEN&&E.send(JSON.stringify({type:"get_state"}))},300))},g=(E,H)=>{var F;const k=m.current,A=k.get(E);if(A!==void 0&&H!==A+1){const X=K.current.chat,$=X.activeConversationId||((F=X.state)==null?void 0:F.conversationId);E===$&&f()}k.set(E,H)},v=l.useCallback((E,H)=>{const k=++u.current;s({type:"notice",notice:{id:k,level:E,text:H}})},[]),T=l.useCallback(E=>{const H=n.current;return H&&H.readyState===WebSocket.OPEN?(E.type==="check_updates_all"&&E.force===!0&&s({type:"updates_check_started"}),H.send(JSON.stringify(E)),!0):!1},[]),D=l.useCallback(()=>{if(!a.current)return;s({type:"status",status:"connecting"});const E=new WebSocket(ja());n.current=E,E.onopen=()=>{n.current===E&&(s({type:"status",status:"open"}),c.current=0,o.current=Date.now(),E.send(JSON.stringify({type:"hello",clientId:es()})))},E.onmessage=H=>{if(n.current!==E)return;o.current=Date.now();let k;try{k=JSON.parse(H.data)}catch{return}switch(k.type){case"ready":s({type:"ready",serverVersion:k.serverVersion,protocolVersion:k.protocolVersion,engine:k.engine}),E.send(JSON.stringify({type:"get_state"})),E.send(JSON.stringify({type:"list_files"})),E.send(JSON.stringify({type:"list_models"})),E.send(JSON.stringify({type:"list_commands"})),E.send(JSON.stringify({type:"get_commands"})),E.send(JSON.stringify({type:"check_update"})),E.send(JSON.stringify({type:"check_updates_all"}));break;case"snapshot":m.current=new Map,s({type:"snapshot",state:k.state});break;case"snapshot_delta":{const A=K.current.chat.state;(!A||A.conversationId!==k.conversationId||A.rev!==k.baseRev)&&f(),s({type:"snapshot_delta",msg:k});break}case"tool_delta":g(k.conversationId,k.seq),s({type:"tool_delta",toolCallId:k.toolCallId,toolName:k.toolName,delta:k.delta});break;case"tool_status":s({type:"tool_status",status:k});break;case"message_delta":{g(k.conversationId,k.seq),s({type:"message_delta",msg:k});break}case"notice":{const A=++u.current;s({type:"notice",notice:{id:A,level:k.level,text:k.text,textEn:k.textEn}});break}case"sessions":s({type:"sessions",sessions:k.sessions});break;case"conversations":s({type:"conversations",conversations:k.conversations,activeId:k.activeId});break;case"projects":s({type:"projects",projects:k.projects});break;case"files":s({type:"files",files:k});break;case"file_changed":s({type:"file_changed",path:k.path});break;case"file_content":s({type:"file_content",content:k});break;case"models":s({type:"models",models:k.models,loading:!1});break;case"models_config":s({type:"models_config",providers:k.providers});break;case"providers_status":s({type:"providers_status",providers:k.providers});break;case"provider_keys":s({type:"provider_keys",keys:k.keys});break;case"fetch_models_result":s({type:"fetch_models_result",result:{reqId:k.reqId,ok:k.ok,models:k.models,error:k.error}});break;case"refresh_provider_result":s({type:"refresh_provider_result",result:{reqId:k.reqId,ok:k.ok,added:k.added,total:k.total,error:k.error}});break;case"clone_provider_result":s({type:"clone_provider_result",result:{reqId:k.reqId,ok:k.ok,config:k.config,configs:k.configs,error:k.error}});break;case"scm_data":s({type:"scm_data",data:k});break;case"search_files_result":s({type:"file_search_result",result:{reqId:k.reqId,ok:k.ok,results:k.results,truncated:k.truncated}});break;case"session_search_results":s({type:"session_search_result",result:{reqId:k.reqId,ok:k.ok,results:k.results}});break;case"scm_changed":s({type:"scm_changed"});break;case"install_result":s({type:"install_result",result:k});break;case"path_completions":s({type:"path_completions",completions:k.completions});break;case"update_status":s({type:"update_status",status:k});break;case"update_status_all":s({type:"update_status_all",items:k.items});break;case"widgets":s({type:"widgets",widgets:k.widgets});break;case"statuses":s({type:"statuses",statuses:k.statuses});break;case"dialog":s({type:"dialog",dialog:{id:k.id,kind:k.kind,title:k.title,args:k.args}});break;case"dialog_closed":s({type:"dialog",dialog:null});break;case"question_pending":s({type:"question",question:{id:k.id,questions:k.questions}});break;case"terminal_output":r.current.write(k.conversationId??K.current.chat.activeConversationId,k.terminalId,k.data);break;case"terminal_exit":s({type:"terminal_exit",conversationId:k.conversationId,terminalId:k.terminalId,exitCode:k.exitCode});break;case"terminal_list":s({type:"terminal_list",conversationId:k.conversationId,terminals:k.terminals});break;case"commands":s({type:"commands",commands:k.commands,path:k.path});break;case"slash_commands":s({type:"slash_commands",commands:k.commands});break;case"goal_status":s({type:"goal_status",status:k.status});break;case"settings_state":s({type:"settings",settings:k.settings});break;case"bg_servers":s({type:"bg_servers",servers:k.servers});break;case"plugins":s({type:"plugins",plugins:k.plugins,epoch:k.epoch});break;case"dsh_patches":s({type:"dsh_patches",patchDir:k.patchDir,files:k.files});break;case"plugin_data":da(k.pluginId,k.payload);break}},E.onclose=()=>{if(n.current===E&&(n.current=null),r.current.clear(),!a.current||n.current&&n.current!==E)return;s({type:"status",status:"closed"});const H=Math.min(1e3*2**c.current,1e4);c.current+=1,i.current=setTimeout(()=>{i.current=null,D()},H)},E.onerror=()=>{}},[]);l.useEffect(()=>{a.current=!0,D();const E=setInterval(()=>{if(!a.current)return;const H=n.current;H&&H.readyState===WebSocket.OPEN&&Date.now()-o.current>3e4&&H.close()},5e3);return()=>{var H;a.current=!1,clearInterval(E),i.current&&(clearTimeout(i.current),i.current=null),(H=n.current)==null||H.close(),n.current=null}},[D]);const O=l.useCallback(E=>s({type:"dismiss_notice",id:E}),[]),N=l.useCallback(E=>s({type:"terminal_add",meta:E}),[]),j=l.useCallback(E=>s({type:"terminal_remove",id:E}),[]),V=l.useCallback(E=>s({type:"terminal_restart",terminalId:E}),[]),q=l.useCallback(E=>s({type:"terminal_active",id:E}),[]),J=l.useCallback((E,H,k)=>r.current.register(E,H,k),[]),K=l.useRef({chat:t,send:T,pushNotice:v,dismissNotice:O,terminal:{create:N,close:j,register:J,restart:V,select:q}});return K.current={chat:t,send:T,pushNotice:v,dismissNotice:O,terminal:{create:N,close:j,register:J,restart:V,select:q}},K.current}const Na=200*1024*1024,Ca=/windows/i.test(navigator.userAgent),Sa=/[<>:"/\\|?*\u0000-\u001f]/g,Ta=/[. ]+$/,Ea=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function Pa(t){const s=t.replace(Sa,"_").replace(Ta,"");return s?Ea.test(s)?`_${s}`:s:"_"}function Fs(t,s=!0){const n=new URLSearchParams({clientId:es(),path:t,...s?{download:"1"}:{}});return Ct(Ve(`/api/file?${n}`))}const Sn="FILE_NOT_FOUND";async function Ma(t,s){const n=Ca?Pa(s):s;try{const r=await fetch(Fs(t));if(!r.ok)return{ok:!1,cancelled:!1,error:await r.text().catch(()=>"")||(r.status===404?Sn:`HTTP ${r.status}`)};if(Number(r.headers.get("content-length")??"0")>Na)return window.location.assign(Fs(t)),{ok:!0};const i=await r.blob();return window.showSaveFilePicker&&window.isSecureContext?Ra(i,n):Gt(i,n)}catch(r){return{ok:!1,cancelled:!1,error:r instanceof Error?r.message:String(r)}}}async function Ra(t,s){let n;const r=window.showSaveFilePicker;if(!r)return Gt(t,s);try{n=await r({suggestedName:s})}catch(c){return c instanceof DOMException&&c.name==="AbortError"?{ok:!1,cancelled:!0}:Gt(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 Gt(t,s){const n=URL.createObjectURL(t),r=document.createElement("a");return r.href=n,r.download=s,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}const Ia=l.memo(function({files:s,fileChanged:n,widgets:r,cwd:c,send:i,onAttach:a,onPreview:o,onNotice:u,collapsible:m,onToggleCollapse:y}){const f=xe(),[g,v]=l.useState(""),[T,D]=l.useState(null),[O,N]=l.useState(!1),[j,V]=l.useState(null),q=l.useRef(""),J=l.useRef(null),K=l.useCallback((d,b)=>{d.preventDefault(),q.current=b,V({x:Math.min(d.clientX,window.innerWidth-220),y:Math.min(d.clientY,window.innerHeight-90)})},[]),E=l.useCallback(()=>V(null),[]);l.useEffect(()=>{if(!j)return;const d=B=>{var se;(se=B.target)!=null&&se.closest(".ctx-menu")||E()},b=B=>{B.key==="Escape"&&E()};window.addEventListener("mousedown",d,!0),window.addEventListener("keydown",b);const w=()=>E();return window.addEventListener("blur",w),()=>{window.removeEventListener("mousedown",d,!0),window.removeEventListener("keydown",b),window.removeEventListener("blur",w)}},[j,E]);const H=l.useCallback(()=>{var d;E(),J.current&&(J.current.value=""),(d=J.current)==null||d.click()},[E]),k=l.useCallback((d,b)=>{for(const w of b){const B=new FileReader;B.onload=()=>{const se=B.result,G=se.slice(se.indexOf(",")+1);G&&i({type:"upload_file",dirPath:d,name:w.name,data:G})},B.readAsDataURL(w)}},[i]),A=l.useCallback(d=>{k(q.current,Array.from(d.target.files??[]))},[k]),F=l.useRef(null),X=d=>{var b;return Array.from(((b=d.dataTransfer)==null?void 0:b.types)??[]).includes("Files")},$=l.useCallback(()=>{var d,b;(d=F.current)==null||d.querySelectorAll(".file-item.drop-target").forEach(w=>w.classList.remove("drop-target")),(b=F.current)==null||b.classList.remove("drop-root")},[]),Y=l.useCallback(d=>{var w,B;if($(),d==null)return;const b=(w=F.current)==null?void 0:w.querySelector(`.file-item[data-path="${CSS.escape(d)}"]`);b?b.classList.add("drop-target"):(B=F.current)==null||B.classList.add("drop-root")},[$]),Q=d=>{const b=d instanceof Element?d.closest(".file-item"):null;return(b==null?void 0:b.dataset.type)==="dir"?b.dataset.path??g:g},P=l.useCallback(()=>{const d=document.querySelector(".app");d&&d.dispatchEvent(new DragEvent("dragleave",{bubbles:!0}))},[]),I=1e4,C=l.useRef(0),W=l.useRef(void 0),U=l.useCallback((d,b)=>{const w=++C.current;v(d),b!=null&&b.silent||N(!0),i({type:"list_files",path:d===""?void 0:d})||C.current===w&&N(!1)},[i]);l.useEffect(()=>{s&&s.path===g&&N(!1)},[s,g]),l.useEffect(()=>{if(c!==W.current){W.current=c,U("",{silent:!0});return}const d=setInterval(()=>{document.visibilityState!=="hidden"&&U(g,{silent:!0})},I);return()=>clearInterval(d)},[c,g,U]),l.useEffect(()=>{n&&n.path===g&&U(g,{silent:!0})},[n,g,U]);const ne=d=>U(d),x=()=>{(s==null?void 0:s.parent)!==null&&(s==null?void 0:s.parent)!==void 0&&U(s.parent)},R=g.split("/").filter(Boolean);return e.jsxs("aside",{className:"panel panel-right",children:[m&&y&&e.jsx("button",{type:"button",className:"panel-collapse-btn",title:f("collapsePanel"),onClick:y,children:e.jsx(hn,{})}),e.jsxs("div",{className:"panel-crumbs",children:[e.jsx("button",{type:"button",className:`crumb ${g===""?"active":""}`,onClick:()=>U(""),children:f("rootDir")}),R.map((d,b)=>{const w=R.slice(0,b+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx(Nt,{}),e.jsx("button",{type:"button",className:`crumb ${w===g?"active":""}`,onClick:()=>U(w),children:d})]},w)})]}),e.jsxs("div",{ref:F,className:"panel-body",onContextMenu:d=>K(d,g),onDragOver:d=>{X(d)&&(d.preventDefault(),d.stopPropagation(),d.dataTransfer.dropEffect="copy",P(),Y(Q(d.target)))},onDragLeave:d=>{d.relatedTarget&&d.currentTarget.contains(d.relatedTarget)||$()},onDrop:d=>{var w;if($(),!X(d))return;d.preventDefault(),d.stopPropagation(),P();const b=Array.from(((w=d.dataTransfer)==null?void 0:w.files)??[]);if(b.length===0){u("warning",f("foldersNotSupported"));return}k(Q(d.target),b)},onDragEnd:$,children:[e.jsx("input",{ref:J,type:"file",multiple:!0,hidden:!0,onChange:A}),O&&e.jsx("div",{className:"panel-empty",children:f("loading")}),!O&&s&&s.path===g&&e.jsxs(e.Fragment,{children:[s.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:x,children:[e.jsx(Ye,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),s.entries.map(d=>d.type==="dir"?e.jsxs("div",{className:"file-item dir","data-type":"dir","data-path":d.path,onContextMenu:b=>{b.stopPropagation(),K(b,d.path)},children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>ne(d.path),children:[e.jsx(Ye,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:d.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":f("linkFolderTip"),onClick:()=>a(d.path,d.name,"reference",!0),children:e.jsx(Kt,{})})]},d.path):e.jsxs("div",{className:"file-item file","data-type":"file","data-path":d.path,onContextMenu:b=>{b.stopPropagation(),K(b,g)},children:[e.jsxs("button",{type:"button",className:"file-name",title:`${d.path} — ${f("previewFile")}`,onClick:()=>o(d.path,d.name),children:[e.jsx(_i,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:d.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":f("downloadFile"),onClick:()=>{Ma(d.path,d.name).then(b=>{b.ok||b.cancelled||u("error",f("downloadFailed",{error:b.error===Sn?f("fileNotFoundShort"):b.error}))})},children:e.jsx(Zt,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":f("attachInlineTip"),onClick:()=>a(d.path,d.name,"inline"),children:e.jsx(He,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":f("referenceTip"),onClick:()=>a(d.path,d.name,"reference"),children:e.jsx(Kt,{})})]},d.path)),s.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:f("filesTruncated")})]}),!O&&!s&&e.jsx("div",{className:"panel-empty",children:f("noFiles")})]}),r.filter(d=>d.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:r.filter(d=>d.lines.length>0).map(d=>e.jsxs("div",{className:"widget",children:[e.jsxs("button",{type:"button",className:"widget-title widget-title-btn",title:f("widgetExpand"),onClick:()=>D(d.key),children:[e.jsx("span",{children:d.key}),e.jsx(Ri,{})]}),e.jsx("pre",{className:"widget-lines",children:d.lines.join(`
|
|
306
|
-
`)})]},d.key))}),T&&(()=>{const d=r.find(b=>b.key===T);return d?e.jsx("div",{className:"modal-backdrop",onClick:()=>D(null),children:e.jsxs("div",{className:"widget-expand",onClick:b=>b.stopPropagation(),children:[e.jsxs("div",{className:"widget-expand-head",children:[e.jsx("span",{className:"widget-expand-title",children:d.key}),e.jsx("button",{type:"button",className:"btn",title:f("close"),onClick:()=>D(null),children:e.jsx(Ee,{})})]}),e.jsx("pre",{className:"widget-expand-lines",children:d.lines.join(`
|
|
307
|
-
`)})]})}):null})(),j&&e.jsx("div",{className:"ctx-menu",style:{left:j.x,top:j.y},onContextMenu:d=>{d.preventDefault(),d.stopPropagation()},children:e.jsxs("button",{type:"button",className:"ctx-item",onClick:H,children:[e.jsx(bi,{}),q.current===g?f("uploadToCurrentDir"):f("uploadToFolder")]})})]})});var La=rn();const Tn=l.memo(function({text:s}){const n=xe(),[r,c]=l.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:r?e.jsx(ut,{}):e.jsx(mn,{})}):null});function Da(t){const s=r=>{var c;if(typeof r=="string"||typeof r=="number"){const i=String(r);return i===""?[[]]:i.split(`
|
|
308
|
-
`).map(a=>a===""?[]:[a])}if(Array.isArray(r)){let i=[];for(const a of r){const o=s(a);if(i.length===0)i=o;else{const u=o[0]??[];i[i.length-1].push(...u),i.push(...o.slice(1))}}return i}if(r&&typeof r=="object"&&"props"in r){const i=r,a=(c=i.props)==null?void 0:c.children,o={...i.props,children:void 0},u=a==null?[]:s(a);return u.length===0?[[l.createElement(i.type,o)]]:u.map(m=>[l.createElement(i.type,o,...m)])}return[[r]]},n=s(t);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}const En=[ri],Pn=[[ai,{detect:!0,ignoreMissing:!0}]];function Mn({text:t}){return e.jsx(an,{remarkPlugins:En,rehypePlugins:Pn,components:{pre:Aa},children:t})}const St=l.memo(function({text:s}){return e.jsx("div",{className:"md",children:e.jsx(Mn,{text:s})})});function Aa({children:t,...s}){var a;const n=t&&typeof t=="object"&&"props"in t?(a=t.props)==null?void 0:a.children:t,r=Da(n),c=r.length>1,i=c?`${String(r.length).length+1}ch`:void 0;return e.jsxs("div",{className:"codeblock",children:[e.jsx(Tn,{text:Qt(t)}),e.jsx("pre",{...s,children:r.map((o,u)=>e.jsxs("div",{className:"code-line",children:[c&&e.jsx("span",{className:"code-num",style:i?{width:i}:void 0,children:u+1}),e.jsx("code",{className:"code-line-body hljs",children:o})]},u))})]})}function Qt(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(Qt).join("");if(t&&typeof t=="object"&&"props"in t){const s=t.props;return Qt(s==null?void 0:s.children)}return""}const Ba=/^\s{0,3}(`{3,}|~{3,})/,_a=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function At(t){return t.trim()===""}function $s(t){const s=Ba.exec(t);return s?s[1]:null}function Fa(t){const s=t.split(`
|
|
309
|
-
`),n=[];let r=[],c=null;for(let i=0;i<s.length;i++){const a=s[i];if(c!==null){const u=$s(a);u&&u[0]===c[0]&&u.length>=c.length&&(c=null),r.push(a);continue}const o=$s(a);if(o&&!At(a)){c=o,r.push(a);continue}if(At(a)){let u=i;for(;u<s.length&&At(s[u]);)u++;if(!(u<s.length&&_a.test(s[u]))&&r.length>0){n.push(r.join(`
|
|
310
|
-
`)),r=[];continue}r.push(a);continue}r.push(a)}return{frozen:n,active:r.join(`
|
|
311
|
-
`),inFence:c!==null}}const $a=l.memo(function({text:s}){return e.jsx(an,{remarkPlugins:En,rehypePlugins:Pn,children:s})}),Hs=200;function Ha({text:t,inFence:s}){const[n,r]=l.useState(t),c=l.useRef(0),i=l.useRef(null);return l.useEffect(()=>{if(s)return;const a=Date.now()-c.current,o=()=>{c.current=Date.now(),r(t)};if(a>=Hs){o();return}return i.current=setTimeout(o,Hs-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(Mn,{text:n})}const Oa=l.memo(function({text:s}){const{frozen:n,active:r,inFence:c}=l.useMemo(()=>Fa(s),[s]);return e.jsxs("div",{className:"md",children:[n.map((i,a)=>e.jsx($a,{text:i},a)),r.length>0&&e.jsx(Ha,{text:r,inFence:c},n.length)]})});function Ka({thinking:t,streaming:s,wrap:n=!0,forceOpen:r=!1}){const c=xe(),[i,a]=l.useState(null),o=i??n,u=o||r,m=s?t.trimEnd().slice(-80):t.split(`
|
|
312
|
-
`)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${u?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>a(!o),children:[u?e.jsx(Ge,{}):e.jsx(Nt,{}),e.jsx(rt,{className:"thinking-icon"}),e.jsx("span",{className:"thinking-label",children:s&&u?e.jsxs("span",{className:"thinking-live-label",children:[c("thinkingNow"),e.jsx("span",{className:"dots"})]}):u?c("thinking"):c("thinkingPreview",{preview:m})})]}),u&&e.jsx("div",{className:"thinking-body",children:t})]})}const Wa={bash:"$",read:"📄",write:"✍️",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function Ua(t){return Wa[t]??"🛠"}const qa=l.memo(function({block:s,view:n,onKillBash:r,wrap:c=!0,forceOpen:i=!1}){var H,k,A,F;const a=xe(),[o,u]=l.useState(c),m=o||i,[y,f]=l.useState(!1),g=!n.result&&n.streaming&&!n.status,v=s.name==="bash"&&g,T=n.result!==void 0,D=!n.result&&!!n.status,O=((H=n.result)==null?void 0:H.isError)??((k=n.status)==null?void 0:k.isError)??!1,j=(n.result?n.result.content.map(X=>X.type==="text"?X.text:"").join(""):n.liveOutput??"").replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(X,$)=>a("liveOutputOmitted",{n:$})),V=O?"err":T?"ok":g||D?"run":"idle";let q=a(O?"error":T?"done":g?"running":D?"toolDoneWaitingModel":"toolQueued");const J=D&&((A=n.status)==null?void 0:A.durationMs)!==void 0?Va(n.status.durationMs):"";D&&J&&(q=`${q} · ${J}`);const K=D&&((F=n.status)==null?void 0:F.exitCode)!==void 0?`exit ${n.status.exitCode}`:"",E=()=>{s.argumentsText&&(navigator.clipboard.writeText(s.argumentsText),f(!0),setTimeout(()=>f(!1),1200))};return e.jsxs("div",{className:`toolcall ${V}`,children:[e.jsxs("div",{className:"toolcall-head",children:[e.jsx("span",{className:"toolcall-icon",children:Ua(s.name)}),e.jsx("span",{className:"toolcall-name",children:s.name}),e.jsxs("span",{className:"toolcall-status",children:[q,K&&e.jsx("em",{className:"toolcall-exit",children:K})]}),e.jsx("span",{className:"toolcall-spacer"}),v&&r&&e.jsxs("button",{type:"button",className:"toolcall-kill",title:a("stopBashTip"),onClick:r,children:[e.jsx(vt,{}),e.jsx("span",{children:a("stopBash")})]}),e.jsx("button",{type:"button",className:"toolcall-copy",title:a("copyArgs"),onClick:E,children:y?e.jsx(Hi,{}):e.jsx(mn,{})}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>u(X=>i?!0:!X),children:m?e.jsx(Ge,{}):e.jsx(Nt,{})})]}),m&&e.jsxs("div",{className:"toolcall-body",children:[s.argumentsText&&e.jsx("div",{className:"toolcall-args",children:s.name==="bash"&&s.argumentsText.startsWith("{")?e.jsx(za,{args:s.argumentsText}):e.jsx("pre",{children:s.argumentsText})}),j.length>0&&e.jsxs("div",{className:"toolcall-output",children:[e.jsxs("div",{className:"toolcall-output-label",children:[a(O?"errorOutput":"output"),(g||D)&&e.jsx("span",{className:"cursor"})]}),e.jsx("pre",{children:j})]}),g&&j.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",a("waitingOutput")]}),D&&j.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",a("waitingModel")]})]})]})});function za({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(et,{className:"termline-icon"}),e.jsx("code",{children:s.command}),typeof s.timeout=="number"&&e.jsxs("span",{className:"termline-timeout",children:["⏱ ",s.timeout,"s"]})]})}function Va(t){if(t===void 0)return"";const s=t/1e3;if(s<60)return`${s.toFixed(1)}s`;const n=Math.floor(s/60),r=Math.round(s%60);return`${n}m ${String(r).padStart(2,"0")}s`}const Ga=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function ts(t){var n;const s=t.match(Ga);return s?{name:s[1],location:s[2],content:s[3],userMessage:((n=s[4])==null?void 0:n.trim())||void 0}:null}const Qa=1568,Ya=2*1024*1024;function We(t){return t.startsWith("image/")&&t!=="image/svg+xml"&&t!=="image/svg"}async function Rn(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,Qa/Math.max(s.width,s.height)),r=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,u]of i){const m=document.createElement("canvas");m.width=r,m.height=c;const y=m.getContext("2d");if(!y)continue;o!=="image/png"&&(y.fillStyle="#ffffff",y.fillRect(0,0,r,c)),y.drawImage(s,0,0,r,c);const f=m.toDataURL(o,u),g=f.match(/^data:([^;]+);base64,/),v=g?g[1]:o,T=f.replace(/^data:[^;]*;base64,/,""),D=Math.floor(T.length*3/4);if(a={data:T,mimeType:v,name:t.name,size:D},D<=Ya)return a}return a}finally{s.close()}}const Ja=20*1024*1024;function ot(t){return t.type==="text"&&typeof t.text=="string"?t:null}function In(t){return t.type==="thinking"&&typeof t.thinking=="string"?t:null}function Ln(t){return t.type==="toolCall"&&typeof t.id=="string"&&typeof t.name=="string"?t:null}function Dn(t){return t.type==="image"&&typeof t.dataUrl=="string"?t:null}function An(t){return t.type==="bash"&&typeof t.command=="string"?t:null}function Xa(t){return t.imageData?"image":t.uploadPath?"upload":t.fileData?"file":"path"}function Za(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 Os=l.memo(function({message:s,toolResults:n,liveOutputs:r,toolStatuses:c,streaming:i,isLast:a,onEdit:o,onKillBash:u,onCollapse:m,questionAttachments:y,qnIndex:f,qnActive:g,onJump:v,thinkingWrap:T,toolsWrap:D,searchActive:O}){const N=xe(),[j,V]=l.useState(!1),[q,J]=l.useState(""),[K,E]=l.useState([]),[H,k]=l.useState(!1),[A,F]=l.useState(null),X=w=>{F(w),window.setTimeout(()=>F(B=>B===w?null:B),4e3)};if(s.role==="toolResult")return null;const $=s.role==="custom"&&s.customType==="file",Y=s.content.map(w=>{var B;return((B=ot(w))==null?void 0:B.text)??""}).filter(Boolean).join(`
|
|
313
|
-
`),Q=s.role==="user"?ts(Y):null,P=Q?Q.userMessage??`skill:${Q.name}`:Y.split(`
|
|
314
|
-
`).join(" ").trim(),I=i&&a&&s.content.length===0,C=s.role==="user"&&!i&&!I&&!!o,W=async w=>{const B=[];for(const se of w){if(!We(se.type))continue;const G=await Rn(se);G&&B.push({path:"",imageData:G.data,mimeType:G.mimeType,name:G.name})}B.length>0&&E(se=>[...se,...B])},U=async w=>{if(w.size>Ja){X(N("fileTooLarge",{name:w.name,size:20}));return}let B;try{B=(await new Promise((G,ie)=>{const ye=new FileReader;ye.onload=()=>G(ye.result),ye.onerror=()=>ie(ye.error??new Error("read failed")),ye.readAsDataURL(w)})).replace(/^data:[^;]*;base64,/,"")}catch{X(N("fileLoadFailed",{name:w.name}));return}E(se=>[...se,{path:"",fileData:B,name:w.name,size:w.size,mimeType:w.type||void 0}])},ne=async w=>{const B=[];for(const se of w)We(se.type)?B.push(se):U(se);B.length>0&&await W(B)},x=()=>{J(Q?`/skill:${Q.name}${Q.userMessage?` ${Q.userMessage}`:""}`:s.content.map(w=>{var B;return((B=ot(w))==null?void 0:B.text)??""}).filter(Boolean).join(`
|
|
315
|
-
`)),E(y??[]),V(!0)},R=()=>{const w=q.trim();w&&(o==null||o(s.id,w,K.length>0?K:void 0),V(!1))},d=s.role==="custom"&&(s.customType==="goal-review"||s.customType==="goal-wizard"),b=s.role==="custom"&&s.customType==="goal-wizard";return e.jsxs("div",{className:`msg msg-${s.role}${d?" 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"?b?N("goalWizardCard"):d?N("goalBarTitle"):s.customType==="file"?N("attachment"):`${N("plugin")} · ${s.customType??N("unknown")}`:Bn(s.role,N)}),s.model&&e.jsx("span",{className:"msg-model",children:s.model}),s.timestamp&&e.jsx("span",{className:"msg-time",children:nr(s.timestamp)}),m&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:N("collapseMsg"),onClick:()=>m(s.id),children:[e.jsx(dt,{})," ",N("collapseMsg")]}),f!==void 0&&v&&e.jsxs("button",{type:"button",className:`qn-tag ${g?"active":""}`,title:`${f+1}. ${P}`,"aria-label":`${f+1}. ${P}`,onClick:()=>v(s.id),children:[e.jsx("span",{className:"qn-tag-bar"}),e.jsx("span",{className:"qn-tag-idx",children:f+1})]})]}),e.jsx("div",{className:"msg-body",children:j?e.jsxs("div",{className:`msg-editor${H?" drag-over":""}`,onDragOver:w=>{w.preventDefault(),w.stopPropagation(),k(!0)},onDragLeave:w=>{w.currentTarget.contains(w.relatedTarget)||k(!1)},onDrop:w=>{var B;w.preventDefault(),w.stopPropagation(),k(!1),ne(Array.from(((B=w.dataTransfer)==null?void 0:B.files)??[]))},children:[K.length>0&&e.jsx("div",{className:"msg-editor-images",children:K.map((w,B)=>{var G;const se=Xa(w);return e.jsxs("span",{className:`msg-editor-img ${se==="image"?"":"file-chip"}`,title:Za(w,N),children:[se==="image"?e.jsx("img",{src:`data:${w.mimeType??"image/png"};base64,${w.imageData}`,alt:w.name}):e.jsxs("span",{className:"msg-editor-file",children:[e.jsx("span",{className:"msg-editor-file-icon",children:se==="path"?w.mode==="reference"?"🔗":"📎":"📄"}),e.jsx("span",{className:"msg-editor-file-name",children:w.name??((G=w.path)==null?void 0:G.split("/").pop())})]}),e.jsx("button",{type:"button",className:"msg-editor-img-remove",title:N("removeAttachment"),onClick:()=>E(ie=>ie.filter((ye,le)=>le!==B)),children:e.jsx(Ee,{})})]},`${w.name??w.path??"att"}-${B}`)})}),A&&e.jsx("div",{className:"msg-editor-notice",children:A}),e.jsx("textarea",{className:"msg-editor-input",value:q,autoFocus:!0,placeholder:N("editPlaceholder"),rows:Math.max(2,Math.min(10,q.split(`
|
|
316
|
-
`).length+1)),onChange:w=>J(w.target.value),onPaste:w=>{var se;const B=[];for(const G of((se=w.clipboardData)==null?void 0:se.items)??[])if(G.kind==="file"&&We(G.type)){const ie=G.getAsFile();ie&&B.push(ie)}B.length!==0&&(w.preventDefault(),W(B))},onKeyDown:w=>{w.key==="Enter"&&(w.metaKey||w.ctrlKey)?(w.preventDefault(),R()):w.key==="Escape"&&V(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsxs("span",{className:"msg-editor-hint",children:[e.jsx(Di,{})," ",N("editAttachmentHint")]}),e.jsx("button",{type:"button",className:"chip",onClick:()=>V(!1),children:N("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!q.trim(),title:N("reaskFromHere"),onClick:R,children:[e.jsx(Ut,{})," ",N("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),$?e.jsx(er,{message:s,forceOpen:O}):Q?e.jsxs(e.Fragment,{children:[e.jsx(sr,{block:Q,forceOpen:O}),Q.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(St,{text:Q.userMessage})}),s.content.map((w,B)=>w.type==="text"?null:e.jsx(Ws,{block:w,toolResults:n,liveOutputs:r,toolStatuses:c,streaming:i,isLast:a,onKillBash:u,toolsWrap:D,thinkingWrap:T,searchActive:O},`${s.id}-${B}`))]}):s.content.map((w,B)=>e.jsx(Ws,{block:w,toolResults:n,liveOutputs:r,toolStatuses:c,streaming:i,isLast:a,onKillBash:u,toolsWrap:D,thinkingWrap:T,searchActive:O},`${s.id}-${B}`)),I&&e.jsxs("div",{className:"thinking-wait",children:[N("thinkingWait"),e.jsx("span",{className:"dot"})]}),i&&a&&!I&&e.jsx("span",{className:"stream-cursor"})]})}),C&&!j&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:N("editReaskTip"),onClick:x,children:[e.jsx(Ut,{})," ",N("editReask")]})})]})});function er({message:t,forceOpen:s=!1}){const n=xe(),[r,c]=l.useState(!1),i=r||s,a=t.details??{},o=a.name??a.path??n("attachment"),u=a.type==="folder",m=a.mode==="reference",y=a.mode==="bridged",f=t.content.filter(D=>D.type==="text").map(D=>D.text).join(`
|
|
317
|
-
`),g=tr(f),v=t.content.find(D=>D.type==="image"),T=g.split(`
|
|
318
|
-
`).length;return e.jsxs("div",{className:`attachcard ${m?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>c(D=>s?!0:!D),children:[e.jsx("span",{className:"attachcard-icon",children:u?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:o}),a.path&&e.jsx("span",{className:"attachcard-path",children:a.path}),e.jsx("span",{className:`attachcard-mode ${a.mode==="lines"?"lines":m?"ref":y?"bridged":"inline"}`,children:m?u?n("folderRefShort"):`${n("refOnlyShort")} · ${Ks(a.size)}`:y?n("bridgedVision"):v?n("image"):a.mode==="lines"?n("inlineLinesRange",{start:a.startLine??1,end:a.endLine??a.lines??1}):n("inlineLines",{n:a.lines??T})}),!m&&(i?e.jsx(Ge,{}):e.jsx(Nt,{}))]}),!m&&i&&(y?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:n("bridgedVisionDetail")}),(v==null?void 0:v.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:v.dataUrl,alt:o})}),g&&e.jsx("pre",{className:"attachcard-content",children:g})]}):v!=null&&v.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:v.dataUrl,alt:o})}):e.jsx("pre",{className:"attachcard-content",children:g})),m&&e.jsx("div",{className:"attachcard-refnote",children:u?n("folderNotExpanded"):n("fileNotExpanded",{size:Ks(a.size)})})]})}function Ks(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function tr(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 sr({block:t,forceOpen:s=!1}){const n=xe(),[r,c]=l.useState(!1),i=r||s;return e.jsxs("div",{className:`skillcard${r?" expanded":""}`,children:[e.jsxs("button",{type:"button",className:"skillcard-head",onClick:()=>c(a=>s?!0:!a),title:t.location,children:[e.jsx("span",{className:"skillcard-icon",children:e.jsx(Oi,{})}),e.jsx("span",{className:"skillcard-name",children:t.name}),e.jsx("span",{className:"skillcard-path",children:t.location}),e.jsxs("span",{className:"skillcard-action",children:[i?e.jsx(dt,{}):e.jsx(Ge,{}),n(i?"collapseMsg":"expandMsg")]})]}),i&&e.jsx("div",{className:"skillcard-body",children:e.jsx(St,{text:t.content})})]})}function Ws({block:t,toolResults:s,liveOutputs:n,toolStatuses:r,streaming:c,isLast:i,onKillBash:a,thinkingWrap:o,toolsWrap:u,searchActive:m}){const y=xe(),f=ot(t);if(f){const O=c&&i;return e.jsxs("div",{className:"msg-text",children:[O?e.jsx(Oa,{text:f.text}):e.jsx(St,{text:f.text}),f.truncated&&e.jsx("div",{className:"trunc-note",children:y("truncated")})]})}const g=In(t);if(g)return e.jsx(Ka,{thinking:g.thinking,streaming:c&&i,wrap:o,forceOpen:m});const v=Ln(t);if(v){const O=s.get(v.id),N=n.get(v.id),j={result:O,liveOutput:N==null?void 0:N.text,streaming:c,status:r.get(v.id)};return e.jsx(qa,{block:v,view:j,onKillBash:a,wrap:u,forceOpen:m})}const T=Dn(t);if(T&&T.dataUrl)return e.jsx("div",{className:"msg-image",children:e.jsx("img",{src:T.dataUrl,alt:"attachment"})});const D=An(t);return D?e.jsxs("div",{className:"bashblock",children:[e.jsxs("div",{className:"bashblock-command",children:[e.jsx("span",{className:"bashblock-prompt",children:"$"}),e.jsx("code",{children:D.command}),D.exitCode!==void 0&&e.jsx("span",{className:`bashblock-exit ${D.exitCode===0?"ok":"err"}`,children:y("exitCode",{code:D.exitCode})}),D.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:y("cancelled")})]}),D.output&&e.jsx("pre",{className:"bashblock-output",children:D.output}),D.truncated&&e.jsx("div",{className:"trunc-note",children:y("outputTruncated")})]}):null}function Bn(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 nr(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),r=String(s.getMinutes()).padStart(2,"0");return`${n}:${r}`}function Us(t,s,n){let r=!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&&(r=!0,t.push({path:"",imageData:a[2],mimeType:a[1]||"image/png",name:n??`image.${(a[1]||"image/png").split("/")[1]??"png"}`}))}return r}function ir(t){const s=new Map;for(let n=0;n<t.length;n++){const r=t[n];if(r.role!=="user"||!r.id)continue;const c=[];Us(c,r.content);for(let i=n+1;i<t.length&&t[i].role==="custom"&&t[i].customType==="file";i++){const a=t[i].details??{};if(!Us(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",u={path:a.path,mode:o};a.mode==="lines"&&typeof a.startLine=="number"&&typeof a.endLine=="number"&&(u.lines={start:a.startLine,end:a.endLine}),c.push(u)}}}c.length>0&&s.set(r.id,c)}return s}const ar=l.memo(function({message:s,onExpand:n}){const r=xe();let c="";for(const f of s.content){const g=ot(f);if(g&&g.text.trim()){const v=ts(g.text);v?c=`skill:${v.name}`+(v.userMessage?` · ${v.userMessage.replace(/\s+/g," ").trim()}`:""):c=g.text.replace(/\s+/g," ").trim();break}}if(!c&&s.role==="custom"&&s.customType==="file"){const f=s.details??{};c=f.name??f.path??""}c.length>90&&(c=`${c.slice(0,90)}…`);let a=0,o=0,u=0,m=0;for(const f of s.content)In(f)?a++:Ln(f)?o++:An(f)?u++:Dn(f)&&m++;const y=[];return a&&y.push(`${r("thinking")} ${a}`),o&&y.push(`${r("toolCalls")} ${o}`),u&&y.push(`${r("bashRuns")} ${u}`),m&&y.push(`${r("images")} ${m}`),e.jsxs("button",{type:"button",className:"msg-collapsed","data-msg-id":s.id,title:`${r("expandMsg")} · ${c||y.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"?r("attachment"):Bn(s.role,r)}),e.jsxs("span",{className:"msg-collapsed-body",children:[c&&e.jsx("span",{className:"msg-collapsed-preview",children:c}),y.length>0&&e.jsx("span",{className:"msg-collapsed-chips",children:y.map((f,g)=>e.jsx("span",{className:"msg-collapsed-chip",children:f},g))})]}),s.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:rr(s.timestamp)}):null,e.jsxs("span",{className:"msg-collapsed-action",children:[e.jsx(Ge,{})," ",r("expandMsg")]})]})});function rr(t){const s=new Date(t),n=String(s.getHours()).padStart(2,"0"),r=String(s.getMinutes()).padStart(2,"0");return`${n}:${r}`}const lr=l.memo(function({id:s,show:n,height:r,containerRef:c,onMeasured:i,lazyRef:a,children:o}){const u=l.useRef(null),m=l.useRef(null);return l.useLayoutEffect(()=>{const y=m.current;if(m.current=n,!n||y!==!1)return;const f=u.current,g=c.current;if(!f||!g)return;const v=f.offsetHeight;i==null||i(s,v);const T=v-r;if(T!==0){const D=f.parentElement;D&&D.getBoundingClientRect().bottom<=g.getBoundingClientRect().top&&(g.scrollTop+=T)}},[n]),n?e.jsx("div",{ref:a,"data-lazy-id":s,children:e.jsx("div",{ref:u,children:o})}):e.jsx("div",{ref:a,className:"msg-lazy-ph","data-msg-id":s,"data-lazy-id":s,style:{height:r},"aria-hidden":"true"})});function or(t,s,n,r){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?r.has(o.id)&&c.push(o.id):r.has(o.id)||(i.push(o.id),o.bottom<=s.top&&(a+=o.bottom-o.top))}return{show:c,hide:i,shrinkAbove:a}}function cr(t,s){if(s.show.length===0&&s.hide.length===0)return t;const n=new Set(t);for(const r of s.show)n.delete(r);for(const r of s.hide)n.add(r);return n}function dr(t,s,n){const r=new Set;let c=0;for(let i=t.length-1;i>=0&&!(i<t.length-1&&c>=n);i--){const a=t[i];r.add(a.id),c+=s.get(a.id)??_n(a.role,a.customType)}return r}function _n(t,s){switch(t){case"user":return 72;case"assistant":return 280;case"toolResult":return 8;case"custom":return s==="file"?96:72;default:return 60}}const ur=["text","thinking","argumentsText","output","command"];function pr(t){let s=0;for(const n of t.content){n.type==="image"&&(s+=1);for(const r of ur){const c=n[r];typeof c=="string"&&(s+=c.length)}}return s}function mr(t,s,n,r){const c=n.get(t);return c&&c.len===s?c.h:r}function hr(t){const s=[];for(const n of t.content)n.type==="text"&&typeof n.text=="string"&&s.push(n.text);return s.join(`
|
|
319
|
-
`)}function gr(t,s){const n=[];for(const r of t.content)if(r.type==="text"&&typeof r.text=="string")n.push(r.text);else if(r.type==="thinking"&&typeof r.thinking=="string")n.push(r.thinking);else if(r.type==="toolCall"){if(typeof r.name=="string"&&n.push(r.name),typeof r.argumentsText=="string"&&n.push(r.argumentsText),typeof r.id=="string"){const c=s.get(r.id);if(c){const i=hr(c);i&&n.push(i)}}}else r.type==="bash"&&(typeof r.command=="string"&&n.push(r.command),typeof r.output=="string"&&n.push(r.output));return n.join(`
|
|
320
|
-
`)}function fr(t,s){let n=0,r=t.indexOf(s);for(;r!==-1;)n++,r=t.indexOf(s,r+s.length);return n}function xr(t,s,n,r){const c=new Map,i=n.toLowerCase();if(!i)return c;for(const a of t){if(!s.has(a.id))continue;const o=fr(gr(a,r).toLowerCase(),i);o>0&&c.set(a.id,o)}return c}function yr(t,s){var i;const n=[],r=s.toLowerCase();if(!r)return n;const c=document.createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(a){const o=a.parentElement;return!o||o.closest(".search-bar")||o.closest(".msg-collapsed")?NodeFilter.FILTER_REJECT:(a.textContent??"").toLowerCase().includes(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let a=c.nextNode();a;a=c.nextNode()){const o=(a.textContent??"").toLowerCase();if(!((i=a.parentElement)!=null&&i.closest("[data-msg-id]")))continue;let u=o.indexOf(r);for(;u!==-1;){const m=document.createRange();m.setStart(a,u),m.setEnd(a,u+r.length),n.push(m),u=o.indexOf(r,u+r.length)}}return n}function vr(t,s,n,r,c){var u;const i=xr(n,r,s,c),a=new Map;for(const m of yr(t,s)){const y=(u=m.startContainer.parentElement)==null?void 0:u.closest("[data-msg-id]");if(!(y!=null&&y.dataset.msgId))continue;const f=a.get(y.dataset.msgId);f?f.push(m):a.set(y.dataset.msgId,[m])}const o=[];for(const m of n){const y=a.get(m.id);if(y)for(let g=0;g<y.length;g++)o.push({kind:"dom",range:y[g],msgId:m.id,k:g});const f=i.get(m.id);if(f)for(let g=0;g<f;g++)o.push({kind:"folded",msgId:m.id,k:g})}return o}function Bt(t,s){return t.findIndex(n=>n.msgId===s.msgId&&n.k===s.k)}function $e(t,s){const n=CSS;if(!n.highlights)return;if(s.length===0){n.highlights.delete(t);return}const r=window.Highlight;r&&n.highlights.set(t,new r(...s))}function kr(t,s){const n=[];let r=t;for(;r&&r!==s;){const c=getComputedStyle(r);/(auto|scroll|hidden)/.test(c.overflowY+c.overflowX)&&(r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth)&&n.push(r),r=r.parentElement}return n}function br(t,s){const n=s.startContainer.parentElement;for(const o of kr(n,t)){const u=s.getBoundingClientRect(),m=o.getBoundingClientRect();if(u.height<=0||u.width<=0)return;u.top>=m.top+4&&u.bottom<=m.bottom-4||(o.scrollTop+=u.top-m.top-(o.clientHeight-u.height)/2),u.left>=m.left+4&&u.right<=m.right-4||(o.scrollLeft+=u.left-m.left-(o.clientWidth-u.width)/2)}const r=s.getBoundingClientRect(),c=t.getBoundingClientRect();if(r.height<=0||r.width<=0)return;const i=r.top>=c.top+6&&r.bottom<=c.bottom-6,a=r.left>=c.left+6&&r.right<=c.right-6;i&&a||(i||(t.scrollTop+=r.top-c.top-(c.height-r.height)/2),a||(t.scrollLeft+=r.left-c.left-(c.width-r.width)/2))}function jr({containerRef:t,messages:s,collapsedIds:n,toolResults:r,onExpand:c,onProgrammaticScroll:i,open:a,onClose:o}){const u=xe(),m=l.useRef(null),[y,f]=l.useState(""),[g,v]=l.useState(null),[T,D]=l.useState(0),[,O]=l.useState(0),N=l.useDeferredValue(y),j=a?N.trim():"",V=l.useRef(null);V.current=g;const q=l.useRef([]),J=l.useRef({key:null}),K=l.useRef("");l.useEffect(()=>{a&&(v(null),requestAnimationFrame(()=>{var k;return(k=m.current)==null?void 0:k.select()}))},[a]),l.useEffect(()=>{if(!a)return;const k=A=>{A.key==="Escape"&&(A.preventDefault(),A.stopPropagation(),o())};return window.addEventListener("keydown",k,!0),()=>window.removeEventListener("keydown",k,!0)},[a,o]),l.useEffect(()=>(a||($e("msg-search",[]),$e("msg-search-active",[])),()=>{$e("msg-search",[]),$e("msg-search-active",[])}),[a]),l.useLayoutEffect(()=>{const k=()=>{D(0),v(null),O(0),q.current=[],$e("msg-search",[]),$e("msg-search-active",[]),J.current={key:null},K.current=""};if(!a||!j){k();return}const A=t.current;if(!A)return;let F=!1,X=0;return X=requestAnimationFrame(()=>{var ne,x;if(F)return;const $=vr(A,j,s,n,r);q.current=$;const Y=$.length;if(D(Y),Y===0){v(null),O(0),$e("msg-search",[]),$e("msg-search-active",[]),J.current={key:null},K.current=j;return}const Q=V.current;let P;if(Q){if(P=Bt($,Q),P===-1){const R=[];for(let d=0;d<$.length;d++)$[d].msgId===Q.msgId&&R.push(d);if(R.length>0){const d=Math.min(Q.k,R.length-1);P=R[d]}else P=0}}else P=0;P<0&&(P=0),P>=Y&&(P=Y-1),(!Q||Q.msgId!==$[P].msgId||Q.k!==$[P].k)&&v({msgId:$[P].msgId,k:$[P].k}),O(P);const I=$[P],C=J.current,W=((ne=C.key)==null?void 0:ne.msgId)!==I.msgId||((x=C.key)==null?void 0:x.k)!==I.k||C.kind==="folded"&&I.kind==="dom"||j!==K.current;J.current={key:{msgId:I.msgId,k:I.k},kind:I.kind},K.current=j;const U=$.filter(R=>R.kind==="dom").map(R=>R.range);if($e("msg-search",U),I.kind==="folded"){$e("msg-search-active",[]),W&&c(I.msgId);return}$e("msg-search-active",[I.range]),W&&(i==null||i(),br(A,I.range))}),()=>{F=!0,cancelAnimationFrame(X)}},[a,j,s,t,g,n,r,c,i]);const E=l.useCallback(k=>{const A=q.current,F=A.length;if(F===0)return;const X=V.current,$=X?Bt(A,X):0,Y=A[($+k+F)%F];v(Y.kind==="dom"||Y.kind==="folded"?{msgId:Y.msgId,k:Y.k}:null)},[]);if(!a)return null;const H=g?(()=>{const k=Bt(q.current,g);return k===-1?0:k})():0;return e.jsxs("div",{className:"search-bar",role:"search",children:[e.jsx("input",{ref:m,className:"search-input",type:"text",value:y,placeholder:u("searchPlaceholder"),onChange:k=>{f(k.target.value)},onKeyDown:k=>{k.key==="Enter"&&(k.preventDefault(),E(k.shiftKey?-1:1))}}),e.jsx("span",{className:`search-count ${T===0?"empty":""}`,children:T===0?u("searchNoResults"):`${Math.min(H+1,T)}/${T}`}),e.jsx("button",{type:"button",className:"search-btn",title:u("searchPrev"),disabled:T===0,onClick:()=>E(-1),children:e.jsx(dt,{})}),e.jsx("button",{type:"button",className:"search-btn",title:u("searchNext"),disabled:T===0,onClick:()=>E(1),children:e.jsx(Ge,{})}),e.jsx("button",{type:"button",className:"search-btn",title:u("searchClose"),onClick:o,children:e.jsx(Ee,{})})]})}function wr(t){const{dSt:s,dSh:n,escaped:r,graceActive:c,stuck:i}=t;return c?{flipEscape:!1,reassert:!1}:s>=-4||s<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:i&&!r}:{flipEscape:!0,reassert:!1}}const Fn=[{id:"setup-matt-pocock-skills",icon:"🛠",titleKey:"tpl.sk.setup",descKey:"tpl.sk.setup.desc",promptKey:"tpl.sk.setup.prompt"},{id:"ask-matt",icon:"🧭",titleKey:"tpl.sk.ask",descKey:"tpl.sk.ask.desc",promptKey:"tpl.sk.ask.prompt"},{id:"grill-with-docs",icon:"🗣",titleKey:"tpl.sk.grilldocs",descKey:"tpl.sk.grilldocs.desc",promptKey:"tpl.sk.grilldocs.prompt"},{id:"to-spec",icon:"📝",titleKey:"tpl.sk.tospec",descKey:"tpl.sk.tospec.desc",promptKey:"tpl.sk.tospec.prompt"},{id:"to-tickets",icon:"🎫",titleKey:"tpl.sk.totickets",descKey:"tpl.sk.totickets.desc",promptKey:"tpl.sk.totickets.prompt"},{id:"implement",icon:"🏗",titleKey:"tpl.sk.implement",descKey:"tpl.sk.implement.desc",promptKey:"tpl.sk.implement.prompt"},{id:"code-review",icon:"🧹",titleKey:"tpl.sk.codeview",descKey:"tpl.sk.codeview.desc",promptKey:"tpl.sk.codeview.prompt"},{id:"wayfinder",icon:"🗺",titleKey:"tpl.sk.wayfinder",descKey:"tpl.sk.wayfinder.desc",promptKey:"tpl.sk.wayfinder.prompt"},{id:"prototype",icon:"🔬",titleKey:"tpl.sk.prototype",descKey:"tpl.sk.prototype.desc",promptKey:"tpl.sk.prototype.prompt"},{id:"research",icon:"📚",titleKey:"tpl.sk.research",descKey:"tpl.sk.research.desc",promptKey:"tpl.sk.research.prompt"},{id:"improve-codebase-architecture",icon:"🏛",titleKey:"tpl.sk.arch",descKey:"tpl.sk.arch.desc",promptKey:"tpl.sk.arch.prompt"},{id:"diagnosing-bugs",icon:"🐛",titleKey:"tpl.sk.debug",descKey:"tpl.sk.debug.desc",promptKey:"tpl.sk.debug.prompt"},{id:"resolving-merge-conflicts",icon:"🔀",titleKey:"tpl.sk.merge",descKey:"tpl.sk.merge.desc",promptKey:"tpl.sk.merge.prompt"},{id:"triage",icon:"🗂",titleKey:"tpl.sk.triage",descKey:"tpl.sk.triage.desc",promptKey:"tpl.sk.triage.prompt"},{id:"wizard",icon:"✨",titleKey:"tpl.sk.wizard",descKey:"tpl.sk.wizard.desc",promptKey:"tpl.sk.wizard.prompt"},{id:"grill-me",icon:"🔍",titleKey:"tpl.sk.grillme",descKey:"tpl.sk.grillme.desc",promptKey:"tpl.sk.grillme.prompt"},{id:"handoff",icon:"🤝",titleKey:"tpl.sk.handoff",descKey:"tpl.sk.handoff.desc",promptKey:"tpl.sk.handoff.prompt"},{id:"to-questionnaire",icon:"📋",titleKey:"tpl.sk.questionnaire",descKey:"tpl.sk.questionnaire.desc",promptKey:"tpl.sk.questionnaire.prompt"},{id:"teach",icon:"🎓",titleKey:"tpl.sk.teach",descKey:"tpl.sk.teach.desc",promptKey:"tpl.sk.teach.prompt"},{id:"wait-what",icon:"💬",titleKey:"tpl.sk.ww",descKey:"tpl.sk.ww.desc",promptKey:"tpl.sk.ww.prompt"},{id:"writing-for-agents",icon:"📄",titleKey:"tpl.sk.wfa",descKey:"tpl.sk.wfa.desc",promptKey:"tpl.sk.wfa.prompt"},{id:"codebase-design",icon:"🧱",titleKey:"tpl.sk.codesign",descKey:"tpl.sk.codesign.desc",promptKey:"tpl.sk.codesign.prompt"},{id:"domain-modeling",icon:"🏷",titleKey:"tpl.sk.domain",descKey:"tpl.sk.domain.desc",promptKey:"tpl.sk.domain.prompt"},{id:"grilling",icon:"🔥",titleKey:"tpl.sk.grilling",descKey:"tpl.sk.grilling.desc",promptKey:"tpl.sk.grilling.prompt"},{id:"tdd",icon:"🧪",titleKey:"tpl.sk.tdd",descKey:"tpl.sk.tdd.desc",promptKey:"tpl.sk.tdd.prompt"}],$n="pi-web-ui:prompt-templates";function Nr(){try{const t=localStorage.getItem($n);if(!t)return[];const s=JSON.parse(t);return Array.isArray(s)?s.filter(n=>!!n&&typeof n=="object"&&typeof n.id=="string"):[]}catch{return[]}}function qs(t){return Fn.some(s=>s.id===t)}function ht(t){return typeof t.title=="string"}const Hn=l.createContext(null);function On(){const t=l.useContext(Hn);if(!t)throw new Error("useTemplates must be used within TemplateProvider");return t}function Cr({send:t,children:s}){const n=xe(),[r,c]=l.useState(Nr),[i,a]=l.useState(!1),[o,u]=l.useState(null),[m,y]=l.useState(!1),[f,g]=l.useState(!1),[v,T]=l.useState(!1);l.useEffect(()=>{try{localStorage.setItem($n,JSON.stringify(r))}catch{}},[r]);const D=l.useMemo(()=>{const $=new Map,Y=new Set;for(const I of r)I.hidden?Y.add(I.id):(ht(I)&&!qs(I.id)||ht(I))&&$.set(I.id,I);const Q=Fn.filter(I=>!Y.has(I.id)).map(I=>{const C=$.get(I.id);return{id:I.id,icon:(C==null?void 0:C.icon)??I.icon,title:(C==null?void 0:C.title)??n(I.titleKey),desc:(C==null?void 0:C.desc)??n(I.descKey),prompt:(C==null?void 0:C.prompt)??n(I.promptKey),builtin:!0}}),P=r.filter(I=>ht(I)&&!qs(I.id)).map(I=>({id:I.id,icon:I.icon??"📌",title:I.title??"",desc:I.desc??"",prompt:I.prompt??""}));return[...Q,...P]},[r,n]),O=l.useCallback(()=>a(!0),[]),N=l.useCallback($=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:$}))},[]),j=l.useCallback(($,Y=!1)=>{T(Y),$?(y(!1),u({...$})):(y(!0),u({id:Ue(),icon:"📌",title:"",desc:"",prompt:""}))},[]),V=l.useCallback(()=>{a(!1),u(null),T(!1)},[]),q=l.useCallback(()=>{f?(c([]),g(!1)):(g(!0),setTimeout(()=>g(!1),5e3))},[f]),J=l.useCallback($=>{a(!1),N($.prompt)},[N]),K=l.useCallback($=>{a(!1),j($,!0)},[j]),E=l.useCallback(()=>{a(!1),j(void 0,!0)},[j]),H=l.useCallback($=>{c(Y=>{const Q=Y.findIndex(P=>P.id===$.id);if(Q>=0){const P=[...Y];return P[Q]=$,P}return[...Y,$]}),u(null),v&&(a(!0),T(!1))},[v]),k=l.useCallback($=>{c(Y=>$.builtin?[...Y.filter(P=>P.id!==$.id),{id:$.id,hidden:!0}]:Y.filter(Q=>Q.id!==$.id)),u(null),v&&(a(!0),T(!1))},[v]),A=l.useCallback($=>{c(Y=>Y.filter(Q=>Q.id!==$.id||Q.hidden)),u(null),v&&(a(!0),T(!1))},[v]),F=l.useMemo(()=>({templates:D,fill:N,openPicker:O,openEdit:j,resetConfirm:f,toggleReset:q}),[D,N,O,j,f,q]),X=o?r.some($=>$.id===o.id&&!$.hidden&&ht($)):!1;return e.jsxs(Hn.Provider,{value:F,children:[s,i&&e.jsx(Tr,{templates:D,resetConfirm:f,onFill:J,onEditTpl:K,onNew:E,onResetToggle:q,onClose:V}),o&&e.jsx(Er,{editing:o,isNew:m,hasOverride:X,onDraft:u,onSave:H,onRestore:()=>A(o),onRemove:()=>k(o),onFill:()=>{window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:o.prompt})),V()},onSend:()=>{const $=o.prompt.trim();$&&t({type:"prompt",text:$,queue:!1})&&V()},onClose:V})]})}function Sr(){const t=xe(),{templates:s,fill:n,openEdit:r,toggleReset:c,resetConfirm:i}=On();return e.jsxs("div",{className:"empty-templates",children:[e.jsxs("div",{className:"empty-templates-head",children:[e.jsx("span",{className:"empty-templates-title",children:t("tpl.title")}),e.jsx("span",{className:"empty-templates-hint",children:t("tpl.hint")})]}),e.jsxs("div",{className:"empty-templates-grid",children:[s.map(a=>e.jsx(Kn,{tpl:a,title:t("tpl.clickCard"),onFill:()=>n(a.prompt),onEdit:()=>r(a),editTitle:t("tpl.editTpl")},a.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:()=>r(),title:t("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(He,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:t("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"empty-templates-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:c,children:[e.jsx(un,{}),t(i?"tpl.resetConfirm":"tpl.reset")]})})]})}function Kn({tpl:t,title:s,onFill:n,onEdit:r,editTitle:c}){const i=xe();return e.jsxs("button",{type:"button",className:"empty-template",title:s,onClick:n,children:[e.jsx("span",{className:"empty-template-icon",children:t.icon}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:t.title}),e.jsx("span",{className:"empty-template-desc",children:t.desc})]}),e.jsx("span",{className:"template-card-ops",role:"button",title:c??i("tpl.editTpl"),onClick:a=>{a.stopPropagation(),r()},children:e.jsx(wt,{})})]})}function Tr({templates:t,resetConfirm:s,onFill:n,onEditTpl:r,onNew:c,onResetToggle:i,onClose:a}){const o=xe();return l.useEffect(()=>{const u=m=>{m.key==="Escape"&&a()};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[a]),e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"modal template-picker",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"template-picker-head",children:[e.jsx("span",{className:"template-picker-title",children:o("tpl.pickerTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:o("close"),onClick:a,children:e.jsx(Ee,{})})]}),e.jsx("div",{className:"template-picker-hint",children:o("tpl.pickerHint")}),e.jsxs("div",{className:"template-picker-grid",children:[t.map(u=>e.jsx(Kn,{tpl:u,title:o("tpl.clickCard"),onFill:()=>n(u),onEdit:()=>r(u),editTitle:o("tpl.editTpl")},u.id)),e.jsxs("button",{type:"button",className:"empty-template add",onClick:c,title:o("tpl.add"),children:[e.jsx("span",{className:"empty-template-icon",children:e.jsx(He,{})}),e.jsxs("span",{className:"empty-template-main",children:[e.jsx("span",{className:"empty-template-title",children:o("tpl.add")}),e.jsx("span",{className:"empty-template-desc",children:o("tpl.addDesc")})]})]})]}),e.jsx("div",{className:"template-picker-foot",children:e.jsxs("button",{type:"button",className:"empty-templates-reset",onClick:i,children:[e.jsx(un,{}),o(s?"tpl.resetConfirm":"tpl.reset")]})})]})})}function Er({editing:t,isNew:s,hasOverride:n,onDraft:r,onSave:c,onRestore:i,onRemove:a,onFill:o,onSend:u,onClose:m}){const y=xe(),f=l.useRef(null);l.useEffect(()=>{const T=D=>{D.key==="Escape"&&m()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[m]),l.useEffect(()=>{const T=f.current;if(!T)return;T.style.height="auto";const D=T.scrollHeight>300;T.style.height=`${Math.min(T.scrollHeight,300)}px`,T.style.overflowY=D?"auto":"hidden"},[t.prompt]);const g=()=>{const T=t.title.trim(),D=t.prompt.trim();if(!T||!D){r({...t,error:y("tpl.required")});return}c({id:t.id,icon:t.icon.trim()||"📌",title:T,desc:t.desc.trim(),prompt:D})},v=!!t.builtin&&!s;return e.jsx("div",{className:"modal-backdrop",onClick:m,children:e.jsxs("div",{className:"modal template-modal",onClick:T=>T.stopPropagation(),children:[e.jsxs("div",{className:"template-modal-head",children:[e.jsx("span",{className:"template-modal-icon",children:t.icon}),e.jsx("span",{className:"template-modal-badge",children:y(v?"tpl.builtin":"tpl.custom")}),e.jsx("span",{className:"template-modal-title",children:y(s?"tpl.newTitle":"tpl.editTitle")}),e.jsx("button",{type:"button",className:"btn template-modal-close",title:y("close"),onClick:m,children:e.jsx(Ee,{})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:y("tpl.fieldIcon")}),e.jsx("input",{className:"template-field-input icon",value:t.icon,maxLength:4,onChange:T=>r({...t,icon:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:y("tpl.fieldTitle")}),e.jsx("input",{className:"template-field-input",value:t.title,placeholder:y("tpl.fieldTitlePh"),onChange:T=>r({...t,title:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:y("tpl.fieldDesc")}),e.jsx("input",{className:"template-field-input",value:t.desc,placeholder:y("tpl.fieldDescPh"),onChange:T=>r({...t,desc:T.target.value})})]}),e.jsxs("label",{className:"template-field",children:[e.jsx("span",{className:"template-field-label",children:y("tpl.fieldPrompt")}),e.jsx("textarea",{ref:f,className:"template-field-prompt",value:t.prompt,placeholder:y("tpl.fieldPromptPh"),onChange:T=>r({...t,prompt:T.target.value})})]}),t.error&&e.jsx("div",{className:"template-error",children:t.error}),e.jsxs("div",{className:"template-modal-actions",children:[e.jsxs("div",{className:"template-modal-actions-left",children:[!s&&v&&n&&e.jsx("button",{type:"button",className:"btn template-btn ghost",title:y("tpl.restoreTip"),onClick:i,children:y("tpl.restore")}),!s&&v&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:y("tpl.removeTip"),onClick:a,children:[e.jsx(Be,{})," ",y("tpl.remove")]}),!s&&!v&&e.jsxs("button",{type:"button",className:"btn template-btn ghost danger",title:y("tpl.deleteTip"),onClick:a,children:[e.jsx(Be,{})," ",y("tpl.delete")]})]}),e.jsxs("div",{className:"template-modal-actions-right",children:[e.jsx("button",{type:"button",className:"btn template-btn",onClick:g,children:y("tpl.save")}),e.jsx("button",{type:"button",className:"btn template-btn fill",onClick:o,title:y("tpl.fillTip"),children:y("tpl.fill")}),e.jsxs("button",{type:"button",className:"btn template-btn send",onClick:u,title:y("tpl.sendTip"),children:[e.jsx(dn,{})," ",y("tpl.sendNow")]})]})]})]})})}const zs=new Map,Pr=15,Vs=30,_t=250,Gs=1200,Mr=1600;function Qs(t){return t.content.some(s=>s.type==="toolCall")}function Rr({state:t,liveOutputs:s,toolStatuses:n,onEdit:r,onKillBash:c,onRemoveQueued:i,thinkingWrap:a,toolsWrap:o,jumpTarget:u,onJumpDone:m}){const y=xe(),f=l.useRef(null),[g,v]=l.useState(!0),T=l.useRef(!0),D=l.useRef(0),O=l.useRef(0),N=l.useRef(!1),j=l.useRef(0),[V,q]=l.useState(()=>new Set),[J,K]=l.useState(!1),E=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,H=l.useMemo(()=>{const S=new Map;for(const L of t.messages)L.role==="toolResult"&&L.toolCallId&&S.set(L.toolCallId,L);return S},[t.messages]),k=l.useMemo(()=>ir(t.messages),[t.messages]),A=E.length>0?E[E.length-1].id:null,F=t.messages.length>Vs?Math.max(0,t.messages.length-Pr):0,X=l.useMemo(()=>{const S=new Set;for(let L=0;L<F;L++){const ae=t.messages[L];ae.role!=="toolResult"&&(V.has(ae.id)||S.add(ae.id))}return S},[t.messages,F,V]),[$,Y]=l.useState(()=>new Set),[Q,P]=l.useState(()=>new Set),I=l.useRef(new Map),C=l.useRef(new Map),W=l.useRef(new Map),U=l.useRef(0),ne=l.useMemo(()=>{const S=new Map;for(const L of t.messages)S.set(L.id,pr(L));return S},[t.messages]),x=l.useRef(ne);x.current=ne;const R=l.useRef($);R.current=$;const d=t.messages.length>Vs&&!J,b=l.useRef(d);b.current=d;const w=dr(t.messages,I.current,Mr),B=l.useRef(w);B.current=w;const se=l.useCallback(()=>{const S=f.current;if(!S)return;if(!b.current){Y(je=>je.size?new Set:je);return}const L=S.getBoundingClientRect(),ae={top:L.top-Gs,bottom:L.bottom+Gs},oe=[];for(const[je,Te]of W.current){const Oe=Te.getBoundingClientRect();oe.push({id:je,top:Oe.top,bottom:Oe.bottom}),R.current.has(je)||ye(je,Oe.bottom-Oe.top,x.current.get(je))}const be=or(oe,ae,B.current,R.current);for(const je of be.hide){const Te=W.current.get(je);Te&&ye(je,Te.offsetHeight,x.current.get(je))}Y(je=>cr(je,be))},[]),G=l.useCallback(()=>{U.current||(U.current=requestAnimationFrame(()=>{U.current=0,se()}))},[se]);l.useLayoutEffect(()=>{se()},[se]);const ie=l.useRef(J);l.useLayoutEffect(()=>{ie.current&&!J&&se(),ie.current=J},[J,se]);const ye=l.useCallback((S,L,ae)=>{ae!==void 0&&(C.current.set(S,{h:L,len:ae}),I.current.set(S,L))},[]),le=l.useCallback((S,L)=>{ye(S,L,x.current.get(S))},[ye]),we=l.useCallback(S=>{S&&W.current.set(S.dataset.lazyId??"",S)},[]);l.useEffect(()=>{const S=new Set(t.messages.map(L=>L.id));for(const L of W.current.keys())S.has(L)||(W.current.delete(L),I.current.delete(L),C.current.delete(L));Y(L=>{let ae=!1;const oe=new Set;for(const be of L)S.has(be)?oe.add(be):ae=!0;return ae?oe:L})},[t.messages,V]),l.useEffect(()=>()=>cancelAnimationFrame(U.current),[]);const ve=l.useMemo(()=>{const S=[];for(const L of t.messages){if(L.role!=="user")continue;const ae=L.content.map(je=>{var Te;return((Te=ot(je))==null?void 0:Te.text)??""}).filter(Boolean).join(" "),oe=ts(ae),be=oe?oe.userMessage??`skill:${oe.name}`:ae.trim();be&&S.push({id:L.id,text:be})}return S},[t.messages]),Pe=l.useMemo(()=>{const S=new Map;return ve.forEach((L,ae)=>S.set(L.id,ae)),S},[ve]),[re,h]=l.useState(-1),z=l.useRef(-1),pe=l.useRef(ve);l.useEffect(()=>{pe.current=ve},[ve]);const ce=l.useCallback(()=>{const S=f.current,L=pe.current;if(!S||L.length===0)return;const ae=S.getBoundingClientRect().top,oe=140;let be=-1;for(let je=0;je<L.length;je++){const Te=S.querySelector(`[data-msg-id="${L[je].id}"]`);if(Te)if(Te.getBoundingClientRect().top<=ae+oe)be=je;else break}be!==z.current&&(z.current=be,h(be))},[]);l.useEffect(()=>{ce()},[ve,ce]);const fe=l.useCallback(S=>{q(L=>L.has(S)?L:new Set(L).add(S))},[]);l.useEffect(()=>{const S=L=>{if(!(L.ctrlKey||L.metaKey)||L.key.toLowerCase()!=="f")return;const ae=L.target;ae&&(ae.tagName==="INPUT"||ae.tagName==="TEXTAREA"||ae.isContentEditable)||(L.preventDefault(),K(!0))};return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[]);const me=l.useCallback(S=>{q(L=>{if(!L.has(S))return L;const ae=new Set(L);return ae.delete(S),ae})},[]),ke=l.useCallback(S=>{const L=t.messages.findIndex(oe=>oe.id===S);La.flushSync(()=>{L>=0&&L<F&&!V.has(S)&&fe(S),P(oe=>oe.has(S)?oe:new Set(oe).add(S))});const ae=pe.current.findIndex(oe=>oe.id===S);z.current=ae,h(ae),requestAnimationFrame(()=>{var be,je,Te;const oe=(be=f.current)==null?void 0:be.querySelector(`[data-msg-id="${S}"]`);oe&&((je=f.current)==null||je.querySelectorAll(".msg-flash").forEach(Oe=>Oe.classList.remove("msg-flash")),oe.scrollIntoView({block:"start"}),oe.classList.remove("msg-flash"),oe.offsetWidth,oe.classList.add("msg-flash"),oe!==((Te=f.current)==null?void 0:Te.lastElementChild)&&(N.current=!0))})},[t.messages,F,V,fe]),Me=l.useMemo(()=>{var S;return u?((S=t.messages.find(L=>L.role===u.role&&L.timestamp===u.timestamp))==null?void 0:S.id)??null:null},[t.messages,u]);l.useEffect(()=>{if(u){if(Me){ke(Me),m==null||m();return}t.sessionFile===u.path&&t.messages.length>0&&(m==null||m())}},[Me,ke,m,u,t.sessionFile,t.messages.length]);const he=l.useCallback(()=>{const S=f.current;if(!S)return;const L=S.scrollTop-D.current,ae=S.scrollHeight-O.current;D.current=S.scrollTop,O.current=S.scrollHeight;const oe=S.scrollHeight-S.scrollTop-S.clientHeight<80,be=Date.now()<j.current,je=wr({dSt:L,dSh:ae,escaped:N.current,graceActive:be,stuck:T.current});je.reassert&&(j.current=Date.now()+_t,S.scrollTop=S.scrollHeight),je.flipEscape&&(N.current=!0),oe&&L>=0&&(N.current=!1),be||(L<0?T.current=oe&&!N.current:oe&&(T.current=!0)),v(T.current),ce(),G()},[ce,G]),Ie=l.useRef(!1);l.useEffect(()=>{const S=Ie.current;if(Ie.current=!!t.isStreaming,S&&!t.isStreaming&&!N.current){const L=()=>{const oe=f.current;oe&&!N.current&&(oe.scrollTop=oe.scrollHeight,T.current=!0,v(!0))};requestAnimationFrame(()=>requestAnimationFrame(L));const ae=setTimeout(L,180);return()=>clearTimeout(ae)}},[t.isStreaming]),l.useEffect(()=>{const S=f.current;S&&T.current&&(S.scrollTop=S.scrollHeight)},[E,t.isStreaming,s]);const Le=t.queue.steering.join("\0")+""+t.queue.followUp.join("\0");l.useEffect(()=>{const S=f.current;S&&T.current&&(S.scrollTop=S.scrollHeight)},[Le]),l.useEffect(()=>{const S=f.current;if(!S||typeof ResizeObserver>"u")return;const L=new ResizeObserver(()=>{T.current&&!N.current&&(S.scrollTop=S.scrollHeight,v(!0))});return L.observe(S),()=>L.disconnect()},[]),l.useEffect(()=>{const S=f.current;if(!S||typeof MutationObserver>"u")return;let L=!1;const ae=new MutationObserver(()=>{L||(L=!0,requestAnimationFrame(()=>{L=!1;const oe=f.current;oe&&T.current&&!N.current&&(oe.scrollTop=oe.scrollHeight,v(!0))}))});return ae.observe(S,{childList:!0,subtree:!0,characterData:!0}),()=>ae.disconnect()},[]);const _e=l.useCallback(()=>{if(!f.current)return;T.current=!0,N.current=!1,v(!0),j.current=Date.now()+_t;const L=()=>{const ae=f.current;!ae||!T.current||N.current||(j.current=Date.now()+_t,ae.scrollTop=ae.scrollHeight)};L(),requestAnimationFrame(()=>requestAnimationFrame(L)),setTimeout(L,120),setTimeout(L,300),setTimeout(L,600)},[]),De=l.useRef(null);l.useEffect(()=>{const S=De.current,L=f.current;if(!S||!L)return;const ae=oe=>{oe.preventDefault();const be=S.querySelector(".qn-list");if(be&&be.contains(oe.target)&&be.scrollHeight>be.clientHeight){be.scrollTop+=oe.deltaY;return}L.scrollTop+=oe.deltaY};return S.addEventListener("wheel",ae,{passive:!1}),()=>S.removeEventListener("wheel",ae)},[]);const[M,ge]=l.useState(0);l.useEffect(()=>{const S=()=>{var L;ge(((L=f.current)==null?void 0:L.clientHeight)??0),G()};return S(),window.addEventListener("resize",S),()=>window.removeEventListener("resize",S)},[G]);const p=ve.length,ee=l.useMemo(()=>p===0?27:Math.max(4,Math.min(27,Math.floor(((M||600)-16)/p)-3)),[p,M]),de=ee<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:`messages${J||g?"":" anchor-live"}`,ref:f,onScroll:he,children:[t.messages.length===0&&!t.streamingMessage&&e.jsx("div",{className:"empty-state",children:e.jsx(Sr,{})}),t.messages.map((S,L)=>{const ae=L<F,oe=ae&&V.has(S.id);if(ae&&!oe)return S.role==="toolResult"?null:e.jsx(ar,{message:S,onExpand:fe},S.id);const be=S.role==="user"?Pe.get(S.id):void 0,je=!d||w.has(S.id)||Q.has(S.id)||!$.has(S.id);return e.jsx(lr,{id:S.id,show:je,height:mr(S.id,ne.get(S.id)??-1,C.current,_n(S.role,S.customType)),containerRef:f,onMeasured:le,lazyRef:we,children:e.jsx(Os,{message:S,qnIndex:be,qnActive:be!==void 0?be===re:void 0,onJump:ke,toolResults:H,liveOutputs:Qs(S)?s:zs,toolStatuses:n,streaming:t.isStreaming,onKillBash:c,toolsWrap:o,thinkingWrap:a,isLast:S.id===A,onEdit:r,questionAttachments:k.get(S.id),onCollapse:oe?me:void 0,searchActive:J},S.id)},S.id)}),t.streamingMessage&&e.jsx(Os,{message:t.streamingMessage,toolResults:H,liveOutputs:Qs(t.streamingMessage)?s:zs,toolStatuses:n,streaming:!0,isLast:!0,onEdit:r,onKillBash:c,toolsWrap:o,thinkingWrap:a,searchActive:J},t.streamingMessage.id),t.isStreaming&&E.length===0&&e.jsx("div",{className:"streaming-wait",children:y("waitingResponse")}),t.queue.steering.map((S,L)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag steer",children:y("queueSteerTag")}),e.jsx("div",{className:"queued-text",children:S}),i&&e.jsx("button",{type:"button",className:"queued-remove",title:y("queueRemoveTip"),onClick:()=>i("steer",S),children:"✕"})]})},`q-steer-${L}`)),t.queue.followUp.map((S,L)=>e.jsx("div",{className:"queued-msg",children:e.jsxs("div",{className:"queued-bubble",children:[e.jsx("span",{className:"queued-tag follow",children:y("queueFollowTag")}),e.jsx("div",{className:"queued-text",children:S}),i&&e.jsx("button",{type:"button",className:"queued-remove",title:y("queueRemoveTip"),onClick:()=>i("followUp",S),children:"✕"})]})},`q-fu-${L}`))]}),!g&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:_e,children:[e.jsx(xn,{})," ",y("backToBottom")]}),e.jsx(jr,{containerRef:f,messages:E,collapsedIds:X,toolResults:H,onExpand:fe,onProgrammaticScroll:()=>{N.current=!0,T.current=!1,v(!1)},open:J,onClose:()=>K(!1)}),ve.length>0&&e.jsxs("div",{className:`qn-rail ${de?"many":""}`,ref:De,"aria-label":y("questionNavTitle"),style:{"--rail-gap":`${ee}px`},children:[ve.map((S,L)=>e.jsx("button",{type:"button",className:`qn-bar ${L===re?"active":""}`,"aria-label":`${L+1}. ${S.text}`,onClick:()=>ke(S.id),children:e.jsxs("span",{className:"qn-bar-text",children:[L+1,". ",S.text]})},S.id)),de&&e.jsx("div",{className:"qn-list",children:ve.map((S,L)=>e.jsxs("button",{type:"button",className:`qn-list-item ${L===re?"active":""}`,"aria-label":`${L+1}. ${S.text}`,onClick:()=>ke(S.id),children:[e.jsx("span",{className:"qn-list-idx",children:L+1}),e.jsx("span",{className:"qn-list-text",children:S.text})]},S.id))})]})]})}const Wn="pi-web-model-usage";function Ir(t){if(!t||typeof t!="object")return{};const s={};for(const[n,r]of Object.entries(t)){const c=typeof r=="number"?Math.floor(r):0;Number.isFinite(c)&&c>0&&(s[n]=c)}return s}function Lr(t,s){return s?{...t,[s]:(t[s]??0)+1}:t}function Dr(t,s){const n=s;return t.map((r,c)=>({m:r,i:c,count:n[r.id]??0})).sort((r,c)=>c.count-r.count||r.i-c.i).map(r=>r.m)}function Un(){try{const t=localStorage.getItem(Wn);return t?Ir(JSON.parse(t)):{}}catch{return{}}}function Ar(t){try{localStorage.setItem(Wn,JSON.stringify(t))}catch{}}function Br(t){const s=Lr(Un(),t);return Ar(s),s}const ss="pi-web-ui:prompt-history",_r=100,qn="pi-web-ui:prompt-history-settings",Yt={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function zn(t){const s=Yt;if(!t||typeof t!="object")return{...s};const n=t;let r=typeof n.maxEntries=="number"?Math.floor(n.maxEntries):s.maxEntries;(!Number.isFinite(r)||r<1)&&(r=1),r>500&&(r=500);let c=typeof n.charLimit=="number"?Math.floor(n.charLimit):s.charLimit;(!Number.isFinite(c)||c<100)&&(c=100),c>2e4&&(c=2e4);const i=typeof n.charLimitEnabled=="boolean"?n.charLimitEnabled:s.charLimitEnabled;return{maxEntries:r,charLimitEnabled:i,charLimit:c}}function Vn(){try{const t=localStorage.getItem(qn);return t?zn(JSON.parse(t)):{...Yt}}catch{return{...Yt}}}function Ft(t){const s=zn(t);try{localStorage.setItem(qn,JSON.stringify(s))}catch{}try{let n=ct();s.charLimitEnabled&&(n=n.map(r=>r.length>s.charLimit?r.slice(0,s.charLimit):r)),n.length>s.maxEntries&&(n=n.slice(n.length-s.maxEntries)),Gn(n)}catch{}}function Fr(t){if(!Array.isArray(t))return[];const s=[];for(const n of t){if(typeof n!="string")continue;const r=n.trim();r&&s.push(r)}return s}function $r(t,s,n=_r){const r=s.trim();if(!r||t.length>0&&t[t.length-1]===r)return t;const c=[...t,r];return c.length>n?c.slice(c.length-n):c}function ct(){try{const t=localStorage.getItem(ss);return t?Fr(JSON.parse(t)):[]}catch{return[]}}function Gn(t){let s=t;for(;s;)try{localStorage.setItem(ss,JSON.stringify(s));return}catch(n){if(!(n instanceof DOMException&&(n.name==="QuotaExceededError"||n.code===22))||s.length<=1)return;s=s.slice(Math.ceil(s.length/2))}}function Hr(t){let s=t.trim();if(!s)return;const n=Vn();n.charLimitEnabled&&s.length>n.charLimit&&(s=s.slice(0,n.charLimit));const r=ct(),c=$r(r,s,n.maxEntries);c!==r&&Gn(c)}function Or(){try{localStorage.removeItem(ss)}catch{}}const Kr=["off","minimal","low","medium","high","xhigh","max"],Wr=l.memo(function({state:s,models:n,modelsLoading:r,send:c,onManageModels:i,providerKeys:a,compact:o=!1}){const u=xe(),m=s==null?void 0:s.model,y=m?`${m.provider}/${m.id}`:null,[f,g]=l.useState(!1),[v,T]=l.useState(!1),[D,O]=l.useState(""),[N,j]=l.useState(null),[V,q]=l.useState({}),J=l.useRef(null),K=l.useRef(null),[E,H]=l.useState(null);l.useEffect(()=>{if(!f){H(null);return}if(n.length===0)return;const C=requestAnimationFrame(()=>{const W=K.current;W&&H(W.offsetWidth)});return()=>cancelAnimationFrame(C)},[f,n.length]),l.useEffect(()=>{f&&q(Un())},[f]),l.useEffect(()=>{f||(O(""),j(null))},[f]);const k=l.useMemo(()=>{const C=new Map;for(const U of n)C.set(U.provider,(C.get(U.provider)??0)+1);const W=[];for(const[U,ne]of[...C.entries()].sort((x,R)=>x[0].localeCompare(R[0]))){const x=a[U];if(x&&x.length>1)for(const R of x)W.push({provider:U,keyName:R.name,count:ne});else W.push({provider:U,keyName:null,count:ne})}return W},[n,a]),A=l.useMemo(()=>Dr(n,V),[n,V]),F=l.useMemo(()=>{let C=A;N&&(C=C.filter(U=>U.provider===N.provider));const W=D.trim().toLowerCase();return W?C.filter(U=>U.name.toLowerCase().includes(W)||U.provider.toLowerCase().includes(W)||U.id.toLowerCase().includes(W)):C},[A,D,N]),X=l.useMemo(()=>{const C=[];for(const W of F){const U=a[W.provider];if(!U||U.length<=1){C.push({model:W,key:null});continue}let ne=U.find(x=>x.active)??U[0];if((N==null?void 0:N.provider)===W.provider&&N.keyName){const x=U.find(R=>R.name===N.keyName);x&&(ne=x)}C.push({model:W,key:ne})}return C},[F,a,N]),[$,Y]=l.useState(!1),Q=s!=null&&s.availableThinkingLevels&&s.availableThinkingLevels.length>0?new Set(s.availableThinkingLevels):null,P=Kr.map(C=>({value:C,label:u(`thinking.${C}`),supported:Q?Q.has(C):!0})),I=C=>{var W;return((W=P.find(U=>U.value===C))==null?void 0:W.label)??C};return l.useEffect(()=>{f&&n.length===0&&!$&&!r&&(Y(!0),c({type:"list_models"}))},[f,n.length,$,r,c]),l.useEffect(()=>{n.length>0&&Y(!1)},[n.length]),l.useEffect(()=>{var W;if(!f)return;const C=(W=J.current)==null?void 0:W.querySelector(".dd-item.active");C==null||C.scrollIntoView({block:"nearest"})},[f,y,n.length]),e.jsxs(e.Fragment,{children:[e.jsxs(ze,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(rt,{}),e.jsx("span",{className:"chip-model",children:m?m.name:u("selectModel")}),!o&&(m==null?void 0:m.vision)&&e.jsx("span",{className:"chip-vision",title:u("vision"),children:"🖼"}),!o&&m&&e.jsx("span",{className:"chip-sub",children:m.provider})]}),open:f,onOpenChange:g,menuClassName:"dd-menu-model",menuRef:K,menuStyle:E!=null?{width:E}:void 0,direction:"up",children:[e.jsx("div",{className:"dd-header",children:u("availableModels")}),e.jsxs("div",{className:"dd-search-row",children:[e.jsx(bt,{}),e.jsx("input",{className:"dd-search",type:"text",placeholder:u("searchModels"),value:D,onChange:C=>O(C.target.value)})]}),e.jsxs("div",{className:"dd-model-body",children:[k.length>1&&e.jsxs("div",{className:"dd-provider-col",children:[e.jsx("div",{className:"dd-provider-head",children:u("providers")}),e.jsx("button",{type:"button",className:`dd-provider-item ${N===null?"active":""}`,onClick:()=>j(null),children:e.jsx("span",{children:u("allProviders")})}),k.map(C=>{const W=(N==null?void 0:N.provider)===C.provider&&(N==null?void 0:N.keyName)===C.keyName;return e.jsxs("button",{type:"button",className:`dd-provider-item ${W?"active":""}`,onClick:()=>j(W?null:{provider:C.provider,keyName:C.keyName}),title:C.keyName?`${C.provider} · ${C.keyName}`:`${C.provider} · ${C.count}`,children:[e.jsxs("span",{className:"dd-provider-txt",children:[e.jsx("span",{className:"dd-provider-name",children:C.provider}),C.keyName&&e.jsx("span",{className:"dd-provider-key",children:C.keyName})]}),e.jsx("span",{className:"dd-provider-count",children:C.count})]},C.keyName?`${C.provider}::${C.keyName}`:C.provider)})]}),e.jsxs("div",{className:"dd-model-scroll",ref:J,children:[($||r)&&e.jsx("div",{className:"dd-loading",children:u("loading")}),n.length===0&&!$&&!r&&e.jsx("div",{className:"dd-loading",children:u("noModels")}),F.length===0&&n.length>0&&e.jsx("div",{className:"dd-loading",children:u("noModelMatches")}),X.map(C=>{const W=C.model,U=y===W.id&&(!C.key||C.key.active);return e.jsx(Re,{active:U,onClick:()=>{C.key&&!C.key.active&&c({type:"activate_provider_key",provider:W.provider,keyName:C.key.name}),y!==W.id&&c({type:"set_model",modelId:W.id}),g(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:W.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:W.provider}),C.key&&e.jsxs("span",{className:`dd-model-key ${C.key.active?"active":""}`,children:[C.key.active?"●":"○"," ",C.key.name]}),(V[W.id]??0)>0&&e.jsx("span",{className:"dd-model-usage",children:u("modelUsedCount",{n:V[W.id]})}),(W.reasoning||W.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[W.reasoning&&e.jsx("span",{className:"dd-model-badge",children:u("reasoning")}),W.vision&&e.jsx("span",{className:"dd-model-badge",children:u("vision")})]})]})]})},C.key?`${W.id}::${C.key.name}`:W.id)})]})]}),e.jsxs("div",{className:"dd-footer",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>c({type:"list_models"}),children:u("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{g(!1),i()},children:u("manageModels")})]})]}),e.jsxs(ze,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(gt,{}),e.jsx("span",{className:"chip-sub",children:u("thinkingChip",{level:s?I(s.thinkingLevel):"—"})})]}),open:v,onOpenChange:T,direction:"up",children:[e.jsx("div",{className:"dd-header",children:u("thinkingLevel")}),P.map(C=>e.jsx(Re,{active:(s==null?void 0:s.thinkingLevel)===C.value,disabled:!C.supported,title:C.supported?void 0:u("thinkingUnsupported"),onClick:()=>{(s==null?void 0:s.thinkingLevel)!==C.value&&c({type:"set_thinking",level:C.value}),T(!1)},children:C.label},C.value))]})]})}),Ur=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches,qr=l.memo(function({ready:s,streaming:n,messages:r,slashCommands:c,modelState:i,models:a,modelsLoading:o,send:u,attachments:m,onRemoveAttachment:y,onAddImageFiles:f,onAddLocalFiles:g,onNotice:v,onSent:T,onManageModels:D,providerKeys:O}){const N=xe(),{locale:j}=pt(),{openPicker:V}=On(),q=h=>j==="en"&&h.descriptionEn?h.descriptionEn:h.description??"",J=h=>j==="en"&&h.argumentHintEn?h.argumentHintEn:h.argumentHint??"",[K,E]=l.useState(""),[H,k]=l.useState(!1),[A,F]=l.useState(null),[X,$]=l.useState(0),[Y,Q]=l.useState(!1),[P,I]=l.useState(void 0),C=l.useRef(null),W=l.useRef(null),U=l.useRef(null),ne=l.useRef(-1),x=l.useRef(""),R={builtin:N("slashBuiltin"),extension:N("slashExtension"),prompt:N("slashPrompt"),skill:N("slashSkill"),plugin:N("slashPlugin")},d=h=>{const z=h.match(/^\/([^\s]*)$/);if(z&&s){const pe=z[1].toLowerCase(),ce=c.filter(fe=>fe.name.toLowerCase().startsWith(pe));F(ce.length>0?ce:null),$(0)}else F(null)};l.useEffect(()=>{var z;const h=(z=U.current)==null?void 0:z.querySelector(".slash-item.active");h==null||h.scrollIntoView({block:"nearest"})},[X,A]);const b=h=>{var me;const z=A??[],pe=h??z[X%Math.max(z.length,1)];if(!pe){F(null);return}const ce=K.match(/^\/([^\s]*)([\s\S]*)$/),fe=ce?ce[2]:"";E(`/${pe.name} ${fe}`),F(null),(me=C.current)==null||me.focus()},w=async()=>{const z=[...r].reverse().find(ce=>ce.role==="assistant"&&ce.content.some(fe=>fe.type==="text"&&fe.text)),pe=z==null?void 0:z.content.filter(ce=>ce.type==="text").map(ce=>ce.text).join(`
|
|
321
|
-
`);if(!pe){v("warning",N("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(pe),v("info",N("slashCopied"))}catch{v("error",N("slashCopyFailed"))}},B=h=>{if(!h||h.length===0){v("warning",N("foldersNotSupported"));return}const z=Array.from(h).filter(fe=>We(fe.type)),pe=Array.from(h).filter(fe=>!We(fe.type)),ce=G();z.length>0&&ce?v("warning",ce):z.length>0&&f(z),pe.length>0&&g(pe)},se=h=>{var fe;const z=(fe=h.clipboardData)==null?void 0:fe.items;if(!z)return;const pe=[];for(const me of z)if(me.kind==="file"&&We(me.type)){const ke=me.getAsFile();ke&&pe.push(ke)}if(pe.length===0)return;h.preventDefault();const ce=G();if(ce){v("warning",ce);return}f(pe)},G=()=>{const h=i==null?void 0:i.model;if(!(h!=null&&h.id))return null;const z=a.find(pe=>pe.id===h.id);return z&&z.vision===!1?N("modelNoVision",{name:z.name}):null},ie=s,ye=l.useRef(K);l.useEffect(()=>{ye.current=K},[K]),l.useEffect(()=>{d(ye.current)},[c]),l.useEffect(()=>{const h=z=>{var ce;const pe=z.detail;E(pe),(ce=C.current)==null||ce.focus()};return window.addEventListener("pi-web:fill",h),()=>window.removeEventListener("pi-web:fill",h)},[]),l.useEffect(()=>{if(!Y)return;const h=z=>{z.key==="Escape"&&Q(!1)};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[Y]),l.useEffect(()=>{const h=C.current;if(!h)return;h.style.height="auto";const z=h.scrollHeight>220;h.style.height=`${Math.min(h.scrollHeight,220)}px`,h.style.overflowY=z?"auto":"hidden"},[K]);const le=h=>h.selectionStart!==h.selectionEnd?!1:!h.value.slice(0,h.selectionStart).includes(`
|
|
322
|
-
`),we=h=>h.selectionStart!==h.selectionEnd?!1:!h.value.slice(h.selectionStart).includes(`
|
|
323
|
-
`),ve=(h=!1)=>{var ce,fe,me,ke,Me;const z=K.trim(),pe=m.some(he=>he.imageData||he.fileData);if(!(!ie||!z&&!pe)){if(z==="/help"){const he=(fe=(ce=C.current)==null?void 0:ce.closest(".inputbox"))==null?void 0:fe.getBoundingClientRect();I(he==null?void 0:he.width),Q(!0),E(""),(me=C.current)==null||me.focus();return}if(z==="/copy"){E(""),(ke=C.current)==null||ke.focus(),w();return}if(u({type:"prompt",text:z,queue:h,attachments:m.map(he=>he.imageData?{path:"",imageData:he.imageData,mimeType:he.mimeType,name:he.name}:he.fileData?{path:"",fileData:he.fileData,mimeType:he.mimeType,name:he.name,size:he.size}:{path:he.path,mode:he.mode,...he.lines?{lines:he.lines}:{}})})){z&&Hr(z),ne.current=-1,x.current="",E(""),T();const he=i==null?void 0:i.model;he&&Br(`${he.provider}/${he.id}`),(Me=C.current)==null||Me.focus()}}},Pe=h=>{if(!h.nativeEvent.isComposing){if(A&&A.length>0)switch(h.key){case"ArrowDown":h.preventDefault(),$(z=>(z+1)%A.length);return;case"ArrowUp":h.preventDefault(),$(z=>(z-1+A.length)%A.length);return;case"Tab":case"Enter":h.preventDefault(),b();return;case"Escape":h.preventDefault(),F(null);return}if(h.key==="ArrowUp"||h.key==="ArrowDown"){if(h.ctrlKey||h.metaKey||h.altKey)return;const z=C.current;if(!z)return;const pe=h.key==="ArrowUp";if(pe&&!le(z)||!pe&&!we(z)||!pe&&ne.current===-1)return;const ce=ct();if(ce.length===0)return;if(h.preventDefault(),pe){if(ne.current===-1){x.current=K;const fe=ce.length-1;ne.current=fe;const me=ce[fe];E(me),d(me),requestAnimationFrame(()=>{const ke=C.current;ke&&(ke.selectionStart=ke.selectionEnd=me.length)})}else if(ne.current>0){const fe=ne.current-1;ne.current=fe;const me=ce[fe];E(me),d(me),requestAnimationFrame(()=>{const ke=C.current;ke&&(ke.selectionStart=ke.selectionEnd=me.length)})}}else{const fe=ne.current+1;if(fe<ce.length){ne.current=fe;const me=ce[fe];E(me),d(me),requestAnimationFrame(()=>{const ke=C.current;ke&&(ke.selectionStart=ke.selectionEnd=me.length)})}else{ne.current=-1;const me=x.current;E(me),d(me),requestAnimationFrame(()=>{const ke=C.current;ke&&(ke.selectionStart=ke.selectionEnd=me.length)})}}return}if(h.key==="Escape"&&ne.current!==-1){h.preventDefault();const z=x.current;ne.current=-1,E(z),d(z),requestAnimationFrame(()=>{const pe=C.current;pe&&(pe.selectionStart=pe.selectionEnd=z.length)});return}if(h.key==="Enter"){if(Ur&&!h.shiftKey&&!(h.ctrlKey||h.metaKey))return;h.shiftKey||(h.preventDefault(),ve())}}},re=()=>e.jsx("div",{className:"inputbox-actions",children:n?e.jsxs(e.Fragment,{children:[K.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:N("supplementTip"),onClick:()=>ve(!0),children:[e.jsx(dn,{})," ",N("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:N("stopAgent"),onClick:()=>u({type:"abort"}),children:e.jsx(vt,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:N("sendTip"),disabled:!ie||!K.trim()&&!m.some(h=>h.imageData||h.fileData),onClick:()=>ve(),children:e.jsx(fn,{})})});return e.jsxs("div",{className:`inputbar${H?" drop-active":""}`,onDragOver:h=>{h.preventDefault(),h.stopPropagation(),k(!0)},onDragLeave:h=>{h.currentTarget.contains(h.relatedTarget)||k(!1)},onDrop:h=>{var z;h.preventDefault(),h.stopPropagation(),k(!1),B(((z=h.dataTransfer)==null?void 0:z.files)??null)},children:[H&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",N("dropHereToAttach")]})}),m.length>0&&e.jsxs("div",{className:"attach-row",children:[m.map(h=>e.jsxs("span",{className:`attach-chip ${h.imageData?"image":h.fileData?"file":h.mode}`,title:h.imageData?N("attachImage",{name:h.name}):h.fileData?N("attachFile",{name:h.name}):h.isDir?N("folderRef",{path:h.path}):h.mode==="reference"?N("refOnly",{path:h.path}):h.mode==="lines"&&h.lines?N("attachLines",{path:h.path,start:h.lines.start,end:h.lines.end}):N("attachContent",{path:h.path}),children:[h.imageData?"🖼":h.fileData?"📄":h.isDir?"📁":h.mode==="reference"?"🔗":"📎"," ",h.name,h.mode==="lines"&&h.lines&&e.jsxs("span",{className:"attach-range",children:["L",h.lines.start,"-",h.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:N("removeAttachment"),onClick:()=>y(h.key??h.path),children:"×"})]},h.key??`${h.path}|${h.mode}|${h.lines?`${h.lines.start}-${h.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:N("attachHint")})]}),A&&A.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:U,"aria-label":N("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:N("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>F(null),children:"Esc"})]}),A.map((h,z)=>e.jsxs("button",{type:"button",className:`slash-item${z===X?" active":""}`,onMouseEnter:()=>$(z),onClick:()=>b(h),children:[e.jsxs("span",{className:"slash-name",children:["/",h.name]}),e.jsx("span",{className:`slash-source ${h.source}`,children:R[h.source]}),e.jsxs("span",{className:"slash-desc",children:[q(h),h.argumentHint&&e.jsx("span",{className:"slash-hint",children:J(h)})]})]},h.name))]}),Y&&e.jsx("div",{className:"modal-backdrop",onClick:()=>Q(!1),children:e.jsxs("div",{className:"slash-help",style:P?{width:P}:void 0,onClick:h=>h.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",N("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>Q(!1),children:N("close")})]}),e.jsx("div",{className:"slash-help-body",children:c.length===0?e.jsx("div",{className:"slash-help-empty",children:N("slashLoading")}):c.map(h=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",h.name]}),e.jsx("span",{className:`slash-source ${h.source}`,children:R[h.source]}),e.jsxs("span",{className:"slash-help-desc",children:[q(h),h.argumentHint&&e.jsx("span",{className:"slash-hint",children:J(h)})]})]},h.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:W,type:"file",multiple:!0,hidden:!0,onChange:h=>{B(h.target.files),h.target.value=""}}),e.jsx("textarea",{ref:C,value:K,rows:1,placeholder:N(ie?n?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!ie,onChange:h=>{ne.current=-1,E(h.target.value),d(h.target.value)},onKeyDown:Pe,onPaste:se}),e.jsxs("div",{className:"composer-tools",children:[e.jsxs("div",{className:"composer-tools-left",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:N("uploadFile"),disabled:!ie,onClick:()=>{var h;return(h=W.current)==null?void 0:h.click()},children:e.jsx(Si,{})}),e.jsx("button",{type:"button",className:"btn tpl-open",title:N("tpl.openPicker"),onClick:V,children:e.jsx(Ai,{})}),e.jsx(Wr,{state:i,models:a,modelsLoading:o,send:u,onManageModels:D,providerKeys:O,compact:!0})]}),e.jsx("div",{className:"composer-tools-right",children:re()})]})]})]})}),zr=l.memo(function({goal:s,models:n,modelsLoading:r,activeConversationId:c,engine:i,send:a}){var P,I,C,W,U,ne,x;const o=xe(),{locale:u}=pt(),m=u==="en"&&s.statusEn?s.statusEn:s.status||"",y=u==="en"&&((P=s.wizard)!=null&&P.statusEn)?s.wizard.statusEn:((I=s.wizard)==null?void 0:I.status)||"",f=i==="dsh",g=!s.conversationId||s.conversationId===c,v=s.goal!==null&&g,[T,D]=l.useState(""),[O,N]=l.useState(s.reviewModel??""),[j,V]=l.useState(s.maxRounds),[q,J]=l.useState(s.locked),[K,E]=l.useState(!1),[H,k]=l.useState(!1),[A,F]=l.useState(!0);l.useEffect(()=>{N(s.reviewModel??""),V(s.maxRounds||0),J(s.locked)},[s.goal,s.reviewModel,s.maxRounds,s.locked]),l.useEffect(()=>{K&&n.length===0&&!H&&!r&&(k(!0),a({type:"list_models"}))},[K,n.length,H,r,a]),l.useEffect(()=>{n.length>0&&k(!1)},[n.length]);const X=()=>{var R;return O?((R=n.find(d=>d.id===O))==null?void 0:R.name)??O:o("goalBarUseMainModel")},$=()=>{const R=T.trim();R&&(a({type:"set_goal",goal:R,...O?{reviewModel:O}:{},maxRounds:j,locked:q}),D(""),F(!1))},Y=()=>{const R=T.trim();R&&(a({type:"start_goal_wizard",text:R,...O?{wizardModel:O}:{},maxRounds:j,locked:q}),D(""),F(!1))},Q=(((C=s.wizard)==null?void 0:C.active)??!1)&&g;return Q?e.jsx("div",{className:`goalbar goalbar-active ${Q?"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:((W=s.wizard)==null?void 0:W.draft)??"",children:[o("goalWizardRunning"),": ",(U=s.wizard)==null?void 0:U.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[o("goalBarRound",{n:(((ne=s.wizard)==null?void 0:ne.step)??0)+1})," / ",((x=s.wizard)==null?void 0:x.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:y||o("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),onClick:()=>{a({type:"clear_goal"}),F(!0)},children:e.jsx(Ee,{})})]})}):v?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:[o("goalBarReviewing")," ",o("goalBarRound",{n:s.round})]}):e.jsx("span",{className:`goalbar-chip ${s.verdict==="pass"?"pass":s.verdict==="fail"?"fail":""}`,children:s.verdict==="pass"?o("goalBarPassed"):s.verdict==="fail"?o("goalBarFailed"):`${o("goalBarRound",{n:s.round||1})} · ${s.locked?o("goalBarLocked"):o("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:m}),e.jsx("button",{type:"button",className:"goalbar-x",title:o("goalBarClear"),disabled:s.reviewing,onClick:()=>{a({type:"clear_goal"}),F(!0)},children:e.jsx(Ee,{})})]})}):A?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:o("goalBarPlaceholder"),onClick:()=>F(!1),children:[e.jsx(ws,{})," ",e.jsx("span",{children:o("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx(ws,{})}),e.jsx("input",{className:"goalbar-input",value:T,placeholder:o("goalBarPlaceholder"),onChange:R=>D(R.target.value),onKeyDown:R=>{R.key==="Enter"&&$()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!T.trim(),onClick:$,children:o("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!T.trim(),title:o("goalWizardTip"),onClick:Y,children:["🔍 ",o("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o(q?"goalBarLocked":"goalBarUnlocked"),onClick:()=>J(R=>(a({type:"set_goal_prefs",locked:!R}),!R)),children:q?e.jsx(Ii,{}):e.jsx(ji,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:o("goalBarClear"),onClick:()=>F(!0),children:e.jsx(dt,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[f?e.jsx("p",{className:"goalbar-dsh-note",children:o("dshNoReviewModel")}):e.jsxs(ze,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[o("goalBarReviewModel"),": ",e.jsx("b",{children:X()})]}),open:K,onOpenChange:E,direction:"up",children:[e.jsx("div",{className:"dd-header",children:o("goalBarReviewModel")}),(H||r)&&e.jsx("div",{className:"dd-loading",children:o("loading")}),n.length===0&&!H&&!r&&e.jsx("div",{className:"dd-loading",children:o("noModels")}),e.jsx(Re,{active:O==="",onClick:()=>{N(""),E(!1),a({type:"set_goal_prefs",reviewModel:""})},children:o("goalBarUseMainModel")}),n.map(R=>e.jsx(Re,{active:O===R.id,onClick:()=>{N(R.id),E(!1),a({type:"set_goal_prefs",reviewModel:R.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:R.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:R.provider})})]})},R.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>a({type:"list_models"}),children:o("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:o("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:o("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:j,placeholder:o("goalBarUnlimitedShort"),onChange:R=>{const d=parseInt(R.target.value,10);if(Number.isNaN(d)||d<0){V(0);return}V(d)},onBlur:()=>a({type:"set_goal_prefs",maxRounds:j}),onKeyDown:R=>{R.key==="Enter"&&(a({type:"set_goal_prefs",maxRounds:j}),R.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:o(q?"goalBarLocked":"goalBarUnlocked")})]})]})});function Vr(t){const s=Math.max(0,t.input??0),n=Math.max(0,t.cacheRead??0),r=Math.max(0,t.cacheWrite??0),c=s+n+r;return{totalInput:c,miss:s,read:n,write:r,hitRate:c>0?Math.min(n/c,1):0,writeRate:c>0?Math.min(r/c,1):0}}const Qn=2e3;function Gr(t,s,n=Qn){return t.filter(r=>s-r.t<=n)}function Qr(t,s=Qn){if(t.length<2)return 0;const n=t[t.length-1],r=t.find(i=>i.t>=n.t-s)??t[0],c=(n.t-r.t)/1e3;return c<=0?0:Math.max(0,(n.out-r.out)/c)}function Ys(t){if(!t)return 0;let s=0;for(let r=0;r<t.length;r++){const c=t.charCodeAt(r);(c>=12352&&c<=12543||c>=13312&&c<=19903||c>=19968&&c<=40959||c>=63744&&c<=64255||c>=65280&&c<=65519||c===12288)&&s++}const n=t.length-s;return Math.round(s+n/4)}function Yr(t){let s=0;for(const n of t)n.type==="text"&&typeof n.text=="string"&&n.text?s+=Ys(n.text):n.type==="thinking"&&typeof n.thinking=="string"&&n.thinking&&(s+=Ys(n.thinking));return s}function Jr({chat:t,send:s}){const n=xe(),r=t.state,[c,i]=l.useState(!1),[a,o]=l.useState(""),[u,m]=l.useState(""),[y,f]=l.useState(!1),[g,v]=l.useState(""),T=l.useRef(null),D=l.useRef(null),O=t.pathCompletions.filter(d=>d.type==="dir"),N=d=>d.endsWith("/")?d:d+"/",j=d=>{let b=d.endsWith("/")?d.slice(0,-1):d;const w=b.lastIndexOf("/");if(w<=0)return null;const B=b.slice(0,w);return/^[A-Za-z]:$/.test(B)?B+"/":B};l.useEffect(()=>{if(!c)return;const d=setTimeout(()=>{s({type:"complete_path",path:N(a)})},60);return()=>clearTimeout(d)},[a,c,s]);const V=l.useRef([]),q=(r==null?void 0:r.isStreaming)??!1,J=r!=null&&r.streamingMessage?Yr(r.streamingMessage.content):0;if(l.useEffect(()=>{if(!q){V.current=[];return}const d=Date.now(),b=V.current,w=b[b.length-1];w&&d-w.t<250||(V.current=Gr([...b,{t:d,out:J}],d))},[q,J]),!r)return null;const K=r.stats,E=Vr(K.tokens),H=E.hitRate*100,k=E.totalInput===0?"":E.hitRate>=.7?"ok":E.hitRate>=.4?"mid":"warn",A=E.totalInput>0?`${H.toFixed(1)}%`:"—",F=q?Qr(V.current):0,X=t.ready?"ok":"busy",$=t.ready?n("connected"):n("connecting"),Y=K.contextUsage,Q=Y.tokens!==null&&Y.percent!==null?`${Xe(Y.tokens)} / ${Xe(Y.contextWindow)}`:"—",P=Y.percent??null,I=P===null?"":P>=80?"warn":P>=50?"mid":"ok",C=r.queue.steering.length+r.queue.followUp.length,W=()=>{m(r.cwd),o(r.cwd),f(!1),v(""),i(!0)},U=d=>{const b=d.trim();b&&b!==r.cwd&&s({type:"set_cwd",path:b}),i(!1)},ne=()=>{const d=g.trim();d&&(s({type:"make_dir",path:`${N(a)}${d}`}),setTimeout(()=>{s({type:"complete_path",path:N(a)})},80),v(""),f(!1))},x=d=>{d.key==="Escape"?(d.stopPropagation(),i(!1)):d.key==="Enter"&&!d.nativeEvent.isComposing&&U(u)},R=j(a);return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${X}`,title:$}),e.jsx("span",{className:"status-item",children:$}),e.jsx("span",{className:"status-sep",children:"·"}),t.engine&&t.engine!=="pi"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`status-item engine-badge engine-${t.engine}`,title:`${n("engineBadge")}: ${t.engine}`,children:t.engine==="dsh"?"DSH":t.engine}),e.jsx("span",{className:"status-sep",children:"·"})]}),e.jsxs("span",{className:"status-item status-ctx",title:n("contextUsage"),children:[n("context"),e.jsx("span",{className:`ctx-bar ${I}`,children:P!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(P,100)}%`}})}),Q]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("cumulativeCost"),children:["$",Xr(K.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-cache",title:n("cacheHitTip",{read:Xe(E.read),write:Xe(E.write),miss:Xe(E.miss),input:Xe(E.totalInput)}),children:[n("cacheHit"),e.jsx("b",{className:`cache-pct ${k}`,children:A})]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:n("sessionMessages"),children:[n("messages")," ",K.totalMessages]}),t.statuses.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsx("span",{className:"status-item ext-status",title:n("pluginStatus"),children:t.statuses.map(d=>d.text).join(" · ")})]}),r.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"),C>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",C," ",n("queued")]})]}),e.jsx("span",{className:"status-item status-rate",title:n("rateTip"),children:F>0?`${Math.round(F)}${n("tps")}`:"…"})]}),c?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"status-cwd-backdrop",onClick:()=>i(!1)}),e.jsxs("div",{className:"cwd-picker",children:[e.jsxs("div",{className:"cwd-picker-head",children:[e.jsxs("span",{className:"cwd-picker-title",title:a,children:[e.jsx(Ye,{}),e.jsx("span",{children:a})]}),e.jsxs("button",{type:"button",className:"cwd-up",disabled:!R,title:n("cwdGoUp"),onClick:()=>{R&&(o(R),m(R))},children:["↑ ",n("cwdGoUp")]})]}),e.jsxs("div",{className:"cwd-picker-row",children:[e.jsx("input",{ref:T,className:"status-cwd-input cwd-picker-input",value:u,placeholder:n("enterPath"),spellCheck:!1,onChange:d=>m(d.target.value),onKeyDown:x}),e.jsx("button",{type:"button",className:"cwd-choose-btn primary",title:n("cwdPickCurrent"),onClick:()=>U(a),children:n("cwdPickCurrent")})]}),e.jsxs("div",{className:"cwd-list",children:[O.length===0&&e.jsx("div",{className:"cwd-empty",children:n("cwdEmpty")}),O.map(d=>e.jsxs("div",{className:"cwd-item",children:[e.jsxs("button",{type:"button",className:"cwd-enter",title:`${n("cwdEnter")} ${d.path}`,onClick:()=>{o(d.path),m(d.path)},children:[e.jsx(Ye,{}),e.jsx("span",{className:"cwd-name",children:d.name})]}),e.jsx("button",{type:"button",className:"cwd-choose-btn",title:n("cwdChoose"),onClick:()=>U(d.path),children:n("cwdChoose")})]},d.path))]}),e.jsx("div",{className:"cwd-picker-foot",children:y?e.jsxs("div",{className:"cwd-newrow",children:[e.jsx("input",{ref:D,value:g,autoFocus:!0,spellCheck:!1,placeholder:n("cwdNewName"),onChange:d=>v(d.target.value),onKeyDown:d=>{d.key==="Enter"&&!d.nativeEvent.isComposing?(d.preventDefault(),ne()):d.key==="Escape"&&(d.stopPropagation(),f(!1),v(""))}}),e.jsx("button",{type:"button",className:"cwd-choose-btn primary",onClick:ne,children:n("cwdCreate")}),e.jsx("button",{type:"button",className:"cwd-choose-btn",onClick:()=>{f(!1),v("")},children:n("cwdCancel")})]}):e.jsxs("button",{type:"button",className:"cwd-newbtn",onClick:()=>f(!0),children:["+ ",n("cwdNewFolder")]})})]})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:n("cwdTip",{path:r.cwd}),onClick:W,children:["📁 ",r.cwd]})]})}function Xe(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function Xr(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function Zr({dialog:t,send:s}){const n=xe(),[r,c]=l.useState(""),[i,a]=l.useState(0),o=y=>{s({type:"dialog_response",id:t.id,value:y})};l.useEffect(()=>{c(""),a(0);const y=f=>{f.key==="Escape"&&o(null)};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t.id]);const u=Array.isArray(t.args[0])?t.args[0]:[],m=typeof t.args[0]=="string"?t.args[0]:"";return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":t.kind,children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children: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:[u.map((y,f)=>e.jsx("button",{type:"button",className:`dialog-option ${f===i?"sel":""}`,onMouseEnter:()=>a(f),onClick:()=>o(y),children:y},f)),u.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:r,placeholder:m||n("inputPlaceholder"),autoFocus:!0,onChange:y=>c(y.target.value),onKeyDown:y=>{y.key==="Enter"&&!y.nativeEvent.isComposing&&o(r)}}),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(r),children:n("ok")})]})]})]})}function el({question:t,send:s}){const n=xe(),[r,c]=l.useState({}),[i,a]=l.useState({}),[o,u]=l.useState(()=>t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1);l.useEffect(()=>{c({}),a({}),u(t.deadline?Math.max(0,Math.ceil((t.deadline-Date.now())/1e3)):-1)},[t.id,t.deadline]),l.useEffect(()=>{if(!t.deadline)return;const g=setInterval(()=>{u(v=>{const T=Math.max(0,Math.ceil((t.deadline-Date.now())/1e3));return T<=0&&v>0&&s({type:"question_answer",id:t.id,answers:[],cancelled:!0}),T})},1e3);return()=>clearInterval(g)},[t.id,t.deadline]);const m=g=>{if(g){s({type:"question_answer",id:t.id,answers:[],cancelled:!0});return}const v=t.questions.map(T=>{const D=r[T.id]??[],O=(i[T.id]??"").trim();return{id:T.id,selected:D,...O?{custom:O}:{}}});s({type:"question_answer",id:t.id,answers:v})};l.useEffect(()=>{const g=v=>{v.key==="Escape"&&m(!0)};return document.addEventListener("keydown",g),()=>document.removeEventListener("keydown",g)},[t.id]);const y=(g,v,T)=>{c(D=>{const O=D[g]??[];return T?{...D,[g]:O.includes(v)?O.filter(N=>N!==v):[...O,v]}:{...D,[g]:[v]}})},f=t.questions.every(g=>{var v;return(((v=r[g.id])==null?void 0:v.length)??0)>0||(i[g.id]??"").trim()!==""});return e.jsxs("div",{className:"dialog-inline","data-dialog-kind":"select",children:[e.jsxs("div",{className:"dialog-head",children:[e.jsx("span",{className:"dialog-badge",children:n("modelQuestion")}),o>=0&&e.jsx("span",{className:"question-timer",children:o>0?n("questionTimeout",{s:o}):n("questionTimeoutExpired")}),e.jsx("button",{type:"button",className:"dialog-dismiss",title:n("cancel"),onClick:()=>m(!0),children:"✕"})]}),t.questions.map((g,v)=>{var T;return e.jsxs("div",{className:"set-section",children:[e.jsx("div",{className:"set-section-title",children:g.header??`${n("modelQuestion")} ${v+1}`}),e.jsx("p",{className:"set-row-desc",children:g.question}),g.detail&&e.jsx("p",{className:"set-hint",children:g.detail}),(((T=g.options)==null?void 0:T.length)??0)>0&&e.jsx("div",{className:"set-list",children:g.options.map(D=>{const O=(r[g.id]??[]).includes(D.label);return e.jsxs("button",{type:"button",className:`set-row question-option${O?" active":""}`,onClick:()=>y(g.id,D.label,!!g.multiSelect),children:[e.jsxs("span",{className:"set-row-name",children:[g.multiSelect?O?"☑ ":"☐ ":O?"● ":"○ ",D.label]}),D.description&&e.jsx("span",{className:"set-row-desc",children:D.description})]},D.label)})}),e.jsx("input",{className:"set-prompt-input question-custom",placeholder:n("modelQuestionCustom"),value:i[g.id]??"",onChange:D=>a(O=>({...O,[g.id]:D.target.value}))})]},g.id)}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"dialog-submit",disabled:!f,onClick:()=>m(!1),children:n("modelQuestionSubmit")}),e.jsx("button",{type:"button",className:"dialog-dismiss-inline",onClick:()=>m(!0),children:n("cancel")})]})]})}const Js=t=>`'${t.replace(/'/g,"'\\''")}'`;function tl(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 sl({chat:t,send:s,terminal:n,active:r,onSwitchToTerminal:c}){var _e,De;const i=xe(),[a,o]=l.useState(null),[u,m]=l.useState([]),[y,f]=l.useState(""),[g,v]=l.useState(new Map),[T,D]=l.useState("changes"),[O,N]=l.useState([]),[j,V]=l.useState(null),[q,J]=l.useState(""),[K,E]=l.useState(!1),[H,k]=l.useState(null),[A,F]=l.useState(null),[X,$]=l.useState(!1),[Y,Q]=l.useState(!1),[P,I]=l.useState(!1),[C,W]=l.useState(null),[U,ne]=l.useState(!1),[x,R]=l.useState(""),d=l.useRef(0),b=l.useRef(-1),w=l.useRef(-1),B=l.useRef(-1),se=l.useRef(-1),G=l.useRef(void 0),ie=l.useRef(null),ye=l.useRef([]),le=l.useCallback(M=>{if(M.reqId===b.current){if(b.current=-1,Q(!1),W(null),!M.ok){W(M.error??i("scmQueryFailedShort"));return}if(M.notRepo){ne(!0),o(null),m([]),v(new Map),N([]),V(null),J(""),F(null);return}ne(!1);const ge={branch:M.branch??"",detached:!!M.detached,upstream:M.upstream??null,ahead:M.ahead??0,behind:M.behind??0,upstreamGone:!!M.upstreamGone,files:(M.files??[]).map(de=>({...de}))},p=(M.branches??[]).map(de=>({...de})),ee=new Map;for(const[de,S]of Object.entries(M.stats??{}))ee.set(de,{add:S[0],del:S[1]});o(ge),m(p),v(ee),f(de=>{var S;return ge.detached?de||"":ge.branch&&p.some(L=>L.name===ge.branch)?ge.branch:de&&p.some(L=>L.name===de)?de:((S=p[0])==null?void 0:S.name)??""}),F(de=>de&&!ge.files.some(S=>S.path===de.file.path)?null:de)}else if(M.reqId===w.current){if(w.current=-1,$(!1),!M.ok){W(M.error??i("scmQueryFailedShort"));return}const ge=ie.current;if(!ge)return;F({file:ge,staged:M.stagedText??"",worktree:M.worktreeText??"",untracked:!1})}else if(M.reqId===se.current){if(se.current=-1,I(!1),!M.ok){W(M.error??i("scmQueryFailedShort"));return}N((M.history??[]).map(ge=>({...ge})))}else if(M.reqId===B.current){if(B.current=-1,E(!1),!M.ok){W(M.error??i("scmQueryFailedShort"));return}J(M.text??"")}},[]);l.useEffect(()=>{const M=t.scmData;M&&M.type==="scm_data"&&le(M)},[t.scmData,le]);const we=l.useCallback((M,ge)=>{if(!t.ready||t.status!=="open")return!1;const p=++d.current;return s({...M,reqId:p})?(ge.current=p,!0):(d.current-=1,!1)},[t.ready,t.status,s]),ve=l.useCallback((M=!1,ge=!1)=>{var p;!t.ready||t.status!=="open"||(p=t.state)!=null&&p.cwd&&(G.current!==void 0&&G.current!==t.state.cwd&&(o(null),m([]),v(new Map),N([]),I(!1),se.current=-1,V(null),J(""),F(null),k(null)),G.current=t.state.cwd,W(null),we({type:"scm_status"},b)&&(ge||Q(!0)))},[t.ready,(_e=t.state)==null?void 0:_e.cwd,t.status,we]),Pe=l.useCallback(M=>{if(k(M),V(null),ie.current=M,M.x==="?"&&M.y==="?"){F({file:M,staged:"",worktree:"",untracked:!0});return}$(!0),W(null),we({type:"scm_filediff",path:M.path},w)||$(!1)},[we]),re=l.useCallback(M=>{V(M),k(null),F(null),J(""),E(!0),W(null),we({type:"scm_commit",hash:M.hash},B)||E(!1)},[we]),h=l.useCallback((M,ge)=>{var S,L;if(!t.ready)return;const p={name:M,command:ge,cwd:"${pwd}"};let ee;const de=t.terminals.find(ae=>ae.title===M);de?(n.restart(de.id),s({type:"run_command",terminalId:de.id,conversationId:de.conversationId,command:p,cols:80,rows:24}),ee=de.id):(ee=Ue(),n.create({id:ee,conversationId:t.activeConversationId||((S=t.state)==null?void 0:S.conversationId)||"",title:M,cwd:((L=t.state)==null?void 0:L.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:p})),n.select(ee),c()},[t.ready,(De=t.state)==null?void 0:De.cwd,t.terminals,c,s,n]),z=l.useCallback(()=>{const M=x.trim();if(!M||U)return;const ge=M.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");h("git commit",`git commit -m "${ge}"`),R("")},[x,U,h]),pe=l.useCallback(()=>{const M=x.trim();if(!M||U)return;const ge=M.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");h("git commit",`git add -A && git commit -m "${ge}"`),R("")},[x,U,h]),ce=l.useCallback(M=>{U||h("git add",`git add -- ${Js(M.path)}`)},[U,h]),fe=l.useCallback(M=>{U||h("git reset",`git reset HEAD -- ${Js(M.path)}`)},[U,h]),me=l.useCallback(()=>{if(!y||U)return;const M=u.find(ge=>ge.name===y);if(M!=null&&M.remote&&typeof M.remote=="string"){const ge=y.slice(M.remote.length+1);h("git checkout",`git checkout -b ${ge} ${y} || git checkout ${y}`)}else h("git checkout",`git checkout ${y}`)},[y,u,U,h]),ke=l.useCallback(()=>h("git push","git push"),[h]),Me=l.useCallback(()=>h("git pull","git pull"),[h]),he=l.useCallback(()=>{we({type:"scm_history"},se)||(se.current=-1)},[we]);l.useEffect(()=>{r&&ve()},[r,ve]),l.useEffect(()=>{T==="history"&&a&&he()},[T,a,he]),l.useEffect(()=>{t.scmDirty>0&&r&&ve(!1,!0)},[t.scmDirty]),l.useEffect(()=>{if(!r||!t.ready||t.status!=="open")return;const M=setInterval(()=>{document.visibilityState!=="hidden"&&ve(!1,!0)},3e4);return()=>clearInterval(M)},[r,t.ready,t.status,ve]),l.useEffect(()=>{const M=ye.current;if(ye.current=t.terminals,!r)return;t.terminals.some(p=>{var de;return p.running!==!1?!1:((de=M.find(S=>S.id===p.id))==null?void 0:de.running)===!0&&p.title.startsWith("git ")})&&t.ready&&t.status==="open"&&(ve(!1,!0),T==="history"&&a&&he())},[t.terminals,r,t.ready,t.status,ve,T,a,he]);const Ie={staged:i("scmStaged"),unstaged:i("scmUnstaged"),untracked:i("scmUntracked"),both:i("scmStagedUnstaged")},Le=M=>{const ge=M.split(`
|
|
324
|
-
`);return e.jsx("pre",{className:"scm-diff-pre",children:ge.map((p,ee)=>{let de="";return p.startsWith("diff --git")||p.startsWith("index ")||p.startsWith("new file")||p.startsWith("deleted file")||p.startsWith("old mode")||p.startsWith("new mode")||p.startsWith("similarity index")||p.startsWith("rename ")||p.startsWith("copy ")||p.startsWith("Binary files")||p.startsWith("---")||p.startsWith("+++")?de="hdr":p.startsWith("@@")?de="hunk":p.startsWith("+")?de="add":p.startsWith("-")&&(de="del"),e.jsx("div",{className:`scm-diff-line ${de}`,children:p||" "},ee)})})};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(ft,{}),i("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":T==="changes",className:T==="changes"?"active":"",onClick:()=>{D("changes"),W(null)},children:i("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":T==="history",className:T==="history"?"active":"",onClick:()=>{D("history"),W(null)},children:i("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:i("scmRefreshTip"),disabled:Y,onClick:()=>ve(!0),children:e.jsx(at,{className:Y?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:i("scmCurrentBranch"),children:[e.jsx(ft,{}),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:y,disabled:U||u.length===0,title:i("scmSwitchBranch"),onChange:M=>f(M.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:i("scmSelectBranch")}),u.filter(M=>!M.remote).map(M=>e.jsx("option",{value:M.name,children:M.current?`* ${M.name}`:M.name},M.name)),u.some(M=>M.remote)&&e.jsx("optgroup",{label:i("scmRemoteBranches"),children:u.filter(M=>M.remote).map(M=>e.jsx("option",{value:M.name,children:M.name},M.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!y||y===(a==null?void 0:a.branch)||U,title:i("scmSwitchBranchTip",{branch:y}),onClick:me,children:[e.jsx(ft,{}),i("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!a||a.detached||U,title:i("scmPushTip"),onClick:ke,children:[e.jsx(fn,{}),i("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!a||a.detached||U,title:i("scmPullTip"),onClick:Me,children:[e.jsx(xn,{}),i("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:x,placeholder:i("scmCommitPlaceholder"),disabled:U,onChange:M=>R(M.target.value),onKeyDown:M=>{M.key==="Enter"&&!M.nativeEvent.isComposing&&z()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!x.trim()||U,title:i("scmCommitTip"),onClick:z,children:[e.jsx(ut,{}),i("scmCommit")]}),e.jsx("button",{type:"button",className:"btn",disabled:!x.trim()||U,title:i("scmCommitAllTip"),onClick:pe,children:i("scmCommitAll")})]})]}),e.jsxs("div",{className:"scm-body",children:[T==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:i("scmHistory")}),O.length>0&&e.jsx("span",{className:"scm-files-count",children:O.length})]}),e.jsx("div",{className:"scm-history-list",children:U?e.jsx("div",{className:"scm-empty",children:i("scmNotGitRepo")}):!a||P?e.jsx("div",{className:"scm-empty",children:t.status==="open"?i("scmLoading"):i("scmConnecting")}):O.length===0?e.jsx("div",{className:"scm-empty",children:i("scmNoHistory")}):O.map(M=>e.jsxs("button",{type:"button",className:`scm-commit ${(j==null?void 0:j.hash)===M.hash?"active":""}`,onClick:()=>re(M),title:M.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:M.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:M.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[M.shortHash," · ",M.author," · ",M.date]}),M.decorations&&e.jsx("span",{className:"scm-commit-refs",children:M.decorations})]})]},M.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children: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:U?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(M=>{const ge=tl(M),p=g.get(M.path);return e.jsxs("div",{className:`scm-file ${(H==null?void 0:H.path)===M.path?"active":""}`,title:Ie[ge],onClick:()=>Pe(M),children:[e.jsx("span",{className:`scm-file-xy ${ge==="untracked"?"q":"x"}`,children:M.x!==" "?M.x:" "}),e.jsx("span",{className:`scm-file-xy ${ge==="untracked"?"q":"y"}`,children:M.y!==" "?M.y:" "}),e.jsx("span",{className:"scm-file-path",children:M.path}),p&&(p.add>0||p.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[p.add>0&&e.jsxs("span",{className:"add",children:["+",p.add]}),p.del>0&&e.jsxs("span",{className:"del",children:["-",p.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(M.y!==" "||ge==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:i("scmStageTip",{path:M.path}),onClick:ee=>{ee.stopPropagation(),ce(M)},children:"+"}),ge==="staged"||ge==="both"?e.jsx("button",{type:"button",className:"scm-act",title:i("scmUnstageTip",{path:M.path}),onClick:ee=>{ee.stopPropagation(),fe(M)},children:"−"}):null]})]},M.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:T==="history"?j?`${j.shortHash} ${j.subject}`:i("scmCommitDetail"):H?H.path:i("scmDiff")}),(T==="history"?K:X)&&e.jsx("span",{className:"scm-diff-loading",children:i("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:T==="history"?e.jsxs(e.Fragment,{children:[C&&e.jsx("div",{className:"scm-error",children:C}),!j&&!C&&e.jsx("div",{className:"scm-empty",children:i("scmSelectCommitHint")}),j&&K&&!C&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),j&&!K&&!C&&q?Le(q):null]}):e.jsxs(e.Fragment,{children:[C&&e.jsx("div",{className:"scm-error",children:C}),!H&&!C&&e.jsx("div",{className:"scm-empty",children:i("scmSelectFileHint")}),H&&!A&&!C&&e.jsx("div",{className:"scm-empty",children:i("scmLoading")}),H&&A&&A.untracked&&e.jsx("div",{className:"scm-empty",children:i("scmUntrackedNote")}),H&&A&&!A.untracked&&e.jsxs(e.Fragment,{children:[A.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmStaged")}),Le(A.staged)]}),A.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:i("scmUnstaged")}),Le(A.worktree)]}),!A.staged&&!A.worktree&&e.jsx("div",{className:"scm-empty",children:i("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(et,{}),e.jsx("span",{children:i("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:c,children:i("scmViewTerminal")})]})]})}function nl({entry:t,send:s}){const n=l.useRef(null),r=xe();return l.useEffect(()=>{const c=n.current;if(!c)return;let i;try{i=t.module.mount(c,ga(t.info.id,a=>s(a)))}catch(a){console.error(`[plugin:${t.info.id}] mount failed:`,a),c.textContent=r("pluginMountFailed",{name:t.info.name})}return()=>{if(typeof i=="function")try{i()}catch(a){console.error(`[plugin:${t.info.id}] cleanup failed:`,a)}c.textContent=""}},[t,s]),e.jsx("div",{className:"plugin-view",ref:n})}function il({send:t,piConfigured:s,piAgentInstalled:n,providers:r,installResult:c,onClose:i}){const a=xe(),[o,u]=l.useState(!1),[m,y]=l.useState(""),[f,g]=l.useState(""),[v,T]=l.useState(!1);l.useEffect(()=>{t({type:"list_providers"})},[t]),l.useEffect(()=>{s&&i()},[s,i]),l.useEffect(()=>{c&&u(!1)},[c]),l.useEffect(()=>{var q;!m&&r.length>0&&y(((q=r.find(J=>!J.configured))==null?void 0:q.id)??r[0].id)},[r,m]);const D=()=>{o||(u(!0),t({type:"install_pi_agent"}))},O=()=>{!f.trim()||v||(T(!0),t({type:"set_provider_api_key",provider:m.trim(),apiKey:f.trim()}),setTimeout(()=>T(!1),3e3))},N=()=>{t({type:"get_state"}),t({type:"list_providers"})},j=r.find(q=>q.id===m),V=c!==null&&!c.ok;return e.jsx("div",{className:"modal-backdrop",children:e.jsxs("div",{className:"modal setup-modal",children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":a("close"),onClick:i,children:e.jsx(Ee,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(rt,{className:"modal-head-icon"}),e.jsx("h2",{children:a("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:a("setupDesc")}),V?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:a("installFailed")}),e.jsx("pre",{className:"setup-detail",children:c.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:D,children:a("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:a("skip")})]})]}):n||c!=null&&c.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:c!=null&&c.ok?a("installDone"):a("cliReadyHint")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:a("provider")}),e.jsxs("select",{value:m,onChange:q=>y(q.target.value),children:[r.length===0&&e.jsx("option",{value:"",children:a("loading")}),r.map(q=>e.jsxs("option",{value:q.id,children:[q.name,"(",q.id,")",q.configured?` · ${a("configured")}`:""]},q.id))]}),(j==null?void 0:j.configured)&&e.jsx("div",{className:"field-hint",children:a("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:a("apiKey")}),e.jsx("input",{type:"password",value:f,onChange:q=>g(q.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!f.trim()||v||!m,onClick:O,children:a(v?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:N,children:[e.jsx(at,{})," ",a("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:o,onClick:D,children:a(o?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:i,children:a("skip")})]})]})})}const al=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],ns=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),rl=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[ns()]});function $t(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:[ns()]).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 ll({send:t,providers:s,providerStatus:n,providerKeys:r,fetchModelsResult:c,cloneProviderResult:i,onClose:a}){const o=xe(),[u,m]=l.useState(null),[y,f]=l.useState({}),[g,v]=l.useState({}),[T,D]=l.useState(null),[O,N]=l.useState(!1),[j,V]=l.useState(0),[q,J]=l.useState(null),K=l.useRef(0),[E,H]=l.useState(null),[k,A]=l.useState(""),[F,X]=l.useState(null);l.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"}),t({type:"list_provider_keys"})},[t]);const $=()=>{if(!u)return;const x=u.baseUrl.trim();if(!x){J({ok:!1,text:o("fetchModelsNeedBaseUrl")});return}if(O)return;N(!0),J(null);const R=j+1;V(R),t({type:"fetch_models",reqId:R,baseUrl:x,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader,api:u.api})};l.useEffect(()=>{var x;if(!(!c||c.reqId===K.current))if(K.current=c.reqId,N(!1),c.ok&&((x=c.models)!=null&&x.length)){const R=c.models;m(d=>{if(!d)return d;const b=d.models.map(G=>{var le;if(!G.id.trim())return G;const ie=R.find(we=>we.id===G.id.trim());if(!ie)return G;const ye={...G};return!ye.name&&ie.name&&(ye.name=ie.name),!ye.contextWindow&&ie.contextWindow&&(ye.contextWindow=String(ie.contextWindow)),!ye.maxTokens&&ie.maxTokens&&(ye.maxTokens=String(ie.maxTokens)),ye.input==="text"&&((le=ie.input)!=null&&le.includes("image"))&&(ye.input="text-image"),!ye.reasoning&&ie.reasoning&&(ye.reasoning=!0),ye}),w=new Set(b.map(G=>G.id.trim()).filter(Boolean)),B=R.filter(G=>!w.has(G.id)).map(G=>{var ie;return{id:G.id,name:G.name??"",reasoning:G.reasoning??!1,input:(ie=G.input)!=null&&ie.includes("image")?"text-image":"text",contextWindow:G.contextWindow?String(G.contextWindow):"",maxTokens:G.maxTokens?String(G.maxTokens):""}}),se=[...b,...B];return se.some(G=>G.id.trim())?{...d,models:se.filter(G=>G.id.trim())}:d}),J({ok:!0,text:o("fetchModelsOk",{n:R.length})})}else J({ok:!1,text:c.error||o("fetchModelsEmpty")})},[c]);const Y=x=>{const R=(y[x.id]??"").trim();!R||T||(D(x.id),t({type:"add_provider_key",provider:x.id,apiKey:R,name:(g[x.id]??"").trim()||void 0}),setTimeout(()=>{D(null),f(d=>({...d,[x.id]:""})),v(d=>({...d,[x.id]:""})),t({type:"list_providers"}),t({type:"list_provider_keys"})},1500))},Q=(x,R)=>{t({type:"activate_provider_key",provider:x,keyName:R}),t({type:"list_provider_keys"})},P=(x,R)=>{window.confirm(o("removeKeyConfirm"))&&(t({type:"remove_provider_key",provider:x,keyName:R}),t({type:"list_provider_keys"}))},I=()=>{if(!F)return;const x=F.providerId.trim();if(!x||!F.apiKey.trim())return;const R=F.models.filter(b=>b.id.trim()).map(b=>({id:b.id.trim(),name:b.name.trim()||void 0,reasoning:b.reasoning||void 0,input:b.input==="text-image"?["text","image"]:void 0,contextWindow:b.contextWindow?Number(b.contextWindow):void 0,maxTokens:b.maxTokens?Number(b.maxTokens):void 0})),d={providerId:x,name:F.name.trim()||void 0,api:F.api.trim()||void 0,baseUrl:F.baseUrl.trim()||void 0,apiKey:F.apiKey.trim()||void 0,authHeader:F.authHeader||void 0,models:R};t({type:"save_model_config",providerId:x,config:d}),X(null),a()},C=()=>{if(!u)return;const x=u.providerId.trim(),R=u.models.filter(b=>b.id.trim()).map(b=>({id:b.id.trim(),name:b.name.trim()||void 0,reasoning:b.reasoning||void 0,input:b.input==="text-image"?["text","image"]:void 0,contextWindow:b.contextWindow?Number(b.contextWindow):void 0,maxTokens:b.maxTokens?Number(b.maxTokens):void 0})),d={providerId:x,name:u.name.trim()||void 0,api:u.api.trim()||void 0,baseUrl:u.baseUrl.trim()||void 0,apiKey:u.apiKey.trim()||void 0,authHeader:u.authHeader||void 0,models:R};t({type:"save_model_config",providerId:x,config:d}),a()};l.useEffect(()=>{if(i&&i.ok){const x=i.configs;if(x&&x.length>1){H(x.map(R=>$t({...R,apiKey:""}))),A("");return}if(i.config){X($t({...i.config,apiKey:""}));return}}},[i]);const W=x=>{window.confirm(o("clearKeyConfirm",{id:x}))&&t({type:"clear_provider_api_key",provider:x})},U=x=>{window.confirm(o("deleteProviderConfirm",{id:x.providerId,n:x.models.length}))&&t({type:"delete_model_config",providerId:x.providerId})},ne=(x,R)=>{u&&m({...u,models:u.models.map((d,b)=>b===x?{...d,...R}:d)})};return e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"modal model-modal",onClick:x=>x.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":o("close"),onClick:a,children:e.jsx(Ee,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:F?o("addKey"):E?o("batchCreateProviders",{n:E.length}):o(u?"editProvider":"manageModelsTitle")})}),F?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:o("secondKeyTitle",{api:F.api,baseUrl:F.baseUrl||o("noBaseUrlShort"),n:F.models.length})}),e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[o("providerNameLabel")," ",e.jsx("em",{children:o("providerNameHint")})]}),e.jsx("input",{type:"text",value:F.providerId,onChange:x=>X({...F,providerId:x.target.value}),placeholder:"opencode-2"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKeyLabel")}),e.jsx("input",{type:"password",value:F.apiKey,onChange:x=>X({...F,apiKey:x.target.value}),placeholder:o("secondKeyPlaceholder")})]})]}),e.jsxs("div",{style:{fontSize:12,opacity:.6,marginTop:8},children:[F.models.slice(0,5).map(x=>x.id).join(", "),F.models.length>5?` … +${F.models.length-5}`:""]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>X(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn",onClick:()=>{const x=F;X(null),m(x)},children:o("advancedEdit")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!F.providerId.trim()||!F.apiKey.trim(),onClick:I,children:o("save")})]})]}):E?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsx("p",{className:"modal-desc",style:{marginBottom:12},children:o("batchDesc",{apis:E.map(x=>x.api).join("、"),n:E.length})}),e.jsxs("label",{className:"field",style:{marginBottom:16},children:[e.jsx("span",{className:"field-label",children:o("batchKeyLabel",{n:E.length})}),e.jsx("input",{type:"password",value:k,onChange:x=>A(x.target.value),placeholder:o("secondKeyPlaceholder")})]}),e.jsx("div",{className:"provider-list",style:{marginBottom:16},children:E.map((x,R)=>e.jsxs("div",{className:"provider-row",style:{flexDirection:"column",alignItems:"stretch",gap:6},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",fontSize:13},children:[e.jsx("strong",{children:x.providerId}),e.jsx("span",{style:{opacity:.7},children:x.api})]}),e.jsxs("div",{className:"provider-sub",style:{fontSize:12,opacity:.7},children:[x.baseUrl||o("noBaseUrlShort")," · ",o("modelsCountShort",{n:x.models.length}),x.models.slice(0,3).map(d=>d.id).join(", "),x.models.length>3?` … +${x.models.length-3}`:""]}),e.jsx("input",{type:"text",value:x.providerId,onChange:d=>H(b=>b.map((w,B)=>B===R?{...w,providerId:d.target.value}:w)),placeholder:o("providerIdPlaceholder"),style:{fontSize:12}}),e.jsx("input",{type:"text",value:x.baseUrl,onChange:d=>H(b=>b.map((w,B)=>B===R?{...w,baseUrl:d.target.value}:w)),placeholder:o("baseUrlExamplePh"),style:{fontSize:12}})]},R))})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>H(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!k.trim(),onClick:()=>{for(const x of E){const R=x.providerId.trim();if(!R)continue;const d=x.models.filter(w=>w.id.trim()).map(w=>({id:w.id.trim(),name:w.name.trim()||void 0,reasoning:w.reasoning||void 0,input:w.input==="text-image"?["text","image"]:void 0,contextWindow:w.contextWindow?Number(w.contextWindow):void 0,maxTokens:w.maxTokens?Number(w.maxTokens):void 0})),b={providerId:R,name:x.name.trim()||void 0,api:x.api.trim()||void 0,baseUrl:x.baseUrl.trim()||void 0,apiKey:k.trim()||void 0,authHeader:x.authHeader||void 0,models:d};t({type:"save_model_config",providerId:R,config:b})}H(null),a()},children:o("saveAllBatch",{n:E.length})})]})]}):u?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-body",children:e.jsxs("div",{className:"provider-form",children:[e.jsxs("div",{className:"form-grid",children:[e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:[o("providerId")," ",e.jsx("em",{children:o("providerIdHint")})]}),e.jsx("input",{type:"text",value:u.providerId,disabled:s.some(x=>x.providerId===u.providerId),onChange:x=>m({...u,providerId:x.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("displayName")}),e.jsx("input",{type:"text",value:u.name,onChange:x=>m({...u,name:x.target.value}),placeholder:o("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiType")}),e.jsx("select",{value:u.api,onChange:x=>m({...u,api:x.target.value}),children:al.map(x=>e.jsx("option",{value:x,children:x},x))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:o("baseUrlHint")})]}),e.jsx("input",{type:"text",value:u.baseUrl,onChange:x=>m({...u,baseUrl:x.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKey")}),e.jsx("input",{type:"password",value:u.apiKey,onChange:x=>m({...u,apiKey:x.target.value}),placeholder:o("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:u.authHeader,onChange:x=>m({...u,authHeader:x.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:[q&&e.jsx("span",{className:`fetch-msg ${q.ok?"ok":"err"}`,title:q.text,children:q.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:O||!u.baseUrl.trim(),title:o("fetchModelsHint"),onClick:$,children:[e.jsx(Zt,{})," ",o(O?"fetchingModels":"fetchModels")]})]})]}),u.models.map((x,R)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:x.id,onChange:d=>ne(R,{id:d.target.value}),placeholder:o("modelIdReq")}),e.jsx("input",{type:"text",value:x.name,onChange:d=>ne(R,{name:d.target.value}),placeholder:o("displayName")}),e.jsxs("select",{value:x.input,onChange:d=>ne(R,{input:d.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:x.reasoning,onChange:d=>ne(R,{reasoning:d.target.checked})}),e.jsx("span",{children:o("reasoning")})]}),e.jsx("input",{type:"number",value:x.contextWindow,onChange:d=>ne(R,{contextWindow:d.target.value}),placeholder:o("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:x.maxTokens,onChange:d=>ne(R,{maxTokens:d.target.value}),placeholder:o("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeModel"),onClick:()=>m({...u,models:u.models.filter((d,b)=>b!==R)}),children:e.jsx(Be,{})})]},R)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>m({...u,models:[...u.models,ns()]}),children:[e.jsx(He,{})," ",o("addModel")]})]})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>m(null),children:o("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!u.providerId.trim()||!u.models.some(x=>x.id.trim()),onClick:C,children:o("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"model-modal-fixed-hint",children:e.jsxs("div",{className:"form-section-title",children:[o("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:o("hintKeyOnly")})]})}),e.jsxs("div",{className:"model-modal-body",children:[e.jsxs("div",{className:"provider-list",children:[n.length===0&&e.jsx("div",{className:"dd-loading",children:o("loading")}),n.map(x=>{const R=r[x.id]??[];return e.jsxs("div",{className:"provider-row provider-key-row",children:[e.jsxs("div",{className:"provider-key-head",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:x.name}),e.jsxs("span",{className:"provider-sub",children:[x.id,x.configured&&e.jsx("span",{className:"auth-badge",children:o("configuredBadge")}),x.source&&!x.configured&&e.jsx("span",{className:"auth-badge dim",children:x.source})]})]}),x.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:o("clearKeyTitle"),onClick:()=>W(x.id),children:[e.jsx(Be,{})," ",o("clearKey")]})]}),e.jsxs("div",{className:"provider-keys",children:[R.length===0&&e.jsx("div",{className:"provider-key-empty",children:o("noKeyYet")}),R.map(d=>e.jsxs("div",{className:`provider-key-item ${d.active?"active":""}`,children:[e.jsx("span",{className:"provider-key-dot",children:d.active?"●":"○"}),e.jsx("span",{className:"provider-key-label",children:d.name}),!d.active&&e.jsx("button",{type:"button",className:"iconbtn",title:o("activateKey"),onClick:()=>Q(x.id,d.name),children:e.jsx(ut,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("removeKey"),onClick:()=>P(x.id,d.name),children:e.jsx(Be,{})})]},d.name)),e.jsxs("div",{className:"provider-add-key",children:[e.jsx("input",{type:"text",className:"key-input key-input-name",placeholder:o("keyNamePh"),value:g[x.id]??"",onChange:d=>v(b=>({...b,[x.id]:d.target.value}))}),e.jsx("input",{type:"password",className:"key-input key-input-value",placeholder:o("addKeyPlaceholder"),value:y[x.id]??"",onChange:d=>f(b=>({...b,[x.id]:d.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(y[x.id]??"").trim()||T===x.id,onClick:()=>Y(x),children:[e.jsx(He,{})," ",T===x.id?o("savingKey"):o("addKey")]})]})]})]},x.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(x=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:x.providerId}),e.jsxs("span",{className:"provider-sub",children:[x.api??"—",x.baseUrl?` · ${x.baseUrl}`:"",x.models.length>0&&` · ${o("modelsCount",{n:x.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:o("edit"),onClick:()=>m($t(x)),children:e.jsx(wt,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:o("delete"),onClick:()=>U(x),children:e.jsx(Be,{})})]})]},x.providerId))})]}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>m(rl()),children:[e.jsx(He,{})," ",o("addProvider")]})})]})]})})}function ol({plugin:t,send:s}){const n=xe(),r=t.settingsSchema??[],[c,i]=l.useState(()=>({...t.settingsValues})),[a,o]=l.useState(!1);if(r.length===0)return null;const u=(g,v)=>i(T=>({...T,[g]:v})),m=r.some(g=>{var v;return c[g.key]!==((v=t.settingsValues)==null?void 0:v[g.key])}),y=()=>{o(!0),s({type:"plugin_settings",pluginId:t.id,values:c}),setTimeout(()=>o(!1),800)},f=()=>i({...t.settingsValues});return e.jsxs("div",{className:"plugin-settings-form",children:[e.jsx("div",{className:"plugin-settings-fields",children:r.map(g=>e.jsxs("label",{className:"plugin-settings-field",title:g.hint,children:[e.jsx("span",{className:"plugin-settings-label",children:g.label}),g.type==="boolean"?e.jsx("input",{type:"checkbox",checked:!!c[g.key],onChange:v=>u(g.key,v.target.checked)}):g.type==="select"?e.jsx("select",{value:String(c[g.key]??""),onChange:v=>u(g.key,v.target.value),children:(g.options??[]).map(v=>e.jsx("option",{value:v,children:v},v))}):e.jsx("input",{type:g.type==="password"?"password":g.type==="number"?"number":"text",value:String(c[g.key]??""),min:g.min,max:g.max,onChange:v=>u(g.key,g.type==="number"?Number(v.target.value):v.target.value)})]},g.key))}),e.jsxs("div",{className:"plugin-settings-actions",children:[e.jsx("button",{type:"button",className:"btn plugin-settings-save",disabled:!m||a,onClick:y,children:n(a?"pluginSettingsSaving":"pluginSettingsSave")}),e.jsx("button",{type:"button",className:"btn plugin-settings-reset",onClick:f,children:n("pluginSettingsReset")})]})]})}function cl(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function Ke({text:t}){const s=l.useRef(null),[n,r]=l.useState(!1),c=()=>{var a;const i=(a=s.current)==null?void 0:a.getBoundingClientRect();i&&r(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 Ae({title:t,subtitle:s,tip:n,enabled:r,onToggle:c,action:i}){const a=xe();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(Ke,{text:n})]}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),i,e.jsx("button",{type:"button",className:`set-switch ${r?"on":""}`,role:"switch","aria-checked":r,title:a(r?"settingsEnabled":"settingsDisabled"),onClick:c,children:e.jsx("span",{className:"set-switch-knob"})})]})}function dl({chat:t,send:s,terminal:n,onSwitchToTerminal:r,onClose:c}){var Ie,Le,_e,De,M,ge;const i=xe(),a=t.settings,o=t.engine==="dsh",[u,m]=l.useState("prompt"),y=l.useRef(null);l.useEffect(()=>{var p;(p=y.current)==null||p.scrollTo({top:0})},[u]),l.useEffect(()=>{u==="plugins"&&t.engine==="dsh"&&s({type:"dsh_patches_list"})},[u,t.engine,s]);const[f,g]=l.useState(""),[v,T]=l.useState("append"),D=l.useRef(!1),[O,N]=l.useState(""),[j,V]=l.useState("append"),q=l.useRef(!1),[J,K]=l.useState(""),E=l.useRef(!1),[H,k]=l.useState(""),[A,F]=l.useState(null),[X,$]=l.useState(null),[Y,Q]=l.useState(!1),[P,I]=l.useState(()=>Vn()),[C,W]=l.useState(()=>{try{return ct().length}catch{return 0}}),[U,ne]=l.useState(!1),x=()=>{try{W(ct().length)}catch{W(0)}};l.useEffect(()=>{u==="prompt-history"&&x()},[u]),l.useEffect(()=>{if(!U)return;const p=window.setTimeout(()=>ne(!1),3e3);return()=>window.clearTimeout(p)},[U]);const[R,d]=l.useState(null),[b,w]=l.useState(null);l.useEffect(()=>{a&&(T(a.promptMode),!D.current&&(g(v==="append"||a.customSystemPrompt?a.customSystemPrompt:a.defaultSystemPrompt||""),V(a.visionBridgePromptMode),!q.current&&(N(j==="append"||a.visionBridgePrompt?a.visionBridgePrompt:a.visionBridgeDefaultPrompt||""),E.current||K(a.reviewPrompt))))},[a,v,j]);const[B,se]=l.useState(String((a==null?void 0:a.terminalBashIdleMs)??15e3));if(l.useEffect(()=>{se(String((a==null?void 0:a.terminalBashIdleMs)??15e3))},[a==null?void 0:a.terminalBashIdleMs]),!a)return null;const G=[{id:"prompt",icon:e.jsx(pn,{}),label:i("settingsSystemPrompt")},{id:"prompt-history",icon:e.jsx(Ts,{}),label:i("settingsPromptHistory"),count:C},{id:"terminal",icon:e.jsx(et,{}),label:i("settingsTerminalTools")},{id:"display",icon:e.jsx(tt,{}),label:i("settingsMessageDisplay")},{id:"markers",icon:e.jsx(Ns,{}),label:i("settingsMarkers"),count:((Ie=a.markers)==null?void 0:Ie.length)??0},{id:"skills",icon:e.jsx(rt,{}),label:i("settingsSkills"),count:a.skills.length},{id:"extensions",icon:e.jsx(Cs,{}),label:i("settingsExtensions"),count:a.extensions.length},{id:"plugins",icon:e.jsx(Et,{}),label:i("settingsUiPlugins"),count:t.plugins.length},{id:"review",icon:e.jsx(gt,{}),label:i("settingsReview"),count:a.reviewSkills.length},...o?[]:[{id:"vision",icon:e.jsx(Wt,{}),label:i("settingsVisionBridge")}],{id:"presets",icon:e.jsx(Ni,{}),label:i("settingsPresets"),count:a.presets.length},...o?[]:[{id:"subagent-templates",icon:e.jsx(js,{}),label:i("settingsSubagentTemplates"),count:a.subagentTemplates.length}]],ie=new Set(a.disabledSkills),ye=new Set(a.disabledExtensions),le=p=>s({type:"set_settings",...p}),we=p=>{const ee=new Set(ie);ee.has(p.name)?ee.delete(p.name):ee.add(p.name),le({disabledSkills:[...ee]})},ve=new Set(a.disabledPlugins??[]),Pe=p=>{const ee=new Set(ve);ee.has(p.id)?ee.delete(p.id):ee.add(p.id),le({disabledPlugins:[...ee]})},re=p=>{const ee=new Set(ye);ee.has(p.id)?ee.delete(p.id):ee.add(p.id),le({disabledExtensions:[...ee]})},h=a.markersEnabled??!0,z=new Set(a.disabledMarkers??[]),pe=p=>{const ee=new Set(z),de=p==="conv"||p==="rename"||p==="title"?["conv","rename","title"]:[p],S=!de.some(L=>ee.has(L));for(const L of de)S?ee.add(L):ee.delete(L);le({disabledMarkers:[...ee]})},ce=(p,ee)=>{var ae,oe;const de={name:p,command:ee,cwd:"${pwd}"};let S;const L=t.terminals.find(be=>be.title===p);L?(n.restart(L.id),s({type:"run_command",terminalId:L.id,conversationId:L.conversationId,command:de,cols:80,rows:24}),S=L.id):(S=Ue(),n.create({id:S,conversationId:t.activeConversationId||((ae=t.state)==null?void 0:ae.conversationId)||"",title:p,cwd:((oe=t.state)==null?void 0:oe.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:de})),n.select(S),r(),c()},fe=p=>{d(null),ce(`${i("uninstallTitle")} ${p}`,`pi remove npm:${p}`)},me=p=>{w(null),ce(`${i("uninstallTitle")} ${p}`,`pi-web-ui uninstall ${p}`)},ke=(p,ee)=>{ce(`${i("pluginUpdate")} ${p}`,`pi-web-ui install ${ee} --name ${p} --force`)},Me=p=>{const ee=new Set(a.reviewSkills.filter(de=>!de.enabled).map(de=>de.name));ee.has(p.name)?ee.delete(p.name):ee.add(p.name),le({reviewDisabledSkills:[...ee]})},he=()=>{const p=v==="replace"&&a.defaultSystemPrompt&&f===a.defaultSystemPrompt?"":f;le({promptMode:v,customSystemPrompt:p})};return e.jsx("div",{className:"modal-backdrop",onClick:c,children:e.jsxs("div",{className:"modal settings-modal",onClick:p=>p.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:c,children:e.jsx(Ee,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(kt,{className:"modal-head-icon"}),e.jsx("h2",{children:i("settingsTitle")}),e.jsx(Ke,{text:i("settingsDesc")})]}),e.jsxs("div",{className:"settings-layout",children:[e.jsx("nav",{className:"settings-rail","aria-label":i("settingsTitle"),children:G.map(p=>e.jsxs("button",{type:"button",className:`settings-tab${u===p.id?" active":""}`,"aria-current":u===p.id?"true":void 0,title:p.label,onClick:()=>m(p.id),children:[e.jsx("span",{className:"settings-tab-icon",children:p.icon}),e.jsx("span",{className:"settings-tab-label",children:p.label}),p.count!==void 0&&e.jsx("span",{className:"set-count",children:p.count})]},p.id))}),e.jsxs("div",{className:"modal-body",ref:y,children:[u==="prompt"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(gt,{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:v,onChange:p=>{const ee=p.target.value;T(ee),le({promptMode:ee})},children:[e.jsx("option",{value:"append",children:i("promptModeAppend")}),e.jsx("option",{value:"replace",children:i("promptModeReplace")})]}),e.jsx(Ke,{text:i(v==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:i("promptPlaceholder"),value:f,onFocus:()=>D.current=!0,onBlur:()=>{D.current=!1,he()},onChange:p=>g(p.target.value)}),e.jsxs("button",{type:"button",className:"set-view-prompt-btn","aria-expanded":Y,onClick:()=>Q(p=>!p),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(Tn,{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")})]})]}),u==="prompt-history"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ts,{className:"set-section-icon"}),i("settingsPromptHistory"),e.jsx(Ke,{text:i("settingsPromptHistoryDesc")}),e.jsx("span",{className:"set-count",children:i("promptHistoryCount",{n:String(C)})})]}),C===0?e.jsx("p",{className:"set-empty",children:i("promptHistoryEmpty")}):e.jsx("p",{className:"set-hint",children:i("promptHistoryCount",{n:String(C)})}),e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"ph-max",children:i("promptHistoryMax")}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("input",{id:"ph-max",className:"set-input",type:"number",min:1,max:500,step:1,value:String(P.maxEntries),onChange:p=>{const ee=Math.floor(Number(p.target.value)||0),de={...P,maxEntries:ee};I(de)},onBlur:()=>{const p={...P};(!Number.isFinite(p.maxEntries)||p.maxEntries<1)&&(p.maxEntries=1),p.maxEntries>500&&(p.maxEntries=500),p.maxEntries=Math.floor(p.maxEntries),I(p),Ft(p),x()}}),e.jsx(Ke,{text:i("promptHistoryMaxHint")})]})]}),e.jsx(Ae,{title:i("promptHistoryCharLimit"),tip:i("promptHistoryCharLimitHint"),enabled:P.charLimitEnabled,onToggle:()=>{const p={...P,charLimitEnabled:!P.charLimitEnabled};I(p),Ft(p),x()}}),P.charLimitEnabled&&e.jsxs("div",{className:"set-field",children:[e.jsx("label",{className:"set-field-label",htmlFor:"ph-char-limit",children:i("promptHistoryCharLimit")}),e.jsx("input",{id:"ph-char-limit",className:"set-input",type:"number",min:100,max:2e4,step:100,placeholder:i("promptHistoryCharLimitPlaceholder"),value:String(P.charLimit),onChange:p=>{const ee=Math.floor(Number(p.target.value)||0);I({...P,charLimit:ee})},onBlur:()=>{let p=Math.floor(Number(P.charLimit)||0);(!Number.isFinite(p)||p<100)&&(p=100),p>2e4&&(p=2e4);const ee={...P,charLimit:p};I(ee),Ft(ee),x()}})]}),e.jsxs("div",{className:"set-field",style:{marginTop:12},children:[e.jsxs("button",{type:"button",className:`set-uninstall${U?" confirm":""}`,disabled:C===0,title:i(C===0?"promptHistoryEmpty":"promptHistoryClear"),onClick:()=>{if(!U){ne(!0);return}Or(),ne(!1),x()},children:[e.jsx(Be,{})," ",i(U?"promptHistoryClearConfirm":"promptHistoryClear")]}),C>0&&e.jsx("span",{className:"set-hint",style:{marginLeft:8},children:i("promptHistoryCount",{n:String(C)})})]}),e.jsxs("p",{className:"set-hint",children:[e.jsx(Wi,{style:{verticalAlign:"-2px",marginRight:4}}),i("settingsPromptHistoryDesc")]})]}),u==="terminal"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(et,{className:"set-section-icon"}),i("settingsTerminalTools")]}),e.jsx(Ae,{title:i("terminalToolsEnabled"),tip:i("settingsTerminalToolsDesc"),enabled:a.terminalToolsEnabled,onToggle:()=>le({terminalToolsEnabled:!a.terminalToolsEnabled})}),!a.terminalToolsEnabled&&e.jsx("p",{className:"set-hint",children:i("terminalToolsOffHint")}),e.jsx(Ae,{title:i("terminalBashTakeover"),tip:i("terminalBashTakeoverDesc"),enabled:a.terminalBash,onToggle:()=>le({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:B,onChange:p=>se(p.target.value),onBlur:()=>{const p=Math.max(0,Math.floor(Number(B)||0));se(String(p)),p!==a.terminalBashIdleMs&&le({terminalBashIdleMs:p})}})]})]}),u==="display"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(tt,{className:"set-section-icon"}),i("settingsMessageDisplay")]}),e.jsx(Ae,{title:i("thinkingWrap"),tip:i("thinkingWrapDesc"),enabled:a.thinkingWrap??!0,onToggle:()=>le({thinkingWrap:!(a.thinkingWrap??!0)})}),e.jsx(Ae,{title:i("toolsWrap"),tip:i("toolsWrapDesc"),enabled:a.toolsWrap??!0,onToggle:()=>le({toolsWrap:!(a.toolsWrap??!0)})})]}),u==="markers"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ns,{className:"set-section-icon"}),i("settingsMarkers"),e.jsx(Ke,{text:i("settingsMarkersDesc")}),e.jsx("span",{className:"set-count",children:((Le=a.markers)==null?void 0:Le.length)??0})]}),e.jsx(Ae,{title:i("markersEnabled"),tip:i("markersEnabledDesc"),enabled:h,onToggle:()=>le({markersEnabled:!h})}),!h&&e.jsx("p",{className:"set-hint",children:i("markersOffHint")}),h&&(((_e=a.markers)==null?void 0:_e.length)??0)===0&&e.jsxs("p",{className:"set-empty",children:[i("loading"),"..."]}),h&&a.markers&&a.markers.length>0&&e.jsx("div",{className:"set-list",children:a.markers.map(p=>e.jsx(Ae,{title:p.name==="todo"?i("markerGroupTodo"):p.name==="svc"?i("markerGroupSvc"):p.name==="notify"?i("markerGroupNotify"):p.name==="conv"||p.name==="rename"||p.name==="title"?i("markerGroupRename"):p.name,subtitle:(p.guidance[0]??"").slice(0,120),tip:p.guidance.join(`
|
|
325
|
-
`),enabled:p.enabled,onToggle:()=>pe(p.name)},p.name))}),h&&e.jsx("p",{className:"set-hint",children:i("markerRenameTip")})]}),u==="skills"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(rt,{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(o?"dshSkillsNote":"noSkills")}):e.jsx("div",{className:"set-list",children:a.skills.map(p=>e.jsx(Ae,{title:p.name,subtitle:p.description,enabled:p.enabled,onToggle:()=>we(p)},p.name))})]}),u==="extensions"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Cs,{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(o?"dshExtensionsNote":"noExtensions")}):e.jsx("div",{className:"set-list",children:a.extensions.map(p=>{const ee=p.id.startsWith("npm:")?p.id.slice(4):null;return e.jsx(Ae,{title:p.name,subtitle:p.path,enabled:p.enabled,onToggle:()=>re(p),action:ee?R===p.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>fe(ee),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("uninstallHint"),onClick:()=>d(p.id),children:[e.jsx(Be,{}),i("uninstallExt")]}):void 0},p.id)})})]}),u==="plugins"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Et,{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(p=>{var ee;return e.jsxs(e.Fragment,{children:[e.jsx(Ae,{title:`${p.icon?`${p.icon} `:""}${p.name}`,subtitle:(p.error?`${p.id} · ${p.error}`:p.source?`${p.id} · ${p.source}`:`${p.id} · ${i("uiPluginNoSource")}`)+((ee=p.permissions)!=null&&ee.length?` · ${i("uiPluginPerms")}: ${p.permissions.join(", ")}`:""),enabled:!ve.has(p.id)&&!p.error,onToggle:()=>!p.error&&Pe(p),action:e.jsxs("div",{className:"set-row-actions",children:[p.source&&e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUpdateHint"),onClick:()=>ke(p.id,p.source),children:[e.jsx(at,{}),i("pluginUpdate")]}),b===p.id?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("pluginUninstallHint"),onClick:()=>me(p.id),children:i("uninstallConfirm")}):e.jsxs("button",{type:"button",className:"set-uninstall",title:i("pluginUninstallHint"),onClick:()=>w(p.id),children:[e.jsx(Be,{}),i("uninstallExt")]})]})},p.id),p.settingsSchema&&p.settingsSchema.length>0&&e.jsx(ol,{plugin:p,send:s})]})})})]}),u==="plugins"&&t.engine==="dsh"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Et,{className:"set-section-icon"}),i("dshPatches"),e.jsx(Ke,{text:i("dshPatchesDesc")}),e.jsx("span",{className:"set-count",children:((De=t.dshPatches)==null?void 0:De.files.length)??0}),e.jsxs("button",{type:"button",className:"set-uninstall",title:i("dshPatchesRescanHint"),onClick:()=>s({type:"dsh_patches_rescan"}),children:[e.jsx(at,{}),i("dshPatchesRescan")]})]}),(((M=t.dshPatches)==null?void 0:M.files.length)??0)===0?e.jsx("p",{className:"set-empty",children:i("dshPatchesEmpty")}):e.jsx("div",{className:"set-list",children:t.dshPatches.files.map(p=>e.jsx("div",{className:"set-row",children:e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:p.name}),e.jsxs("div",{className:"set-row-desc",children:[cl(p.size)," · ",new Date(p.mtimeMs).toLocaleString()]})]})},p.name))}),e.jsxs("p",{className:"set-hint",children:[i("dshPatchesPath")," ",((ge=t.dshPatches)==null?void 0:ge.patchDir)??""]})]}),u==="review"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(gt,{className:"set-section-icon"}),i("settingsReview"),e.jsx(Ke,{text:i("settingsReviewDesc")}),e.jsx("span",{className:"set-count",children:a.reviewSkills.length})]}),o&&e.jsx("p",{className:"set-hint",children:i("dshReviewPromptNote")}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:i("reviewPromptPlaceholder"),value:J,onFocus:()=>E.current=!0,onBlur:()=>{E.current=!1,le({reviewPrompt:J})},onChange:p=>K(p.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(p=>e.jsx(Ae,{title:p.name,subtitle:p.description,enabled:p.enabled,onToggle:()=>Me(p)},`review-${p.name}`))})]}),u==="vision"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Wt,{className:"set-section-icon"}),i("settingsVisionBridge")]}),e.jsx(Ae,{title:i("visionBridgeEnabled"),tip:i("settingsVisionBridgeDesc"),enabled:a.visionBridgeEnabled,onToggle:()=>le({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:p=>le({visionBridgeModel:p.target.value||null}),children:[e.jsx("option",{value:"",children:i("visionBridgeAuto")}),a.visionModels.map(p=>e.jsx("option",{value:`${p.provider}/${p.id}`,children:p.label},`${p.provider}/${p.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:j,onChange:p=>{const ee=p.target.value;V(ee),le({visionBridgePromptMode:ee})},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:O,onFocus:()=>q.current=!0,onBlur:()=>{q.current=!1;const p=j==="replace"&&a.visionBridgeDefaultPrompt&&O===a.visionBridgeDefaultPrompt?"":O;le({visionBridgePromptMode:j,visionBridgePrompt:p})},onChange:p=>N(p.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")})}))]}),u==="presets"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(kt,{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:H,onChange:p=>k(p.target.value),onKeyDown:p=>{p.key==="Enter"&&H.trim()&&(s({type:"save_preset",name:H.trim()}),k(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!H.trim(),onClick:()=>{s({type:"save_preset",name:H.trim()}),k("")},children:[e.jsx(He,{})," ",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(p=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:p.name}),e.jsxs("div",{className:"set-row-desc",children:[p.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend"),p.disabledSkills.length>0&&` · ${i("settingsSkills")} ${p.disabledSkills.length}`,p.disabledExtensions.length>0&&` · ${i("settingsExtensions")} ${p.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:p.name}),children:i("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("deletePreset"),onClick:()=>s({type:"delete_preset",name:p.name}),children:e.jsx(Be,{})})]})]},p.name))})]}),u==="subagent-templates"&&e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(js,{className:"set-section-icon"}),i("settingsSubagentTemplates"),e.jsx(Ke,{text:i("settingsSubagentTemplatesDesc")}),e.jsx("span",{className:"set-count",children:a.subagentTemplates.length}),e.jsxs("button",{type:"button",className:"set-save-btn",title:i("subagentTemplateNew"),onClick:()=>F({name:"",description:"",promptMode:"replace",systemPrompt:"",enabledSkills:[],enabledExtensions:[],enabled:!0}),children:[e.jsx(He,{})," ",i("subagentTemplateNew")]})]}),A&&e.jsxs("div",{className:"tpl-editor",children:[e.jsxs("div",{className:"tpl-fields",children:[e.jsx("input",{className:"set-input",placeholder:i("tplNamePlaceholder"),value:A.name,onChange:p=>F({...A,name:p.target.value})}),e.jsx("input",{className:"set-input",placeholder:i("tplDescriptionPlaceholder"),value:A.description,onChange:p=>F({...A,description:p.target.value})})]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:i("tplPromptModeLabel")}),e.jsxs("select",{className:"set-select",value:A.promptMode,onChange:p=>F({...A,promptMode:p.target.value}),children:[e.jsx("option",{value:"replace",children:i("promptModeReplace")}),e.jsx("option",{value:"append",children:i("promptModeAppend")})]})]}),e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:`${i("tplSystemPromptLabel")}:${i("tplSystemPromptPlaceholder")}`,value:A.systemPrompt,onChange:p=>F({...A,systemPrompt:p.target.value})}),e.jsxs("div",{className:"tpl-pick-block",children:[e.jsx("div",{className:"tpl-pick-head",children:e.jsxs("span",{children:[i("tplSkillsLabel")," · ",i("tplWhitelistHint")]})}),a.skills.length===0?e.jsx("p",{className:"set-hint",children:i("noSkills")}):e.jsx("div",{className:"tpl-pick",children:a.skills.map(p=>e.jsxs("label",{className:`tpl-chip${A.enabledSkills.includes(p.name)?" on":""}`,children:[e.jsx("input",{type:"checkbox",checked:A.enabledSkills.includes(p.name),onChange:ee=>{const de=ee.target.checked;F({...A,enabledSkills:de?[...A.enabledSkills,p.name]:A.enabledSkills.filter(S=>S!==p.name)})}}),p.name]},p.name))})]}),e.jsxs("div",{className:"tpl-pick-block",children:[e.jsx("div",{className:"tpl-pick-head",children:e.jsxs("span",{children:[i("tplExtensionsLabel")," · ",i("tplWhitelistHint")]})}),a.extensions.length===0?e.jsx("p",{className:"set-hint",children:i("noExtensions")}):e.jsx("div",{className:"tpl-pick",children:a.extensions.map(p=>e.jsxs("label",{className:`tpl-chip${A.enabledExtensions.includes(p.id)?" on":""}`,children:[e.jsx("input",{type:"checkbox",checked:A.enabledExtensions.includes(p.id),onChange:ee=>{const de=ee.target.checked;F({...A,enabledExtensions:de?[...A.enabledExtensions,p.id]:A.enabledExtensions.filter(S=>S!==p.id)})}}),p.name]},p.id))})]}),e.jsxs("div",{className:"tpl-actions",children:[e.jsx("button",{type:"button",className:"set-save-btn",disabled:!A.name.trim(),onClick:()=>{s({type:"save_subagent_template",template:{...A,name:A.name.trim()}}),F(null)},children:i("tplSave")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>F(null),children:i("tplCancel")})]})]}),a.subagentTemplates.length===0?e.jsx("p",{className:"set-empty",children:i("noSubagentTemplates")}):e.jsx("div",{className:"set-list",children:a.subagentTemplates.map(p=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsxs("div",{className:"set-row-name",children:[p.name,a.subagentDefaultTemplates.includes(p.name)&&e.jsx("span",{className:"tpl-badge default",children:i("tplDefaultBadge")}),!p.enabled&&e.jsx("span",{className:"tpl-badge",children:i("subagentTemplateClosed")})]}),e.jsxs("div",{className:"set-row-desc",children:[p.description||`${p.promptMode==="replace"?i("promptModeReplace"):i("promptModeAppend")}`,p.enabledSkills.length>0&&` · ${i("tplSkillsLabel")} ${p.enabledSkills.length}`,p.enabledExtensions.length>0&&` · ${i("tplExtensionsLabel")} ${p.enabledExtensions.length}`,!p.description&&p.enabledSkills.length===0&&p.enabledExtensions.length===0&&` · ${i("tplInherit")}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:`set-switch${p.enabled?" on":""}`,role:"switch","aria-checked":p.enabled,title:`${p.enabled?i("subagentTemplateDisable"):i("subagentTemplateEnable")} · ${i("subagentTemplateOffHint")}`,onClick:()=>s({type:"save_subagent_template",template:{...p,enabled:!p.enabled}}),children:e.jsx("span",{className:"set-switch-knob"})}),e.jsx("button",{type:"button",className:"dd-refresh",title:i("subagentTemplateEdit"),onClick:()=>F({...p}),children:i("subagentTemplateEdit")}),X===p.name?e.jsx("button",{type:"button",className:"set-uninstall confirm",title:i("uninstallConfirmHint"),onClick:()=>{s({type:"delete_subagent_template",name:p.name}),$(null)},children:i("uninstallConfirm")}):e.jsx("button",{type:"button",className:"set-icon-btn danger",title:i("tplDelete"),onClick:()=>$(p.name),children:e.jsx(Be,{})})]})]},p.name))})]})]})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:c,children:i("close")})})]})})}function ul(t,s){const n=Math.max(0,Date.now()-t),r=Math.floor(n/6e4);if(r<1)return s("bgTaskJustNow");if(r<60)return s("bgTaskMinutes",{n:r});const c=Math.floor(r/60);return c<24?s("bgTaskHours",{n:c}):s("bgTaskDays",{n:Math.floor(c/24)})}function pl({servers:t,send:s,onClose:n}){const r=xe(),[c,i]=l.useState(new Set),a=o=>i(u=>{const m=new Set(u);return m.has(o)?m.delete(o):m.add(o),m});return l.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(jt,{})," ",r("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:r("close"),onClick:n,children:e.jsx(Ee,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(jt,{}),e.jsx("span",{children:r("bgTasksEmpty")}),e.jsx("small",{children:r("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(o=>{const u=!!o.taskId,m=o.taskId??String(o.port);return e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:u?o.plugin:r("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[u?e.jsxs("span",{className:"bg-task-port",title:o.taskId,children:["🧩 ",o.plugin]}):e.jsxs("span",{className:"bg-task-port",children:[":",o.port]}),o.name&&e.jsx("span",{className:"bg-task-name",children:o.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[!u&&e.jsxs("span",{children:[r("bgTaskPid")," ",o.pid]}),e.jsxs("span",{children:[r("bgTaskSince")," ",ul(o.since,r)]}),u&&o.status&&e.jsx("span",{className:"bg-task-status",children:o.status})]}),o.command&&e.jsxs("button",{type:"button",className:`bg-task-cmd ${c.has(m)?"open":""}`,title:`${r("bgTaskCommand")}: ${o.command}`,onClick:()=>a(m),children:[e.jsx(et,{}),e.jsx("code",{children:o.command})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:r("bgTaskStop"),onClick:()=>s(u?{type:"kill_background_server",taskId:o.taskId}:{type:"kill_background_server",port:o.port}),children:[e.jsx(vt,{}),e.jsx("span",{children:r("bgTaskStop")})]})]},m)})}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:r("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(at,{}),e.jsx("span",{children:r("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:r("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(vt,{}),e.jsx("span",{children:r("bgTaskStopAll")})]})]})]})})}function ml(t,s){return t.toLowerCase().includes(s)}function hl({open:t,send:s,projects:n,cwd:r,fileSearch:c,sessionSearch:i,onClose:a,onSwitchSession:o,onSwitchProject:u,onPreviewFile:m}){const y=xe(),f=l.useRef(null),[g,v]=l.useState(""),T=l.useDeferredValue(g),[D,O]=l.useState(0),N=l.useRef(1),j=l.useRef(0),V=l.useRef(null);l.useEffect(()=>{if(!t)return;s({type:"list_sessions"}),s({type:"list_projects"});const P=g.trim();if(P){const I=++N.current;j.current=I,J(!0),s({type:"search_files",reqId:I,query:P}),s({type:"search_sessions",reqId:I,query:P})}requestAnimationFrame(()=>{var I;return(I=f.current)==null?void 0:I.select()})},[t]);const[q,J]=l.useState(!1);l.useEffect(()=>{V.current&&clearTimeout(V.current);const P=T.trim();if(!P){J(!1);return}return V.current=setTimeout(()=>{const I=++N.current;j.current=I,J(!0),s({type:"search_files",reqId:I,query:P}),s({type:"search_sessions",reqId:I,query:P})},300),()=>{V.current&&clearTimeout(V.current)}},[T]);const K=T.trim().toLowerCase(),E=l.useMemo(()=>!K||!i||i.reqId!==j.current||!i.ok?[]:i.results,[i,K]),H=l.useMemo(()=>K?n.filter(P=>ml(P.path,K)).slice(0,10):[],[n,K]),k=l.useMemo(()=>!K||!c||c.reqId!==j.current||!c.ok?[]:c.results,[c,K]);l.useEffect(()=>{c&&c.reqId===j.current&&i&&i.reqId===j.current&&j.current!==0&&J(!1)},[c,i]);const A=!!c&&c.ok&&c.truncated,F=l.useMemo(()=>[...E.map(P=>({kind:"session",path:P.path,anchors:P.anchors})),...H.map(P=>({kind:"project",path:P.path})),...k.filter(P=>P.type==="file").map(P=>({kind:"file",path:P.path,name:P.name}))],[E,H,k]);l.useEffect(()=>{O(0)},[T]);const X=l.useCallback(P=>{if(P)if(P.kind==="session")o(P.path,P.anchors),a();else if(P.kind==="project"){u(P.path),s({type:"list_sessions"}),s({type:"list_projects"});const I=T.trim();if(I){const C=++N.current;j.current=C,J(!0),s({type:"search_files",reqId:C,query:I}),s({type:"search_sessions",reqId:C,query:I})}}else m(P.path,P.name)},[o,u,m,s,T]);l.useEffect(()=>{if(!t)return;const P=I=>{I.key==="Escape"?(I.preventDefault(),I.stopPropagation(),a()):I.key==="ArrowDown"?(I.preventDefault(),O(C=>Math.min(C+1,F.length-1))):I.key==="ArrowUp"?(I.preventDefault(),O(C=>Math.max(C-1,0))):I.key==="Enter"&&(I.preventDefault(),X(F[D]))};return window.addEventListener("keydown",P,!0),()=>window.removeEventListener("keydown",P,!0)},[F,D,X,a,t]);const $=E.length+H.length+k.length,Y=(P,I,C)=>e.jsxs("div",{className:"gs-section-head",children:[C,e.jsx("span",{children:P}),e.jsx("em",{children:I})]});let Q=-1;return t?e.jsx("div",{className:"modal-backdrop gs-backdrop",onClick:a,children:e.jsxs("div",{className:"gs-modal",onClick:P=>P.stopPropagation(),children:[e.jsxs("div",{className:"gs-input-row",children:[e.jsx(bt,{}),e.jsx("input",{ref:f,type:"text",value:g,placeholder:y("gsPlaceholder"),onChange:P=>v(P.target.value)}),e.jsx("button",{type:"button",className:"gs-close",title:y("close"),onClick:a,children:e.jsx(Ee,{})})]}),e.jsxs("div",{className:"gs-results",children:[!K&&e.jsx("div",{className:"gs-empty",children:y("gsHint")}),K&&$===0&&!A&&e.jsx("div",{className:"gs-empty",children:y(q?"gsSearching":"gsNoResults")}),E.length>0&&e.jsxs("div",{className:"gs-section",children:[Y(y("gsSessions"),E.length,e.jsx(tt,{})),E.map(P=>{Q++;const I=Q;return e.jsxs("button",{type:"button",className:I===D?"gs-item active":"gs-item",onMouseEnter:()=>O(I),onClick:()=>X({kind:"session",path:P.path,anchors:P.anchors}),children:[e.jsxs("span",{className:"gs-item-title",children:[P.name||P.path.split(/[\\/]/).pop(),e.jsx("em",{className:"gs-item-meta",children:P.messageCount})]}),e.jsx("span",{className:"gs-item-sub",children:P.firstMessage})]},P.path)})]}),H.length>0&&e.jsxs("div",{className:"gs-section",children:[Y(y("gsProjects"),H.length,e.jsx(Ye,{})),H.map(P=>{Q++;const I=Q,C=r&&P.path===r;return e.jsxs("button",{type:"button",className:I===D?"gs-item active":"gs-item",onMouseEnter:()=>O(I),onClick:()=>X({kind:"project",path:P.path}),children:[e.jsxs("span",{className:"gs-item-title",children:[P.path.split(/[\\/]/).pop(),C&&e.jsx("em",{className:"gs-item-meta",children:y("gsCurrentProject")})]}),e.jsx("span",{className:"gs-item-sub",children:P.path})]},P.path)})]}),(k.length>0||K&&A)&&e.jsxs("div",{className:"gs-section",children:[Y(y("gsFiles"),k.length,e.jsx(pn,{})),k.map(P=>{Q++;const I=Q;return e.jsxs("button",{type:"button",className:I===D?"gs-item active":"gs-item",disabled:P.type==="dir",title:P.type==="dir"?void 0:y("gsOpenPreview"),onMouseEnter:()=>O(I),onClick:()=>{P.type==="file"&&X({kind:"file",path:P.path,name:P.name})},children:[e.jsx("span",{className:"gs-item-title",children:P.name}),e.jsx("span",{className:"gs-item-sub",children:P.path})]},`${P.type}:${P.path}`)}),A&&e.jsx("div",{className:"gs-truncated",children:y("gsTruncated")})]})]}),e.jsxs("div",{className:"gs-foot",children:[e.jsxs("span",{children:["↑↓ ",y("gsNavigate")]}),e.jsxs("span",{children:["Enter ",y("gsOpen")]}),e.jsxs("span",{children:["Esc ",y("gsCloseHint")]})]})]})}):null}const Ht=5e3;function gl({file:t,content:s,send:n,onAddLines:r,onAttach:c,onClose:i}){const a=xe(),[o,u]=l.useState(null),[m,y]=l.useState(!1),[f,g]=l.useState(null),[v,T]=l.useState(!1),[D,O]=l.useState(!1),[N,j]=l.useState(!1),[V,q]=l.useState(""),[J,K]=l.useState(!0),E=l.useRef(!1),[H,k]=l.useState(!0),[A,F]=l.useState(!1),[X,$]=l.useState(100),Y=l.useRef(0),Q=l.useRef(!1),P=l.useRef(null);l.useEffect(()=>{y(!0),u(null),g(null),j(!1),q(""),K(!0),E.current=!1,n({type:"read_file",path:t.path})},[t.path,n]),l.useEffect(()=>{s&&s.path===t.path&&(u(s),N||q(s.text),y(!1))},[s,N,t.path]),l.useEffect(()=>{const re=h=>{if(h.key==="Escape"){B();return}if((h.ctrlKey||h.metaKey)&&h.key.toLowerCase()==="s"&&N){h.preventDefault(),w();return}const z=h.target,pe=z&&(z.tagName==="INPUT"||z.tagName==="TEXTAREA"||z.isContentEditable);(h.ctrlKey||h.metaKey)&&h.key.toLowerCase()==="a"&&!pe&&(h.preventDefault(),ne())};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[i,o,N,V]),l.useEffect(()=>{const re=()=>{Q.current=!1,T(!1)};return window.addEventListener("mouseup",re),()=>window.removeEventListener("mouseup",re)},[]);const I=l.useMemo(()=>{if(!o)return[];const re=o.text.split(`
|
|
326
|
-
`);return re.length>0&&re[re.length-1]===""&&re.pop(),re.slice(0,Ht)},[o]),C=(o==null?void 0:o.lines)??0,W=C>Ht,U=(re,h)=>{if(h){const z=Y.current>0?Y.current:re;g({start:Math.min(z,re),end:Math.max(z,re)})}else Y.current=re,g({start:re,end:re})},ne=()=>{I.length!==0&&(Y.current=1,g({start:1,end:I.length}))},x=()=>{f&&(r(t.path,t.name,f.start,f.end),O(!0),P.current&&clearTimeout(P.current),P.current=setTimeout(()=>O(!1),1400))},R=o!==null&&o.kind==="text"&&!o.binary&&!o.truncated,d=()=>{q((o==null?void 0:o.text)??""),j(!1),E.current&&K(!0)},b=()=>{if(N){if(V!==((o==null?void 0:o.text)??"")&&!window.confirm(a("discardFileChanges")))return;d();return}!R||!o||(E.current=Ot(t.name)&&J,Ot(t.name)&&K(!1),g(null),q(o.text),j(!0))},w=()=>{!N||!o||!R||n({type:"write_file",path:t.path,text:V})&&(j(!1),E.current&&K(!0),g(null))},B=()=>{N&&V!==((o==null?void 0:o.text)??"")&&!window.confirm(a("discardFileChanges"))||i()},se=re=>{$(Math.min(200,Math.max(50,re)))},G=f?f.end-f.start+1:0,ie=(o==null?void 0:o.binary)??!1,ye=(o==null?void 0:o.truncated)??!1,le=(o==null?void 0:o.kind)??"text",we=Ot(t.name),ve=we&&J&&!N&&le==="text"&&!ie,Pe=re=>Ct(Ve(`/api/file?clientId=${encodeURIComponent(es())}&path=${encodeURIComponent(re)}`));return e.jsx("div",{className:`fp-overlay ${A?"fullscreen":""}`,onMouseDown:re=>{re.target===re.currentTarget&&B()},children:e.jsxs("div",{className:`fp ${A?"fullscreen":""}`,style:{"--fp-zoom":X/100},children:[e.jsxs("div",{className:"fp-head",children:[e.jsx("span",{className:"fp-name",title:t.path,children:t.name}),e.jsx("span",{className:"fp-path",children:t.path}),e.jsxs("span",{className:"fp-meta",children:[o&&le==="text"&&!ie&&a("fileLines",{n:C}),o&&` · ${fl(o.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[we&&le==="text"&&!ie&&o&&e.jsx("button",{type:"button",className:`fp-attach markdown ${J?"on":""}`,"data-tip":a(J?"showMarkdownSource":"showMarkdownPreview"),disabled:N,onClick:()=>K(re=>!re),children:J?e.jsx(Wt,{}):e.jsx($i,{})}),le==="text"&&!ie&&o&&e.jsx("button",{type:"button",className:`fp-attach edit ${N?"on":""}`,"data-tip":a(ye?"fileEditTruncated":N?"exitEditFile":"editFile"),disabled:!R&&!N,onClick:b,children:e.jsx(Ut,{})}),le==="text"&&!ie&&!ve&&e.jsx("button",{type:"button",className:`fp-attach wrap ${H?"on":""}`,"data-tip":a(H?"disableWrap":"enableWrap"),onClick:()=>k(re=>!re),children:e.jsx(Fi,{})}),le==="text"&&o&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":a("zoomOut"),disabled:X<=50,onClick:()=>se(X-10),children:e.jsx(vi,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:a("resetZoom"),onClick:()=>$(100),children:[X,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":a("zoomIn"),disabled:X>=200,onClick:()=>se(X+10),children:e.jsx(ki,{})})]}),le!=="video"&&le!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":a("attachInlineTip"),onClick:()=>c(t.path,t.name,"inline"),children:e.jsx(He,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":a("referenceTip"),onClick:()=>c(t.path,t.name,"reference"),children:e.jsx(Kt,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${A?"on":""}`,"data-tip":a(A?"exitFullscreen":"fullscreen"),onClick:()=>F(re=>!re),children:A?e.jsx(Ei,{}):e.jsx(Mi,{})}),e.jsx("button",{type:"button",className:"fp-close",title:a("close"),onClick:B,children:e.jsx(Ee,{})})]})]}),ye&&le==="text"&&!ie&&e.jsx("div",{className:"fp-notice",children:a("previewTruncated")}),m&&!o&&e.jsx("div",{className:"fp-empty",children:a("loading")}),!m&&le==="none"&&!ie&&e.jsx("div",{className:"fp-empty",children:a("previewNotSupported")}),!m&&le==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:Pe(t.path),alt:t.name})}),!m&&le==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:Pe(t.path),controls:!0,preload:"metadata"})}),!m&&ve&&o&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(St,{text:o.text})})}),!m&&ie&&le!=="image"&&le!=="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&&N&&le==="text"&&!ie&&o&&e.jsx("textarea",{className:`fp-editor ${H?"":"no-wrap"}`,value:V,onChange:re=>q(re.target.value),wrap:H?"soft":"off",spellCheck:!1,autoFocus:!0}),!m&&!ve&&!N&&le==="text"&&!ie&&o&&I.length===0&&e.jsx("div",{className:"fp-empty",children:a("emptyFile")}),!m&&!ve&&!N&&le==="text"&&!ie&&I.length>0&&e.jsxs("div",{className:`fp-code ${v?"dragging":""} ${H?"":"no-wrap"}`,onMouseDown:re=>{re.button===0&&re.preventDefault()},children:[I.map((re,h)=>{const z=h+1,pe=f!==null&&z>=f.start&&z<=f.end;return e.jsxs("div",{className:`fp-line ${pe?"sel":""}`,onMouseDown:ce=>{ce.button===0&&(U(z,ce.shiftKey),Q.current=!0,T(!0))},onMouseEnter:()=>{Q.current&&U(z,!0)},children:[e.jsx("span",{className:"fp-num",children:z}),e.jsx("span",{className:"fp-code-text",children:re})]},z)}),W&&e.jsx("div",{className:"fp-lines-note",children:a("previewLinesTruncated",{n:Ht})})]}),e.jsx("div",{className:"fp-foot",children:N?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:b,children:a("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:V===((o==null?void 0:o.text)??""),onClick:w,children:[e.jsx(Ci,{})," ",a("saveFile")]})]})]}):!ve&&le==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:f?a("selectedRange",{n:G,start:f.start,end:f.end}):a("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:I.length===0,onClick:ne,children:a("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!f,onClick:()=>g(null),children:a("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!f||ie,onClick:x,children:[D?e.jsx(ut,{}):null,a(D?"addedToChat":"addToChat")]})]})]})})]})})}function Ot(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function fl(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const Yn="pi-web-sounds",st={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function Jn(){try{const t=localStorage.getItem(Yn);if(!t)return{...st};const s=JSON.parse(t),n={...st,...s};for(const r of["enabled","question","done","start","error"])typeof n[r]!="boolean"&&(n[r]=st[r]);return typeof n.volume!="number"||!Number.isFinite(n.volume)?n.volume=st.volume:n.volume=Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...st}}}function xl(t){try{localStorage.setItem(Yn,JSON.stringify(t))}catch{}}let nt=null;function yl(){try{if(!nt){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;nt=new t}return nt.state==="suspended"&&nt.resume(),nt}catch{return null}}const vl=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],kl=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],bl=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],jl=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],wl={question:vl,done:kl,start:bl,error:jl};function Nl(t,s,n){const r=t.createOscillator(),c=t.createGain();r.type=s.type,r.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),r.connect(c),c.connect(t.destination),r.start(i),r.stop(i+s.dur+.05)}function it(t,s=Jn()){if(!s.enabled||!s[t])return;const n=yl();if(!n)return;const r=Math.max(0,Math.min(1,s.volume/100));for(const c of wl[t])Nl(n,c,r)}const Jt="pi-web-ui:theme",Xn="dark",Xs="theme-stylesheet",Zs="pi-web-ui:theme-change";function Zn(){try{const t=localStorage.getItem(Jt);if(t&&t!==Xn)return t}catch{}return null}function Cl(t){try{t?localStorage.setItem(Jt,t):localStorage.removeItem(Jt)}catch{}}function ei(t){let s=document.getElementById(Xs);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(Zs));return}s||(s=document.createElement("link"),s.id=Xs,s.rel="stylesheet",document.head.appendChild(s)),s.href=Ve(`/themes/${encodeURIComponent(t)}.css`),s.onload=()=>window.dispatchEvent(new CustomEvent(Zs))}async function Sl(){try{const t=await fetch(Ct(Ve("/api/themes")));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function Tl(){const[t,s]=l.useState([]),[n,r]=l.useState(()=>Zn());return l.useEffect(()=>{let i=!1;return Sl().then(a=>{i||s(a)}),()=>{i=!0}},[]),l.useEffect(()=>{ei(n),Cl(n)},[n]),{themes:t,theme:n,switchTheme:i=>r(i===Xn?null:i)}}function Al(){const t=getComputedStyle(document.documentElement),s=(n,r)=>t.getPropertyValue(n).trim()||r;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 El=l.lazy(()=>ui(()=>import("./TerminalPanel-C5VIdPmn.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function Pl({notice:t,onDismiss:s}){const n=xe(),{locale:r}=pt(),c=r==="en"&&t.textEn?t.textEn:t.text,[i,a]=l.useState(!1);l.useEffect(()=>{if(i)return;const u=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(u)},[i,t.id,t.level,s]);const o=t.level==="error"?qi:t.level==="warning"?Ui:Li;return e.jsxs("div",{className:`notice notice-${t.level}${i?" paused":""}`,role:"status",onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),children:[e.jsx(o,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:c}),e.jsx("button",{type:"button",className:"notice-close",title:n("close"),onClick:()=>s(t.id),children:e.jsx(Ee,{})})]})}const Ml=[],ti=180,si=520,ni=240,ii=t=>`pi-web-ui:${t}-panel-width`;function en(t){const s=Number(localStorage.getItem(ii(t)));return Number.isFinite(s)&&s>=ti&&s<=si?s:ni}const Xt=t=>`pi-web-ui:${t}-panel-collapsed`;function tn(t){return localStorage.getItem(Xt(t))==="1"}function sn({side:t,width:s,onResize:n}){const r=xe(),c=l.useCallback(i=>{i.preventDefault();const a=i.clientX,o=s;let u=o;const m=f=>{const g=t==="left"?f.clientX-a:a-f.clientX;u=Math.min(si,Math.max(ti,Math.round(o+g))),n(u)},y=()=>{window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",y),document.body.classList.remove("panel-resizing"),localStorage.setItem(ii(t),String(u))};window.addEventListener("pointermove",m),window.addEventListener("pointerup",y),document.body.classList.add("panel-resizing")},[t,s,n]);return e.jsx("div",{className:`resize-handle resize-${t}`,title:r("dragToResize"),onPointerDown:c,onDoubleClick:()=>n(ni)})}function nn({side:t,onClick:s}){const n=xe();return e.jsx("button",{type:"button",className:`panel-rail panel-rail-${t}`,title:n("expandPanel"),onClick:s,children:t==="left"?e.jsx(hn,{}):e.jsx(gn,{})})}function Rl(){var Oe,is,as,rs,ls,os,cs,ds,us,ps,ms,hs,gs,fs;const t=xe(),{chat:s,send:n,dismissNotice:r,pushNotice:c,terminal:i}=wa(),[a,o]=l.useState([]),[u,m]=l.useState(null),[y,f]=l.useState(!1),[g,v]=l.useState("chat"),T=l.useMemo(()=>s.plugins.filter(_=>{var Z,ue;return!((ue=(Z=s.settings)==null?void 0:Z.disabledPlugins)!=null&&ue.includes(_.id))}),[s.plugins,(Oe=s.settings)==null?void 0:Oe.disabledPlugins]),[D,O]=l.useState([]);l.useEffect(()=>ma(O),[]),l.useEffect(()=>{ha(T,s.pluginsEpoch)},[T,s.pluginsEpoch]);const[N,j]=l.useState(()=>en("left")),[V,q]=l.useState(()=>en("right")),J=l.useCallback(_=>j(_),[]),K=l.useCallback(_=>q(_),[]),[E,H]=l.useState(()=>tn("left")),[k,A]=l.useState(()=>tn("right")),F=l.useCallback(()=>{H(_=>(localStorage.setItem(Xt("left"),_?"0":"1"),!_))},[]),X=l.useCallback(()=>{A(_=>(localStorage.setItem(Xt("right"),_?"0":"1"),!_))},[]),[$,Y]=l.useState(null),[Q,P]=l.useState(()=>window.matchMedia("(max-width: 768px)").matches);l.useEffect(()=>{const _=window.matchMedia("(max-width: 768px)"),Z=ue=>P(ue.matches);return _.addEventListener("change",Z),()=>_.removeEventListener("change",Z)},[]);const[I,C]=l.useState(!1),[W,U]=l.useState(!1),[ne,x]=l.useState(!1),[R,d]=l.useState(!1),[b,w]=l.useState(!1),[B,se]=l.useState(null);l.useEffect(()=>{if(!B)return;const _=setTimeout(()=>se(null),15e3);return()=>clearTimeout(_)},[B]),l.useEffect(()=>{const _=Z=>{var qe,xs;const ue=Z.detail,Ne=(ue==null?void 0:ue.title)||t("pluginCommandFallback"),Ce=ue==null?void 0:ue.command;if(!Ce||!s.ready)return;const Fe={name:Ne,command:Ce,cwd:"${pwd}"},Se=s.terminals.find(Tt=>Tt.title===Ne);if(Se)i.restart(Se.id),n({type:"run_command",terminalId:Se.id,conversationId:Se.conversationId,command:Fe,cols:80,rows:24});else{const Tt=Ue();i.create({id:Tt,conversationId:s.activeConversationId||((qe=s.state)==null?void 0:qe.conversationId)||"",title:Ne,cwd:((xs=s.state)==null?void 0:xs.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:Fe})}v("terminal")};return window.addEventListener("pi-web-ui:plugin-run-command",_),()=>window.removeEventListener("pi-web-ui:plugin-run-command",_)},[s,i,n]),l.useEffect(()=>{const _=Z=>{!(Z.ctrlKey||Z.metaKey)||Z.key.toLowerCase()!=="k"||(Z.preventDefault(),w(ue=>!ue))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[]);const[G,ie]=l.useState(Jn),{themes:ye,theme:le,switchTheme:we}=Tl(),ve=l.useRef(null),Pe=l.useRef(null),re=l.useRef(0),h=l.useRef(!1),z=l.useRef(s.terminals);l.useEffect(()=>{xl(G)},[G]),l.useEffect(()=>{var Z;const _=z.current;z.current=s.terminals;for(const ue of s.terminals){const Ne=((Z=ue.command)==null?void 0:Z.command)??"",Ce=_.find(Fe=>Fe.id===ue.id);!(Ce!=null&&Ce.running)||ue.running||(Ne.startsWith("pi remove ")?n({type:"extensions_reload"}):Ne.startsWith("pi-web-ui install ")||Ne.startsWith("pi-web-ui uninstall ")?n({type:"plugins_reload"}):Ne.startsWith("npm i -g ")&&(n({type:"extensions_reload"}),n({type:"plugins_reload"}),n({type:"check_updates_all",force:!0})))}},[s.terminals,n]),l.useEffect(()=>{var ue;const _=((ue=s.state)==null?void 0:ue.isStreaming)??!1,Z=ve.current;ve.current=_,Z!==null&&(!Z&&_?it("start",G):Z&&!_&&(it("done",G),Rt(t("notifyDoneTitle"),t("notifyDoneBody"))))},[(is=s.state)==null?void 0:is.isStreaming,G]),l.useEffect(()=>{var Z;const _=((Z=s.dialog)==null?void 0:Z.id)??null;_!==null&&_!==Pe.current&&(it("question",G),Rt(t("notifyQuestionTitle"),t("notifyQuestionBody"))),Pe.current=_},[s.dialog,G]),l.useEffect(()=>{const _=[...s.notices].reverse().find(Z=>Z.level==="error");_&&_.id!==re.current&&(re.current=_.id,it("error",G),Rt(t("notifyErrorTitle"),t("notifyErrorBody")))},[s.notices,G]);const pe=(_,Z,ue,Ne=!1,Ce)=>{const Fe=`${_}|${ue}|${Ce?`${Ce.start}-${Ce.end}`:""}`;o(Se=>Se.some(qe=>`${qe.path}|${qe.mode}|${qe.lines?`${qe.lines.start}-${qe.lines.end}`:""}`===Fe)?Se:[...Se,{path:_,name:Z,mode:ue,isDir:Ne,...Ce?{lines:Ce}:{}}])},ce=_=>o(Z=>Z.filter(ue=>ue.key?ue.key!==_:ue.path!==_)),fe=l.useCallback(_=>(!_.type.startsWith("list_")&&!_.type.startsWith("get_")&&Y(null),n(_)),[n]),me=l.useRef(0),ke=l.useRef(0),Me=_=>{var Ne;const Z=Date.now();(Ne=s.state)!=null&&Ne.model&&!s.state.model.vision&&Z-ke.current>1e4&&(ke.current=Z,c("warning",t("imageNotSupported")));const ue=`paste-${++me.current}`;o(Ce=>[...Ce,{path:"",key:ue,name:_.name,mode:"inline",imageData:_.data,mimeType:_.mimeType}])},he=async _=>{for(const Z of _){const ue=await Rn(Z);if(!ue){c("error",t("imageLoadFailed",{name:Z.name}));continue}Me(ue)}},Ie=20*1024*1024,Le=l.useRef(0),_e=async _=>{if(_.size>Ie){c("warning",t("fileTooLarge",{name:_.name,size:Ie/1024/1024}));return}let Z;try{Z=(await new Promise((Ce,Fe)=>{const Se=new FileReader;Se.onload=()=>Ce(Se.result),Se.onerror=()=>Fe(Se.error??new Error("read failed")),Se.readAsDataURL(_)})).replace(/^data:[^;]*;base64,/,"")}catch{c("error",t("fileLoadFailed",{name:_.name}));return}const ue=`upload-${++Le.current}`;o(Ne=>[...Ne,{path:"",key:ue,name:_.name,mode:"inline",fileData:Z,size:_.size,mimeType:_.type||void 0}])},De=async _=>{for(const Z of _)We(Z.type)?await he([Z]):await _e(Z)},M=l.useCallback((_,Z,ue)=>{n({type:"edit_message",messageId:_,text:Z,attachments:ue})},[n]),ge=l.useCallback((_,Z)=>{n({type:"queue_remove",kind:_,text:Z})},[n]),p=l.useCallback(()=>U(!0),[]),ee=l.useCallback(()=>o([]),[]),de=l.useCallback(ce,[]),S=l.useCallback(he,[he]),L=l.useCallback(De,[De]),ae=(as=s.state)==null?void 0:as.model,oe=(rs=s.state)==null?void 0:rs.thinkingLevel,be=(ls=s.state)==null?void 0:ls.availableThinkingLevels,je=l.useMemo(()=>ae?{model:ae,thinkingLevel:oe??"off",availableThinkingLevels:be??[]}:null,[ae,oe,be]),Te=l.useCallback(()=>{var _,Z;return!s.ready||s.terminals.length!==0?!1:(i.create({id:Ue(),conversationId:s.activeConversationId||((_=s.state)==null?void 0:_.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((Z=s.state)==null?void 0:Z.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,(os=s.state)==null?void 0:os.cwd,s.terminals.length,t,i]);return l.useEffect(()=>{if(h.current){if(g!=="terminal"||s.terminals.length!==0){h.current=!1;return}Te()&&(h.current=!1)}},[s.terminals.length,Te,g]),e.jsxs("div",{className:"app",onDragOver:_=>{var Z;Array.from(((Z=_.dataTransfer)==null?void 0:Z.types)??[]).includes("Files")&&(_.preventDefault(),f(!0))},onDragLeave:_=>{_.currentTarget.contains(_.relatedTarget)||f(!1)},onDrop:_=>{var Ce,Fe;if(f(!1),!Array.from(((Ce=_.dataTransfer)==null?void 0:Ce.types)??[]).includes("Files"))return;_.preventDefault();const Z=Array.from(((Fe=_.dataTransfer)==null?void 0:Fe.files)??[]);if(Z.length===0){c("warning",t("foldersNotSupported"));return}const ue=Z.filter(Se=>We(Se.type)),Ne=Z.filter(Se=>!We(Se.type));ue.length>0&&he(ue),Ne.length>0&&De(Ne)},children:[y&&e.jsx("div",{className:"app-drop-overlay","aria-hidden":!0,children:e.jsxs("span",{children:["📎 ",t("dropHereToAttach")]})}),e.jsx(ea,{chat:s,send:n,terminal:i,view:g,plugins:T,onViewChange:_=>{h.current=_==="terminal"&&s.terminals.length===0,h.current&&Te()&&(h.current=!1),v(_),Y(null)},onOpenPanel:Y,onOpenSettings:()=>x(!0),onOpenBgTasks:()=>d(!0),onOpenGlobalSearch:()=>w(!0),sound:G,onSoundChange:ie,onSoundPreview:_=>it(_,G),themes:ye,theme:le,onThemeChange:we}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(_=>e.jsx(Pl,{notice:_,onDismiss:r},_.id))}),e.jsx(Cr,{send:n,children:e.jsxs("div",{className:"layout",style:{"--left-w":`${N}px`,"--right-w":`${V}px`},children:[$&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>Y(null)}),e.jsxs("div",{className:`view-pane ${g==="chat"?"":"hidden"}`,children:[!Q&&E&&e.jsx(nn,{side:"left",onClick:F}),e.jsx("div",{className:`panel-drawer drawer-left ${$==="left"?"open":""}${Q?"":E?" hidden":""}`,children:e.jsx(ra,{collapsible:!Q,onToggleCollapse:F,send:fe,active:!Q||$==="left",ready:s.ready,status:s.status,cwd:((cs=s.state)==null?void 0:cs.cwd)??"",sessionFile:((ds=s.state)==null?void 0:ds.sessionFile)??null,conversations:s.conversations,sessions:s.sessions,projects:s.projects,activeConversationId:s.activeConversationId})}),!Q&&e.jsx(sn,{side:"left",width:N,onResize:J}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(Rr,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:M,onKillBash:()=>n({type:"abort_bash"}),onRemoveQueued:ge,thinkingWrap:((us=s.settings)==null?void 0:us.thinkingWrap)??!0,toolsWrap:((ps=s.settings)==null?void 0:ps.toolsWrap)??!0,jumpTarget:B,onJumpDone:()=>se(null)},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(zr,{send:n,goal:s.goal,models:s.models,modelsLoading:s.modelsLoading,activeConversationId:s.activeConversationId,engine:s.engine}),s.dialog&&e.jsx(Zr,{dialog:s.dialog,send:n}),s.question&&e.jsx(el,{question:s.question,send:n}),e.jsx(qr,{send:n,ready:s.ready,streaming:((ms=s.state)==null?void 0:ms.isStreaming)??!1,messages:((hs=s.state)==null?void 0:hs.messages)??Ml,slashCommands:s.slashCommands,modelState:je,models:s.models,modelsLoading:s.modelsLoading,providerKeys:s.providerKeys,attachments:a,onRemoveAttachment:de,onAddImageFiles:S,onAddLocalFiles:L,onNotice:c,onManageModels:p,onSent:ee})]}),!Q&&e.jsx(sn,{side:"right",width:V,onResize:K}),e.jsx("div",{className:`panel-drawer drawer-right ${$==="right"?"open":""}${Q?"":k?" hidden":""}`,children:e.jsx(Ia,{collapsible:!Q,onToggleCollapse:X,send:fe,files:s.files,fileChanged:s.fileChanged,widgets:s.widgets,cwd:((gs=s.state)==null?void 0:gs.cwd)??"",onAttach:(_,Z,ue,Ne)=>{Y(null),pe(_,Z,ue,Ne)},onPreview:(_,Z)=>{Y(null),m({path:_,name:Z})},onNotice:(_,Z)=>c(_,Z)})}),!Q&&k&&e.jsx(nn,{side:"right",onClick:X})]}),e.jsx("div",{className:`view-pane ${g==="terminal"?"":"hidden"}`,children:e.jsx(l.Suspense,{fallback:null,children:e.jsx(El,{chat:s,send:n,terminal:i})})}),e.jsx("div",{className:`view-pane ${g==="git"?"":"hidden"}`,children:e.jsx(sl,{chat:s,send:n,terminal:i,active:g==="git",onSwitchToTerminal:()=>v("terminal")})}),D.map(_=>{const Z=`plugin:${_.info.id}`;return e.jsx("div",{className:`view-pane ${g===Z?"":"hidden"}`,children:e.jsx(nl,{entry:_,send:n})},_.info.id)})]})}),e.jsx(Jr,{chat:s,send:n}),u&&e.jsx(gl,{file:u,content:s.fileContent,send:n,onAddLines:(_,Z,ue,Ne)=>pe(_,Z,"lines",!1,{start:ue,end:Ne}),onAttach:(_,Z,ue)=>pe(_,Z,ue),onClose:()=>m(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!I&&!W&&e.jsx(il,{send:n,piConfigured:s.state.piConfigured,piAgentInstalled:s.state.piAgentInstalled,providers:s.providers,installResult:s.installResult,onClose:()=>C(!0)}),W&&e.jsx(ll,{send:n,providers:s.modelsConfig,providerStatus:s.providers,providerKeys:s.providerKeys,fetchModelsResult:s.fetchModelsResult,cloneProviderResult:s.cloneProviderResult,onClose:()=>U(!1)}),ne&&e.jsx(dl,{chat:s,send:n,terminal:i,onSwitchToTerminal:()=>v("terminal"),onClose:()=>x(!1)}),R&&e.jsx(pl,{servers:s.bgServers,send:n,onClose:()=>d(!1)}),e.jsx(hl,{open:b,send:n,projects:s.projects,cwd:((fs=s.state)==null?void 0:fs.cwd)??"",fileSearch:s.fileSearch,sessionSearch:s.sessionSearch,onClose:()=>w(!1),onSwitchSession:(_,Z)=>{n({type:"switch_session",path:_});const ue=Z&&Z[0];se(ue?{path:_,role:ue.role,timestamp:ue.timestamp}:null)},onSwitchProject:_=>{n({type:"set_cwd",path:_})},onPreviewFile:(_,Z)=>{m({path:_,name:Z})}})]})}la();ei(Zn());oi.createRoot(document.getElementById("root")).render(e.jsx(l.StrictMode,{children:e.jsx(Gi,{children:e.jsx(Rl,{})})}));"serviceWorker"in navigator&&window.addEventListener("load",()=>{const t=kn();navigator.serviceWorker.register(`${t}sw.js`,{scope:t}).catch(s=>{console.warn("Service worker registration failed:",s)})});export{at as F,Zs as T,xe as a,Al as b,He as c,Dl as d,wt as e,Be as f,Pi as g,et as h,Ee as i,Ue as r,pt as u};
|