pi-web-ui 0.28.2 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +295 -295
  3. package/README.zh-CN.md +279 -279
  4. package/bin/pi-web-ui.mjs +0 -0
  5. package/deploy/com.xingshuyin.pi-web-ui.plist +48 -48
  6. package/deploy/nginx-subpath.conf +88 -88
  7. package/deploy/pi-web-ui-task.xml +71 -71
  8. package/deploy/pi-web-ui.service +31 -31
  9. package/dist/server/agent-service.js +408 -3851
  10. package/dist/server/attachments.js +621 -0
  11. package/dist/server/bg-servers.js +138 -0
  12. package/dist/server/client-state.js +148 -0
  13. package/dist/server/files-service.js +633 -0
  14. package/dist/server/goal-service.js +869 -0
  15. package/dist/server/index.js +144 -8
  16. package/dist/server/model-admin.js +727 -0
  17. package/dist/server/process-utils.js +86 -0
  18. package/dist/server/protocol-version.js +11 -0
  19. package/dist/server/scm.js +298 -0
  20. package/dist/server/settings-service.js +268 -0
  21. package/dist/server/slash-commands.js +245 -0
  22. package/dist/server/terminals.js +98 -0
  23. package/dist/server/text-sniff.js +268 -0
  24. package/dist/server/uploads.js +107 -0
  25. package/dist/server/webui-context.js +208 -0
  26. package/extensions/webui.ts +192 -192
  27. package/package.json +94 -87
  28. package/themes/light.css +6318 -6318
  29. package/web/dist/assets/TerminalPanel-6GBZ9nXN.css +32 -0
  30. package/web/dist/assets/TerminalPanel-B-bsYqea.js +2 -0
  31. package/web/dist/assets/index-BsrqFaSZ.js +13 -0
  32. package/web/dist/assets/index-Dsb8Bak1.css +10 -0
  33. package/web/dist/assets/markdown-DRBrS2Nf.js +51 -0
  34. package/web/dist/assets/react-C9ovnpIm.js +24 -0
  35. package/web/dist/assets/xterm-D1D2FVe3.js +38 -0
  36. package/web/dist/favicon.svg +8 -8
  37. package/web/dist/index.html +17 -15
  38. package/web/public/favicon.svg +8 -8
  39. package/web/dist/assets/index-BnDkdKFN.css +0 -41
  40. package/web/dist/assets/index-DmmSVSzk.js +0 -129
@@ -0,0 +1,13 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/TerminalPanel-B-bsYqea.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 fe,a as l,j as e,M as as,b as is,c as rs}from"./markdown-DRBrS2Nf.js";import{r as Rt}from"./react-C9ovnpIm.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&n(i)}).observe(document,{childList:!0,subtree:!0});function a(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(r){if(r.ep)return;r.ep=!0;const o=a(r);fetch(r.href,o)}})();var Se={},ct;function ls(){if(ct)return Se;ct=1;var t=Rt();return Se.createRoot=t.createRoot,Se.hydrateRoot=t.hydrateRoot,Se}var os=ls();const cs="modulepreload",ds=function(t){return"/"+t},dt={},us=function(s,a,n){let r=Promise.resolve();if(a&&a.length>0){let i=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),h=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));r=i(a.map(d=>{if(d=ds(d),d in dt)return;dt[d]=!0;const m=d.endsWith(".css"),f=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${f}`))return;const v=document.createElement("link");if(v.rel=m?"stylesheet":cs,m||(v.as="script"),v.crossOrigin="",v.href=d,h&&v.setAttribute("nonce",h),document.head.appendChild(v),m)return new Promise((g,w)=>{v.addEventListener("load",g),v.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return r.then(i=>{for(const c of i||[])c.status==="rejected"&&o(c.reason);return s().catch(o)})};var Lt={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},ut=fe.createContext&&fe.createContext(Lt),ms=["attr","size","title"];function ps(t,s){if(t==null)return{};var a,n,r=hs(t,s);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);for(n=0;n<o.length;n++)a=o[n],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(r[a]=t[a])}return r}function hs(t,s){if(t==null)return{};var a={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(s.indexOf(n)!==-1)continue;a[n]=t[n]}return a}function Le(){return Le=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var n in a)({}).hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t},Le.apply(null,arguments)}function mt(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);s&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),a.push.apply(a,n)}return a}function Ie(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?mt(Object(a),!0).forEach(function(n){gs(t,n,a[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):mt(Object(a)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(a,n))})}return t}function gs(t,s,a){return(s=fs(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function fs(t){var s=xs(t,"string");return typeof s=="symbol"?s:s+""}function xs(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var n=a.call(t,s);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function It(t){return t&&t.map((s,a)=>fe.createElement(s.tag,Ie({key:a},s.attr),It(s.child)))}function H(t){return s=>fe.createElement(vs,Le({attr:Ie({},t.attr)},s),It(t.child))}function vs(t){var s=a=>{var n=t.attr,r=t.size,o=t.title,i=ps(t,ms),c=r||a.size||"1em",h;return a.className&&(h=a.className),t.className&&(h=(h?h+" ":"")+t.className),fe.createElement("svg",Le({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},a.attr,n,i,{className:h,style:Ie(Ie({color:t.color||a.color},a.style),t.style),height:c,width:c,xmlns:"http://www.w3.org/2000/svg"}),o&&fe.createElement("title",null,o),t.children)};return ut!==void 0?fe.createElement(ut.Consumer,null,a=>s(a)):s(Lt)}function ys(t){return H({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 js(t){return H({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 Ke(t){return H({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 he(t){return H({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 Pt(t){return H({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 bs(t){return H({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 Me(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"3 6 5 6 21 6"},child:[]},{tag:"path",attr:{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"},child:[]},{tag:"line",attr:{x1:"10",y1:"11",x2:"10",y2:"17"},child:[]},{tag:"line",attr:{x1:"14",y1:"11",x2:"14",y2:"17"},child:[]}]})(t)}function Ze(t){return H({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 pt(t){return H({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 ks(t){return H({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 Pe(t){return H({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 Be(t){return H({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 Ns(t){return H({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 ws(t){return H({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 Xe(t){return H({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 xe(t){return H({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 va(t){return H({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 ht(t){return H({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 H({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 Ss(t){return H({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 Ts(t){return H({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 ze(t){return H({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 Ms(t){return H({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 Es(t){return H({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 Rs(t){return H({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 Ve(t){return H({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 De(t){return H({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 Ls(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"},child:[]}]})(t)}function Is(t){return H({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 Ps(t){return H({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 gt(t){return H({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 Ee(t){return H({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 ke(t){return H({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 Bt(t){return H({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 Dt(t){return H({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 Ge(t){return H({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 ft(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"path",attr:{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"},child:[]}]})(t)}function et(t){return H({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 Fe(t){return H({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 Bs(t){return H({attr:{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},child:[{tag:"polyline",attr:{points:"9 10 4 15 9 20"},child:[]},{tag:"path",attr:{d:"M20 4v7a4 4 0 0 1-4 4H4"},child:[]}]})(t)}function _t(t){return H({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 Ds(t){return H({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 tt(t){return H({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 $e(t){return H({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 ve(t){return H({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 st(t){return H({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 _s(t){return H({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 Fs(t){return H({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 Ft(t){return H({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 $t(t){return H({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 $s(t){return H({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 As(t){return H({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 pe({trigger:t,open:s,onOpenChange:a,children:n,align:r="right",fit:o=!1,direction:i="down"}){const c=l.useRef(null);return l.useEffect(()=>{if(!s)return;const h=m=>{c.current&&!c.current.contains(m.target)&&a(!1)},d=m=>{m.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",h),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("keydown",d)}},[s,a]),e.jsxs("div",{className:`dropdown ${r} ${o?"fit":""} ${i==="up"?"dd-up":""}`,ref:c,children:[e.jsxs("button",{type:"button",className:"chip",onClick:()=>a(!s),"aria-expanded":s,children:[t,e.jsx(ve,{className:`dd-caret ${s?"up":""}`})]}),s&&e.jsx("div",{className:"dd-menu",children:n})]})}function me({active:t,disabled:s=!1,title:a,onClick:n,children:r}){return e.jsx("button",{type:"button",className:`dd-item ${t?"active":""}`,disabled:s,title:a,onClick:n,children:r})}const At="pi-web-ui:lang",Os={cancel:"取消",ok:"确定",save:"保存",close:"关闭",loading:"加载中…",connected:"已连接",connecting:"连接中…",reconnecting:"重连中…",language:"语言",langZh:"中文",langEn:"English",githubRepo:"GitHub 仓库(xing-shuyin/pi-web-ui)",copy:"复制",viewSwitch:"视图切换",chat:"对话",terminal:"终端",selectModel:"选择模型",availableModels:"可用模型",noModels:"暂无可用模型(请先配置 API 密钥)",reasoning:"推理",vision:"识图",refreshModels:"刷新模型列表(保留手填,合并新增)",manageModels:"⚙ 管理模型(新增 / 修改)",manageModelsTitle:"管理模型",thinkingLevel:"思考强度",thinking:"思考",thinkingChip:"思考:{level}",sound:"声音",theme:"主题",themeDefault:"深色(默认)",newChat:"新对话",more:"更多",newChatTip:"新建对话(每个浏览器独立保存会话)","thinking.off":"关闭","thinking.minimal":"极简","thinking.low":"低","thinking.medium":"中","thinking.high":"高","thinking.xhigh":"极高","thinking.max":"最大",thinkingUnsupported:"当前模型不支持该级别,已按模型能力就近生效",context:"上下文",contextUsage:"上下文用量",cumulativeCost:"累计成本",sessionMessages:"会话消息数",messages:"消息",pluginStatus:"插件状态",working:"工作中",queued:"排队",enterPath:"输入路径,Enter 切换",cwdTip:"工作目录:{path}(点击切换)",folderRef:"文件夹引用:{path}",refOnly:"仅引用:{path}",attachContent:"附加内容:{path}",attachLines:"附加选中行:{path}(第 {start}-{end} 行)",attachImage:"图片:{name}",attachFile:"文件:{name}",removeAttachment:"移除附件",attachHint:"将随下一条消息发送",uploadFile:"添加文件(图片/文本/任意文件,也可直接拖入或粘贴截图)",dropHereToAttach:"松开以添加文件",imageNotSupported:"当前模型不支持识图:图片将交给视觉桥转写(若未配置视觉模型则可能被忽略)",imageLoadFailed:"图片读取失败:{name}",fileLoadFailed:"文件读取失败:{name}",fileTooLarge:"文件过大已跳过(>{size}MB):{name}",foldersNotSupported:"不支持直接拖入文件夹,请展开后选择文件",followUpQueued:"⏳ {n} 条跟进消息排队中",steeringQueued:"⏳ {n} 条转向消息排队中",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:"等当前回复全部生成完后再发送(不打断)",sendTip:"发送(Enter)",slashCommands:"命令",slashMenuHint:"↑↓ 选择 · Enter/Tab 补全",slashHelpTitle:"pi 命令",slashHelpHint:"输入 / 随时打开命令列表",slashLoading:"命令列表加载中…(连接服务器后可用)",slashBuiltin:"内置",slashExtension:"扩展",slashPrompt:"模板",slashSkill:"技能",slashCopied:"已复制上一条助手回复",slashCopyFailed:"复制失败,请手动复制",slashCopyEmpty:"还没有可复制的助手回复",recentProjects:"最近项目",runningConversations:"运行的对话",historySessions:"历史对话",openHistory:"历史对话",openFiles:"文件列表",streaming:"进行中…",noHistory:"还没有历史对话",current:"当前",messageCount:"{n} 条消息",tuiTip:"pi 终端(TUI)中的对话",emptyChat:"空对话",editReask:"编辑重问",editReaskTip:"修改此问题,并从这里重新提问(会新建一个分支对话,原对话保留)",reaskFromHere:"从此处重新提问",editPlaceholder:"修改问题内容…",editHint:"⌘/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:"立即更新",confirmUpdate:"确认更新(覆盖全局安装)",updateSuccess:"✅ 已更新,正在重启…",updateFailed:"更新失败:{detail}",restartHint:"重启:pi-web-ui server restart",rootDir:"根目录",noFiles:"暂无文件",filesTruncated:"目录过大,列表已截断,仅显示前 2000 项",linkFolderTip:"链接文件夹路径到对话",attachInlineTip:"附加内容到对话",referenceTip:"仅引用路径(AI 按需读取)",previewFile:"预览",downloadFile:"下载文件",downloadFailed:"下载失败:{error}",protocolMismatch:"页面版本与服务器不一致(应用刚更新过),请刷新页面以恢复全部功能。",selectLinesHint:"点击选择行;拖拽或 Shift+点击选择范围",enableWrap:"开启自动换行",disableWrap:"关闭自动换行",selectedRange:"已选 {n} 行(第 {start}-{end} 行)",fileLines:"{n} 行",selectAll:"全选",clearSelection:"清除",addToChat:"添加到对话",addedToChat:"已添加",previewTruncated:"⚠ 文件过大,仅预览前 512KB",previewLinesTruncated:"… 文件行数过多,仅显示前 {n} 行",binaryFile:"🔣 二进制文件,已显示前 4KB 十六进制",binaryHexTruncated:"(文件更大,可下载完整文件)",previewNotSupported:"该类型文件不支持预览(仅图片 / 视频 / 文本)",emptyFile:"(空文件)",editFile:"编辑文件",exitEditFile:"退出编辑",saveFile:"保存文件",discardFileChanges:"放弃未保存的修改?",fileSaved:"已保存",fileEditTruncated:"文件过大,预览不完整,无法编辑",showMarkdownSource:"显示 Markdown 原文",showMarkdownPreview:"显示 Markdown 预览",fullscreen:"全屏",exitFullscreen:"退出全屏",zoomIn:"放大字号",zoomOut:"缩小字号",resetZoom:"重置缩放",pluginRequest:"插件请求",noOptions:"(无选项)",inputPlaceholder:"输入内容",soundHeader:"声音提示",enableSound:"启用声音",preview:"试听",volume:"音量","sound.question":"问卷弹出","sound.question.desc":"ask_user_question 出现时","sound.done":"回复结束","sound.done.desc":"智能体完成一轮回答时","sound.start":"回复开始","sound.start.desc":"智能体开始新一轮时","sound.error":"出错","sound.error.desc":"出现错误提示时",setupTitle:"未检测到 pi agent 配置",setupDesc:"pi-web-ui 需要 pi 的配置目录(~/.pi/agent)和至少一个 API 密钥才能运行智能体。pi 内置了 openai、anthropic、deepseek 等服务商——选一个填密钥即可,全程无需打开终端。",installFailed:"✖ pi agent 安装失败:",retryInstall:"重试安装",skip:"跳过",installDone:"✅ pi agent CLI 已安装。选择服务商并填入 API 密钥即可开始对话:",provider:"服务商",configured:"已配置",providerKeyReady:"该服务商已配置密钥,可直接使用或更换新密钥。",apiKey:"API 密钥",saving:"保存中…",saveAndStart:"保存并开始使用",recheck:"重新检测",installing:"正在安装 pi agent CLI…",autoInstall:"自动安装 pi agent",attachment:"附件",plugin:"插件",unknown:"未知",thinkingWait:"正在思考",exitCode:"退出码 {code}",cancelled:"已取消",truncated:"… 内容过长,当前视图已截断",outputTruncated:"… 输出过长,当前视图已截断",refOnlyShort:"仅引用",folderRefShort:"文件夹 · 仅引用",inlineLines:"内联 · {n} 行",inlineLinesRange:"行 {start}-{end}",image:"🖼 图片",bridgedVision:"👁 已转写",bridgedVisionDetail:"图片已由视觉桥转写(当前模型不支持识图)",folderNotExpanded:"文件夹,未展开内容 —— 智能体会按需浏览目录",fileNotExpanded:"文件较大({size}),未展开内容 —— 智能体会按需读取","role.user":"你","role.assistant":"pi","role.tool":"工具","role.bash":"终端","role.branch":"分支摘要","role.compaction":"上下文已压缩",welcomeTitle:"pi 编码智能体",welcomeSub:"检查、编辑、运行 —— 随时待命",directory:"目录",clickToFill:"点击填入输入框",waitingResponse:"正在等待模型响应…",backToBottom:"回到底部",questionNavTitle:"问题列表",questionNavTip:"本对话的全部问题,悬浮展开,点击跳转","ex.understand":"了解这个项目","ex.understand.prompt":"介绍一下这个项目:整体结构、主要模块和如何运行?","ex.debug":"排查一个问题","ex.debug.prompt":"帮我排查一个 bug,请先说明问题现象,我会补充细节。","ex.test":"编写测试","ex.test.prompt":"为项目的核心模块编写单元测试。","ex.review":"代码审查","ex.review.prompt":"审查最近改动的代码,指出潜在问题和改进建议。",error:"出错",done:"完成",running:"执行中…",toolQueued:"排队中",copyArgs:"复制参数",errorOutput:"错误输出",output:"输出",waitingOutput:"等待输出…",toolDoneWaitingModel:"已结束 · 等模型",waitingModel:"等待模型响应…",thinkingNow:"思考中",thinkingPreview:"思考:{preview}",commands:"命令",newCommand:"新建命令",newTerminal:"新建终端",name:"名称",command:"命令",cwdHint:"(${pwd} = 当前工作目录)",noCommands:"还没有命令,点 + 添加一个",clickToRun:"点击运行",edit:"编辑",delete:"删除",confirmQ:"确认?",builtinTerminal:"内置终端",termEmptySub:"点击左侧命令运行,或点右侧 + 新建终端",noTerminal:"暂无终端",exited:"(已退出{code})",closeTerminal:"关闭终端",rerun:"重新读取 .pi/commands.json",terminalTitle:"终端 {n}",exampleName:"例如:启动开发服务器",exampleCommand:"例如:npm run dev",scmTab:"Git",scmTitle:"源代码管理",scmRefreshTip:"重新查询 Git 状态与差异",scmCurrentBranch:"当前分支",scmUpstreamGone:"上游已删除",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"分离 HEAD",scmSelectBranch:"选择分支…",scmRemoteBranches:"远程分支",scmStageTip:"暂存 {path}",scmUnstageTip:"取消暂存 {path}",scmSwitch:"切换",scmSwitchBranch:"切换分支",scmSwitchBranchTip:"在终端中执行 git checkout {branch}",scmPush:"推送",scmPushTip:"在终端中执行 git push",scmPull:"拉取",scmPullTip:"在终端中执行 git pull",scmCommit:"提交",scmCommitTip:'在终端中执行 git add -A && git commit -m "…"(提交全部更改,含未跟踪)',scmCommitPlaceholder:"输入提交信息…",scmChanges:"更改",scmHistory:"提交树",scmCommitDetail:"提交详情",scmSelectCommitHint:"点击左侧提交查看详情",scmNoHistory:"暂无提交记录",scmNoChanges:"工作区干净,没有更改",scmNotGitRepo:"当前目录不是 Git 仓库",scmLoading:"查询中…",scmConnecting:"等待连接…",scmDiff:"差异",scmSelectFileHint:"点击左侧文件查看差异",scmNoDiff:"(无差异)",scmStaged:"已暂存",scmUnstaged:"未暂存",scmStagedUnstaged:"已暂存 + 未暂存",scmUntracked:"未跟踪",scmUntrackedNote:"未跟踪文件:差异不显示,提交时会一并包含",scmQueryFailed:"Git 查询失败:{error}",scmTooManyFailures:"Git 查询连续失败,请点击刷新重试",scmRunsInTerminal:"提交 / 切换分支 / 推送 / 拉取在终端中执行",scmViewTerminal:"去终端",editProvider:"编辑服务商",builtinProviders:"内置服务商",hintKeyOnly:"只需填入 API 密钥",configuredBadge:"✓ 已配置",keyReady:"密钥已就绪",replaceKey:"更换密钥",replaceKeyTitle:"替换已保存的密钥",clearKey:"清空",clearKeyTitle:"清除该服务商保存在 auth.json 的密钥,回到未配置状态(环境变量来源的无法在此清除)",clearKeyConfirm:"清空 {id} 已保存的密钥?其模型将从列表消失,直到重新配置。",pasteKey:"粘贴 API 密钥…",savingKey:"保存中",saveKey:"保存密钥",customProviders:"自定义服务商",customDesc:"用于 Ollama / vLLM / 兼容 OpenAI 的代理等,写入 pi 的 models.json,保存后热重载、立即生效。",noCustomProviders:"还没有自定义服务商",modelsCount:"{n} 个模型",addProvider:"新增服务商",providerId:"服务商 ID",providerIdHint:"(必填,如 ollama / my-proxy)",displayName:"显示名",displayNamePh:"我的代理",apiType:"API 类型",baseUrlHint:"(OpenAI 兼容端点)",apiKeyHint:"sk-…(可留空,用 auth.json 的密钥)",authHeader:"自动添加 Authorization 请求头",modelsTitle:"模型",modelIdReq:"模型 ID(必填)",text:"文本",textImage:"文本+图片",contextWindow:"上下文",maxOutput:"最大输出",removeModel:"移除模型",addModel:"添加模型",deleteProviderConfirm:"删除服务商 {id} 及其 {n} 个模型?",fetchModels:"自动获取模型列表",fetchModelsHint:"从 baseUrl 的 /models 接口自动拉取模型 ID(服务端请求,不受 CORS 限制)",fetchingModels:"获取中…",fetchModelsOk:"已获取 {n} 个模型",fetchModelsEmpty:"接口未返回任何模型",fetchModelsErr:"获取失败:{msg}",fetchModelsNeedBaseUrl:"请先填写 baseUrl 再获取",goalBarTitle:"目标",goalBarPlaceholder:"设定一个目标,agent 完成后自动审查…",goalBarSet:"开始",goalBarClear:"取消",goalBarLocked:"锁定:应用到后续所有回合",goalBarUnlocked:"仅本回合(改完自动清除)",goalBarReviewModel:"审查模型",goalBarUseMainModel:"使用主模型",goalBarMaxRounds:"最大轮数",goalBarMaxRoundsTip:"最大审查重改轮数;0 或不填 = 不限(持续改到通过)",goalBarUnlimitedShort:"不限",goalBarReviewing:"审查中…",goalBarRound:"第 {n} 轮",goalBarActive:"目标生效中",goalBarPassed:"已通过",goalBarFailed:"未通过",goalBarStatusPending:"等待生成…",goalWizardBtn:"AI 提炼",goalWizardTip:"让 AI 通过问卷调研细化需求,收敛为目标",goalWizardRunning:"目标调研中",goalWizardAnswer:"回答",goalWizardCard:"目标调研",settings:"设置",settingsTitle:"设置",settingsDesc:"修改立即生效:系统提示词、技能与插件开关会重建当前会话;审查提示词与审查技能只影响后续目标审查(回复进行中则主会话变更自动延迟)。",settingsSystemPrompt:"系统提示词",settingsPromptMode:"模式",promptModeAppend:"追加",promptModeReplace:"替换",promptAppendHint:"追加模式:自定义内容拼接到默认系统提示词末尾(推荐,保留默认行为约束)。",promptReplaceHint:"替换模式:完全用自定义内容替换系统提示词(项目上下文与技能段仍会自动附加)。切换后输入框会显示原本的默认提示词,可直接修改;不改动失焦则仍使用默认。",promptPlaceholder:"输入自定义系统提示词…(失焦后自动应用)",settingsSkills:"技能",settingsReview:"目标审查",settingsReviewDesc:"为独立的目标审查会话配置额外提示词和技能;不会改变主会话设置。",settingsReviewSkills:"审查可用技能",reviewPromptPlaceholder:"输入审查自定义提示词…(失焦后自动应用)",reviewPromptHint:"这些内容会追加到审查任务中;审查仍会强制要求输出 pass/fail JSON。技能开关仅对审查生效。",settingsVisionBridge:"视觉桥",settingsVisionBridgeDesc:"当前模型不支持识图时,把图片交给已配置的视觉模型转写为文字证据,再让模型回答",visionBridgeEnabled:"启用视觉桥",visionBridgeModel:"转写模型",visionBridgeAuto:"自动选择(按顺序)",visionBridgeNoModels:"未找到已配置的视觉模型:在模型配置里添加任意支持图片的模型(如 qwen-vl、GLM-4V、Gemini)即可自动启用",visionBridgeOffHint:"已关闭:图片将原样发送,纯文本模型可能看不到图片内容",visionBridgeCurrent:"当前转写模型:{model}",visionBridgePromptMode:"转写提示词",visionBridgePromptPlaceholder:"输入自定义转写提示词…(留空 = 使用内置默认提示词,失焦后自动应用)",visionBridgePromptAppendHint:"追加模式:自定义内容拼接到内置转写提示词末尾(推荐,保留默认的逐字转写约束)。",visionBridgePromptReplaceHint:"替换模式:完全用自定义内容替换内置转写提示词。切换后输入框会显示内置默认提示词,可直接修改;不改动失焦则仍使用默认。",settingsExtensions:"插件",settingsPresets:"预设",settingsEnabled:"已启用",settingsDisabled:"已禁用",presetNamePlaceholder:"预设名称…",saveAsPreset:"保存为预设",applyPreset:"应用",deletePreset:"删除预设",noSkills:"暂无技能",noExtensions:"暂无插件",noPresets:"暂无预设(先调整上面的设置,再保存为预设组合)",loadingSession:"正在加载会话…",connectingServer:"正在连接 pi-web-ui 服务器…"},Ws={cancel:"Cancel",ok:"OK",save:"Save",close:"Close",loading:"Loading…",connected:"Connected",connecting:"Connecting…",reconnecting:"Reconnecting…",language:"Language",langZh:"中文",langEn:"English",githubRepo:"GitHub repository (xing-shuyin/pi-web-ui)",copy:"Copy",viewSwitch:"Switch view",chat:"Chat",terminal:"Terminal",selectModel:"Select model",availableModels:"Available models",noModels:"No models available (configure an API key first)",reasoning:"reasoning",vision:"vision",refreshModels:"Refresh model list (keeps manual rows, merges new ones)",manageModels:"⚙ Manage models (add / edit)",manageModelsTitle:"Manage models",thinkingLevel:"Thinking level",thinking:"Thinking",thinkingChip:"Thinking: {level}",sound:"Sound",theme:"Theme",themeDefault:"Dark (default)",newChat:"New chat",more:"More",newChatTip:"New chat (sessions are saved per browser)","thinking.off":"Off","thinking.minimal":"Minimal","thinking.low":"Low","thinking.medium":"Medium","thinking.high":"High","thinking.xhigh":"Extra high","thinking.max":"Max",thinkingUnsupported:"Not supported by this model — snapped to the nearest supported level",context:"Context",contextUsage:"Context usage",cumulativeCost:"Cumulative cost",sessionMessages:"Session messages",messages:"messages",pluginStatus:"Plugin status",working:"Working",queued:"queued",enterPath:"Type a path, Enter to switch",cwdTip:"Working directory: {path} (click to switch)",folderRef:"Folder reference: {path}",refOnly:"Reference only: {path}",attachContent:"Attached content: {path}",attachLines:"Attached selected lines: {path} (lines {start}-{end})",attachImage:"Image: {name}",attachFile:"File: {name}",removeAttachment:"Remove attachment",attachHint:"Will be sent with the next message",uploadFile:"Add files (images / text / any file — or drag in / paste a screenshot)",dropHereToAttach:"Release to attach file",imageNotSupported:"The current model doesn't support vision — images will be transcribed by the vision bridge (may be ignored if no vision model is configured)",imageLoadFailed:"Couldn't read image: {name}",fileLoadFailed:"Couldn't read file: {name}",fileTooLarge:"File too large, skipped (> {size}MB): {name}",foldersNotSupported:"Folders can't be dropped directly — expand and pick files instead",followUpQueued:"⏳ {n} follow-up message(s) queued",steeringQueued:"⏳ {n} steering message(s) queued",placeholderStreaming:"The agent is working… (messages will queue)",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:"Follow-up",supplementTip:"Send after the current reply has fully finished (no interruption)",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",slashCopied:"Copied the last assistant reply",slashCopyFailed:"Copy failed — please copy manually",slashCopyEmpty:"No assistant reply to copy yet",recentProjects:"Recent projects",runningConversations:"Running chats",historySessions:"History",openHistory:"History",openFiles:"Files",streaming:"Streaming…",noHistory:"No previous chats",current:"Current",messageCount:"{n} messages",tuiTip:"Chat in the pi terminal (TUI)",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",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 now",confirmUpdate:"Confirm (replaces global install)",updateSuccess:"✅ Updated — restarting…",updateFailed:"Update failed: {detail}",restartHint:"Restart: pi-web-ui server restart",rootDir:"Root",noFiles:"No files",filesTruncated:"Directory too large — list truncated (first 2000 shown)",linkFolderTip:"Link folder path to chat",attachInlineTip:"Attach content to chat",referenceTip:"Reference path only (AI reads on demand)",previewFile:"Preview",downloadFile:"Download file",downloadFailed:"Download failed: {error}",protocolMismatch:"Page version differs from the server (the app was just updated). Refresh the page to restore full functionality.",selectLinesHint:"Click a line to select; drag or Shift+click for a range",enableWrap:"Enable line wrap",disableWrap:"Disable line wrap",selectedRange:"Selected {n} lines (lines {start}-{end})",fileLines:"{n} lines",selectAll:"Select all",clearSelection:"Clear",addToChat:"Add to chat",addedToChat:"Added",previewTruncated:"⚠ File too large — previewing the first 512KB",previewLinesTruncated:"… too many lines — showing the first {n}",binaryFile:"🔣 Binary file — first 4KB shown as hex",binaryHexTruncated:" (file larger — download for the full file)",previewNotSupported:"This file type can't be previewed (only images / videos / text)",emptyFile:"(empty file)",editFile:"Edit file",exitEditFile:"Exit editing",saveFile:"Save file",discardFileChanges:"Discard unsaved changes?",fileSaved:"Saved",fileEditTruncated:"The preview is incomplete, so this file can't be edited",showMarkdownSource:"Show Markdown source",showMarkdownPreview:"Show Markdown preview",fullscreen:"Fullscreen",exitFullscreen:"Exit fullscreen",zoomIn:"Increase font size",zoomOut:"Decrease font size",resetZoom:"Reset zoom",pluginRequest:"Plugin request",noOptions:"(no options)",inputPlaceholder:"Enter content",soundHeader:"Sound notifications",enableSound:"Enable sound",preview:"Preview",volume:"Volume","sound.question":"Question popup","sound.question.desc":"When ask_user_question appears","sound.done":"Reply finished","sound.done.desc":"When the agent finishes a turn","sound.start":"Reply started","sound.start.desc":"When the agent starts a new turn","sound.error":"Error","sound.error.desc":"When an error notice appears",setupTitle:"pi agent config not detected",setupDesc:"pi-web-ui needs pi's config directory (~/.pi/agent) and at least one API key to run the agent. pi has built-in providers such as openai, anthropic, and deepseek — just pick one and enter a key, no terminal needed.",installFailed:"✖ pi agent installation failed:",retryInstall:"Retry install",skip:"Skip",installDone:"✅ pi agent CLI installed. Pick a provider and enter an API key to start chatting:",provider:"Provider",configured:"configured",providerKeyReady:"This provider already has a key — use it or replace it.",apiKey:"API key",saving:"Saving…",saveAndStart:"Save and start using",recheck:"Recheck",installing:"Installing pi agent CLI…",autoInstall:"Auto-install pi agent",attachment:"Attachment",plugin:"plugin",unknown:"unknown",thinkingWait:"Thinking",exitCode:"Exit code {code}",cancelled:"Cancelled",truncated:"… content too long, truncated in this view",outputTruncated:"… output too long, truncated in this view",refOnlyShort:"Reference only",folderRefShort:"Folder · reference only",inlineLines:"Inline · {n} lines",inlineLinesRange:"Lines {start}-{end}",image:"🖼 Image",bridgedVision:"👁 Transcribed",bridgedVisionDetail:"Image transcribed by the vision bridge (current model can't see images)",folderNotExpanded:"Folder — content not expanded, the agent will browse it as needed",fileNotExpanded:"Large file ({size}) — content not expanded, the agent will read it as needed","role.user":"You","role.assistant":"pi","role.tool":"Tool","role.bash":"Terminal","role.branch":"Branch summary","role.compaction":"Context compacted",welcomeTitle:"pi coding agent",welcomeSub:"Inspect, edit, run — always ready",directory:"Directory",clickToFill:"Click to fill input",waitingResponse:"Waiting for model response…",backToBottom:"Back to bottom",questionNavTitle:"Questions",questionNavTip:"All questions in this conversation — hover to expand, click to jump","ex.understand":"Understand this project","ex.understand.prompt":"Introduce this project: overall structure, main modules, and how to run it?","ex.debug":"Debug an issue","ex.debug.prompt":"Help me debug a bug — describe the symptom first, and I'll add details.","ex.test":"Write tests","ex.test.prompt":"Write unit tests for the core modules.","ex.review":"Code review","ex.review.prompt":"Review the recently changed code and point out potential issues and improvements.",error:"Error",done:"Done",running:"Running…",toolQueued:"Queued",copyArgs:"Copy args",errorOutput:"Error output",output:"Output",waitingOutput:"Waiting for output…",toolDoneWaitingModel:"Done · waiting on model",waitingModel:"Waiting for model response…",thinkingNow:"Thinking",thinkingPreview:"Thinking: {preview}",commands:"Commands",newCommand:"New command",newTerminal:"New terminal",name:"Name",command:"Command",cwdHint:"(${pwd} = current working directory)",noCommands:"No commands yet — click + to add one",clickToRun:"Click to run",edit:"Edit",delete:"Delete",confirmQ:"Confirm?",builtinTerminal:"Built-in terminal",termEmptySub:"Click a command on the left to run it, or + on the right for a new terminal",noTerminal:"No terminals",exited:"(exited{code})",closeTerminal:"Close terminal",rerun:"Reload .pi/commands.json",terminalTitle:"Terminal {n}",exampleName:"e.g. start dev server",exampleCommand:"e.g. npm run dev",scmTab:"Git",scmTitle:"Source Control",scmRefreshTip:"Re-query git status & diff",scmCurrentBranch:"Current branch",scmUpstreamGone:"Upstream deleted",scmAheadBehind:"↑{ahead} ↓{behind}",scmDetached:"Detached HEAD",scmSelectBranch:"Select branch…",scmRemoteBranches:"Remote branches",scmStageTip:"Stage {path}",scmUnstageTip:"Unstage {path}",scmSwitch:"Switch",scmSwitchBranch:"Switch branch",scmSwitchBranchTip:"Runs git checkout {branch} in the terminal",scmPush:"Push",scmPushTip:"Runs git push in the terminal",scmPull:"Pull",scmPullTip:"Runs git pull in the terminal",scmCommit:"Commit",scmCommitTip:'Runs git add -A && git commit -m "…" in the terminal (commits all changes incl. untracked)',scmCommitPlaceholder:"Type a commit message…",scmChanges:"Changes",scmHistory:"Commit tree",scmCommitDetail:"Commit details",scmSelectCommitHint:"Click a commit on the left to view its details",scmNoHistory:"No commits yet",scmNoChanges:"Working tree clean — no changes",scmNotGitRepo:"Current directory is not a Git repository",scmLoading:"Querying…",scmConnecting:"Waiting for connection…",scmDiff:"Diff",scmSelectFileHint:"Click a file on the left to view its diff",scmNoDiff:"(no diff)",scmStaged:"Staged",scmUnstaged:"Unstaged",scmStagedUnstaged:"Staged + unstaged",scmUntracked:"Untracked",scmUntrackedNote:"Untracked file — not shown in diff, included on commit",scmQueryFailed:"Git query failed: {error}",scmTooManyFailures:"Git queries keep failing — click refresh to retry",scmRunsInTerminal:"Commit / branch switch / push / pull run in the terminal",scmViewTerminal:"Open terminal",editProvider:"Edit provider",builtinProviders:"Built-in providers",hintKeyOnly:"Just enter an API key",configuredBadge:"✓ Configured",keyReady:"Key ready",replaceKey:"Replace key",replaceKeyTitle:"Replace the saved key",clearKey:"Clear",clearKeyTitle:"Remove this provider's key stored in auth.json; it returns to unconfigured (env-var sourced keys can't be cleared here)",clearKeyConfirm:"Clear the stored key for {id}? Its models will leave the list until you configure it again.",pasteKey:"Paste API key…",savingKey:"Saving",saveKey:"Save key",customProviders:"Custom providers",customDesc:"For Ollama / vLLM / OpenAI-compatible proxies, etc. Written to pi's models.json — hot-reloaded immediately.",noCustomProviders:"No custom providers yet",modelsCount:"{n} models",addProvider:"Add provider",providerId:"Provider ID",providerIdHint:"(required, e.g. ollama / my-proxy)",displayName:"Display name",displayNamePh:"My proxy",apiType:"API type",baseUrlHint:"(OpenAI-compatible endpoint)",apiKeyHint:"sk-… (optional — uses the auth.json key)",authHeader:"Auto-add Authorization header",modelsTitle:"Models",modelIdReq:"Model ID (required)",text:"Text",textImage:"Text+image",contextWindow:"Context",maxOutput:"Max output",removeModel:"Remove model",addModel:"Add model",deleteProviderConfirm:"Delete provider {id} and its {n} models?",fetchModels:"Fetch model list",fetchModelsHint:"Pull model IDs from the baseUrl /models endpoint (server-side, no CORS)",fetchingModels:"Fetching…",fetchModelsOk:"Fetched {n} models",fetchModelsEmpty:"The endpoint returned no models",fetchModelsErr:"Fetch failed: {msg}",fetchModelsNeedBaseUrl:"Enter a baseUrl first",goalBarTitle:"Goal",goalBarPlaceholder:"Set a goal; the agent's output is auto-reviewed…",goalBarSet:"Start",goalBarClear:"Cancel",goalBarLocked:"Locked: applies to every later turn",goalBarUnlocked:"This turn only (cleared afterwards)",goalBarReviewModel:"Review model",goalBarUseMainModel:"Use the main model",goalBarMaxRounds:"Max rounds",goalBarMaxRoundsTip:"Max review-revision rounds; 0 or empty = unlimited (keep revising until it passes)",goalBarUnlimitedShort:"Unlimited",goalBarReviewing:"Reviewing…",goalBarRound:"Round {n}",goalBarActive:"Goal active",goalBarPassed:"Passed",goalBarFailed:"Failed",goalBarStatusPending:"Waiting to generate…",goalWizardBtn:"AI Scrape",goalWizardTip:"Let AI refine the requirement into a goal via a Q&A survey",goalWizardRunning:"Scoping the goal",goalWizardAnswer:"Answer",goalWizardCard:"Goal survey",settings:"Settings",settingsTitle:"Settings",settingsDesc:"Changes apply immediately: system prompt, skill and extension toggles rebuild the current session; review instructions and review skills affect later goal reviews (main-session changes are deferred while streaming).",settingsSystemPrompt:"System prompt",settingsPromptMode:"Mode",promptModeAppend:"Append",promptModeReplace:"Replace",promptAppendHint:"Append mode: your text is appended to the end of the default system prompt (recommended — keeps the default behavior constraints).",promptReplaceHint:"Replace mode: your text fully replaces the system prompt (project context and skills are still appended automatically). After switching, the editor shows the built-in default prompt ready to edit; blurring without changes keeps the default.",promptPlaceholder:"Type a custom system prompt… (applied on blur)",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",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.",settingsExtensions:"Extensions",settingsPresets:"Presets",settingsEnabled:"Enabled",settingsDisabled:"Disabled",presetNamePlaceholder:"Preset name…",saveAsPreset:"Save as preset",applyPreset:"Apply",deletePreset:"Delete preset",noSkills:"No skills",noExtensions:"No extensions",noPresets:"No presets yet (tune the settings above, then save them as a preset)",loadingSession:"Loading session…",connectingServer:"Connecting to pi-web-ui server…"},Ot=l.createContext(null);function Hs(){try{const t=localStorage.getItem(At);if(t==="zh"||t==="en")return t}catch{}return"zh"}function Us({children:t}){const[s,a]=l.useState(Hs),n=l.useCallback(i=>{a(i);try{localStorage.setItem(At,i)}catch{}},[]),r=l.useCallback((i,c)=>{let h=Ws[i];if(s==="zh"&&(h=Os[i]),c)for(const[d,m]of Object.entries(c))h=h.replaceAll(`{${d}}`,String(m));return h},[s]);l.useEffect(()=>{document.documentElement.lang=s==="zh"?"zh-CN":"en"},[s]);const o=l.useMemo(()=>({locale:s,setLocale:n,t:r}),[s,n,r]);return e.jsx(Ot.Provider,{value:o,children:t})}function nt(){const t=l.useContext(Ot);if(!t)throw new Error("useI18n must be used within LanguageProvider");return t}function ie(){return nt().t}const qs=["off","minimal","low","medium","high","xhigh","max"];function Wt({chat:t,send:s,onManageModels:a,compact:n=!1}){const r=ie(),o=t.state,i=o==null?void 0:o.model,c=i?`${i.provider}/${i.id}`:null,[h,d]=l.useState(!1),[m,f]=l.useState(!1),[v,g]=l.useState(!1),w=o!=null&&o.availableThinkingLevels&&o.availableThinkingLevels.length>0?new Set(o.availableThinkingLevels):null,F=qs.map(C=>({value:C,label:r(`thinking.${C}`),supported:w?w.has(C):!0})),j=C=>{var D;return((D=F.find(y=>y.value===C))==null?void 0:D.label)??C};return l.useEffect(()=>{h&&t.models.length===0&&!v&&(g(!0),s({type:"list_models"}))},[h,t.models.length,v,s]),l.useEffect(()=>{t.models.length>0&&g(!1)},[t.models.length]),e.jsxs(e.Fragment,{children:[e.jsxs(pe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Fe,{}),e.jsx("span",{className:"chip-model",children:i?i.name:r("selectModel")}),!n&&(i==null?void 0:i.vision)&&e.jsx("span",{className:"chip-vision",title:r("vision"),children:"🖼"}),!n&&i&&e.jsx("span",{className:"chip-sub",children:i.provider})]}),open:h,onOpenChange:d,children:[e.jsx("div",{className:"dd-header",children:r("availableModels")}),(v||t.modelsLoading)&&e.jsx("div",{className:"dd-loading",children:r("loading")}),t.models.length===0&&!v&&!t.modelsLoading&&e.jsx("div",{className:"dd-loading",children:r("noModels")}),t.models.map(C=>e.jsx(me,{active:c===C.id,onClick:()=>{c!==C.id&&s({type:"set_model",modelId:C.id}),d(!1)},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:C.name}),e.jsxs("span",{className:"dd-model-meta",children:[e.jsx("span",{className:"dd-model-provider",children:C.provider}),(C.reasoning||C.vision)&&e.jsxs("span",{className:"dd-model-badges",children:[C.reasoning&&e.jsx("span",{className:"dd-model-badge",children:r("reasoning")}),C.vision&&e.jsx("span",{className:"dd-model-badge",children:r("vision")})]})]})]})},C.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"list_models"}),children:r("refreshModels")}),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>{d(!1),a()},children:r("manageModels")})]}),e.jsxs(pe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ke,{}),e.jsx("span",{className:"chip-sub",children:r("thinkingChip",{level:o?j(o.thinkingLevel):"—"})})]}),open:m,onOpenChange:f,children:[e.jsx("div",{className:"dd-header",children:r("thinkingLevel")}),F.map(C=>e.jsx(me,{active:(o==null?void 0:o.thinkingLevel)===C.value,disabled:!C.supported,title:C.supported?void 0:r("thinkingUnsupported"),onClick:()=>{(o==null?void 0:o.thinkingLevel)!==C.value&&s({type:"set_thinking",level:C.value}),f(!1)},children:C.label},C.value))]})]})}const Ks=[{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 xt({settings:t,onChange:s,onPreview:a}){const n=ie(),r=o=>s({...t,...o});return e.jsxs("div",{className:"sound-menu",children:[e.jsx("div",{className:"dd-header",children:n("soundHeader")}),e.jsxs("label",{className:"sound-row sound-master",children:[e.jsxs("span",{className:"sound-label",children:[e.jsx(Pt,{className:"sound-icon"}),e.jsx("span",{children:n("enableSound")})]}),e.jsx("input",{type:"checkbox",checked:t.enabled,onChange:o=>r({enabled:o.target.checked})})]}),Ks.map(({kind:o,labelKey:i,descKey:c})=>e.jsxs("label",{className:`sound-row ${t.enabled?"":"disabled"}`,children:[e.jsxs("span",{className:"sound-label",children:[e.jsx("span",{className:"sound-name",children:n(i)}),e.jsx("span",{className:"sound-desc",children:n(c)})]}),e.jsxs("span",{className:"sound-right",children:[e.jsx("button",{type:"button",className:"sound-preview",title:n("preview"),disabled:!t.enabled,onClick:h=>{h.preventDefault(),a(o)},children:n("preview")}),e.jsx("input",{type:"checkbox",checked:t[o],disabled:!t.enabled,onChange:h=>r({[o]:h.target.checked})})]})]},o)),e.jsxs("div",{className:`sound-volume ${t.enabled?"":"disabled"}`,children:[e.jsx("span",{className:"sound-name",children:n("volume")}),e.jsx("input",{type:"range",min:0,max:100,step:5,value:t.volume,disabled:!t.enabled,onChange:o=>r({volume:Number(o.target.value)})}),e.jsxs("span",{className:"sound-vol-num",children:[t.volume,"%"]})]})]})}function zs({chat:t,send:s,view:a,onViewChange:n,onOpenPanel:r,onManageModels:o,onOpenSettings:i,onOpenBgTasks:c,sound:h,onSoundChange:d,onSoundPreview:m,themes:f,theme:v,onThemeChange:g}){var U;const{locale:w,setLocale:F,t:j}=nt(),[C,D]=l.useState(!1),[y,I]=l.useState(!1),[M,E]=l.useState(!1),[k,S]=l.useState(!1),[B,O]=l.useState(!1),[N,R]=l.useState(!1),J=[{value:"zh",label:j("langZh")},{value:"en",label:j("langEn")}],A=t.ready?j("connected"):t.status==="closed"?j("reconnecting"):j("connecting"),b=t.ready?"ok":"busy",z=()=>{var u,L,W,G;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",((u=t.update)==null?void 0:u.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")})]}),((L=t.update)==null?void 0:L.pendingRestart)&&e.jsx("div",{className:"dd-note ok",children:j("updateSuccess")}),t.update&&!t.update.pendingRestart&&t.update.upToDate&&e.jsx("div",{className:"dd-note ok",children:j("upToDate")}),t.update&&!t.update.pendingRestart&&!t.update.upToDate&&t.update.latest&&e.jsx("div",{className:"dd-note warn",children:j("updateAvailable",{version:t.update.latest})}),((W=t.update)==null?void 0:W.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.updateResult&&!t.updateResult.ok&&e.jsx("div",{className:"dd-note err",children:j("updateFailed",{detail:t.updateResult.detail})}),((G=t.update)==null?void 0:G.pendingRestart)&&e.jsx("div",{className:"dd-note",children:j("restartHint")})]}),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.pendingRestart&&!t.update.upToDate&&t.update.latest&&e.jsx("button",{type:"button",className:`dd-refresh accent ${N?"armed":""}`,onClick:()=>{if(!N){R(!0);return}R(!1),S(!1),O(!1),s({type:"update_app"})},children:j(N?"confirmUpdate":"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:()=>r("left"),children:e.jsx(Ms,{})}),e.jsx("span",{className:"brand-logo",children:"π"}),e.jsx("span",{className:"brand-name",children:"pi-web-ui"}),e.jsx("span",{className:`conn-dot ${b}`,title:A}),e.jsx("span",{className:"conn-label",children:A})]}),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":a==="chat",className:a==="chat"?"active":"",onClick:()=>n("chat"),children:[e.jsx(ze,{}),e.jsx("span",{children:j("chat")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":a==="terminal",className:a==="terminal"?"active":"",onClick:()=>n("terminal"),children:[e.jsx(Ze,{}),e.jsx("span",{children:j("terminal")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":a==="git",className:a==="git"?"active":"",onClick:()=>n("git"),children:[e.jsx(Ee,{}),e.jsx("span",{children:j("scmTab")})]})]}),e.jsxs("div",{className:"topbar-desktop",children:[e.jsxs("button",{type:"button",className:"chip bg-task-chip","data-tip":j("bgTasksTip"),onClick:c,children:[e.jsx(De,{}),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.jsx(Wt,{chat:t,send:s,onManageModels:o}),e.jsxs("button",{type:"button",className:"chip",title:j("settingsTitle"),onClick:i,children:[e.jsx(Be,{}),e.jsx("span",{className:"chip-sub",children:j("settings")})]}),e.jsx(pe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Pt,{}),e.jsx("span",{className:"chip-sub",children:j("sound")})]}),open:C,onOpenChange:D,children:e.jsx(xt,{settings:h,onChange:d,onPreview:m})}),e.jsxs(pe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ps,{}),e.jsx("span",{className:"chip-sub",children:w==="zh"?j("langZh"):"EN"})]}),open:y,onOpenChange:I,children:[e.jsx("div",{className:"dd-header",children:j("language")}),J.map(u=>e.jsx(me,{active:w===u.value,onClick:()=>{F(u.value),I(!1)},children:u.label},u.value))]}),e.jsxs(pe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(ks,{}),e.jsx("span",{className:"chip-sub",children:j("theme")})]}),open:M,onOpenChange:E,children:[e.jsx("div",{className:"dd-header",children:j("theme")}),e.jsx(me,{active:v===null,onClick:()=>{g(null),E(!1)},children:j("themeDefault")}),f.map(u=>e.jsx(me,{active:v===u.id,onClick:()=>{g(u.id),E(!1)},children:u.name},u.id))]}),e.jsxs(pe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(et,{}),e.jsxs("span",{className:"chip-sub",children:["v",((U=t.update)==null?void 0:U.current)??"…"]}),t.update&&!t.update.upToDate&&!t.update.pendingRestart&&e.jsx("span",{className:"update-dot",title:j("updateAvailable",{version:t.update.latest??""})})]}),open:k,onOpenChange:u=>{S(u),R(!1),u&&s({type:"check_update"})},fit:!0,children:[e.jsx("div",{className:"dd-header",children:j("update")}),z()]}),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(gt,{})})]}),e.jsxs("button",{type:"button",className:"chip newchat","data-tip":j("newChatTip"),onClick:()=>s({type:"new_chat"}),children:[e.jsx(xe,{}),e.jsx("span",{children:j("newChat")})]}),e.jsx("div",{className:"topbar-more",children:e.jsxs(pe,{trigger:e.jsxs(e.Fragment,{children:[e.jsx(Ss,{}),e.jsx("span",{className:"chip-sub",children:j("more")}),t.update&&!t.update.upToDate&&!t.update.pendingRestart&&e.jsx("span",{className:"update-dot"})]}),open:B,onOpenChange:u=>{O(u),R(!1),u&&s({type:"check_update"})},children:[e.jsx("div",{className:"dd-header",children:j("sound")}),e.jsx("div",{className:"dd-header",children:j("settings")}),e.jsxs(me,{onClick:()=>{O(!1),i()},children:[e.jsx(Be,{})," ",j("settingsTitle")]}),e.jsxs(me,{onClick:()=>{O(!1),c()},children:[e.jsx(De,{})," ",j("bgTasks"),t.bgServers.length>0&&e.jsx("em",{className:"bg-task-badge",children:t.bgServers.length})]}),e.jsx(xt,{settings:h,onChange:d,onPreview:m}),e.jsx("div",{className:"dd-header",children:j("language")}),J.map(u=>e.jsx(me,{active:w===u.value,onClick:()=>F(u.value),children:u.label},u.value)),e.jsx("div",{className:"dd-header",children:j("theme")}),e.jsx(me,{active:v===null,onClick:()=>{g(null),O(!1)},children:j("themeDefault")}),f.map(u=>e.jsx(me,{active:v===u.id,onClick:()=>{g(u.id),O(!1)},children:u.name},u.id)),e.jsx("div",{className:"dd-header",children:j("update")}),z(),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(gt,{})," ",j("githubRepo")]})]})}),e.jsx("button",{type:"button",className:"panel-toggle",title:j("openFiles"),onClick:()=>r("right"),children:e.jsx(ke,{})})]})]})}function vt(t){const s=new Date(t),a=new Date;return s.toDateString()===a.toDateString()?`${String(s.getHours()).padStart(2,"0")}:${String(s.getMinutes()).padStart(2,"0")}`:`${s.getMonth()+1}/${s.getDate()}`}function Vs({chat:t,send:s,active:a}){var m,f,v;const n=ie(),r=(m=t.state)==null?void 0:m.sessionFile,o=(f=t.state)==null?void 0:f.cwd,i=t.sessions,c=t.projects;l.useEffect(()=>{var g;!a||!t.ready||t.status!=="open"||(g=t.state)!=null&&g.cwd&&(s({type:"list_sessions"}),s({type:"list_projects"}))},[a,t.ready,t.status,(v=t.state)==null?void 0:v.cwd,s]);const h=g=>{const w=g.name||g.firstMessage.trim();return w.length>0?w:n("emptyChat")},d=g=>g.split(/[\\/]/).pop()||g;return e.jsxs("aside",{className:"panel panel-left",children:[c.length>0&&e.jsxs("div",{className:"panel-projects",children:[e.jsx("div",{className:"panel-section-title",children:n("recentProjects")}),e.jsx("div",{className:"projects-scroll",children:c.map(g=>{const w=o===g.path;return e.jsxs("button",{type:"button",className:`project-item ${w?"active":""}`,title:g.path,onClick:()=>{w||s({type:"set_cwd",path:g.path})},children:[e.jsx(ke,{className:"project-icon"}),e.jsxs("span",{className:"project-info",children:[e.jsx("span",{className:"project-name",children:d(g.path)}),e.jsx("span",{className:"project-path",children:g.path})]}),e.jsx("span",{className:"project-time",children:vt(g.lastUsed)})]},g.path)})})]}),t.conversations.length>0&&e.jsxs("div",{className:"panel-convs",children:[e.jsx("div",{className:"panel-section-title",children:n("runningConversations")}),t.conversations.map(g=>{const w=t.activeConversationId===g.id;return e.jsxs("button",{type:"button",className:`session-item ${w?"active":""}`,title:g.title,onClick:()=>{w||s({type:"switch_conversation",id:g.id})},children:[e.jsx(ze,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:g.title}),e.jsx("span",{className:"session-sub",children:w?n("current"):n("messageCount",{n:g.messageCount})})]}),g.isStreaming&&e.jsx("span",{className:"conv-streaming",title:n("streaming")})]},g.id)}),e.jsx("div",{className:"panel-section-divider"})]}),e.jsxs("div",{className:"panel-sessions",children:[e.jsx("div",{className:"panel-section-title",children:n("historySessions")}),e.jsxs("div",{className:"sessions-scroll",children:[i.length===0&&e.jsx("div",{className:"panel-empty",children:n("noHistory")}),i.map(g=>{const w=r===g.path;return e.jsxs("button",{type:"button",className:`session-item ${w?"active":""}`,title:g.path,onClick:()=>{w||s({type:"switch_session",path:g.path})},children:[e.jsx(ze,{className:"session-icon"}),e.jsxs("span",{className:"session-info",children:[e.jsx("span",{className:"session-title",children:h(g)}),e.jsxs("span",{className:"session-sub",children:[w?n("current"):n("messageCount",{n:g.messageCount}),g.source==="tui"&&e.jsx("span",{className:"session-src",title:n("tuiTip"),children:"TUI"})]})]}),e.jsx("span",{className:"session-time",children:vt(g.modified)})]},g.path)})]})]})]})}function _e(){if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();const t=new Uint8Array(16);if(typeof crypto<"u"&&typeof crypto.getRandomValues=="function")crypto.getRandomValues(t);else for(let a=0;a<16;a++)t[a]=Math.floor(Math.random()*256);t[6]=t[6]&15|64,t[8]=t[8]&63|128;const s=[...t].map(a=>a.toString(16).padStart(2,"0")).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}const Ht="pi-web-ui:token";function Gs(){try{const t=new URL(window.location.href),s=t.searchParams.get("token");s&&(localStorage.setItem(Ht,s.trim()),t.searchParams.delete("token"),window.history.replaceState(null,"",t.toString()))}catch{}}function Js(){try{return localStorage.getItem(Ht)??""}catch{return""}}function Ae(t){const s=Js();return s?`${t}${t.includes("?")?"&":"?"}token=${encodeURIComponent(s)}`:t}function Qs(t,s){const a=s.assistantMessageEvent,n=t.stats.tokens,r=s.usage!==null?{...n,...s.usage}:n,o=r===n?t.stats:{...t.stats,tokens:r};if(a.type!=="text_delta"&&a.type!=="thinking_delta")return o===t.stats?t:{...t,stats:o};const i=a.delta??"";if(!i)return o===t.stats?t:{...t,stats:o};const c=t.streamingMessage??null,h=c&&c.id===s.messageId?c:{id:s.messageId,content:[]},d=[...h.content],m=a.type==="thinking_delta"?"thinking":"text",f=a.contentIndex??d.length-1;return f>=0&&f<d.length&&d[f].type===m?d[f]=m==="thinking"?{type:"thinking",thinking:(d[f].thinking??"")+i}:{type:"text",text:(d[f].text??"")+i}:d.push(m==="thinking"?{type:"thinking",thinking:i}:{type:"text",text:i}),{...t,stats:o,streamingMessage:{...h,id:s.messageId,content:d}}}const Ys=1,yt=2e5,Zs=2e5,Xs={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 en(){const t=new Map,s=new Map,a=(n,r)=>`${n}:${r}`;return{write(n,r,o){const i=a(n,r),c=t.get(i);if(c&&c.size>0){for(const m of c)try{m.write(o)}catch{}return}const h=s.get(i)??"",d=h.length+o.length>Zs?o:h+o;s.set(i,d)},register(n,r,o){const i=a(n,r);let c=t.get(i);c||(c=new Set,t.set(i,c)),c.add(o);const h=s.get(i);if(h){try{o.write(h)}catch{}s.delete(i)}return()=>{const d=t.get(i);d&&(d.delete(o),d.size===0&&t.delete(i)),s.delete(i)}},clear(){t.clear(),s.clear()}}}function tn(t,s){const a=new Set;for(const r of s.messages)r.role==="toolResult"&&r.toolCallId&&a.add(r.toolCallId),r.role==="bashExecution"&&a.add(`bash-${r.id}`);let n=!1;for(const r of t.keys())a.has(r)&&(t.delete(r),n=!0);return n?new Map(t):t}function sn(t,s){let a=!1;for(const n of t.keys())s.messages.some(o=>o.role==="toolResult"&&o.toolCallId===n)&&(t.delete(n),a=!0);return a?new Map(t):t}function nn(t,s){var a,n,r,o;switch(s.type){case"status":return{...t,status:s.status,ready:s.status==="open"?t.ready:!1,terminals:s.status==="closed"?[]:t.terminals};case"ready":return{...t,serverVersion:s.serverVersion,ready:!0,protocolMismatch:s.protocolVersion!==void 0&&s.protocolVersion!==Ys};case"snapshot":return{...t,ready:!0,state:s.state,activeConversationId:s.state.conversationId,liveOutputs:tn(t.liveOutputs,s.state),toolStatuses:sn(t.toolStatuses,s.state)};case"tool_delta":{const i=t.liveOutputs.get(s.toolCallId),c=((i==null?void 0:i.text)??"")+s.delta,h=c.length>yt?c.slice(0,yt):c,d=new Map(t.liveOutputs);return d.set(s.toolCallId,{toolName:s.toolName,text:h}),{...t,liveOutputs:d}}case"message_delta":{const i=t.state;return!i||i.conversationId!==s.msg.conversationId?t:{...t,state:Qs(i,s.msg)}}case"tool_status":return{...t,toolStatuses:new Map(t.toolStatuses).set(s.status.toolCallId,s.status)};case"notice":return{...t,notices:[...t.notices,s.notice].slice(-6)};case"dismiss_notice":return{...t,notices:t.notices.filter(i=>i.id!==s.id)};case"sessions":return{...t,sessions:s.sessions};case"conversations":return{...t,conversations:s.conversations,activeConversationId:s.activeId};case"projects":return{...t,projects:s.projects};case"files":return{...t,files:s.files};case"file_changed":return{...t,fileChanged:{path:s.path}};case"file_content":return{...t,fileContent:s.content};case"models":return{...t,models:s.models,modelsLoading:s.loading};case"models_config":return{...t,modelsConfig:s.providers};case"providers_status":return{...t,providers:s.providers};case"fetch_models_result":return{...t,fetchModelsResult:s.result};case"refresh_provider_result":return{...t,refreshProviderResult:s.result};case"install_result":return{...t,installResult:s.result};case"scm_data":return{...t,scmData:s.data};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_result":return{...t,updateResult:s.result};case"widgets":return{...t,widgets:s.widgets};case"statuses":return{...t,statuses:s.statuses};case"dialog":return{...t,dialog:s.dialog};case"commands":return{...t,commands:s.commands,commandsPath:s.path};case"slash_commands":return{...t,slashCommands:s.commands};case"goal_status":return{...t,goal:s.status};case"settings":return{...t,settings:s.settings};case"bg_servers":return{...t,bgServers:s.servers};case"terminal_add":return{...t,terminals:[...t.terminals,s.meta]};case"terminal_remove":return{...t,terminals:t.terminals.filter(i=>i.id!==s.id)};case"terminal_exit":return s.conversationId&&(t.activeConversationId||(a=t.state)!=null&&a.conversationId)&&s.conversationId!==(t.activeConversationId||((n=t.state)==null?void 0:n.conversationId))?t:{...t,terminals:t.terminals.map(i=>i.id===s.terminalId?{...i,running:!1,exitCode:s.exitCode}:i)};case"terminal_restart":return{...t,terminals:t.terminals.map(i=>i.id===s.terminalId?{...i,running:!0,exitCode:null}:i)};case"terminal_list":return s.conversationId&&(t.activeConversationId||(r=t.state)!=null&&r.conversationId)&&s.conversationId!==(t.activeConversationId||((o=t.state)==null?void 0:o.conversationId))?t:{...t,terminals:s.terminals.map(i=>{var c;return{...i,conversationId:s.conversationId??((c=t.state)==null?void 0:c.conversationId)??""}})};default:return t}}const jt="pi-web-client-id";let He=null;function at(){if(He)return He;let t=null;try{t=sessionStorage.getItem(jt),t||(t=_e(),sessionStorage.setItem(jt,t))}catch{t=t??_e()}return He=t,t}function an(){const t=location.protocol==="https:"?"wss:":"ws:";return Ae(`${t}//${location.host}/ws`)}function rn(){const[t,s]=l.useReducer(nn,{status:"connecting",ready:!1,state:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:[],conversations:[],activeConversationId:"",projects:[],files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],installResult:null,pathCompletions:[],update:null,updateResult:null,widgets:[],statuses:[],dialog:null,commands:[],commandsPath:"",slashCommands:[],terminals:[],goal:Xs,bgServers:[],settings:null,fetchModelsResult:null,refreshProviderResult:null,scmData:null,scmDirty:0,protocolMismatch:!1}),a=l.useRef(null),n=l.useRef(en()),r=l.useRef(0),o=l.useRef(null),i=l.useRef(!0),c=l.useRef(0),h=l.useRef(0),d=l.useRef(new Map),m=l.useRef(null),f=(M,E)=>{var B;const k=d.current,S=k.get(M);if(S!==void 0&&E!==S+1&&!m.current){const O=I.current.chat,N=O.activeConversationId||((B=O.state)==null?void 0:B.conversationId);M===N&&(m.current=setTimeout(()=>{m.current=null;const R=a.current;R&&R.readyState===WebSocket.OPEN&&R.send(JSON.stringify({type:"get_state"}))},300))}k.set(M,E)},v=l.useCallback((M,E)=>{const k=++h.current;s({type:"notice",notice:{id:k,level:M,text:E}})},[]),g=l.useCallback(M=>{const E=a.current;return E&&E.readyState===WebSocket.OPEN?(E.send(JSON.stringify(M)),!0):!1},[]),w=l.useCallback(()=>{if(!i.current)return;s({type:"status",status:"connecting"});const M=new WebSocket(an());a.current=M,M.onopen=()=>{a.current===M&&(s({type:"status",status:"open"}),r.current=0,c.current=Date.now(),M.send(JSON.stringify({type:"hello",clientId:at()})))},M.onmessage=E=>{if(a.current!==M)return;c.current=Date.now();let k;try{k=JSON.parse(E.data)}catch{return}switch(k.type){case"ready":s({type:"ready",serverVersion:k.serverVersion,protocolVersion:k.protocolVersion}),M.send(JSON.stringify({type:"get_state"})),M.send(JSON.stringify({type:"list_files"})),M.send(JSON.stringify({type:"list_models"})),M.send(JSON.stringify({type:"list_commands"})),M.send(JSON.stringify({type:"get_commands"})),M.send(JSON.stringify({type:"check_update"}));break;case"snapshot":d.current=new Map,s({type:"snapshot",state:k.state});break;case"tool_delta":f(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":{f(k.conversationId,k.seq),s({type:"message_delta",msg:k});break}case"notice":{const S=++h.current;s({type:"notice",notice:{id:S,level:k.level,text:k.text}});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"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"scm_data":s({type:"scm_data",data:k});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_result":s({type:"update_result",result:k});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"terminal_output":n.current.write(k.conversationId??I.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}},M.onclose=()=>{if(a.current===M&&(a.current=null),n.current.clear(),!i.current||a.current&&a.current!==M)return;s({type:"status",status:"closed"});const E=Math.min(1e3*2**r.current,1e4);r.current+=1,o.current=setTimeout(()=>{o.current=null,w()},E)},M.onerror=()=>{}},[]);l.useEffect(()=>{i.current=!0,w();const M=setInterval(()=>{if(!i.current)return;const E=a.current;E&&E.readyState===WebSocket.OPEN&&Date.now()-c.current>3e4&&E.close()},5e3);return()=>{var E;i.current=!1,clearInterval(M),o.current&&(clearTimeout(o.current),o.current=null),(E=a.current)==null||E.close(),a.current=null}},[w]);const F=l.useCallback(M=>s({type:"dismiss_notice",id:M}),[]),j=l.useCallback(M=>s({type:"terminal_add",meta:M}),[]),C=l.useCallback(M=>s({type:"terminal_remove",id:M}),[]),D=l.useCallback(M=>s({type:"terminal_restart",terminalId:M}),[]),y=l.useCallback((M,E,k)=>n.current.register(M,E,k),[]),I=l.useRef({chat:t,send:g,pushNotice:v,dismissNotice:F,terminal:{create:j,close:C,register:y,restart:D}});return I.current={chat:t,send:g,pushNotice:v,dismissNotice:F,terminal:{create:j,close:C,register:y,restart:D}},I.current}const ln=200*1024*1024,on=/windows/i.test(navigator.userAgent),cn=/[<>:"/\\|?*\u0000-\u001f]/g,dn=/[. ]+$/,un=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function mn(t){const s=t.replace(cn,"_").replace(dn,"");return s?un.test(s)?`_${s}`:s:"_"}function bt(t,s=!0){const a=new URLSearchParams({clientId:at(),path:t,...s?{download:"1"}:{}});return Ae(`/api/file?${a}`)}async function pn(t,s){const a=on?mn(s):s;try{const n=await fetch(bt(t));if(!n.ok)return{ok:!1,cancelled:!1,error:await n.text().catch(()=>"")||(n.status===404?"文件不存在":`HTTP ${n.status}`)};if(Number(n.headers.get("content-length")??"0")>ln)return window.location.assign(bt(t)),{ok:!0};const o=await n.blob();return window.showSaveFilePicker&&window.isSecureContext?hn(o,a):Je(o,a)}catch(n){return{ok:!1,cancelled:!1,error:n instanceof Error?n.message:String(n)}}}async function hn(t,s){let a;const n=window.showSaveFilePicker;if(!n)return Je(t,s);try{a=await n({suggestedName:s})}catch(r){return r instanceof DOMException&&r.name==="AbortError"?{ok:!1,cancelled:!0}:Je(t,s)}try{const r=await a.createWritable();return await r.write(t),await r.close(),{ok:!0}}catch(r){return{ok:!1,cancelled:!1,error:r instanceof Error?r.message:String(r)}}}function Je(t,s){const a=URL.createObjectURL(t),n=document.createElement("a");return n.href=a,n.download=s,document.body.appendChild(n),n.click(),n.remove(),setTimeout(()=>URL.revokeObjectURL(a),1e4),{ok:!0}}function gn({chat:t,send:s,onAttach:a,onPreview:n,onNotice:r}){var D;const o=ie(),[i,c]=l.useState(""),[h,d]=l.useState(!1),m=t.files,f=1e4,v=l.useRef(0),g=l.useRef(void 0),w=l.useCallback((y,I)=>{const M=++v.current;c(y),I!=null&&I.silent||d(!0),s({type:"list_files",path:y===""?void 0:y})||v.current===M&&d(!1)},[s]);l.useEffect(()=>{m&&m.path===i&&d(!1)},[m,i]),l.useEffect(()=>{var M;const y=(M=t.state)==null?void 0:M.cwd;if(y!==g.current){g.current=y,w("",{silent:!0});return}const I=setInterval(()=>{document.visibilityState!=="hidden"&&w(i,{silent:!0})},f);return()=>clearInterval(I)},[(D=t.state)==null?void 0:D.cwd,i,w]),l.useEffect(()=>{const y=t.fileChanged;y&&y.path===i&&w(i,{silent:!0})},[t.fileChanged,i,w]);const F=y=>w(y),j=()=>{(m==null?void 0:m.parent)!==null&&(m==null?void 0:m.parent)!==void 0&&w(m.parent)},C=i.split("/").filter(Boolean);return e.jsxs("aside",{className:"panel panel-right",children:[e.jsxs("div",{className:"panel-crumbs",children:[e.jsx("button",{type:"button",className:`crumb ${i===""?"active":""}`,onClick:()=>w(""),children:o("rootDir")}),C.map((y,I)=>{const M=C.slice(0,I+1).join("/");return e.jsxs("span",{className:"crumb-seg",children:[e.jsx($e,{}),e.jsx("button",{type:"button",className:`crumb ${M===i?"active":""}`,onClick:()=>w(M),children:y})]},M)})]}),e.jsxs("div",{className:"panel-body",children:[h&&e.jsx("div",{className:"panel-empty",children:o("loading")}),!h&&m&&m.path===i&&e.jsxs(e.Fragment,{children:[m.path!==""&&e.jsxs("button",{type:"button",className:"file-item dir",onClick:j,children:[e.jsx(ke,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:".."})]}),m.entries.map(y=>y.type==="dir"?e.jsxs("div",{className:"file-item dir",children:[e.jsxs("button",{type:"button",className:"file-dir-main",onClick:()=>F(y.path),children:[e.jsx(ke,{className:"file-icon"}),e.jsx("span",{className:"file-name",children:y.name})]}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":o("linkFolderTip"),onClick:()=>a(y.path,y.name,"reference",!0),children:e.jsx(Ve,{})})]},y.path):e.jsxs("div",{className:"file-item file",children:[e.jsxs("button",{type:"button",className:"file-name",title:`${y.path} — ${o("previewFile")}`,onClick:()=>n(y.path,y.name),children:[e.jsx(Bt,{className:"file-icon"}),e.jsx("span",{className:"file-name-text",children:y.name})]}),e.jsx("button",{type:"button",className:"file-attach download","data-tip":o("downloadFile"),onClick:()=>{pn(y.path,y.name).then(I=>{I.ok||I.cancelled||r("error",o("downloadFailed",{error:I.error}))})},children:e.jsx(et,{})}),e.jsx("button",{type:"button",className:"file-attach inline","data-tip":o("attachInlineTip"),onClick:()=>a(y.path,y.name,"inline"),children:e.jsx(xe,{})}),e.jsx("button",{type:"button",className:"file-attach ref","data-tip":o("referenceTip"),onClick:()=>a(y.path,y.name,"reference"),children:e.jsx(Ve,{})})]},y.path)),m.truncated&&e.jsx("div",{className:"panel-empty files-truncated",children:o("filesTruncated")})]}),!h&&!m&&e.jsx("div",{className:"panel-empty",children:o("noFiles")})]}),t.widgets.filter(y=>y.lines.length>0).length>0&&e.jsx("div",{className:"panel-widgets",children:t.widgets.filter(y=>y.lines.length>0).map(y=>e.jsxs("div",{className:"widget",children:[e.jsx("div",{className:"widget-title",children:y.key}),e.jsx("pre",{className:"widget-lines",children:y.lines.join(`
3
+ `)})]},y.key))})]})}var fn=Rt();const xn=l.memo(function({text:s}){const a=ie(),[n,r]=l.useState(!1);return s?e.jsx("button",{type:"button",className:"copy-btn",title:a("copy"),onClick:()=>{navigator.clipboard.writeText(s).then(()=>{r(!0),setTimeout(()=>r(!1),1200)})},children:n?e.jsx(st,{}):e.jsx(_t,{})}):null}),Oe=l.memo(function({text:s}){return e.jsx("div",{className:"md",children:e.jsx(as,{remarkPlugins:[rs],rehypePlugins:[[is,{detect:!0,ignoreMissing:!0}]],components:{pre:({children:a,...n})=>e.jsxs("div",{className:"codeblock",children:[e.jsx(xn,{text:Qe(a)}),e.jsx("pre",{...n,children:a})]})},children:s})})});function Qe(t){if(typeof t=="string")return t;if(Array.isArray(t))return t.map(Qe).join("");if(t&&typeof t=="object"&&"props"in t){const s=t.props;return Qe(s==null?void 0:s.children)}return""}function vn({thinking:t,streaming:s}){const a=ie(),[n,r]=l.useState(s),o=t.split(`
4
+ `)[0].slice(0,80);return e.jsxs("div",{className:`thinking ${n?"open":""} ${s?"live":""}`,children:[e.jsxs("button",{type:"button",className:"thinking-toggle",onClick:()=>r(i=>!i),children:[n?e.jsx(ve,{}):e.jsx($e,{}),e.jsx(Fe,{className:"thinking-icon"}),e.jsx("span",{className:"thinking-label",children:s?e.jsxs("span",{className:"thinking-live-label",children:[a("thinkingNow"),e.jsx("span",{className:"dots"})]}):n?a("thinking"):a("thinkingPreview",{preview:o})})]}),n&&e.jsx("div",{className:"thinking-body",children:t})]})}const yn={bash:"$",read:"📄",write:"✍️",edit:"✏️",grep:"🔍",find:"🧭",ls:"📂"};function jn(t){return yn[t]??"🛠"}const bn=l.memo(function({block:s,view:a,onKillBash:n}){var I,M,E,k;const r=ie(),[o,i]=l.useState(!0),[c,h]=l.useState(!1),d=!a.result&&a.streaming&&!a.status,m=s.name==="bash"&&d,f=a.result!==void 0,v=!a.result&&!!a.status,g=((I=a.result)==null?void 0:I.isError)??((M=a.status)==null?void 0:M.isError)??!1,w=a.result?a.result.content.map(S=>S.type==="text"?S.text:"").join(""):a.liveOutput??"",F=g?"err":f?"ok":d||v?"run":"idle";let j=r(g?"error":f?"done":d?"running":v?"toolDoneWaitingModel":"toolQueued");const C=v&&((E=a.status)==null?void 0:E.durationMs)!==void 0?Nn(a.status.durationMs):"";v&&C&&(j=`${j} · ${C}`);const D=v&&((k=a.status)==null?void 0:k.exitCode)!==void 0?`exit ${a.status.exitCode}`:"",y=()=>{s.argumentsText&&(navigator.clipboard.writeText(s.argumentsText),h(!0),setTimeout(()=>h(!1),1200))};return e.jsxs("div",{className:`toolcall ${F}`,children:[e.jsxs("div",{className:"toolcall-head",children:[e.jsx("span",{className:"toolcall-icon",children:jn(s.name)}),e.jsx("span",{className:"toolcall-name",children:s.name}),e.jsxs("span",{className:"toolcall-status",children:[j,D&&e.jsx("em",{className:"toolcall-exit",children:D})]}),e.jsx("span",{className:"toolcall-spacer"}),m&&n&&e.jsxs("button",{type:"button",className:"toolcall-kill",title:r("stopBashTip"),onClick:n,children:[e.jsx(Pe,{}),e.jsx("span",{children:r("stopBash")})]}),e.jsx("button",{type:"button",className:"toolcall-copy",title:r("copyArgs"),onClick:y,children:c?e.jsx(_s,{}):e.jsx(_t,{})}),e.jsx("button",{type:"button",className:"toolcall-toggle",onClick:()=>i(S=>!S),children:o?e.jsx(ve,{}):e.jsx($e,{})})]}),o&&e.jsxs("div",{className:"toolcall-body",children:[s.argumentsText&&e.jsx("div",{className:"toolcall-args",children:s.name==="bash"&&s.argumentsText.startsWith("{")?e.jsx(kn,{args:s.argumentsText}):e.jsx("pre",{children:s.argumentsText})}),w.length>0&&e.jsxs("div",{className:"toolcall-output",children:[e.jsxs("div",{className:"toolcall-output-label",children:[r(g?"errorOutput":"output"),(d||v)&&e.jsx("span",{className:"cursor"})]}),e.jsx("pre",{children:w})]}),d&&w.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",r("waitingOutput")]}),v&&w.length===0&&e.jsxs("div",{className:"toolcall-waiting",children:[e.jsx("span",{className:"cursor"})," ",r("waitingModel")]})]})]})});function kn({args:t}){let s=null;try{s=JSON.parse(t)}catch{return e.jsx("pre",{children:t})}return typeof s.command!="string"?e.jsx("pre",{children:t}):e.jsxs("div",{className:"termline",children:[e.jsx(Ze,{className:"termline-icon"}),e.jsx("code",{children:s.command}),typeof s.timeout=="number"&&e.jsxs("span",{className:"termline-timeout",children:["⏱ ",s.timeout,"s"]})]})}function Nn(t){if(t===void 0)return"";const s=t/1e3;if(s<60)return`${s.toFixed(1)}s`;const a=Math.floor(s/60),n=Math.round(s%60);return`${a}m ${String(n).padStart(2,"0")}s`}const wn=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function it(t){var a;const s=t.match(wn);return s?{name:s[1],location:s[2],content:s[3],userMessage:((a=s[4])==null?void 0:a.trim())||void 0}:null}function Ne(t){return t.type==="text"&&typeof t.text=="string"?t:null}function Ut(t){return t.type==="thinking"&&typeof t.thinking=="string"?t:null}function qt(t){return t.type==="toolCall"&&typeof t.id=="string"&&typeof t.name=="string"?t:null}function Kt(t){return t.type==="image"&&typeof t.dataUrl=="string"?t:null}function zt(t){return t.type==="bash"&&typeof t.command=="string"?t:null}const kt=l.memo(function({message:s,toolResults:a,liveOutputs:n,toolStatuses:r,streaming:o,isLast:i,onEdit:c,onKillBash:h,onCollapse:d,qnIndex:m,qnActive:f,onJump:v}){const g=ie(),[w,F]=l.useState(!1),[j,C]=l.useState("");if(s.role==="toolResult")return null;const D=s.role==="custom"&&s.customType==="file",y=s.content.map(R=>{var J;return((J=Ne(R))==null?void 0:J.text)??""}).filter(Boolean).join(`
5
+ `),I=s.role==="user"?it(y):null,M=I?I.userMessage??`skill:${I.name}`:y.split(`
6
+ `).join(" ").trim(),E=o&&i&&s.content.length===0,k=s.role==="user"&&!o&&!E&&!!c,S=()=>{C(I?`/skill:${I.name}${I.userMessage?` ${I.userMessage}`:""}`:s.content.map(R=>{var J;return((J=Ne(R))==null?void 0:J.text)??""}).filter(Boolean).join(`
7
+ `)),F(!0)},B=()=>{const R=j.trim();R&&(c==null||c(s.id,R),F(!1))},O=s.role==="custom"&&(s.customType==="goal-review"||s.customType==="goal-wizard"),N=s.role==="custom"&&s.customType==="goal-wizard";return e.jsxs("div",{className:`msg msg-${s.role}${O?" 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"?N?g("goalWizardCard"):O?g("goalBarTitle"):s.customType==="file"?g("attachment"):`${g("plugin")} · ${s.customType??g("unknown")}`:Vt(s.role,g)}),s.model&&e.jsx("span",{className:"msg-model",children:s.model}),s.timestamp&&e.jsx("span",{className:"msg-time",children:Mn(s.timestamp)}),d&&e.jsxs("button",{type:"button",className:"msg-collapse-btn",title:g("collapseMsg"),onClick:()=>d(s.id),children:[e.jsx(tt,{})," ",g("collapseMsg")]}),m!==void 0&&v&&e.jsxs("button",{type:"button",className:`qn-tag ${f?"active":""}`,title:`${m+1}. ${M}`,"aria-label":`${m+1}. ${M}`,onClick:()=>v(s.id),children:[e.jsx("span",{className:"qn-tag-bar"}),e.jsx("span",{className:"qn-tag-idx",children:m+1})]})]}),e.jsx("div",{className:"msg-body",children:w?e.jsxs("div",{className:"msg-editor",children:[e.jsx("textarea",{className:"msg-editor-input",value:j,autoFocus:!0,placeholder:g("editPlaceholder"),rows:Math.max(2,Math.min(10,j.split(`
8
+ `).length+1)),onChange:R=>C(R.target.value),onKeyDown:R=>{R.key==="Enter"&&(R.metaKey||R.ctrlKey)?(R.preventDefault(),B()):R.key==="Escape"&&F(!1)}}),e.jsxs("div",{className:"msg-editor-actions",children:[e.jsx("span",{className:"msg-editor-hint",children:g("editHint")}),e.jsx("button",{type:"button",className:"chip",onClick:()=>F(!1),children:g("cancel")}),e.jsxs("button",{type:"button",className:"chip primary",disabled:!j.trim(),title:g("reaskFromHere"),onClick:B,children:[e.jsx(Ge,{})," ",g("reaskFromHere")]})]})]}):e.jsxs(e.Fragment,{children:[s.errorMessage&&e.jsx("div",{className:"msg-error",children:s.errorMessage}),D?e.jsx(Cn,{message:s}):I?e.jsxs(e.Fragment,{children:[e.jsx(Tn,{block:I}),I.userMessage&&e.jsx("div",{className:"msg-text",children:e.jsx(Oe,{text:I.userMessage})}),s.content.map((R,J)=>R.type==="text"?null:e.jsx(wt,{block:R,toolResults:a,liveOutputs:n,toolStatuses:r,streaming:o,isLast:i,onKillBash:h},`${s.id}-${J}`))]}):s.content.map((R,J)=>e.jsx(wt,{block:R,toolResults:a,liveOutputs:n,toolStatuses:r,streaming:o,isLast:i,onKillBash:h},`${s.id}-${J}`)),E&&e.jsxs("div",{className:"thinking-wait",children:[g("thinkingWait"),e.jsx("span",{className:"dot"})]}),o&&i&&!E&&e.jsx("span",{className:"stream-cursor"})]})}),k&&!w&&e.jsx("div",{className:"msg-actions",children:e.jsxs("button",{type:"button",className:"msg-action",title:g("editReaskTip"),onClick:S,children:[e.jsx(Ge,{})," ",g("editReask")]})})]})});function Cn({message:t}){const s=ie(),[a,n]=l.useState(!1),r=t.details??{},o=r.name??r.path??s("attachment"),i=r.type==="folder",c=r.mode==="reference",h=r.mode==="bridged",d=t.content.filter(g=>g.type==="text").map(g=>g.text).join(`
9
+ `),m=Sn(d),f=t.content.find(g=>g.type==="image"),v=m.split(`
10
+ `).length;return e.jsxs("div",{className:`attachcard ${c?"reference":""}`,children:[e.jsxs("button",{type:"button",className:"attachcard-head",onClick:()=>n(g=>!g),children:[e.jsx("span",{className:"attachcard-icon",children:i?"📁":"📎"}),e.jsx("span",{className:"attachcard-name",children:o}),r.path&&e.jsx("span",{className:"attachcard-path",children:r.path}),e.jsx("span",{className:`attachcard-mode ${r.mode==="lines"?"lines":c?"ref":h?"bridged":"inline"}`,children:c?i?s("folderRefShort"):`${s("refOnlyShort")} · ${Nt(r.size)}`:h?s("bridgedVision"):f?s("image"):r.mode==="lines"?s("inlineLinesRange",{start:r.startLine??1,end:r.endLine??r.lines??1}):s("inlineLines",{n:r.lines??v})}),!c&&(a?e.jsx(ve,{}):e.jsx($e,{}))]}),!c&&a&&(h?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"attachcard-bridgenote",children:s("bridgedVisionDetail")}),(f==null?void 0:f.dataUrl)&&e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:f.dataUrl,alt:o})}),m&&e.jsx("pre",{className:"attachcard-content",children:m})]}):f!=null&&f.dataUrl?e.jsx("div",{className:"attachcard-image",children:e.jsx("img",{src:f.dataUrl,alt:o})}):e.jsx("pre",{className:"attachcard-content",children:m})),c&&e.jsx("div",{className:"attachcard-refnote",children:i?s("folderNotExpanded"):s("fileNotExpanded",{size:Nt(r.size)})})]})}function Nt(t){return t===void 0?"":t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}function Sn(t){const s=t.match(/^\s*<file path="[^"]*"(?:\s+lines="[^"]*")?>\s*```\s*\n?([\s\S]*?)\n?```\s*<\/file>\s*$/);if(s)return s[1].trim();const a=t.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return a?a[1].trim():t.trim()}function Tn({block:t}){const s=ie(),[a,n]=l.useState(!1);return e.jsxs("div",{className:`skillcard${a?" expanded":""}`,children:[e.jsxs("button",{type:"button",className:"skillcard-head",onClick:()=>n(r=>!r),title:t.location,children:[e.jsx("span",{className:"skillcard-icon",children:e.jsx(Fs,{})}),e.jsx("span",{className:"skillcard-name",children:t.name}),e.jsx("span",{className:"skillcard-path",children:t.location}),e.jsxs("span",{className:"skillcard-action",children:[a?e.jsx(tt,{}):e.jsx(ve,{}),s(a?"collapseMsg":"expandMsg")]})]}),a&&e.jsx("div",{className:"skillcard-body",children:e.jsx(Oe,{text:t.content})})]})}function wt({block:t,toolResults:s,liveOutputs:a,toolStatuses:n,streaming:r,isLast:o,onKillBash:i}){const c=ie(),h=Ne(t);if(h)return e.jsxs("div",{className:"msg-text",children:[e.jsx(Oe,{text:h.text}),h.truncated&&e.jsx("div",{className:"trunc-note",children:c("truncated")})]});const d=Ut(t);if(d)return e.jsx(vn,{thinking:d.thinking,streaming:r&&o});const m=qt(t);if(m){const g=s.get(m.id),w=a.get(m.id),F={result:g,liveOutput:w==null?void 0:w.text,streaming:r,status:n.get(m.id)};return e.jsx(bn,{block:m,view:F,onKillBash:i})}const f=Kt(t);if(f&&f.dataUrl)return e.jsx("div",{className:"msg-image",children:e.jsx("img",{src:f.dataUrl,alt:"attachment"})});const v=zt(t);return v?e.jsxs("div",{className:"bashblock",children:[e.jsxs("div",{className:"bashblock-command",children:[e.jsx("span",{className:"bashblock-prompt",children:"$"}),e.jsx("code",{children:v.command}),v.exitCode!==void 0&&e.jsx("span",{className:`bashblock-exit ${v.exitCode===0?"ok":"err"}`,children:c("exitCode",{code:v.exitCode})}),v.cancelled&&e.jsx("span",{className:"bashblock-exit err",children:c("cancelled")})]}),v.output&&e.jsx("pre",{className:"bashblock-output",children:v.output}),v.truncated&&e.jsx("div",{className:"trunc-note",children:c("outputTruncated")})]}):null}function Vt(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 Mn(t){const s=new Date(t),a=String(s.getHours()).padStart(2,"0"),n=String(s.getMinutes()).padStart(2,"0");return`${a}:${n}`}const En=l.memo(function({message:s,onExpand:a}){const n=ie();let r="";for(const f of s.content){const v=Ne(f);if(v&&v.text.trim()){const g=it(v.text);g?r=`skill:${g.name}`+(g.userMessage?` · ${g.userMessage.replace(/\s+/g," ").trim()}`:""):r=v.text.replace(/\s+/g," ").trim();break}}if(!r&&s.role==="custom"&&s.customType==="file"){const f=s.details??{};r=f.name??f.path??""}r.length>90&&(r=`${r.slice(0,90)}…`);let i=0,c=0,h=0,d=0;for(const f of s.content)Ut(f)?i++:qt(f)?c++:zt(f)?h++:Kt(f)&&d++;const m=[];return i&&m.push(`${n("thinking")} ${i}`),c&&m.push(`${n("toolCalls")} ${c}`),h&&m.push(`${n("bashRuns")} ${h}`),d&&m.push(`${n("images")} ${d}`),e.jsxs("button",{type:"button",className:"msg-collapsed","data-msg-id":s.id,title:`${n("expandMsg")} · ${r||m.join(" · ")||s.role}`,onClick:()=>a(s.id),children:[e.jsx("span",{className:`msg-collapsed-role role-${s.role}`,children:s.role==="custom"&&s.customType==="file"?n("attachment"):Vt(s.role,n)}),e.jsxs("span",{className:"msg-collapsed-body",children:[r&&e.jsx("span",{className:"msg-collapsed-preview",children:r}),m.length>0&&e.jsx("span",{className:"msg-collapsed-chips",children:m.map((f,v)=>e.jsx("span",{className:"msg-collapsed-chip",children:f},v))})]}),s.timestamp?e.jsx("span",{className:"msg-collapsed-time",children:Rn(s.timestamp)}):null,e.jsxs("span",{className:"msg-collapsed-action",children:[e.jsx(ve,{})," ",n("expandMsg")]})]})});function Rn(t){const s=new Date(t),a=String(s.getHours()).padStart(2,"0"),n=String(s.getMinutes()).padStart(2,"0");return`${a}:${n}`}const Ct=new Map,Ln=15,In=30;function St(t){return t.content.some(s=>s.type==="toolCall")}const Pn=[{key:"ex.understand",icon:"🔍"},{key:"ex.debug",icon:"🐛"},{key:"ex.test",icon:"🧪"},{key:"ex.review",icon:"🧹"}];function Bn(t){return Pn.map(({key:s,icon:a})=>({icon:a,text:t(s),prompt:t(`${s}.prompt`)}))}function Dn({state:t,liveOutputs:s,toolStatuses:a,onEdit:n,onKillBash:r}){const o=ie(),i=l.useRef(null),[c,h]=l.useState(!0),d=l.useRef(!0),[m,f]=l.useState(()=>new Set),v=t.streamingMessage?[...t.messages,t.streamingMessage]:t.messages,g=l.useMemo(()=>{const u=new Map;for(const L of t.messages)L.role==="toolResult"&&L.toolCallId&&u.set(L.toolCallId,L);return u},[t.messages]),w=v.length>0?v[v.length-1].id:null,F=t.messages.length>In?Math.max(0,t.messages.length-Ln):0,j=l.useMemo(()=>{const u=[];for(const L of t.messages){if(L.role!=="user")continue;const W=L.content.map(Q=>{var te;return((te=Ne(Q))==null?void 0:te.text)??""}).filter(Boolean).join(" "),G=it(W),$=G?G.userMessage??`skill:${G.name}`:W.trim();$&&u.push({id:L.id,text:$})}return u},[t.messages]),C=l.useMemo(()=>{const u=new Map;return j.forEach((L,W)=>u.set(L.id,W)),u},[j]),[D,y]=l.useState(-1),I=l.useRef(-1),M=l.useRef(j);l.useEffect(()=>{M.current=j},[j]);const E=l.useCallback(()=>{const u=i.current,L=M.current;if(!u||L.length===0)return;const W=u.getBoundingClientRect().top,G=140;let $=-1;for(let Q=0;Q<L.length;Q++){const te=u.querySelector(`[data-msg-id="${L[Q].id}"]`);if(te)if(te.getBoundingClientRect().top<=W+G)$=Q;else break}$!==I.current&&(I.current=$,y($))},[]);l.useEffect(()=>{E()},[j,E]);const k=l.useCallback(u=>{f(L=>L.has(u)?L:new Set(L).add(u))},[]),S=l.useCallback(u=>{f(L=>{if(!L.has(u))return L;const W=new Set(L);return W.delete(u),W})},[]),B=l.useCallback(u=>{const L=t.messages.findIndex(G=>G.id===u);L>=0&&L<F&&!m.has(u)&&fn.flushSync(()=>k(u));const W=M.current.findIndex(G=>G.id===u);I.current=W,y(W),requestAnimationFrame(()=>{var $,Q;const G=($=i.current)==null?void 0:$.querySelector(`[data-msg-id="${u}"]`);G&&((Q=i.current)==null||Q.querySelectorAll(".msg-flash").forEach(te=>te.classList.remove("msg-flash")),G.scrollIntoView({block:"start"}),G.classList.remove("msg-flash"),G.offsetWidth,G.classList.add("msg-flash"))})},[t.messages,F,m,k]),O=l.useCallback(()=>{const u=i.current;if(!u)return;const L=u.scrollHeight-u.scrollTop-u.clientHeight<80;d.current=L,h(L),E()},[E]);l.useEffect(()=>{const u=i.current;u&&d.current&&(u.scrollTop=u.scrollHeight)},[v,t.isStreaming,s]);const N=l.useCallback(()=>{const u=i.current;u&&(u.scrollTop=u.scrollHeight),d.current=!0,h(!0)},[]),R=l.useRef(null);l.useEffect(()=>{const u=R.current,L=i.current;if(!u||!L)return;const W=G=>{G.preventDefault();const $=u.querySelector(".qn-list");if($&&$.contains(G.target)&&$.scrollHeight>$.clientHeight){$.scrollTop+=G.deltaY;return}L.scrollTop+=G.deltaY};return u.addEventListener("wheel",W,{passive:!1}),()=>u.removeEventListener("wheel",W)},[]);const[J,A]=l.useState(0);l.useEffect(()=>{const u=()=>{var L;return A(((L=i.current)==null?void 0:L.clientHeight)??0)};return u(),window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[]);const b=j.length,z=l.useMemo(()=>b===0?27:Math.max(4,Math.min(27,Math.floor(((J||600)-16)/b)-3)),[b,J]),U=z<20;return e.jsxs("div",{className:"messages-wrap",children:[e.jsxs("div",{className:"messages",ref:i,onScroll:O,children:[t.messages.length===0&&!t.streamingMessage&&e.jsxs("div",{className:"empty-state",children:[e.jsx("div",{className:"empty-logo-wrap",children:e.jsx("div",{className:"empty-logo",children:"π"})}),e.jsx("h2",{className:"empty-title",children:o("welcomeTitle")}),e.jsx("p",{className:"empty-sub",children:o("welcomeSub")}),e.jsxs("div",{className:"empty-cwd",children:[e.jsx("span",{className:"empty-cwd-label",children:o("directory")}),e.jsx("span",{className:"empty-cwd-path",children:t.cwd})]}),e.jsx("div",{className:"empty-examples",children:Bn(o).map(u=>e.jsxs("button",{type:"button",className:"empty-example",title:o("clickToFill"),onClick:()=>window.dispatchEvent(new CustomEvent("pi-web:fill",{detail:u.prompt})),children:[e.jsx("span",{className:"empty-example-icon",children:u.icon}),e.jsx("span",{className:"empty-example-text",children:u.text})]},u.prompt))})]}),t.messages.map((u,L)=>{const W=L<F,G=W&&m.has(u.id);if(W&&!G)return u.role==="toolResult"?null:e.jsx(En,{message:u,onExpand:k},u.id);const $=u.role==="user"?C.get(u.id):void 0;return e.jsx(kt,{message:u,qnIndex:$,qnActive:$!==void 0?$===D:void 0,onJump:B,toolResults:g,liveOutputs:St(u)?s:Ct,toolStatuses:a,streaming:t.isStreaming,onKillBash:r,isLast:u.id===w,onEdit:n,onCollapse:G?S:void 0},u.id)}),t.streamingMessage&&e.jsx(kt,{message:t.streamingMessage,toolResults:g,liveOutputs:St(t.streamingMessage)?s:Ct,toolStatuses:a,streaming:!0,isLast:!0,onEdit:n,onKillBash:r},t.streamingMessage.id),t.isStreaming&&v.length===0&&e.jsx("div",{className:"streaming-wait",children:o("waitingResponse")})]}),!c&&e.jsxs("button",{type:"button",className:"scroll-bottom",onClick:N,children:[e.jsx($t,{})," ",o("backToBottom")]}),j.length>0&&e.jsxs("div",{className:`qn-rail ${U?"many":""}`,ref:R,"aria-label":o("questionNavTitle"),style:{"--rail-gap":`${z}px`},children:[j.map((u,L)=>e.jsx("button",{type:"button",className:`qn-bar ${L===D?"active":""}`,"aria-label":`${L+1}. ${u.text}`,onClick:()=>B(u.id),children:e.jsxs("span",{className:"qn-bar-text",children:[L+1,". ",u.text]})},u.id)),U&&e.jsx("div",{className:"qn-list",children:j.map((u,L)=>e.jsxs("button",{type:"button",className:`qn-list-item ${L===D?"active":""}`,"aria-label":`${L+1}. ${u.text}`,onClick:()=>B(u.id),children:[e.jsx("span",{className:"qn-list-idx",children:L+1}),e.jsx("span",{className:"qn-list-text",children:u.text})]},u.id))})]})]})}const _n=1568,Fn=2*1024*1024;function Re(t){return t.startsWith("image/")&&t!=="image/svg+xml"&&t!=="image/svg"}async function $n(t){if(!t.type.startsWith("image/"))return null;let s;try{s=await createImageBitmap(t,{imageOrientation:"from-image"})}catch{return null}try{const a=Math.min(1,_n/Math.max(s.width,s.height)),n=Math.max(1,Math.round(s.width*a)),r=Math.max(1,Math.round(s.height*a)),o=t.type==="image/jpeg"||t.type==="image/jpg"?[["image/jpeg",.85],["image/jpeg",.6],["image/webp",.8]]:[["image/png",1],["image/jpeg",.85],["image/jpeg",.6]];let i=null;for(const[c,h]of o){const d=document.createElement("canvas");d.width=n,d.height=r;const m=d.getContext("2d");if(!m)continue;c!=="image/png"&&(m.fillStyle="#ffffff",m.fillRect(0,0,n,r)),m.drawImage(s,0,0,n,r);const f=d.toDataURL(c,h),v=f.match(/^data:([^;]+);base64,/),g=v?v[1]:c,w=f.replace(/^data:[^;]*;base64,/,""),F=Math.floor(w.length*3/4);if(i={data:w,mimeType:g,name:t.name,size:F},F<=Fn)return i}return i}finally{s.close()}}function An({chat:t,send:s,attachments:a,onRemoveAttachment:n,onAddImageFiles:r,onAddLocalFiles:o,onNotice:i,onSent:c,onManageModels:h}){const d=ie(),{locale:m}=nt(),f=p=>m==="en"&&p.descriptionEn?p.descriptionEn:p.description??"",v=p=>m==="en"&&p.argumentHintEn?p.argumentHintEn:p.argumentHint??"",[g,w]=l.useState(""),[F,j]=l.useState(!1),[C,D]=l.useState(null),[y,I]=l.useState(0),[M,E]=l.useState(!1),[k,S]=l.useState(void 0),B=l.useRef(null),O=l.useRef(null),N=l.useRef(null),R={builtin:d("slashBuiltin"),extension:d("slashExtension"),prompt:d("slashPrompt"),skill:d("slashSkill")},J=p=>{const K=p.match(/^\/([^\s]*)$/);if(K&&t.ready){const se=K[1].toLowerCase(),ee=t.slashCommands.filter(Y=>Y.name.toLowerCase().startsWith(se));D(ee.length>0?ee:null),I(0)}else D(null)};l.useEffect(()=>{var K;const p=(K=N.current)==null?void 0:K.querySelector(".slash-item.active");p==null||p.scrollIntoView({block:"nearest"})},[y,C]);const A=p=>{var re;const K=C??[],se=p??K[y%Math.max(K.length,1)];if(!se){D(null);return}const ee=g.match(/^\/([^\s]*)([\s\S]*)$/),Y=ee?ee[2]:"";w(`/${se.name} ${Y}`),D(null),(re=B.current)==null||re.focus()},b=async()=>{var ee;const K=[...((ee=t.state)==null?void 0:ee.messages)??[]].reverse().find(Y=>Y.role==="assistant"&&Y.content.some(re=>re.type==="text"&&re.text)),se=K==null?void 0:K.content.filter(Y=>Y.type==="text").map(Y=>Y.text).join(`
11
+ `);if(!se){i("warning",d("slashCopyEmpty"));return}try{await navigator.clipboard.writeText(se),i("info",d("slashCopied"))}catch{i("error",d("slashCopyFailed"))}},z=p=>{if(!p||p.length===0){i("warning",d("foldersNotSupported"));return}const K=Array.from(p).filter(ee=>Re(ee.type)),se=Array.from(p).filter(ee=>!Re(ee.type));K.length>0&&r(K),se.length>0&&o(se)},U=p=>{var ee;const K=(ee=p.clipboardData)==null?void 0:ee.items;if(!K)return;const se=[];for(const Y of K)if(Y.kind==="file"&&Re(Y.type)){const re=Y.getAsFile();re&&se.push(re)}se.length!==0&&(p.preventDefault(),r(se))},u=t.state,L=(u==null?void 0:u.isStreaming)??!1,W=t.ready,G=u?u.queue.steering+u.queue.followUp:0,$=l.useRef(g);l.useEffect(()=>{$.current=g},[g]),l.useEffect(()=>{J($.current)},[t.slashCommands]),l.useEffect(()=>{const p=K=>{var ee;const se=K.detail;w(se),(ee=B.current)==null||ee.focus()};return window.addEventListener("pi-web:fill",p),()=>window.removeEventListener("pi-web:fill",p)},[]),l.useEffect(()=>{if(!M)return;const p=K=>{K.key==="Escape"&&E(!1)};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[M]),l.useEffect(()=>{const p=B.current;if(!p)return;p.style.height="auto";const K=p.scrollHeight>220;p.style.height=`${Math.min(p.scrollHeight,220)}px`,p.style.overflowY=K?"auto":"hidden"},[g]);const Q=(p=!1)=>{var ee,Y,re,T,_;const K=g.trim(),se=a.some(P=>P.imageData||P.fileData);if(!(!W||!K&&!se)){if(K==="/help"){const P=(Y=(ee=B.current)==null?void 0:ee.closest(".inputbox"))==null?void 0:Y.getBoundingClientRect();S(P==null?void 0:P.width),E(!0),w(""),(re=B.current)==null||re.focus();return}if(K==="/copy"){w(""),(T=B.current)==null||T.focus(),b();return}s({type:"prompt",text:K,queue:p,attachments:a.map(P=>P.imageData?{path:"",imageData:P.imageData,mimeType:P.mimeType,name:P.name}:P.fileData?{path:"",fileData:P.fileData,mimeType:P.mimeType,name:P.name,size:P.size}:{path:P.path,mode:P.mode,...P.lines?{lines:P.lines}:{}})})&&(w(""),c(),(_=B.current)==null||_.focus())}},te=p=>{if(!p.nativeEvent.isComposing){if(C&&C.length>0)switch(p.key){case"ArrowDown":p.preventDefault(),I(K=>(K+1)%C.length);return;case"ArrowUp":p.preventDefault(),I(K=>(K-1+C.length)%C.length);return;case"Tab":case"Enter":p.preventDefault(),A();return;case"Escape":p.preventDefault(),D(null);return}p.key==="Enter"&&!p.shiftKey&&(p.preventDefault(),Q())}},oe=()=>e.jsx("div",{className:"inputbox-actions",children:L?e.jsxs(e.Fragment,{children:[g.trim()!==""&&e.jsxs("button",{type:"button",className:"btn supplement",title:d("supplementTip"),onClick:()=>Q(!0),children:[e.jsx(Ns,{})," ",d("supplement")]}),e.jsx("button",{type:"button",className:"btn stop",title:d("stopAgent"),onClick:()=>s({type:"abort"}),children:e.jsx(Pe,{})})]}):e.jsx("button",{type:"button",className:"btn send",title:d("sendTip"),disabled:!W||!g.trim()&&!a.some(p=>p.imageData||p.fileData),onClick:()=>Q(),children:e.jsx(Ft,{})})});return e.jsxs("div",{className:`inputbar${F?" drop-active":""}`,onDragOver:p=>{p.preventDefault(),p.stopPropagation(),j(!0)},onDragLeave:p=>{p.currentTarget.contains(p.relatedTarget)||j(!1)},onDrop:p=>{var K;p.preventDefault(),p.stopPropagation(),j(!1),z(((K=p.dataTransfer)==null?void 0:K.files)??null)},children:[F&&e.jsx("div",{className:"drop-overlay",children:e.jsxs("span",{children:["📎 ",d("dropHereToAttach")]})}),a.length>0&&e.jsxs("div",{className:"attach-row",children:[a.map(p=>e.jsxs("span",{className:`attach-chip ${p.imageData?"image":p.fileData?"file":p.mode}`,title:p.imageData?d("attachImage",{name:p.name}):p.fileData?d("attachFile",{name:p.name}):p.isDir?d("folderRef",{path:p.path}):p.mode==="reference"?d("refOnly",{path:p.path}):p.mode==="lines"&&p.lines?d("attachLines",{path:p.path,start:p.lines.start,end:p.lines.end}):d("attachContent",{path:p.path}),children:[p.imageData?"🖼":p.fileData?"📄":p.isDir?"📁":p.mode==="reference"?"🔗":"📎"," ",p.name,p.mode==="lines"&&p.lines&&e.jsxs("span",{className:"attach-range",children:["L",p.lines.start,"-",p.lines.end]}),e.jsx("button",{type:"button",className:"attach-remove",title:d("removeAttachment"),onClick:()=>n(p.key??p.path),children:"×"})]},p.key??`${p.path}|${p.mode}|${p.lines?`${p.lines.start}-${p.lines.end}`:""}`)),e.jsx("span",{className:"attach-hint",children:d("attachHint")})]}),L&&G>0&&u&&e.jsxs("div",{className:"queue-hint",children:[u.queue.followUp>0&&e.jsx("span",{children:d("followUpQueued",{n:u.queue.followUp})}),u.queue.steering>0&&e.jsx("span",{children:d("steeringQueued",{n:u.queue.steering})})]}),C&&C.length>0&&e.jsxs("div",{className:"slash-menu",role:"listbox",ref:N,"aria-label":d("slashCommands"),children:[e.jsxs("div",{className:"slash-menu-hint",children:[e.jsx("span",{children:d("slashMenuHint")}),e.jsx("span",{className:"slash-menu-close",onClick:()=>D(null),children:"Esc"})]}),C.map((p,K)=>e.jsxs("button",{type:"button",className:`slash-item${K===y?" active":""}`,onMouseEnter:()=>I(K),onClick:()=>A(p),children:[e.jsxs("span",{className:"slash-name",children:["/",p.name]}),e.jsx("span",{className:`slash-source ${p.source}`,children:R[p.source]}),e.jsxs("span",{className:"slash-desc",children:[f(p),p.argumentHint&&e.jsx("span",{className:"slash-hint",children:v(p)})]})]},p.name))]}),M&&e.jsx("div",{className:"modal-backdrop",onClick:()=>E(!1),children:e.jsxs("div",{className:"slash-help",style:k?{width:k}:void 0,onClick:p=>p.stopPropagation(),children:[e.jsxs("div",{className:"slash-help-head",children:[e.jsxs("span",{children:["⚡ ",d("slashHelpTitle")]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>E(!1),children:d("close")})]}),e.jsx("div",{className:"slash-help-body",children:t.slashCommands.length===0?e.jsx("div",{className:"slash-help-empty",children:d("slashLoading")}):t.slashCommands.map(p=>e.jsxs("div",{className:"slash-help-row",children:[e.jsxs("span",{className:"slash-help-cmd",children:["/",p.name]}),e.jsx("span",{className:`slash-source ${p.source}`,children:R[p.source]}),e.jsxs("span",{className:"slash-help-desc",children:[f(p),p.argumentHint&&e.jsx("span",{className:"slash-hint",children:v(p)})]})]},p.name))})]})}),e.jsxs("div",{className:"inputbox",children:[e.jsx("input",{ref:O,type:"file",multiple:!0,hidden:!0,onChange:p=>{z(p.target.files),p.target.value=""}}),e.jsxs("div",{className:"inputbox-row",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:d("uploadFile"),disabled:!W,onClick:()=>{var p;return(p=O.current)==null?void 0:p.click()},children:e.jsx(ht,{})}),e.jsx("textarea",{ref:B,value:g,rows:1,placeholder:d(W?L?"placeholderStreaming":"placeholderIdle":"placeholderConnecting"),disabled:!W,onChange:p=>{w(p.target.value),J(p.target.value)},onKeyDown:te,onPaste:U}),oe()]}),e.jsxs("div",{className:"input-tools",children:[e.jsx("div",{className:"input-tools-left",children:e.jsx(Wt,{chat:t,send:s,onManageModels:h,compact:!0})}),e.jsxs("div",{className:"input-tools-right",children:[e.jsx("button",{type:"button",className:"btn attach-img",title:d("uploadFile"),disabled:!W,onClick:()=>{var p;return(p=O.current)==null?void 0:p.click()},children:e.jsx(ht,{})}),oe()]})]})]})]})}function On({chat:t,send:s}){var S,B,O,N,R,J;const a=ie(),n=t.goal,r=!n.conversationId||n.conversationId===t.activeConversationId,o=n.goal!==null&&r,[i,c]=l.useState(""),[h,d]=l.useState(n.reviewModel??""),[m,f]=l.useState(n.maxRounds),[v,g]=l.useState(n.locked),[w,F]=l.useState(!1),[j,C]=l.useState(!1),[D,y]=l.useState(!0);l.useEffect(()=>{d(n.reviewModel??""),f(n.maxRounds||0),g(n.locked)},[n.goal,n.reviewModel,n.maxRounds,n.locked]),l.useEffect(()=>{w&&t.models.length===0&&!j&&(C(!0),s({type:"list_models"}))},[w,t.models.length,j,s]),l.useEffect(()=>{t.models.length>0&&C(!1)},[t.models.length]);const I=()=>{var A;return h?((A=t.models.find(b=>b.id===h))==null?void 0:A.name)??h:a("goalBarUseMainModel")},M=()=>{const A=i.trim();A&&(s({type:"set_goal",goal:A,...h?{reviewModel:h}:{},maxRounds:m,locked:v}),c(""),y(!1))},E=()=>{const A=i.trim();A&&(s({type:"start_goal_wizard",text:A,...h?{wizardModel:h}:{},maxRounds:m,locked:v}),c(""),y(!1))},k=(((S=n.wizard)==null?void 0:S.active)??!1)&&r;return k?e.jsx("div",{className:`goalbar goalbar-active ${k?"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:((B=n.wizard)==null?void 0:B.draft)??"",children:[a("goalWizardRunning"),": ",(O=n.wizard)==null?void 0:O.draft]}),e.jsxs("span",{className:"goalbar-chip reviewing",children:[a("goalBarRound",{n:(((N=n.wizard)==null?void 0:N.step)??0)+1})," ","/ ",((R=n.wizard)==null?void 0:R.maxSteps)??6]}),e.jsx("span",{className:"goalbar-detail",children:((J=n.wizard)==null?void 0:J.status)||a("goalBarReviewing")}),e.jsx("button",{type:"button",className:"goalbar-x",title:a("goalBarClear"),onClick:()=>{s({type:"clear_goal"}),y(!0)},children:e.jsx(he,{})})]})}):o?e.jsx("div",{className:`goalbar goalbar-active ${n.reviewing?"reviewing":""}`,children:e.jsxs("div",{className:"goalbar-active-row",children:[e.jsx("span",{className:"goalbar-icon",children:n.reviewing?e.jsx("span",{className:"goalbar-spin",children:"◌"}):"🎯"}),e.jsx("span",{className:"goalbar-text",title:n.goal??"",children:n.goal}),n.reviewing?e.jsxs("span",{className:"goalbar-chip reviewing",children:[a("goalBarReviewing")," ",a("goalBarRound",{n:n.round})]}):e.jsx("span",{className:`goalbar-chip ${n.verdict==="pass"?"pass":n.verdict==="fail"?"fail":""}`,children:n.verdict==="pass"?a("goalBarPassed"):n.verdict==="fail"?a("goalBarFailed"):`${a("goalBarRound",{n:n.round||1})} · ${n.locked?a("goalBarLocked"):a("goalBarUnlocked")}`}),e.jsx("span",{className:"goalbar-detail",children:n.status}),e.jsx("button",{type:"button",className:"goalbar-x",title:a("goalBarClear"),disabled:n.reviewing,onClick:()=>{s({type:"clear_goal"}),y(!0)},children:e.jsx(he,{})})]})}):D?e.jsx("div",{className:"goalbar goalbar-collapsed",children:e.jsxs("button",{type:"button",className:"goalbar-hint",title:a("goalBarPlaceholder"),onClick:()=>y(!1),children:[e.jsx(pt,{})," ",e.jsx("span",{children:a("goalBarTitle")})]})}):e.jsxs("div",{className:"goalbar",children:[e.jsxs("div",{className:"goalbar-row",children:[e.jsx("span",{className:"goalbar-icon",children:e.jsx(pt,{})}),e.jsx("input",{className:"goalbar-input",value:i,placeholder:a("goalBarPlaceholder"),onChange:A=>c(A.target.value),onKeyDown:A=>{A.key==="Enter"&&M()}}),e.jsx("button",{type:"button",className:"goalbar-btn",disabled:!i.trim(),onClick:M,children:a("goalBarSet")}),e.jsxs("button",{type:"button",className:"goalbar-btn wizard",disabled:!i.trim(),title:a("goalWizardTip"),onClick:E,children:["🔍 ",a("goalWizardBtn")]}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:a(v?"goalBarLocked":"goalBarUnlocked"),onClick:()=>g(A=>(s({type:"set_goal_prefs",locked:!A}),!A)),children:v?e.jsx(Rs,{}):e.jsx(bs,{})}),e.jsx("button",{type:"button",className:"goalbar-icon-btn",title:a("goalBarClear"),onClick:()=>y(!0),children:e.jsx(tt,{})})]}),e.jsxs("div",{className:"goalbar-opts",children:[e.jsxs(pe,{trigger:e.jsxs("span",{className:"goalbar-opt",children:[a("goalBarReviewModel"),": ",e.jsx("b",{children:I()})]}),open:w,onOpenChange:F,direction:"up",children:[e.jsx("div",{className:"dd-header",children:a("goalBarReviewModel")}),(j||t.modelsLoading)&&e.jsx("div",{className:"dd-loading",children:a("loading")}),t.models.length===0&&!j&&!t.modelsLoading&&e.jsx("div",{className:"dd-loading",children:a("noModels")}),e.jsx(me,{active:h==="",onClick:()=>{d(""),F(!1),s({type:"set_goal_prefs",reviewModel:""})},children:a("goalBarUseMainModel")}),t.models.map(A=>e.jsx(me,{active:h===A.id,onClick:()=>{d(A.id),F(!1),s({type:"set_goal_prefs",reviewModel:A.id})},children:e.jsxs("span",{className:"dd-model-cell",children:[e.jsx("span",{className:"dd-model-name",children:A.name}),e.jsx("span",{className:"dd-model-meta",children:e.jsx("span",{className:"dd-model-provider",children:A.provider})})]})},A.id)),e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"list_models"}),children:a("refreshModels")})]}),e.jsxs("label",{className:"goalbar-round",title:a("goalBarMaxRoundsTip"),children:[e.jsx("span",{children:a("goalBarMaxRounds")}),e.jsx("input",{type:"number",min:0,step:1,value:m,placeholder:a("goalBarUnlimitedShort"),onChange:A=>{const b=parseInt(A.target.value,10);if(Number.isNaN(b)||b<0){f(0);return}f(b)},onBlur:()=>s({type:"set_goal_prefs",maxRounds:m}),onKeyDown:A=>{A.key==="Enter"&&(s({type:"set_goal_prefs",maxRounds:m}),A.target.blur())}})]}),e.jsx("span",{className:"goalbar-lock-hint",children:a(v?"goalBarLocked":"goalBarUnlocked")})]})]})}function Wn({chat:t,send:s}){const a=ie(),n=t.state,[r,o]=l.useState(!1),[i,c]=l.useState(""),[h,d]=l.useState(0),m=l.useRef(null),f=t.pathCompletions;if(l.useEffect(()=>{if(!r)return;const S=setTimeout(()=>{s({type:"complete_path",path:i})},150);return()=>clearTimeout(S)},[i,r,s]),l.useEffect(()=>d(0),[f]),l.useEffect(()=>{const S=document.querySelector(`.status-completions .pc-item[data-idx="${h}"]`);S==null||S.scrollIntoView({block:"nearest"})},[h]),!n)return null;const v=n.stats,g=t.ready?"ok":"busy",w=t.ready?a("connected"):a("connecting"),F=v.contextUsage,j=F.tokens!==null&&F.percent!==null?`${Tt(F.tokens)} / ${Tt(F.contextWindow)}`:"—",C=F.percent??null,D=C===null?"":C>=80?"warn":C>=50?"mid":"ok",y=n.queue.steering+n.queue.followUp,I=()=>{c(n.cwd),o(!0)},M=(S,B)=>{var N;const O=S.includes("\\")?"\\":"/";c(B?`${S}${O}`:S),d(0),(N=m.current)==null||N.focus()},E=S=>{const B=S.trim();B&&B!==n.cwd&&s({type:"set_cwd",path:B}),o(!1)},k=S=>{if(S.key==="ArrowDown")S.preventDefault(),d(B=>Math.min(B+1,f.length-1));else if(S.key==="ArrowUp")S.preventDefault(),d(B=>Math.max(B-1,0));else if(S.key==="Tab"&&f.length>0){S.preventDefault();const B=f[Math.min(h,f.length-1)];M(B.path,B.type==="dir")}else if(S.key==="Enter"&&!S.nativeEvent.isComposing){const B=i.trim();if(B.endsWith("/")||B.endsWith("\\"))E(B);else if(f.some(O=>O.path===B))E(B);else if(f.length>0&&f[h]){S.preventDefault();const O=f[h];M(O.path,O.type==="dir")}else E(B)}else S.key==="Escape"&&(f.length>0?(S.stopPropagation(),s({type:"complete_path",path:""})):o(!1))};return e.jsxs("footer",{className:"statusbar",children:[e.jsx("span",{className:`status-dot ${g}`,title:w}),e.jsx("span",{className:"status-item",children:w}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item status-ctx",title:a("contextUsage"),children:[a("context"),e.jsx("span",{className:`ctx-bar ${D}`,children:C!==null&&e.jsx("span",{className:"ctx-bar-fill",style:{width:`${Math.min(C,100)}%`}})}),j]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:a("cumulativeCost"),children:["$",Hn(v.cost)]}),e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item",title:a("sessionMessages"),children:[a("messages")," ",v.totalMessages]}),t.statuses.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsx("span",{className:"status-item ext-status",title:a("pluginStatus"),children:t.statuses.map(S=>S.text).join(" · ")})]}),n.isStreaming&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"status-sep",children:"·"}),e.jsxs("span",{className:"status-item working",children:[e.jsx("span",{className:"working-spin"}),a("working"),y>0&&e.jsxs("span",{className:"status-queue",children:["⏳ ",y," ",a("queued")]})]})]}),r?e.jsxs("div",{className:"status-cwd-wrap",children:[e.jsx("input",{ref:m,className:"status-cwd-input",value:i,autoFocus:!0,placeholder:a("enterPath"),onChange:S=>c(S.target.value),onKeyDown:k,onBlur:()=>o(!1)}),f.length>0&&e.jsx("ul",{className:"status-completions",onMouseDown:S=>S.preventDefault(),children:f.map((S,B)=>e.jsx("li",{children:e.jsxs("button",{type:"button","data-idx":B,className:`pc-item ${B===h?"sel":""}`,onMouseEnter:()=>d(B),onClick:()=>M(S.path,S.type==="dir"),children:[e.jsx("span",{className:"pc-icon",children:S.type==="dir"?e.jsx(ke,{}):e.jsx(Bt,{})}),e.jsxs("span",{className:"pc-body",children:[e.jsx("span",{className:"pc-name",children:S.name}),e.jsx("span",{className:"pc-path",children:S.path})]})]})},S.path))})]}):e.jsxs("button",{type:"button",className:"status-item status-cwd",title:a("cwdTip",{path:n.cwd}),onClick:I,children:["📁 ",n.cwd]})]})}function Tt(t){return t>=1e3?`${(t/1e3).toFixed(1).replace(/\.0$/,"")}K`:String(t)}function Hn(t){return t<=0?"0":t<1e-4?"<0.0001":t.toFixed(4).replace(/\.?0+$/,"")}function Un({dialog:t,send:s}){const a=ie(),[n,r]=l.useState(""),[o,i]=l.useState(0),c=m=>{s({type:"dialog_response",id:t.id,value:m})};l.useEffect(()=>{r(""),i(0);const m=f=>{f.key==="Escape"&&c(null)};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[t.id]);const h=Array.isArray(t.args[0])?t.args[0]:[],d=typeof t.args[0]=="string"?t.args[0]:"";return e.jsx("div",{className:"dialog-overlay",onMouseDown:m=>{m.target===m.currentTarget&&c(null)},children:e.jsxs("div",{className:"dialog",children:[e.jsx("div",{className:"dialog-title",children:t.title||a("pluginRequest")}),t.kind==="select"&&e.jsxs("div",{className:"dialog-options",children:[h.map((m,f)=>e.jsx("button",{type:"button",className:`dialog-option ${f===o?"sel":""}`,onMouseEnter:()=>i(f),onClick:()=>c(m),children:m},f)),h.length===0&&e.jsx("div",{className:"dialog-hint",children:a("noOptions")})]}),t.kind==="confirm"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("p",{children:d}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>c(!1),children:a("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>c(!0),children:a("ok")})]})]}),t.kind==="input"&&e.jsxs("div",{className:"dialog-body",children:[e.jsx("input",{className:"dialog-input",value:n,placeholder:d||a("inputPlaceholder"),autoFocus:!0,onChange:m=>r(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.nativeEvent.isComposing&&c(n)}}),e.jsxs("div",{className:"dialog-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>c(null),children:a("cancel")}),e.jsx("button",{type:"button",className:"btn primary",onClick:()=>c(n),children:a("ok")})]})]})]})})}function qn(t){if(t.x==="?"&&t.y==="?")return"untracked";const s=t.x!==" "&&t.x!=="?",a=t.y!==" "&&t.y!=="?";return s&&a?"both":s?"staged":"unstaged"}function Kn({chat:t,send:s,terminal:a,active:n,onSwitchToTerminal:r}){var lt,ot;const o=ie(),[i,c]=l.useState(null),[h,d]=l.useState([]),[m,f]=l.useState(""),[v,g]=l.useState(new Map),[w,F]=l.useState("changes"),[j,C]=l.useState([]),[D,y]=l.useState(null),[I,M]=l.useState(""),[E,k]=l.useState(!1),[S,B]=l.useState(null),[O,N]=l.useState(null),[R,J]=l.useState(!1),[A,b]=l.useState(!1),[z,U]=l.useState(!1),[u,L]=l.useState(null),[W,G]=l.useState(!1),[$,Q]=l.useState(""),te=l.useRef(0),oe=l.useRef(-1),p=l.useRef(-1),K=l.useRef(-1),se=l.useRef(-1),ee=l.useRef(void 0),Y=l.useRef(null),re=l.useRef([]),T=l.useCallback(x=>{if(x.reqId===oe.current){if(oe.current=-1,b(!1),L(null),!x.ok){L(x.error??"查询失败");return}if(x.notRepo){G(!0),c(null),d([]),g(new Map),C([]),y(null),M(""),N(null);return}G(!1);const Z={branch:x.branch??"",detached:!!x.detached,upstream:x.upstream??null,ahead:x.ahead??0,behind:x.behind??0,upstreamGone:!!x.upstreamGone,files:(x.files??[]).map(ae=>({...ae}))},V=(x.branches??[]).map(ae=>({...ae})),ce=new Map;for(const[ae,ue]of Object.entries(x.stats??{}))ce.set(ae,{add:ue[0],del:ue[1]});c(Z),d(V),g(ce),f(ae=>{var ue;return Z.detached?ae||"":Z.branch&&V.some(ge=>ge.name===Z.branch)?Z.branch:ae&&V.some(ge=>ge.name===ae)?ae:((ue=V[0])==null?void 0:ue.name)??""}),N(ae=>ae&&!Z.files.some(ue=>ue.path===ae.file.path)?null:ae)}else if(x.reqId===p.current){if(p.current=-1,J(!1),!x.ok){L(x.error??"查询失败");return}const Z=Y.current;if(!Z)return;N({file:Z,staged:x.stagedText??"",worktree:x.worktreeText??"",untracked:!1})}else if(x.reqId===se.current){if(se.current=-1,U(!1),!x.ok){L(x.error??"查询失败");return}C((x.history??[]).map(Z=>({...Z})))}else if(x.reqId===K.current){if(K.current=-1,k(!1),!x.ok){L(x.error??"查询失败");return}M(x.text??"")}},[]);l.useEffect(()=>{const x=t.scmData;x&&x.type==="scm_data"&&T(x)},[t.scmData,T]);const _=l.useCallback((x,Z)=>{if(!t.ready||t.status!=="open")return!1;const V=++te.current;return s({...x,reqId:V})?(Z.current=V,!0):(te.current-=1,!1)},[t.ready,t.status,s]),P=l.useCallback((x=!1,Z=!1)=>{var V;!t.ready||t.status!=="open"||(V=t.state)!=null&&V.cwd&&(ee.current!==void 0&&ee.current!==t.state.cwd&&(c(null),d([]),g(new Map),C([]),U(!1),se.current=-1,y(null),M(""),N(null),B(null)),ee.current=t.state.cwd,L(null),_({type:"scm_status"},oe)&&(Z||b(!0)))},[t.ready,(lt=t.state)==null?void 0:lt.cwd,t.status,_]),le=l.useCallback(x=>{if(B(x),y(null),Y.current=x,x.x==="?"&&x.y==="?"){N({file:x,staged:"",worktree:"",untracked:!0});return}J(!0),L(null),_({type:"scm_filediff",path:x.path},p)||J(!1)},[_]),q=l.useCallback(x=>{y(x),B(null),N(null),M(""),k(!0),L(null),_({type:"scm_commit",hash:x.hash},K)||k(!1)},[_]),X=l.useCallback((x,Z)=>{var ae,ue;if(!t.ready)return;const V={name:x,command:Z,cwd:"${pwd}"},ce=t.terminals.find(ge=>ge.title===x);if(ce)a.restart(ce.id),s({type:"run_command",terminalId:ce.id,conversationId:ce.conversationId,command:V,cols:80,rows:24});else{const ge=_e();a.create({id:ge,conversationId:t.activeConversationId||((ae=t.state)==null?void 0:ae.conversationId)||"",title:x,cwd:((ue=t.state)==null?void 0:ue.cwd)??"",cols:80,rows:24,running:!0,exitCode:null,command:V})}r()},[t.ready,(ot=t.state)==null?void 0:ot.cwd,t.terminals,r,s,a]),ne=l.useCallback(()=>{const x=$.trim();if(!x||W)return;const Z=x.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/`/g,"\\`").replace(/\$/g,"\\$");X("git commit",`git add -A && git commit -m "${Z}"`),Q("")},[$,W,X]),de=x=>`'${x.replace(/'/g,"'\\''")}`,we=l.useCallback(x=>{W||X("git add",`git add -- ${de(x.path)}`)},[W,X]),Xt=l.useCallback(x=>{W||X("git reset",`git reset HEAD -- ${de(x.path)}`)},[W,X]),es=l.useCallback(()=>{if(!m||W)return;const x=h.find(Z=>Z.name===m);if(x!=null&&x.remote&&typeof x.remote=="string"){const Z=m.slice(x.remote.length+1);X("git checkout",`git checkout -b ${Z} ${m} || git checkout ${m}`)}else X("git checkout",`git checkout ${m}`)},[m,h,W,X]),ts=l.useCallback(()=>X("git push","git push"),[X]),ss=l.useCallback(()=>X("git pull","git pull"),[X]),Ce=l.useCallback(()=>{_({type:"scm_history"},se)||(se.current=-1)},[_]);l.useEffect(()=>{n&&P()},[n,P]),l.useEffect(()=>{w==="history"&&i&&Ce()},[w,i,Ce]),l.useEffect(()=>{t.scmDirty>0&&n&&P(!1,!0)},[t.scmDirty]),l.useEffect(()=>{if(!n||!t.ready||t.status!=="open")return;const x=setInterval(()=>{document.visibilityState!=="hidden"&&P(!1,!0)},3e4);return()=>clearInterval(x)},[n,t.ready,t.status,P]),l.useEffect(()=>{const x=re.current;if(re.current=t.terminals,!n)return;t.terminals.some(V=>{var ae;return V.running!==!1?!1:((ae=x.find(ue=>ue.id===V.id))==null?void 0:ae.running)===!0&&/^git /.test(V.title)})&&t.ready&&t.status==="open"&&(P(!1,!0),w==="history"&&i&&Ce())},[t.terminals,n,t.ready,t.status,P,w,i,Ce]);const ns={staged:o("scmStaged"),unstaged:o("scmUnstaged"),untracked:o("scmUntracked"),both:o("scmStagedUnstaged")},We=x=>{const Z=x.split(`
12
+ `);return e.jsx("pre",{className:"scm-diff-pre",children:Z.map((V,ce)=>{let ae="";return V.startsWith("diff --git")||V.startsWith("index ")||V.startsWith("new file")||V.startsWith("deleted file")||V.startsWith("old mode")||V.startsWith("new mode")||V.startsWith("similarity index")||V.startsWith("rename ")||V.startsWith("copy ")||V.startsWith("Binary files")||V.startsWith("---")||V.startsWith("+++")?ae="hdr":V.startsWith("@@")?ae="hunk":V.startsWith("+")?ae="add":V.startsWith("-")&&(ae="del"),e.jsx("div",{className:`scm-diff-line ${ae}`,children:V||" "},ce)})})};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(Ee,{}),o("scmTitle")]}),e.jsxs("div",{className:"scm-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":w==="changes",className:w==="changes"?"active":"",onClick:()=>{F("changes"),L(null)},children:o("scmChanges")}),e.jsx("button",{type:"button",role:"tab","aria-selected":w==="history",className:w==="history"?"active":"",onClick:()=>{F("history"),L(null)},children:o("scmHistory")})]}),e.jsx("button",{type:"button",className:"panel-refresh",title:o("scmRefreshTip"),disabled:A,onClick:()=>P(!0),children:e.jsx(Xe,{className:A?"scm-spin":""})})]}),e.jsxs("div",{className:"scm-row",children:[e.jsxs("span",{className:"scm-branch-current",title:o("scmCurrentBranch"),children:[e.jsx(Ee,{}),i?i.detached?o("scmDetached"):i.branch:"…",(i==null?void 0:i.upstream)&&e.jsx("span",{className:"scm-upstream",children:i.upstreamGone?o("scmUpstreamGone"):i.ahead>0||i.behind>0?o("scmAheadBehind",{ahead:i.ahead,behind:i.behind}):i.upstream})]}),e.jsxs("select",{className:"scm-select",value:m,disabled:W||h.length===0,title:o("scmSwitchBranch"),onChange:x=>f(x.target.value),children:[e.jsx("option",{value:"",disabled:!0,children:o("scmSelectBranch")}),h.filter(x=>!x.remote).map(x=>e.jsx("option",{value:x.name,children:x.current?`* ${x.name}`:x.name},x.name)),h.some(x=>x.remote)&&e.jsx("optgroup",{label:o("scmRemoteBranches"),children:h.filter(x=>x.remote).map(x=>e.jsx("option",{value:x.name,children:x.name},x.name))})]}),e.jsxs("button",{type:"button",className:"btn",disabled:!m||m===(i==null?void 0:i.branch)||W,title:o("scmSwitchBranchTip",{branch:m}),onClick:es,children:[e.jsx(Ee,{}),o("scmSwitch")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!i||i.detached||W,title:o("scmPushTip"),onClick:ts,children:[e.jsx(Ft,{}),o("scmPush")]}),e.jsxs("button",{type:"button",className:"btn",disabled:!i||i.detached||W,title:o("scmPullTip"),onClick:ss,children:[e.jsx($t,{}),o("scmPull")]}),e.jsx("input",{className:"scm-commit-input",value:$,placeholder:o("scmCommitPlaceholder"),disabled:W,onChange:x=>Q(x.target.value),onKeyDown:x=>{x.key==="Enter"&&!x.nativeEvent.isComposing&&ne()}}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!$.trim()||W,title:o("scmCommitTip"),onClick:ne,children:[e.jsx(st,{}),o("scmCommit")]})]})]}),e.jsxs("div",{className:"scm-body",children:[w==="history"?e.jsxs("div",{className:"scm-history",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:o("scmHistory")}),j.length>0&&e.jsx("span",{className:"scm-files-count",children:j.length})]}),e.jsx("div",{className:"scm-history-list",children:W?e.jsx("div",{className:"scm-empty",children:o("scmNotGitRepo")}):!i||z?e.jsx("div",{className:"scm-empty",children:t.status==="open"?o("scmLoading"):o("scmConnecting")}):j.length===0?e.jsx("div",{className:"scm-empty",children:o("scmNoHistory")}):j.map(x=>e.jsxs("button",{type:"button",className:`scm-commit ${(D==null?void 0:D.hash)===x.hash?"active":""}`,onClick:()=>q(x),title:x.hash,children:[e.jsx("span",{className:"scm-commit-graph","aria-hidden":"true",children:x.graph||"* "}),e.jsxs("span",{className:"scm-commit-info",children:[e.jsx("span",{className:"scm-commit-subject",children:x.subject}),e.jsxs("span",{className:"scm-commit-meta",children:[x.shortHash," · ",x.author," · ",x.date]}),x.decorations&&e.jsx("span",{className:"scm-commit-refs",children:x.decorations})]})]},x.hash))})]}):e.jsxs("div",{className:"scm-files",children:[e.jsxs("div",{className:"scm-files-header",children:[e.jsx("span",{children:o("scmChanges")}),i&&i.files.length>0&&e.jsx("span",{className:"scm-files-count",children:i.files.length})]}),e.jsx("div",{className:"scm-files-list",children:W?e.jsx("div",{className:"scm-empty",children:o("scmNotGitRepo")}):i?i.files.length===0?e.jsx("div",{className:"scm-empty",children:o("scmNoChanges")}):i.files.map(x=>{const Z=qn(x),V=v.get(x.path);return e.jsxs("div",{className:`scm-file ${(S==null?void 0:S.path)===x.path?"active":""}`,title:ns[Z],onClick:()=>le(x),children:[e.jsx("span",{className:`scm-file-xy ${Z==="untracked"?"q":"x"}`,children:x.x!==" "?x.x:" "}),e.jsx("span",{className:`scm-file-xy ${Z==="untracked"?"q":"y"}`,children:x.y!==" "?x.y:" "}),e.jsx("span",{className:"scm-file-path",children:x.path}),V&&(V.add>0||V.del>0)&&e.jsxs("span",{className:"scm-file-stat",children:[V.add>0&&e.jsxs("span",{className:"add",children:["+",V.add]}),V.del>0&&e.jsxs("span",{className:"del",children:["-",V.del]})]}),e.jsxs("span",{className:"scm-file-actions",children:[(x.y!==" "||Z==="untracked")&&e.jsx("button",{type:"button",className:"scm-act",title:o("scmStageTip",{path:x.path}),onClick:ce=>{ce.stopPropagation(),we(x)},children:"+"}),Z==="staged"||Z==="both"?e.jsx("button",{type:"button",className:"scm-act",title:o("scmUnstageTip",{path:x.path}),onClick:ce=>{ce.stopPropagation(),Xt(x)},children:"−"}):null]})]},x.path)}):e.jsx("div",{className:"scm-empty",children:t.status==="open"?o("scmLoading"):o("scmConnecting")})})]}),e.jsxs("div",{className:"scm-diff",children:[e.jsxs("div",{className:"scm-diff-header",children:[e.jsx("span",{children:w==="history"?D?`${D.shortHash} ${D.subject}`:o("scmCommitDetail"):S?S.path:o("scmDiff")}),(w==="history"?E:R)&&e.jsx("span",{className:"scm-diff-loading",children:o("scmLoading")})]}),e.jsx("div",{className:"scm-diff-body",children:w==="history"?e.jsxs(e.Fragment,{children:[u&&e.jsx("div",{className:"scm-error",children:u}),!D&&!u&&e.jsx("div",{className:"scm-empty",children:o("scmSelectCommitHint")}),D&&E&&!u&&e.jsx("div",{className:"scm-empty",children:o("scmLoading")}),D&&!E&&!u&&I?We(I):null]}):e.jsxs(e.Fragment,{children:[u&&e.jsx("div",{className:"scm-error",children:u}),!S&&!u&&e.jsx("div",{className:"scm-empty",children:o("scmSelectFileHint")}),S&&!O&&!u&&e.jsx("div",{className:"scm-empty",children:o("scmLoading")}),S&&O&&O.untracked&&e.jsx("div",{className:"scm-empty",children:o("scmUntrackedNote")}),S&&O&&!O.untracked&&e.jsxs(e.Fragment,{children:[O.staged&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:o("scmStaged")}),We(O.staged)]}),O.worktree&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"scm-diff-section",children:o("scmUnstaged")}),We(O.worktree)]}),!O.staged&&!O.worktree&&e.jsx("div",{className:"scm-empty",children:o("scmNoDiff")})]})]})})]})]}),e.jsxs("div",{className:"scm-hint",children:[e.jsx(Ze,{}),e.jsx("span",{children:o("scmRunsInTerminal")}),e.jsx("button",{type:"button",className:"scm-goto-term",onClick:r,children:o("scmViewTerminal")})]})]})}function zn({send:t,piConfigured:s,providers:a,installResult:n,onClose:r}){const o=ie(),[i,c]=l.useState(!1),[h,d]=l.useState(""),[m,f]=l.useState(""),[v,g]=l.useState(!1);l.useEffect(()=>{t({type:"list_providers"})},[t]),l.useEffect(()=>{s&&r()},[s,r]),l.useEffect(()=>{n&&c(!1)},[n]),l.useEffect(()=>{var y;!h&&a.length>0&&d(((y=a.find(I=>!I.configured))==null?void 0:y.id)??a[0].id)},[a,h]);const w=()=>{i||(c(!0),t({type:"install_pi_agent"}))},F=()=>{!m.trim()||v||(g(!0),t({type:"set_provider_api_key",provider:h.trim(),apiKey:m.trim()}),setTimeout(()=>g(!1),3e3))},j=()=>{t({type:"get_state"}),t({type:"list_providers"})},C=a.find(y=>y.id===h),D=n!==null&&!n.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":o("close"),onClick:r,children:e.jsx(he,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(Fe,{className:"modal-head-icon"}),e.jsx("h2",{children:o("setupTitle")})]}),e.jsx("p",{className:"modal-desc",children:o("setupDesc")}),D?e.jsxs("div",{className:"setup-failed",children:[e.jsx("div",{className:"setup-done",children:o("installFailed")}),e.jsx("pre",{className:"setup-detail",children:n.detail}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:i,onClick:w,children:o("retryInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:r,children:o("skip")})]})]}):n!=null&&n.ok?e.jsxs("div",{className:"setup-key-form",children:[e.jsx("div",{className:"setup-done",children:o("installDone")}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("provider")}),e.jsxs("select",{value:h,onChange:y=>d(y.target.value),children:[a.length===0&&e.jsx("option",{value:"",children:o("loading")}),a.map(y=>e.jsxs("option",{value:y.id,children:[y.name,"(",y.id,")",y.configured?` · ${o("configured")}`:""]},y.id))]}),(C==null?void 0:C.configured)&&e.jsx("div",{className:"field-hint",children:o("providerKeyReady")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:o("apiKey")}),e.jsx("input",{type:"password",value:m,onChange:y=>f(y.target.value),placeholder:"sk-…"})]}),e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:!m.trim()||v||!h,onClick:F,children:o(v?"saving":"saveAndStart")}),e.jsxs("button",{type:"button",className:"btn",onClick:j,children:[e.jsx(Xe,{})," ",o("recheck")]})]})]}):e.jsxs("div",{className:"setup-actions",children:[e.jsx("button",{type:"button",className:"btn primary",disabled:i,onClick:w,children:o(i?"installing":"autoInstall")}),e.jsx("button",{type:"button",className:"btn",onClick:r,children:o("skip")})]})]})})}const Vn=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"],rt=()=>({id:"",name:"",reasoning:!1,input:"text",contextWindow:"",maxTokens:""}),Gn=()=>({providerId:"",name:"",api:"openai-completions",baseUrl:"",apiKey:"",authHeader:!0,models:[rt()]});function Jn(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:[rt()]).map(s=>{var a;return{id:s.id,name:s.name??"",reasoning:s.reasoning??!1,input:(a=s.input)!=null&&a.includes("image")?"text-image":"text",contextWindow:s.contextWindow?String(s.contextWindow):"",maxTokens:s.maxTokens?String(s.maxTokens):""}})}}function Qn({send:t,providers:s,providerStatus:a,fetchModelsResult:n,refreshProviderResult:r,onClose:o}){const i=ie(),[c,h]=l.useState(null),[d,m]=l.useState({}),[f,v]=l.useState(null),[g,w]=l.useState({}),[F,j]=l.useState(!1),[C,D]=l.useState(0),[y,I]=l.useState(null),M=l.useRef(0),[E,k]=l.useState({});l.useRef(0);const S=l.useRef(0);l.useEffect(()=>{t({type:"list_models_config"}),t({type:"list_providers"})},[t]);const B=()=>{if(!c)return;const b=c.baseUrl.trim();if(!b){I({ok:!1,text:i("fetchModelsNeedBaseUrl")});return}if(F)return;j(!0),I(null);const z=C+1;D(z),t({type:"fetch_models",reqId:z,baseUrl:b,apiKey:c.apiKey.trim()||void 0,authHeader:c.authHeader,api:c.api})};l.useEffect(()=>{var b;if(!(!n||n.reqId===M.current))if(M.current=n.reqId,j(!1),n.ok&&((b=n.models)!=null&&b.length)){const z=n.models;h(U=>{if(!U)return U;const u=U.models.map($=>{var oe;if(!$.id.trim())return $;const Q=z.find(p=>p.id===$.id.trim());if(!Q)return $;const te={...$};return!te.name&&Q.name&&(te.name=Q.name),!te.contextWindow&&Q.contextWindow&&(te.contextWindow=String(Q.contextWindow)),!te.maxTokens&&Q.maxTokens&&(te.maxTokens=String(Q.maxTokens)),te.input==="text"&&((oe=Q.input)!=null&&oe.includes("image"))&&(te.input="text-image"),!te.reasoning&&Q.reasoning&&(te.reasoning=!0),te}),L=new Set(u.map($=>$.id.trim()).filter(Boolean)),W=z.filter($=>!L.has($.id)).map($=>{var Q;return{id:$.id,name:$.name??"",reasoning:$.reasoning??!1,input:(Q=$.input)!=null&&Q.includes("image")?"text-image":"text",contextWindow:$.contextWindow?String($.contextWindow):"",maxTokens:$.maxTokens?String($.maxTokens):""}}),G=[...u,...W];return G.some($=>$.id.trim())?{...U,models:G.filter($=>$.id.trim())}:U}),I({ok:!0,text:i("fetchModelsOk",{n:z.length})})}else I({ok:!1,text:n.error||i("fetchModelsEmpty")})},[n]);const O=b=>{const z=(d[b.id]??"").trim();!z||f||(v(b.id),t({type:"set_provider_api_key",provider:b.id,apiKey:z}),setTimeout(()=>{v(null),m(U=>({...U,[b.id]:""})),w(U=>({...U,[b.id]:!1})),t({type:"list_providers"})},1500))},N=()=>{if(!c)return;const b=c.providerId.trim(),z=c.models.filter(u=>u.id.trim()).map(u=>({id:u.id.trim(),name:u.name.trim()||void 0,reasoning:u.reasoning||void 0,input:u.input==="text-image"?["text","image"]:void 0,contextWindow:u.contextWindow?Number(u.contextWindow):void 0,maxTokens:u.maxTokens?Number(u.maxTokens):void 0})),U={providerId:b,name:c.name.trim()||void 0,api:c.api.trim()||void 0,baseUrl:c.baseUrl.trim()||void 0,apiKey:c.apiKey.trim()||void 0,authHeader:c.authHeader||void 0,models:z};t({type:"save_model_config",providerId:b,config:U}),o()};l.useEffect(()=>{!r||r.reqId===S.current||(S.current=r.reqId,k({}))},[r]);const R=b=>{window.confirm(i("clearKeyConfirm",{id:b}))&&t({type:"clear_provider_api_key",provider:b})},J=b=>{window.confirm(i("deleteProviderConfirm",{id:b.providerId,n:b.models.length}))&&t({type:"delete_model_config",providerId:b.providerId})},A=(b,z)=>{c&&h({...c,models:c.models.map((U,u)=>u===b?{...U,...z}:U)})};return e.jsx("div",{className:"modal-backdrop",onClick:o,children:e.jsxs("div",{className:"modal model-modal",onClick:b=>b.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":i("close"),onClick:o,children:e.jsx(he,{})}),e.jsx("div",{className:"modal-head",children:e.jsx("h2",{children:i(c?"editProvider":"manageModelsTitle")})}),c?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:[i("providerId")," ",e.jsx("em",{children:i("providerIdHint")})]}),e.jsx("input",{type:"text",value:c.providerId,disabled:s.some(b=>b.providerId===c.providerId),onChange:b=>h({...c,providerId:b.target.value}),placeholder:"my-proxy"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:i("displayName")}),e.jsx("input",{type:"text",value:c.name,onChange:b=>h({...c,name:b.target.value}),placeholder:i("displayNamePh")})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:i("apiType")}),e.jsx("select",{value:c.api,onChange:b=>h({...c,api:b.target.value}),children:Vn.map(b=>e.jsx("option",{value:b,children:b},b))})]}),e.jsxs("label",{className:"field",children:[e.jsxs("span",{className:"field-label",children:["baseUrl ",e.jsx("em",{children:i("baseUrlHint")})]}),e.jsx("input",{type:"text",value:c.baseUrl,onChange:b=>h({...c,baseUrl:b.target.value}),placeholder:"http://localhost:11434/v1"})]}),e.jsxs("label",{className:"field",children:[e.jsx("span",{className:"field-label",children:i("apiKey")}),e.jsx("input",{type:"password",value:c.apiKey,onChange:b=>h({...c,apiKey:b.target.value}),placeholder:i("apiKeyHint")})]}),e.jsxs("label",{className:"field check",children:[e.jsx("input",{type:"checkbox",checked:c.authHeader,onChange:b=>h({...c,authHeader:b.target.checked})}),e.jsx("span",{children:i("authHeader")})]})]}),e.jsxs("div",{className:"model-section-head",children:[e.jsx("span",{className:"form-section-title",children:i("modelsTitle")}),e.jsxs("span",{className:"model-section-actions",children:[y&&e.jsx("span",{className:`fetch-msg ${y.ok?"ok":"err"}`,title:y.text,children:y.text}),e.jsxs("button",{type:"button",className:"btn sm",disabled:F||!c.baseUrl.trim(),title:i("fetchModelsHint"),onClick:B,children:[e.jsx(et,{})," ",i(F?"fetchingModels":"fetchModels")]})]})]}),c.models.map((b,z)=>e.jsxs("div",{className:"model-row",children:[e.jsx("input",{type:"text",value:b.id,onChange:U=>A(z,{id:U.target.value}),placeholder:i("modelIdReq")}),e.jsx("input",{type:"text",value:b.name,onChange:U=>A(z,{name:U.target.value}),placeholder:i("displayName")}),e.jsxs("select",{value:b.input,onChange:U=>A(z,{input:U.target.value}),children:[e.jsx("option",{value:"text",children:i("text")}),e.jsx("option",{value:"text-image",children:i("textImage")})]}),e.jsxs("label",{className:"check",children:[e.jsx("input",{type:"checkbox",checked:b.reasoning,onChange:U=>A(z,{reasoning:U.target.checked})}),e.jsx("span",{children:i("reasoning")})]}),e.jsx("input",{type:"number",value:b.contextWindow,onChange:U=>A(z,{contextWindow:U.target.value}),placeholder:i("contextWindow"),title:"contextWindow"}),e.jsx("input",{type:"number",value:b.maxTokens,onChange:U=>A(z,{maxTokens:U.target.value}),placeholder:i("maxOutput"),title:"maxTokens"}),e.jsx("button",{type:"button",className:"iconbtn danger",title:i("removeModel"),onClick:()=>h({...c,models:c.models.filter((U,u)=>u!==z)}),children:e.jsx(Me,{})})]},z)),e.jsxs("button",{type:"button",className:"btn",onClick:()=>h({...c,models:[...c.models,rt()]}),children:[e.jsx(xe,{})," ",i("addModel")]}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:()=>h(null),children:i("cancel")}),e.jsx("button",{type:"button",className:"btn primary",disabled:!c.providerId.trim()||!c.models.some(b=>b.id.trim()),onClick:N,children:i("save")})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-section-title",children:[i("builtinProviders")," ",e.jsx("em",{className:"section-hint",children:i("hintKeyOnly")})]}),e.jsxs("div",{className:"provider-list",children:[a.length===0&&e.jsx("div",{className:"dd-loading",children:i("loading")}),a.map(b=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:b.name}),e.jsxs("span",{className:"provider-sub",children:[b.id,b.configured&&e.jsx("span",{className:"auth-badge",children:i("configuredBadge")}),b.source&&!b.configured&&e.jsx("span",{className:"auth-badge dim",children:b.source})]})]}),e.jsx("div",{className:"provider-actions",children:b.configured&&!g[b.id]?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"auth-badge",children:i("keyReady")}),e.jsxs("button",{type:"button",className:"btn sm",title:i("replaceKeyTitle"),onClick:()=>w(z=>({...z,[b.id]:!0})),children:[e.jsx(ft,{})," ",i("replaceKey")]}),b.source==="stored"&&e.jsxs("button",{type:"button",className:"btn sm danger",title:i("clearKeyTitle"),onClick:()=>R(b.id),children:[e.jsx(Me,{})," ",i("clearKey")]})]}):e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"password",className:"key-input",placeholder:i("pasteKey"),value:d[b.id]??"",onChange:z=>m(U=>({...U,[b.id]:z.target.value}))}),e.jsxs("button",{type:"button",className:"btn primary sm",disabled:!(d[b.id]??"").trim()||f===b.id,onClick:()=>O(b),children:[e.jsx(Ls,{})," ",f===b.id?i("savingKey"):i("saveKey")]})]})})]},b.id))]}),e.jsx("div",{className:"form-section-title",children:i("customProviders")}),e.jsx("p",{className:"modal-desc",children:i("customDesc")}),s.length===0&&e.jsx("div",{className:"dd-loading",children:i("noCustomProviders")}),e.jsx("div",{className:"provider-list",children:s.map(b=>e.jsxs("div",{className:"provider-row",children:[e.jsxs("div",{className:"provider-info",children:[e.jsx("span",{className:"provider-name",children:b.providerId}),e.jsxs("span",{className:"provider-sub",children:[b.api??"—",b.baseUrl?` · ${b.baseUrl}`:"",b.models.length>0&&` · ${i("modelsCount",{n:b.models.length})}`]})]}),e.jsxs("div",{className:"provider-actions",children:[e.jsx("button",{type:"button",className:"iconbtn",title:i("edit"),onClick:()=>h(Jn(b)),children:e.jsx(ft,{})}),e.jsx("button",{type:"button",className:"iconbtn danger",title:i("delete"),onClick:()=>J(b),children:e.jsx(Me,{})})]})]},b.providerId))}),e.jsx("div",{className:"modal-actions",children:e.jsxs("button",{type:"button",className:"btn primary",onClick:()=>h(Gn()),children:[e.jsx(xe,{})," ",i("addProvider")]})})]})]})})}function Te({title:t,subtitle:s,enabled:a,onToggle:n}){const r=ie();return e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:t}),s&&e.jsx("div",{className:"set-row-desc",children:s})]}),e.jsx("button",{type:"button",className:`set-switch ${a?"on":""}`,role:"switch","aria-checked":a,title:r(a?"settingsEnabled":"settingsDisabled"),onClick:n,children:e.jsx("span",{className:"set-switch-knob"})})]})}function Yn({chat:t,send:s,onClose:a}){const n=ie(),r=t.settings,[o,i]=l.useState(""),[c,h]=l.useState("append"),d=l.useRef(!1),[m,f]=l.useState(""),[v,g]=l.useState("append"),w=l.useRef(!1),[F,j]=l.useState(""),C=l.useRef(!1),[D,y]=l.useState("");if(l.useEffect(()=>{r&&(h(r.promptMode),!d.current&&(i(c==="append"||r.customSystemPrompt?r.customSystemPrompt:r.defaultSystemPrompt||""),g(r.visionBridgePromptMode),!w.current&&(f(v==="append"||r.visionBridgePrompt?r.visionBridgePrompt:r.visionBridgeDefaultPrompt||""),C.current||j(r.reviewPrompt))))},[r,c,v]),!r)return null;const I=new Set(r.disabledSkills),M=new Set(r.disabledExtensions),E=N=>s({type:"set_settings",...N}),k=N=>{const R=new Set(I);R.has(N.name)?R.delete(N.name):R.add(N.name),E({disabledSkills:[...R]})},S=N=>{const R=new Set(M);R.has(N.id)?R.delete(N.id):R.add(N.id),E({disabledExtensions:[...R]})},B=N=>{const R=new Set(r.reviewSkills.filter(J=>!J.enabled).map(J=>J.name));R.has(N.name)?R.delete(N.name):R.add(N.name),E({reviewDisabledSkills:[...R]})},O=()=>{const N=c==="replace"&&r.defaultSystemPrompt&&o===r.defaultSystemPrompt?"":o;E({promptMode:c,customSystemPrompt:N})};return e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"modal settings-modal",onClick:N=>N.stopPropagation(),children:[e.jsx("button",{type:"button",className:"modal-close","aria-label":n("close"),onClick:a,children:e.jsx(he,{})}),e.jsxs("div",{className:"modal-head",children:[e.jsx(Be,{className:"modal-head-icon"}),e.jsx("h2",{children:n("settingsTitle")})]}),e.jsx("p",{className:"modal-desc",children:n("settingsDesc")}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ke,{className:"set-section-icon"}),n("settingsSystemPrompt")]}),e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:n("settingsPromptMode")}),e.jsxs("select",{className:"set-select",value:c,onChange:N=>{const R=N.target.value;h(R),E({promptMode:R})},children:[e.jsx("option",{value:"append",children:n("promptModeAppend")}),e.jsx("option",{value:"replace",children:n("promptModeReplace")})]})]}),e.jsx("textarea",{className:"set-prompt-input",rows:6,placeholder:n("promptPlaceholder"),value:o,onFocus:()=>d.current=!0,onBlur:()=>{d.current=!1,O()},onChange:N=>i(N.target.value)}),e.jsx("p",{className:"set-hint",children:n(c==="append"?"promptAppendHint":"promptReplaceHint")})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Fe,{className:"set-section-icon"}),n("settingsSkills"),e.jsx("span",{className:"set-count",children:r.skills.length})]}),r.skills.length===0?e.jsx("p",{className:"set-empty",children:n("noSkills")}):e.jsx("div",{className:"set-list",children:r.skills.map(N=>e.jsx(Te,{title:N.name,subtitle:N.description,enabled:N.enabled,onToggle:()=>k(N)},N.name))})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Cs,{className:"set-section-icon"}),n("settingsExtensions"),e.jsx("span",{className:"set-count",children:r.extensions.length})]}),r.extensions.length===0?e.jsx("p",{className:"set-empty",children:n("noExtensions")}):e.jsx("div",{className:"set-list",children:r.extensions.map(N=>e.jsx(Te,{title:N.name,subtitle:N.path,enabled:N.enabled,onToggle:()=>S(N)},N.id))})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Ke,{className:"set-section-icon"}),n("settingsReview"),e.jsx("span",{className:"set-count",children:r.reviewSkills.length})]}),e.jsx("p",{className:"set-hint",children:n("settingsReviewDesc")}),e.jsx("textarea",{className:"set-prompt-input",rows:5,placeholder:n("reviewPromptPlaceholder"),value:F,onFocus:()=>C.current=!0,onBlur:()=>{C.current=!1,E({reviewPrompt:F})},onChange:N=>j(N.target.value)}),e.jsx("p",{className:"set-hint",children:n("reviewPromptHint")}),e.jsx("div",{className:"set-field-label",children:n("settingsReviewSkills")}),r.reviewSkills.length===0?e.jsx("p",{className:"set-empty",children:n("noSkills")}):e.jsx("div",{className:"set-list",children:r.reviewSkills.map(N=>e.jsx(Te,{title:N.name,subtitle:N.description,enabled:N.enabled,onToggle:()=>B(N)},`review-${N.name}`))})]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Dt,{className:"set-section-icon"}),n("settingsVisionBridge")]}),e.jsx(Te,{title:n("visionBridgeEnabled"),subtitle:n("settingsVisionBridgeDesc"),enabled:r.visionBridgeEnabled,onToggle:()=>E({visionBridgeEnabled:!r.visionBridgeEnabled})}),!r.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:n("visionBridgeOffHint")}),r.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:n("visionBridgeModel")}),e.jsxs("select",{className:"set-select",value:r.visionBridgeModel??"",onChange:N=>E({visionBridgeModel:N.target.value||null}),children:[e.jsx("option",{value:"",children:n("visionBridgeAuto")}),r.visionModels.map(N=>e.jsx("option",{value:`${N.provider}/${N.id}`,children:N.label},`${N.provider}/${N.id}`))]})]}),r.visionBridgeEnabled&&e.jsxs("div",{className:"set-mode-row",children:[e.jsx("label",{className:"set-field-label",children:n("visionBridgePromptMode")}),e.jsxs("select",{className:"set-select",value:v,onChange:N=>{const R=N.target.value;g(R),E({visionBridgePromptMode:R})},children:[e.jsx("option",{value:"append",children:n("promptModeAppend")}),e.jsx("option",{value:"replace",children:n("promptModeReplace")})]})]}),r.visionBridgeEnabled&&e.jsx("textarea",{className:"set-prompt-input",rows:4,placeholder:n("visionBridgePromptPlaceholder"),value:m,onFocus:()=>w.current=!0,onBlur:()=>{w.current=!1;const N=v==="replace"&&r.visionBridgeDefaultPrompt&&m===r.visionBridgeDefaultPrompt?"":m;E({visionBridgePromptMode:v,visionBridgePrompt:N})},onChange:N=>f(N.target.value)}),r.visionBridgeEnabled&&e.jsx("p",{className:"set-hint",children:n(v==="append"?"visionBridgePromptAppendHint":"visionBridgePromptReplaceHint")}),r.visionBridgeEnabled&&(r.visionModels.length===0?e.jsx("p",{className:"set-hint",children:n("visionBridgeNoModels")}):e.jsx("p",{className:"set-hint",children:n("visionBridgeCurrent",{model:r.visionBridgeModel??n("visionBridgeAuto")})}))]}),e.jsxs("div",{className:"set-section",children:[e.jsxs("div",{className:"set-section-title",children:[e.jsx(Be,{className:"set-section-icon"}),n("settingsPresets"),e.jsx("span",{className:"set-count",children:r.presets.length})]}),e.jsxs("div",{className:"set-preset-save",children:[e.jsx("input",{className:"set-input",placeholder:n("presetNamePlaceholder"),value:D,onChange:N=>y(N.target.value),onKeyDown:N=>{N.key==="Enter"&&D.trim()&&(s({type:"save_preset",name:D.trim()}),y(""))}}),e.jsxs("button",{type:"button",className:"set-save-btn",disabled:!D.trim(),onClick:()=>{s({type:"save_preset",name:D.trim()}),y("")},children:[e.jsx(xe,{})," ",n("saveAsPreset")]})]}),r.presets.length===0?e.jsx("p",{className:"set-empty",children:n("noPresets")}):e.jsx("div",{className:"set-list",children:r.presets.map(N=>e.jsxs("div",{className:"set-row",children:[e.jsxs("div",{className:"set-row-info",children:[e.jsx("div",{className:"set-row-name",children:N.name}),e.jsxs("div",{className:"set-row-desc",children:[N.promptMode==="replace"?n("promptModeReplace"):n("promptModeAppend"),N.disabledSkills.length>0&&` · ${n("settingsSkills")} ${N.disabledSkills.length}`,N.disabledExtensions.length>0&&` · ${n("settingsExtensions")} ${N.disabledExtensions.length}`]})]}),e.jsxs("div",{className:"set-row-actions",children:[e.jsx("button",{type:"button",className:"dd-refresh",onClick:()=>s({type:"apply_preset",name:N.name}),children:n("applyPreset")}),e.jsx("button",{type:"button",className:"set-icon-btn danger",title:n("deletePreset"),onClick:()=>s({type:"delete_preset",name:N.name}),children:e.jsx(Me,{})})]})]},N.name))})]}),e.jsx("div",{className:"modal-actions",children:e.jsx("button",{type:"button",className:"dd-refresh",onClick:a,children:n("close")})})]})})}function Zn(t,s){const a=Math.max(0,Date.now()-t),n=Math.floor(a/6e4);if(n<1)return s("bgTaskJustNow");if(n<60)return s("bgTaskMinutes",{n});const r=Math.floor(n/60);return r<24?s("bgTaskHours",{n:r}):s("bgTaskDays",{n:Math.floor(r/24)})}function Xn({servers:t,send:s,onClose:a}){const n=ie();return l.useEffect(()=>{s({type:"list_bg_servers"})},[]),e.jsx("div",{className:"modal-backdrop",onClick:a,children:e.jsxs("div",{className:"bg-task-modal",onClick:r=>r.stopPropagation(),children:[e.jsxs("div",{className:"bg-task-head",children:[e.jsxs("span",{className:"bg-task-title",children:[e.jsx(De,{})," ",n("bgTasks"),t.length>0&&e.jsx("em",{className:"bg-task-count",children:t.length})]}),e.jsx("button",{type:"button",className:"btn",title:n("close"),onClick:a,children:e.jsx(he,{})})]}),t.length===0?e.jsxs("div",{className:"bg-task-empty",children:[e.jsx(De,{}),e.jsx("span",{children:n("bgTasksEmpty")}),e.jsx("small",{children:n("bgTasksDesc")})]}):e.jsx("ul",{className:"bg-task-list",children:t.map(r=>e.jsxs("li",{className:"bg-task-item",children:[e.jsx("span",{className:"bg-task-icon",title:n("bgTaskPort")}),e.jsxs("div",{className:"bg-task-info",children:[e.jsxs("div",{className:"bg-task-line1",children:[e.jsxs("span",{className:"bg-task-port",children:[":",r.port]}),r.name&&e.jsx("span",{className:"bg-task-name",children:r.name})]}),e.jsxs("div",{className:"bg-task-line2",children:[e.jsxs("span",{children:[n("bgTaskPid")," ",r.pid]}),e.jsxs("span",{children:[n("bgTaskSince")," ",Zn(r.since,n)]})]})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stop",title:n("bgTaskStop"),onClick:()=>s({type:"kill_background_server",port:r.port}),children:[e.jsx(Pe,{}),e.jsx("span",{children:n("bgTaskStop")})]})]},r.port))}),e.jsxs("div",{className:"bg-task-foot",children:[e.jsxs("button",{type:"button",className:"btn",title:n("bgTaskRefresh"),onClick:()=>s({type:"list_bg_servers"}),children:[e.jsx(Xe,{}),e.jsx("span",{children:n("bgTaskRefresh")})]}),e.jsxs("button",{type:"button",className:"btn bg-task-stopall",disabled:t.length===0,title:n("bgTaskStopAll"),onClick:()=>s({type:"kill_background_servers"}),children:[e.jsx(Pe,{}),e.jsx("span",{children:n("bgTaskStopAll")})]})]})]})})}const Ue=5e3;function ea({file:t,content:s,send:a,onAddLines:n,onAttach:r,onClose:o}){const i=ie(),[c,h]=l.useState(null),[d,m]=l.useState(!1),[f,v]=l.useState(null),[g,w]=l.useState(!1),[F,j]=l.useState(!1),[C,D]=l.useState(!1),[y,I]=l.useState(""),[M,E]=l.useState(!0),k=l.useRef(!1),[S,B]=l.useState(!0),[O,N]=l.useState(!1),[R,J]=l.useState(100),A=l.useRef(0),b=l.useRef(!1),z=l.useRef(null);l.useEffect(()=>{m(!0),h(null),v(null),D(!1),I(""),E(!0),k.current=!1,a({type:"read_file",path:t.path})},[t.path,a]),l.useEffect(()=>{s&&s.path===t.path&&(h(s),C||I(s.text),m(!1))},[s,C,t.path]),l.useEffect(()=>{const q=X=>{if(X.key==="Escape"){K();return}if((X.ctrlKey||X.metaKey)&&X.key.toLowerCase()==="s"&&C){X.preventDefault(),p();return}const ne=X.target,de=ne&&(ne.tagName==="INPUT"||ne.tagName==="TEXTAREA"||ne.isContentEditable);(X.ctrlKey||X.metaKey)&&X.key.toLowerCase()==="a"&&!de&&(X.preventDefault(),G())};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[o,c,C,y]),l.useEffect(()=>{const q=()=>{b.current=!1,w(!1)};return window.addEventListener("mouseup",q),()=>window.removeEventListener("mouseup",q)},[]);const U=l.useMemo(()=>{if(!c)return[];const q=c.text.split(`
13
+ `);return q.length>0&&q[q.length-1]===""&&q.pop(),q.slice(0,Ue)},[c]),u=(c==null?void 0:c.lines)??0,L=u>Ue,W=(q,X)=>{if(X){const ne=A.current>0?A.current:q;v({start:Math.min(ne,q),end:Math.max(ne,q)})}else A.current=q,v({start:q,end:q})},G=()=>{U.length!==0&&(A.current=1,v({start:1,end:U.length}))},$=()=>{f&&(n(t.path,t.name,f.start,f.end),j(!0),z.current&&clearTimeout(z.current),z.current=setTimeout(()=>j(!1),1400))},Q=c!==null&&c.kind==="text"&&!c.binary&&!c.truncated,te=()=>{I((c==null?void 0:c.text)??""),D(!1),k.current&&E(!0)},oe=()=>{if(C){if(y!==((c==null?void 0:c.text)??"")&&!window.confirm(i("discardFileChanges")))return;te();return}!Q||!c||(k.current=qe(t.name)&&M,qe(t.name)&&E(!1),v(null),I(c.text),D(!0))},p=()=>{!C||!c||!Q||a({type:"write_file",path:t.path,text:y})&&(D(!1),k.current&&E(!0),v(null))},K=()=>{C&&y!==((c==null?void 0:c.text)??"")&&!window.confirm(i("discardFileChanges"))||o()},se=q=>{J(Math.min(200,Math.max(50,q)))},ee=f?f.end-f.start+1:0,Y=(c==null?void 0:c.binary)??!1,re=(c==null?void 0:c.truncated)??!1,T=(c==null?void 0:c.kind)??"text",_=qe(t.name),P=_&&M&&!C&&T==="text"&&!Y,le=q=>Ae(`/api/file?clientId=${encodeURIComponent(at())}&path=${encodeURIComponent(q)}`);return e.jsx("div",{className:`fp-overlay ${O?"fullscreen":""}`,onMouseDown:q=>{q.target===q.currentTarget&&K()},children:e.jsxs("div",{className:`fp ${O?"fullscreen":""}`,style:{"--fp-zoom":R/100},children:[e.jsxs("div",{className:"fp-head",children:[e.jsx("span",{className:"fp-name",title:t.path,children:t.name}),e.jsx("span",{className:"fp-path",children:t.path}),e.jsxs("span",{className:"fp-meta",children:[c&&T==="text"&&!Y&&i("fileLines",{n:u}),c&&` · ${ta(c.size)}`]}),e.jsxs("span",{className:"fp-head-actions",children:[_&&T==="text"&&!Y&&c&&e.jsx("button",{type:"button",className:`fp-attach markdown ${M?"on":""}`,"data-tip":i(M?"showMarkdownSource":"showMarkdownPreview"),disabled:C,onClick:()=>E(q=>!q),children:M?e.jsx(Dt,{}):e.jsx(Ds,{})}),T==="text"&&!Y&&c&&e.jsx("button",{type:"button",className:`fp-attach edit ${C?"on":""}`,"data-tip":i(re?"fileEditTruncated":C?"exitEditFile":"editFile"),disabled:!Q&&!C,onClick:oe,children:e.jsx(Ge,{})}),T==="text"&&!Y&&!P&&e.jsx("button",{type:"button",className:`fp-attach wrap ${S?"on":""}`,"data-tip":i(S?"disableWrap":"enableWrap"),onClick:()=>B(q=>!q),children:e.jsx(Bs,{})}),T==="text"&&c&&e.jsxs("span",{className:"fp-zoom",children:[e.jsx("button",{type:"button",className:"fp-attach zoom-out","data-tip":i("zoomOut"),disabled:R<=50,onClick:()=>se(R-10),children:e.jsx(ys,{})}),e.jsxs("button",{type:"button",className:"fp-zoom-val",title:i("resetZoom"),onClick:()=>J(100),children:[R,"%"]}),e.jsx("button",{type:"button",className:"fp-attach zoom-in","data-tip":i("zoomIn"),disabled:R>=200,onClick:()=>se(R+10),children:e.jsx(js,{})})]}),T!=="video"&&T!=="none"&&e.jsx("button",{type:"button",className:"fp-attach inline","data-tip":i("attachInlineTip"),onClick:()=>r(t.path,t.name,"inline"),children:e.jsx(xe,{})}),e.jsx("button",{type:"button",className:"fp-attach ref","data-tip":i("referenceTip"),onClick:()=>r(t.path,t.name,"reference"),children:e.jsx(Ve,{})}),e.jsx("button",{type:"button",className:`fp-attach full ${O?"on":""}`,"data-tip":i(O?"exitFullscreen":"fullscreen"),onClick:()=>N(q=>!q),children:O?e.jsx(Ts,{}):e.jsx(Es,{})}),e.jsx("button",{type:"button",className:"fp-close",title:i("close"),onClick:K,children:e.jsx(he,{})})]})]}),re&&T==="text"&&!Y&&e.jsx("div",{className:"fp-notice",children:i("previewTruncated")}),d&&!c&&e.jsx("div",{className:"fp-empty",children:i("loading")}),!d&&T==="none"&&!Y&&e.jsx("div",{className:"fp-empty",children:i("previewNotSupported")}),!d&&T==="image"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("img",{className:"fp-media",src:le(t.path),alt:t.name})}),!d&&T==="video"&&e.jsx("div",{className:"fp-media-wrap",children:e.jsx("video",{className:"fp-media",src:le(t.path),controls:!0,preload:"metadata"})}),!d&&P&&c&&e.jsx("div",{className:"fp-markdown msg-text",children:e.jsx("div",{className:"fp-markdown-zoom",children:e.jsx(Oe,{text:c.text})})}),!d&&Y&&T!=="image"&&T!=="video"&&c&&e.jsxs("div",{className:"fp-hex-wrap",children:[e.jsxs("div",{className:"fp-notice",children:[i("binaryFile"),c.truncated&&i("binaryHexTruncated")]}),e.jsx("pre",{className:"fp-hex",children:c.text})]}),!d&&C&&T==="text"&&!Y&&c&&e.jsx("textarea",{className:`fp-editor ${S?"":"no-wrap"}`,value:y,onChange:q=>I(q.target.value),wrap:S?"soft":"off",spellCheck:!1,autoFocus:!0}),!d&&!P&&!C&&T==="text"&&!Y&&c&&U.length===0&&e.jsx("div",{className:"fp-empty",children:i("emptyFile")}),!d&&!P&&!C&&T==="text"&&!Y&&U.length>0&&e.jsxs("div",{className:`fp-code ${g?"dragging":""} ${S?"":"no-wrap"}`,onMouseDown:q=>{q.button===0&&q.preventDefault()},children:[U.map((q,X)=>{const ne=X+1,de=f!==null&&ne>=f.start&&ne<=f.end;return e.jsxs("div",{className:`fp-line ${de?"sel":""}`,onMouseDown:we=>{we.button===0&&(W(ne,we.shiftKey),b.current=!0,w(!0))},onMouseEnter:()=>{b.current&&W(ne,!0)},children:[e.jsx("span",{className:"fp-num",children:ne}),e.jsx("span",{className:"fp-code-text",children:q})]},ne)}),L&&e.jsx("div",{className:"fp-lines-note",children:i("previewLinesTruncated",{n:Ue})})]}),e.jsx("div",{className:"fp-foot",children:C?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:i("editFile")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:oe,children:i("cancel")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:y===((c==null?void 0:c.text)??""),onClick:p,children:[e.jsx(ws,{})," ",i("saveFile")]})]})]}):!P&&T==="text"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"fp-hint",children:f?i("selectedRange",{n:ee,start:f.start,end:f.end}):i("selectLinesHint")}),e.jsxs("div",{className:"fp-actions",children:[e.jsx("button",{type:"button",className:"btn",disabled:U.length===0,onClick:G,children:i("selectAll")}),e.jsx("button",{type:"button",className:"btn",disabled:!f,onClick:()=>v(null),children:i("clearSelection")}),e.jsxs("button",{type:"button",className:"btn primary",disabled:!f||Y,onClick:$,children:[F?e.jsx(st,{}):null,i(F?"addedToChat":"addToChat")]})]})]})})]})})}function qe(t){const s=t.toLowerCase();return s.endsWith(".md")||s.endsWith(".markdown")}function ta(t){return t>=1024*1024?`${(t/(1024*1024)).toFixed(1)} MB`:t>=1024?`${Math.round(t/1024)} KB`:`${t} B`}const Gt="pi-web-sounds",ye={enabled:!0,question:!0,done:!0,start:!1,error:!0,volume:100};function Jt(){try{const t=localStorage.getItem(Gt);if(!t)return{...ye};const s=JSON.parse(t),a={...ye,...s};for(const n of["enabled","question","done","start","error"])typeof a[n]!="boolean"&&(a[n]=ye[n]);return typeof a.volume!="number"||!Number.isFinite(a.volume)?a.volume=ye.volume:a.volume=Math.round(Math.max(0,Math.min(100,a.volume))/5)*5,a}catch{return{...ye}}}function sa(t){try{localStorage.setItem(Gt,JSON.stringify(t))}catch{}}let je=null;function na(){try{if(!je){const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;je=new t}return je.state==="suspended"&&je.resume(),je}catch{return null}}const aa=[{type:"sine",freq:587.33,start:0,dur:.13,peak:.5},{type:"sine",freq:880,start:.11,dur:.24,peak:.5}],ia=[{type:"sine",freq:880,start:0,dur:.15,peak:.35},{type:"sine",freq:587.33,start:.15,dur:.32,peak:.35}],ra=[{type:"triangle",freq:660,start:0,dur:.08,peak:.22}],la=[{type:"square",freq:220,start:0,dur:.16,peak:.18},{type:"square",freq:174.61,start:.18,dur:.26,peak:.18}],oa={question:aa,done:ia,start:ra,error:la};function ca(t,s,a){const n=t.createOscillator(),r=t.createGain();n.type=s.type,n.frequency.value=s.freq;const o=t.currentTime+s.start,i=Math.max(1e-4,s.peak*a);r.gain.setValueAtTime(1e-4,o),r.gain.exponentialRampToValueAtTime(i,o+.012),r.gain.exponentialRampToValueAtTime(1e-4,o+s.dur),n.connect(r),r.connect(t.destination),n.start(o),n.stop(o+s.dur+.05)}function be(t,s=Jt()){if(!s.enabled||!s[t])return;const a=na();if(!a)return;const n=Math.max(0,Math.min(1,s.volume/100));for(const r of oa[t])ca(a,r,n)}const Ye="pi-web-ui:theme",Qt="dark",Mt="theme-stylesheet",Et="pi-web-ui:theme-change";function Yt(){try{const t=localStorage.getItem(Ye);if(t&&t!==Qt)return t}catch{}return null}function da(t){try{t?localStorage.setItem(Ye,t):localStorage.removeItem(Ye)}catch{}}function Zt(t){let s=document.getElementById(Mt);if(!t){s==null||s.remove(),window.dispatchEvent(new CustomEvent(Et));return}s||(s=document.createElement("link"),s.id=Mt,s.rel="stylesheet",document.head.appendChild(s)),s.href=`/themes/${encodeURIComponent(t)}.css`,s.onload=()=>window.dispatchEvent(new CustomEvent(Et))}async function ua(){try{const t=await fetch(Ae("/api/themes"));if(!t.ok)return[];const s=await t.json();return Array.isArray(s.themes)?s.themes:[]}catch{return[]}}function ma(){const[t,s]=l.useState([]),[a,n]=l.useState(()=>Yt());return l.useEffect(()=>{let o=!1;return ua().then(i=>{o||s(i)}),()=>{o=!0}},[]),l.useEffect(()=>{Zt(a),da(a)},[a]),{themes:t,theme:a,switchTheme:o=>n(o===Qt?null:o)}}function ya(){const t=getComputedStyle(document.documentElement),s=(a,n)=>t.getPropertyValue(a).trim()||n;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 pa=l.lazy(()=>us(()=>import("./TerminalPanel-B-bsYqea.js"),__vite__mapDeps([0,1,2,3,4])).then(t=>({default:t.TerminalPanel})));function ha({notice:t,onDismiss:s}){const a=ie(),[n,r]=l.useState(!1);l.useEffect(()=>{if(n)return;const i=setTimeout(()=>s(t.id),t.level==="error"?12e3:7e3);return()=>clearTimeout(i)},[n,t.id,t.level,s]);const o=t.level==="error"?As:t.level==="warning"?$s:Is;return e.jsxs("div",{className:`notice notice-${t.level}${n?" paused":""}`,role:"status",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:[e.jsx(o,{className:"notice-icon"}),e.jsx("span",{className:"notice-text",children:t.text}),e.jsx("button",{type:"button",className:"notice-close",title:a("close"),onClick:()=>s(t.id),children:e.jsx(he,{})})]})}function ga(){var Y,re;const t=ie(),{chat:s,send:a,dismissNotice:n,pushNotice:r,terminal:o}=rn(),[i,c]=l.useState([]),[h,d]=l.useState(null),[m,f]=l.useState("chat"),[v,g]=l.useState(null),[w,F]=l.useState(()=>window.matchMedia("(max-width: 768px)").matches);l.useEffect(()=>{const T=window.matchMedia("(max-width: 768px)"),_=P=>F(P.matches);return T.addEventListener("change",_),()=>T.removeEventListener("change",_)},[]);const[j,C]=l.useState(!1),[D,y]=l.useState(!1),[I,M]=l.useState(!1),[E,k]=l.useState(!1),[S,B]=l.useState(Jt),{themes:O,theme:N,switchTheme:R}=ma(),J=l.useRef(null),A=l.useRef(null),b=l.useRef(0),z=l.useRef(!1);l.useEffect(()=>{sa(S)},[S]),l.useEffect(()=>{var P;const T=((P=s.state)==null?void 0:P.isStreaming)??!1,_=J.current;J.current=T,_!==null&&(!_&&T?be("start",S):_&&!T&&be("done",S))},[(Y=s.state)==null?void 0:Y.isStreaming,S]),l.useEffect(()=>{var _;const T=((_=s.dialog)==null?void 0:_.id)??null;T!==null&&T!==A.current&&be("question",S),A.current=T},[s.dialog,S]),l.useEffect(()=>{const T=[...s.notices].reverse().find(_=>_.level==="error");T&&T.id!==b.current&&(b.current=T.id,be("error",S))},[s.notices,S]);const U=(T,_,P,le=!1,q)=>{const X=`${T}|${P}|${q?`${q.start}-${q.end}`:""}`;c(ne=>ne.some(de=>`${de.path}|${de.mode}|${de.lines?`${de.lines.start}-${de.lines.end}`:""}`===X)?ne:[...ne,{path:T,name:_,mode:P,isDir:le,...q?{lines:q}:{}}])},u=T=>c(_=>_.filter(P=>P.key?P.key!==T:P.path!==T)),L=l.useCallback(T=>(g(null),a(T)),[a]),W=l.useRef(0),G=l.useRef(0),$=T=>{var le;const _=Date.now();(le=s.state)!=null&&le.model&&!s.state.model.vision&&_-G.current>1e4&&(G.current=_,r("warning",t("imageNotSupported")));const P=`paste-${++W.current}`;c(q=>[...q,{path:"",key:P,name:T.name,mode:"inline",imageData:T.data,mimeType:T.mimeType}])},Q=async T=>{for(const _ of T){const P=await $n(_);if(!P){r("error",t("imageLoadFailed",{name:_.name}));continue}$(P)}},te=20*1024*1024,oe=l.useRef(0),p=async T=>{if(T.size>te){r("warning",t("fileTooLarge",{name:T.name,size:te/1024/1024}));return}let _;try{_=(await new Promise((q,X)=>{const ne=new FileReader;ne.onload=()=>q(ne.result),ne.onerror=()=>X(ne.error??new Error("read failed")),ne.readAsDataURL(T)})).replace(/^data:[^;]*;base64,/,"")}catch{r("error",t("fileLoadFailed",{name:T.name}));return}const P=`upload-${++oe.current}`;c(le=>[...le,{path:"",key:P,name:T.name,mode:"inline",fileData:_,size:T.size,mimeType:T.type||void 0}])},K=async T=>{for(const _ of T)Re(_.type)?await Q([_]):await p(_)},se=l.useCallback((T,_)=>{a({type:"edit_message",messageId:T,text:_})},[a]),ee=l.useCallback(()=>{var T,_;return!s.ready||s.terminals.length!==0?!1:(o.create({id:_e(),conversationId:s.activeConversationId||((T=s.state)==null?void 0:T.conversationId)||"",title:t("terminalTitle",{n:1}),cwd:((_=s.state)==null?void 0:_.cwd)??"",cols:80,rows:24,running:!0,exitCode:null}),!0)},[s.ready,(re=s.state)==null?void 0:re.cwd,s.terminals.length,t,o]);return l.useEffect(()=>{if(z.current){if(m!=="terminal"||s.terminals.length!==0){z.current=!1;return}ee()&&(z.current=!1)}},[s.terminals.length,ee,m]),e.jsxs("div",{className:"app",onDragOver:T=>T.preventDefault(),onDrop:T=>T.preventDefault(),children:[e.jsx(zs,{chat:s,send:a,view:m,onViewChange:T=>{z.current=T==="terminal"&&s.terminals.length===0,z.current&&ee()&&(z.current=!1),f(T),g(null)},onOpenPanel:g,onManageModels:()=>y(!0),onOpenSettings:()=>M(!0),onOpenBgTasks:()=>k(!0),sound:S,onSoundChange:B,onSoundPreview:T=>be(T,S),themes:O,theme:N,onThemeChange:R}),s.protocolMismatch&&e.jsxs("div",{className:"protocol-banner",children:["⚠ ",t("protocolMismatch")]}),e.jsx("div",{className:"notices",children:s.notices.map(T=>e.jsx(ha,{notice:T,onDismiss:n},T.id))}),e.jsxs("div",{className:"layout",children:[v&&e.jsx("div",{className:"drawer-backdrop",onClick:()=>g(null)}),e.jsxs("div",{className:`view-pane ${m==="chat"?"":"hidden"}`,children:[e.jsx("div",{className:`panel-drawer drawer-left ${v==="left"?"open":""}`,children:e.jsx(Vs,{chat:s,send:L,active:!w||v==="left"})}),e.jsxs("main",{className:"main",children:[s.state?e.jsx(Dn,{state:s.state,liveOutputs:s.liveOutputs,toolStatuses:s.toolStatuses,onEdit:se,onKillBash:()=>a({type:"abort_bash"})},s.state.conversationId??"boot"):e.jsx("div",{className:"boot-wait",children:s.ready?t("loadingSession"):t("connectingServer")}),e.jsx(On,{chat:s,send:a}),e.jsx(An,{chat:s,send:a,attachments:i,onRemoveAttachment:u,onAddImageFiles:Q,onAddLocalFiles:K,onNotice:r,onManageModels:()=>y(!0),onSent:()=>c([])})]}),e.jsx("div",{className:`panel-drawer drawer-right ${v==="right"?"open":""}`,children:e.jsx(gn,{chat:s,send:L,onAttach:(T,_,P,le)=>{g(null),U(T,_,P,le)},onPreview:(T,_)=>{g(null),d({path:T,name:_})},onNotice:(T,_)=>r(T,_)})})]}),e.jsx("div",{className:`view-pane ${m==="terminal"?"":"hidden"}`,children:e.jsx(l.Suspense,{fallback:null,children:e.jsx(pa,{chat:s,send:a,terminal:o})})}),e.jsx("div",{className:`view-pane ${m==="git"?"":"hidden"}`,children:e.jsx(Kn,{chat:s,send:a,terminal:o,active:m==="git",onSwitchToTerminal:()=>f("terminal")})})]}),e.jsx(Wn,{chat:s,send:a}),s.dialog&&e.jsx(Un,{dialog:s.dialog,send:a}),h&&e.jsx(ea,{file:h,content:s.fileContent,send:a,onAddLines:(T,_,P,le)=>U(T,_,"lines",!1,{start:P,end:le}),onAttach:(T,_,P)=>U(T,_,P),onClose:()=>d(null)}),s.ready&&s.state&&s.state.piConfigured===!1&&!j&&!D&&e.jsx(zn,{send:a,piConfigured:s.state.piConfigured,providers:s.providers,installResult:s.installResult,onClose:()=>C(!0)}),D&&e.jsx(Qn,{send:a,providers:s.modelsConfig,providerStatus:s.providers,fetchModelsResult:s.fetchModelsResult,refreshProviderResult:s.refreshProviderResult,onClose:()=>y(!1)}),I&&e.jsx(Yn,{chat:s,send:a,onClose:()=>M(!1)}),E&&e.jsx(Xn,{servers:s.bgServers,send:a,onClose:()=>k(!1)})]})}Gs();Zt(Yt());os.createRoot(document.getElementById("root")).render(e.jsx(l.StrictMode,{children:e.jsx(Us,{children:e.jsx(ga,{})})}));export{Xe as F,Et as T,xe as a,ya as b,va as c,ft as d,Me as e,he as f,Ms as g,Ze as h,_e as r,ie as u};